src/HOL/Library/code_test.ML
author wenzelm
Sat Dec 17 14:13:15 2016 +0100 (2016-12-17)
changeset 64581 ee4b9cea7fb5
parent 64580 43ad19fbe9dc
child 64582 3d20ded18f14
permissions -rw-r--r--
tuned signature -- suppress pointless exports;
wenzelm@59720
     1
(*  Title:      HOL/Library/code_test.ML
wenzelm@64577
     2
    Author:     Andreas Lochbihler, ETH Z├╝rich
Andreas@58039
     3
wenzelm@64577
     4
Test infrastructure for the code generator.
Andreas@58039
     5
*)
Andreas@58039
     6
wenzelm@64577
     7
signature CODE_TEST =
wenzelm@64577
     8
sig
wenzelm@64577
     9
  val add_driver:
wenzelm@64577
    10
    string * ((Proof.context -> (string * string) list * string -> Path.T -> string) * string) ->
wenzelm@64577
    11
    theory -> theory
wenzelm@64577
    12
  val overlord: bool Config.T
wenzelm@64577
    13
  val successN: string
wenzelm@64577
    14
  val failureN: string
wenzelm@64577
    15
  val start_markerN: string
wenzelm@64577
    16
  val end_markerN: string
wenzelm@64577
    17
  val test_terms: Proof.context -> term list -> string -> unit
wenzelm@64578
    18
  val test_targets: Proof.context -> term list -> string list -> unit
wenzelm@64580
    19
  val test_code_cmd: string list -> string list -> Proof.context -> unit
wenzelm@64577
    20
  val eval_term: string -> Proof.context -> term -> term
wenzelm@64581
    21
  val evaluate:
wenzelm@64577
    22
   (theory -> Path.T -> string list -> string ->
wenzelm@64577
    23
    {files: (Path.T * string) list,
wenzelm@64577
    24
     compile_cmd: string option,
wenzelm@64577
    25
     run_cmd: string,
wenzelm@64577
    26
     mk_code_file: string -> Path.T}) ->
wenzelm@64577
    27
   string -> string -> string -> theory -> (string * string) list * string -> Path.T -> string
wenzelm@64577
    28
  val evaluate_in_polyml: Proof.context -> (string * string) list * string -> Path.T -> string
wenzelm@64577
    29
  val evaluate_in_mlton: Proof.context -> (string * string) list * string -> Path.T -> string
wenzelm@64577
    30
  val evaluate_in_smlnj: Proof.context -> (string * string) list * string -> Path.T -> string
wenzelm@64577
    31
  val evaluate_in_ocaml: Proof.context -> (string * string) list * string -> Path.T -> string
wenzelm@64577
    32
  val ghc_options: string Config.T
wenzelm@64577
    33
  val evaluate_in_ghc: Proof.context -> (string * string) list * string -> Path.T -> string
wenzelm@64577
    34
  val evaluate_in_scala: Proof.context -> (string * string) list * string -> Path.T -> string
Andreas@58039
    35
end
Andreas@58039
    36
wenzelm@64577
    37
structure Code_Test: CODE_TEST =
wenzelm@64577
    38
struct
Andreas@58039
    39
Andreas@58039
    40
(* convert a list of terms into nested tuples and back *)
wenzelm@64577
    41
Andreas@58039
    42
fun mk_tuples [] = @{term "()"}
Andreas@58039
    43
  | mk_tuples [t] = t
Andreas@58039
    44
  | mk_tuples (t :: ts) = HOLogic.mk_prod (t, mk_tuples ts)
Andreas@58039
    45
Andreas@58039
    46
fun dest_tuples (Const (@{const_name Pair}, _) $ l $ r) = l :: dest_tuples r
Andreas@58039
    47
  | dest_tuples t = [t]
Andreas@58039
    48
Andreas@58039
    49
Andreas@58039
    50
fun last_field sep str =
Andreas@58039
    51
  let
wenzelm@64577
    52
    val n = size sep
wenzelm@64577
    53
    val len = size str
Andreas@58039
    54
    fun find i =
Andreas@58039
    55
      if i < 0 then NONE
Andreas@58039
    56
      else if String.substring (str, i, n) = sep then SOME i
wenzelm@64577
    57
      else find (i - 1)
Andreas@58039
    58
  in
Andreas@58039
    59
    (case find (len - n) of
Andreas@58039
    60
      NONE => NONE
Andreas@58039
    61
    | SOME i => SOME (String.substring (str, 0, i), String.extract (str, i + n, NONE)))
wenzelm@64577
    62
  end
Andreas@58039
    63
Andreas@58039
    64
fun split_first_last start stop s =
wenzelm@64577
    65
  (case first_field start s of
wenzelm@64577
    66
    NONE => NONE
wenzelm@64577
    67
  | SOME (initial, rest) =>
wenzelm@64577
    68
      (case last_field stop rest of
wenzelm@64577
    69
        NONE => NONE
wenzelm@64577
    70
      | SOME (middle, tail) => SOME (initial, middle, tail)))
Andreas@58039
    71
wenzelm@64577
    72
wenzelm@64577
    73
(* data slot for drivers *)
Andreas@58039
    74
Andreas@58039
    75
structure Drivers = Theory_Data
Andreas@58039
    76
(
wenzelm@64577
    77
  type T =
wenzelm@64577
    78
    (string * ((Proof.context -> (string * string) list * string -> Path.T -> string) * string)) list
wenzelm@64577
    79
  val empty = []
wenzelm@64577
    80
  val extend = I
wenzelm@64577
    81
  fun merge data : T = AList.merge (op =) (K true) data
Andreas@58039
    82
)
Andreas@58039
    83
wenzelm@64577
    84
val add_driver = Drivers.map o AList.update (op =)
wenzelm@64577
    85
val get_driver = AList.lookup (op =) o Drivers.get
Andreas@58039
    86
Andreas@58039
    87
(*
Andreas@58039
    88
  Test drivers must produce output of the following format:
wenzelm@64577
    89
Andreas@58039
    90
  The start of the relevant data is marked with start_markerN,
Andreas@58039
    91
  its end with end_markerN.
Andreas@58039
    92
Andreas@58039
    93
  Between these two markers, every line corresponds to one test.
Andreas@58039
    94
  Lines of successful tests start with successN, failures start with failureN.
Andreas@58039
    95
  The failure failureN may continue with the YXML encoding of the evaluated term.
Andreas@58039
    96
  There must not be any additional whitespace in between.
Andreas@58039
    97
*)
Andreas@58039
    98
wenzelm@64577
    99
wenzelm@64577
   100
(* parsing of results *)
Andreas@58039
   101
Andreas@58039
   102
val successN = "True"
Andreas@58039
   103
val failureN = "False"
Andreas@58039
   104
val start_markerN = "*@*Isabelle/Code_Test-start*@*"
Andreas@58039
   105
val end_markerN = "*@*Isabelle/Code_Test-end*@*"
Andreas@58039
   106
Andreas@58039
   107
fun parse_line line =
Andreas@58039
   108
  if String.isPrefix successN line then (true, NONE)
wenzelm@64577
   109
  else if String.isPrefix failureN line then (false,
Andreas@58039
   110
    if size line > size failureN then
Andreas@58039
   111
      String.extract (line, size failureN, NONE)
Andreas@58039
   112
      |> YXML.parse_body
Andreas@58039
   113
      |> Term_XML.Decode.term
Andreas@58039
   114
      |> dest_tuples
Andreas@58039
   115
      |> SOME
Andreas@58039
   116
    else NONE)
Andreas@58039
   117
  else raise Fail ("Cannot parse result of evaluation:\n" ^ line)
Andreas@58039
   118
Andreas@58039
   119
fun parse_result target out =
wenzelm@64577
   120
  (case split_first_last start_markerN end_markerN out of
wenzelm@64577
   121
    NONE => error ("Evaluation failed for " ^ target ^ "!\nBash output:\n" ^ out)
wenzelm@64577
   122
  | SOME (_, middle, _) => middle |> trim_line |> split_lines |> map parse_line)
Andreas@58039
   123
wenzelm@64577
   124
wenzelm@64577
   125
(* pretty printing of test results *)
Andreas@58039
   126
Andreas@58039
   127
fun pretty_eval _ NONE _ = []
wenzelm@64577
   128
  | pretty_eval ctxt (SOME evals) ts =
wenzelm@64577
   129
      [Pretty.fbrk,
wenzelm@64577
   130
       Pretty.big_list "Evaluated terms"
wenzelm@64577
   131
         (map (fn (t, eval) => Pretty.block
wenzelm@64577
   132
           [Syntax.pretty_term ctxt t, Pretty.brk 1, Pretty.str "=", Pretty.brk 1,
wenzelm@64577
   133
            Syntax.pretty_term ctxt eval])
wenzelm@64577
   134
         (ts ~~ evals))]
Andreas@58039
   135
Andreas@58039
   136
fun pretty_failure ctxt target (((_, evals), query), eval_ts) =
wenzelm@60022
   137
  Pretty.block (Pretty.text ("Test in " ^ target ^ " failed for")
wenzelm@60022
   138
    @ [Pretty.brk 1, Pretty.quote (Syntax.pretty_term ctxt query)]
Andreas@58039
   139
    @ pretty_eval ctxt evals eval_ts)
Andreas@58039
   140
Andreas@58039
   141
fun pretty_failures ctxt target failures =
Andreas@58039
   142
  Pretty.blk (0, Pretty.fbreaks (map (pretty_failure ctxt target) failures))
Andreas@58039
   143
Andreas@58039
   144
wenzelm@64577
   145
(* driver invocation *)
wenzelm@64577
   146
wenzelm@64577
   147
val overlord = Attrib.setup_config_bool @{binding "code_test_overlord"} (K false)
Andreas@58039
   148
Andreas@58039
   149
fun with_overlord_dir name f =
Andreas@58039
   150
  let
wenzelm@64577
   151
    val path =
wenzelm@64577
   152
      Path.append (Path.explode "$ISABELLE_HOME_USER") (Path.basic (name ^ serial_string ()))
wenzelm@64577
   153
    val _ = Isabelle_System.mkdirs path
wenzelm@64577
   154
  in Exn.release (Exn.capture f path) end
Andreas@58039
   155
Andreas@58039
   156
fun dynamic_value_strict ctxt t compiler =
Andreas@58039
   157
  let
Andreas@58039
   158
    val thy = Proof_Context.theory_of ctxt
wenzelm@64577
   159
    val (driver, target) =
wenzelm@64577
   160
      (case get_driver thy compiler of
wenzelm@64577
   161
        NONE => error ("No driver for target " ^ compiler)
wenzelm@64577
   162
      | SOME f => f)
Andreas@58039
   163
    val debug = Config.get (Proof_Context.init_global thy) overlord
Andreas@58039
   164
    val with_dir = if debug then with_overlord_dir else Isabelle_System.with_tmp_dir
Andreas@58039
   165
    fun evaluate f = with_dir "Code_Test" (driver ctxt f) |> parse_result compiler
Andreas@58039
   166
    fun evaluator program _ vs_ty deps =
wenzelm@64577
   167
      Exn.interruptible_capture evaluate
wenzelm@64577
   168
        (Code_Target.computation_text ctxt target program deps true vs_ty)
wenzelm@64578
   169
    fun postproc f = map (apsnd (Option.map (map f)))
wenzelm@64577
   170
  in Exn.release (Code_Thingol.dynamic_value ctxt (Exn.map_res o postproc) evaluator t) end
Andreas@58039
   171
wenzelm@64577
   172
wenzelm@64577
   173
(* term preprocessing *)
Andreas@58039
   174
Andreas@58039
   175
fun add_eval (Const (@{const_name Trueprop}, _) $ t) = add_eval t
Andreas@58039
   176
  | add_eval (Const (@{const_name "HOL.eq"}, _) $ lhs $ rhs) = (fn acc =>
wenzelm@64577
   177
      acc
wenzelm@64577
   178
      |> add_eval rhs
wenzelm@64577
   179
      |> add_eval lhs
wenzelm@64577
   180
      |> cons rhs
wenzelm@64577
   181
      |> cons lhs)
Andreas@58039
   182
  | add_eval (Const (@{const_name "Not"}, _) $ t) = add_eval t
Andreas@58039
   183
  | add_eval (Const (@{const_name "Orderings.ord_class.less_eq"}, _) $ lhs $ rhs) = (fn acc =>
wenzelm@64577
   184
      lhs :: rhs :: acc)
Andreas@58039
   185
  | add_eval (Const (@{const_name "Orderings.ord_class.less"}, _) $ lhs $ rhs) = (fn acc =>
wenzelm@64577
   186
      lhs :: rhs :: acc)
Andreas@58039
   187
  | add_eval _ = I
Andreas@58039
   188
Andreas@58039
   189
fun mk_term_of [] = @{term "None :: (unit \<Rightarrow> yxml_of_term) option"}
Andreas@58039
   190
  | mk_term_of ts =
wenzelm@64577
   191
      let
wenzelm@64577
   192
        val tuple = mk_tuples ts
wenzelm@64577
   193
        val T = fastype_of tuple
wenzelm@64577
   194
      in
wenzelm@64577
   195
        @{term "Some :: (unit \<Rightarrow> yxml_of_term) \<Rightarrow> (unit \<Rightarrow> yxml_of_term) option"} $
wenzelm@64577
   196
          (absdummy @{typ unit} (@{const yxml_string_of_term} $
wenzelm@64577
   197
            (Const (@{const_name Code_Evaluation.term_of}, T --> @{typ term}) $ tuple)))
wenzelm@64577
   198
      end
Andreas@58039
   199
Andreas@58039
   200
fun test_terms ctxt ts target =
Andreas@58039
   201
  let
Andreas@58039
   202
    val thy = Proof_Context.theory_of ctxt
Andreas@58039
   203
Andreas@58039
   204
    fun term_of t = Sign.of_sort thy (fastype_of t, @{sort term_of})
Andreas@58039
   205
wenzelm@64577
   206
    fun ensure_bool t =
wenzelm@64577
   207
      (case fastype_of t of
wenzelm@64577
   208
        @{typ bool} => ()
wenzelm@64579
   209
      | _ =>
wenzelm@64579
   210
        error (Pretty.string_of
wenzelm@64579
   211
          (Pretty.block [Pretty.str "Test case not of type bool:", Pretty.brk 1,
wenzelm@64579
   212
            Syntax.pretty_term ctxt t])))
Andreas@58039
   213
wenzelm@64578
   214
    val _ = List.app ensure_bool ts
Andreas@58039
   215
Andreas@58039
   216
    val evals = map (fn t => filter term_of (add_eval t [])) ts
Andreas@58039
   217
    val eval = map mk_term_of evals
Andreas@58039
   218
wenzelm@64578
   219
    val t =
wenzelm@64578
   220
      HOLogic.mk_list @{typ "bool \<times> (unit \<Rightarrow> yxml_of_term) option"}
wenzelm@64578
   221
        (map HOLogic.mk_prod (ts ~~ eval))
Andreas@58039
   222
wenzelm@64577
   223
    val result = dynamic_value_strict ctxt t target
Andreas@58039
   224
Andreas@58039
   225
    val failed =
Andreas@58039
   226
      filter_out (fst o fst o fst) (result ~~ ts ~~ evals)
wenzelm@64577
   227
      handle ListPair.UnequalLengths =>
Andreas@58039
   228
        error ("Evaluation failed!\nWrong number of test results: " ^ Int.toString (length result))
Andreas@58039
   229
  in
wenzelm@64578
   230
    (case failed of [] =>
wenzelm@64578
   231
      ()
wenzelm@64578
   232
    | _ => error (Pretty.string_of (pretty_failures ctxt target failed)))
Andreas@58039
   233
  end
Andreas@58039
   234
wenzelm@64578
   235
fun test_targets ctxt = List.app o test_terms ctxt
Andreas@58039
   236
wenzelm@64579
   237
fun pretty_free ctxt = Syntax.pretty_term ctxt o Free
wenzelm@64579
   238
wenzelm@64580
   239
fun test_code_cmd raw_ts targets ctxt =
Andreas@58039
   240
  let
wenzelm@64577
   241
    val ts = Syntax.read_terms ctxt raw_ts
wenzelm@64579
   242
    val frees = fold Term.add_frees ts []
wenzelm@64578
   243
    val _ =
wenzelm@64578
   244
      if null frees then ()
wenzelm@64579
   245
      else error (Pretty.string_of
wenzelm@64579
   246
        (Pretty.block (Pretty.str "Terms contain free variables:" :: Pretty.brk 1 ::
wenzelm@64579
   247
          Pretty.commas (map (pretty_free ctxt) frees))))
wenzelm@64578
   248
  in test_targets ctxt ts targets end
Andreas@58039
   249
Andreas@58348
   250
fun eval_term target ctxt t =
Andreas@58348
   251
  let
wenzelm@64579
   252
    val frees = Term.add_frees t []
wenzelm@64578
   253
    val _ =
wenzelm@64578
   254
      if null frees then ()
wenzelm@64579
   255
      else
wenzelm@64579
   256
        error (Pretty.string_of
wenzelm@64579
   257
          (Pretty.block (Pretty.str "Term contains free variables:" :: Pretty.brk 1 ::
wenzelm@64579
   258
            Pretty.commas (map (pretty_free ctxt) frees))))
Andreas@58039
   259
wenzelm@64579
   260
    val T = fastype_of t
wenzelm@64578
   261
    val _ =
wenzelm@64579
   262
      if Sign.of_sort (Proof_Context.theory_of ctxt) (T, @{sort term_of}) then ()
wenzelm@64579
   263
      else error ("Type " ^ Syntax.string_of_typ ctxt T ^
wenzelm@64579
   264
       " of term not of sort " ^ Syntax.string_of_sort ctxt @{sort term_of})
Andreas@58039
   265
wenzelm@64578
   266
    val t' =
wenzelm@64578
   267
      HOLogic.mk_list @{typ "bool \<times> (unit \<Rightarrow> yxml_of_term) option"}
wenzelm@64578
   268
        [HOLogic.mk_prod (@{term "False"}, mk_term_of [t])]
Andreas@58039
   269
wenzelm@64577
   270
    val result = dynamic_value_strict ctxt t' target
wenzelm@64577
   271
  in (case result of [(_, SOME [t])] => t | _ => error "Evaluation failed") end
Andreas@58039
   272
wenzelm@64577
   273
wenzelm@64577
   274
(* generic driver *)
Andreas@58039
   275
wenzelm@64581
   276
fun evaluate mk_driver env_var env_var_dest compilerN ctxt (code_files, value_name) =
Andreas@58039
   277
  let
Andreas@58039
   278
    val compiler = getenv env_var
wenzelm@64577
   279
    val _ =
wenzelm@64577
   280
      if compiler <> "" then ()
wenzelm@64577
   281
      else error (Pretty.string_of (Pretty.para
wenzelm@64578
   282
        ("Environment variable " ^ env_var ^ " is not set. To test code generation with " ^
wenzelm@64579
   283
          compilerN ^ ", set this variable to your " ^ env_var_dest ^
wenzelm@64579
   284
          " in the $ISABELLE_HOME_USER/etc/settings file.")))
Andreas@58039
   285
Andreas@58039
   286
    fun compile NONE = ()
Andreas@58039
   287
      | compile (SOME cmd) =
wenzelm@64577
   288
          let
wenzelm@64577
   289
            val (out, ret) = Isabelle_System.bash_output cmd
wenzelm@64577
   290
          in
wenzelm@64578
   291
            if ret = 0 then ()
wenzelm@64578
   292
            else error ("Compilation with " ^ compilerN ^ " failed:\n" ^ cmd ^ "\n" ^ out)
wenzelm@64577
   293
          end
Andreas@58039
   294
wenzelm@64577
   295
    fun run path =
Andreas@58039
   296
      let
Andreas@58039
   297
        val modules = map fst code_files
wenzelm@64577
   298
        val {files, compile_cmd, run_cmd, mk_code_file} = mk_driver ctxt path modules value_name
Andreas@58039
   299
wenzelm@64578
   300
        val _ = List.app (fn (name, code) => File.write (mk_code_file name) code) code_files
wenzelm@64578
   301
        val _ = List.app (fn (name, content) => File.write name content) files
Andreas@58039
   302
Andreas@58039
   303
        val _ = compile compile_cmd
Andreas@58039
   304
Andreas@58039
   305
        val (out, res) = Isabelle_System.bash_output run_cmd
wenzelm@64578
   306
        val _ =
wenzelm@64578
   307
          if res = 0 then ()
wenzelm@64578
   308
          else error ("Evaluation for " ^ compilerN ^ " terminated with error code " ^
wenzelm@64578
   309
            Int.toString res ^ "\nBash output:\n" ^ out)
wenzelm@64577
   310
      in out end
wenzelm@64577
   311
  in run end
Andreas@58039
   312
wenzelm@64577
   313
wenzelm@64577
   314
(* driver for PolyML *)
Andreas@58039
   315
wenzelm@58415
   316
val ISABELLE_POLYML = "ISABELLE_POLYML"
wenzelm@64577
   317
val polymlN = "PolyML"
Andreas@58039
   318
Andreas@58039
   319
fun mk_driver_polyml _ path _ value_name =
Andreas@58039
   320
  let
Andreas@58039
   321
    val generatedN = "generated.sml"
Andreas@58039
   322
    val driverN = "driver.sml"
Andreas@58039
   323
Andreas@58039
   324
    val code_path = Path.append path (Path.basic generatedN)
Andreas@58039
   325
    val driver_path = Path.append path (Path.basic driverN)
wenzelm@64577
   326
    val driver =
Andreas@58039
   327
      "fun main prog_name = \n" ^
Andreas@58039
   328
      "  let\n" ^
wenzelm@64577
   329
      "    fun format_term NONE = \"\"\n" ^
Andreas@58039
   330
      "      | format_term (SOME t) = t ();\n" ^
Andreas@58039
   331
      "    fun format (true, _) = \"" ^ successN ^ "\\n\"\n" ^
Andreas@58039
   332
      "      | format (false, to) = \"" ^ failureN ^ "\" ^ format_term to ^ \"\\n\";\n" ^
Andreas@58039
   333
      "    val result = " ^ value_name ^ " ();\n" ^
Andreas@58039
   334
      "    val _ = print \"" ^ start_markerN ^ "\";\n" ^
Andreas@58039
   335
      "    val _ = map (print o format) result;\n" ^
Andreas@58039
   336
      "    val _ = print \"" ^ end_markerN ^ "\";\n" ^
Andreas@58039
   337
      "  in\n" ^
Andreas@58039
   338
      "    ()\n" ^
Andreas@58039
   339
      "  end;\n"
Andreas@58039
   340
    val cmd =
wenzelm@64577
   341
      "echo \"use \\\"" ^ Path.implode code_path ^ "\\\"; use \\\"" ^
wenzelm@64577
   342
      Path.implode driver_path ^ "\\\"; main ();\" | " ^
wenzelm@58415
   343
      Path.implode (Path.variable ISABELLE_POLYML)
Andreas@58039
   344
  in
Andreas@58039
   345
    {files = [(driver_path, driver)], compile_cmd = NONE, run_cmd = cmd, mk_code_file = K code_path}
Andreas@58039
   346
  end
Andreas@58039
   347
wenzelm@58832
   348
fun evaluate_in_polyml ctxt =
wenzelm@64581
   349
  evaluate mk_driver_polyml ISABELLE_POLYML "PolyML executable" polymlN ctxt
Andreas@58039
   350
wenzelm@64577
   351
wenzelm@64577
   352
(* driver for mlton *)
Andreas@58039
   353
Andreas@58039
   354
val mltonN = "MLton"
Andreas@58039
   355
val ISABELLE_MLTON = "ISABELLE_MLTON"
Andreas@58039
   356
Andreas@58039
   357
fun mk_driver_mlton _ path _ value_name =
Andreas@58039
   358
  let
Andreas@58039
   359
    val generatedN = "generated.sml"
Andreas@58039
   360
    val driverN = "driver.sml"
Andreas@58039
   361
    val projectN = "test"
Andreas@58039
   362
    val ml_basisN = projectN ^ ".mlb"
Andreas@58039
   363
Andreas@58039
   364
    val code_path = Path.append path (Path.basic generatedN)
Andreas@58039
   365
    val driver_path = Path.append path (Path.basic driverN)
Andreas@58039
   366
    val ml_basis_path = Path.append path (Path.basic ml_basisN)
wenzelm@64577
   367
    val driver =
wenzelm@64577
   368
      "fun format_term NONE = \"\"\n" ^
Andreas@58039
   369
      "  | format_term (SOME t) = t ();\n" ^
Andreas@58039
   370
      "fun format (true, _) = \"" ^ successN ^ "\\n\"\n" ^
Andreas@58039
   371
      "  | format (false, to) = \"" ^ failureN ^ "\" ^ format_term to ^ \"\\n\";\n" ^
Andreas@58039
   372
      "val result = " ^ value_name ^ " ();\n" ^
Andreas@58039
   373
      "val _ = print \"" ^ start_markerN ^ "\";\n" ^
Andreas@58039
   374
      "val _ = map (print o format) result;\n" ^
Andreas@58039
   375
      "val _ = print \"" ^ end_markerN ^ "\";\n"
Andreas@58039
   376
    val ml_basis =
Andreas@58039
   377
      "$(SML_LIB)/basis/basis.mlb\n" ^
Andreas@58039
   378
      generatedN ^ "\n" ^
Andreas@58039
   379
      driverN
Andreas@58039
   380
Andreas@58039
   381
    val compile_cmd =
wenzelm@62549
   382
      File.bash_path (Path.variable ISABELLE_MLTON) ^
wenzelm@62549
   383
      " -default-type intinf " ^ File.bash_path ml_basis_path
wenzelm@62549
   384
    val run_cmd = File.bash_path (Path.append path (Path.basic projectN))
Andreas@58039
   385
  in
Andreas@58039
   386
    {files = [(driver_path, driver), (ml_basis_path, ml_basis)],
Andreas@58039
   387
     compile_cmd = SOME compile_cmd, run_cmd = run_cmd, mk_code_file = K code_path}
Andreas@58039
   388
  end
Andreas@58039
   389
wenzelm@58832
   390
fun evaluate_in_mlton ctxt =
wenzelm@64581
   391
  evaluate mk_driver_mlton ISABELLE_MLTON "MLton executable" mltonN ctxt
Andreas@58039
   392
wenzelm@64577
   393
wenzelm@64577
   394
(* driver for SML/NJ *)
Andreas@58039
   395
Andreas@58039
   396
val smlnjN = "SMLNJ"
Andreas@58039
   397
val ISABELLE_SMLNJ = "ISABELLE_SMLNJ"
Andreas@58039
   398
Andreas@58039
   399
fun mk_driver_smlnj _ path _ value_name =
Andreas@58039
   400
  let
Andreas@58039
   401
    val generatedN = "generated.sml"
Andreas@58039
   402
    val driverN = "driver.sml"
Andreas@58039
   403
Andreas@58039
   404
    val code_path = Path.append path (Path.basic generatedN)
Andreas@58039
   405
    val driver_path = Path.append path (Path.basic driverN)
wenzelm@64577
   406
    val driver =
Andreas@58039
   407
      "structure Test = struct\n" ^
Andreas@58039
   408
      "fun main prog_name =\n" ^
Andreas@58039
   409
      "  let\n" ^
wenzelm@64577
   410
      "    fun format_term NONE = \"\"\n" ^
Andreas@58039
   411
      "      | format_term (SOME t) = t ();\n" ^
Andreas@58039
   412
      "    fun format (true, _) = \"" ^ successN ^ "\\n\"\n" ^
Andreas@58039
   413
      "      | format (false, to) = \"" ^ failureN ^ "\" ^ format_term to ^ \"\\n\";\n" ^
Andreas@58039
   414
      "    val result = " ^ value_name ^ " ();\n" ^
Andreas@58039
   415
      "    val _ = print \"" ^ start_markerN ^ "\";\n" ^
Andreas@58039
   416
      "    val _ = map (print o format) result;\n" ^
Andreas@58039
   417
      "    val _ = print \"" ^ end_markerN ^ "\";\n" ^
Andreas@58039
   418
      "  in\n" ^
Andreas@58039
   419
      "    0\n" ^
Andreas@58039
   420
      "  end;\n" ^
Andreas@58039
   421
      "end;"
Andreas@58039
   422
    val cmd =
Andreas@58039
   423
      "echo \"Control.MC.matchRedundantError := false; Control.MC.matchRedundantWarn := false;" ^
Andreas@58039
   424
      "use \\\"" ^ Path.implode code_path ^ "\\\"; use \\\"" ^ Path.implode driver_path ^ "\\\";" ^
Andreas@58039
   425
      "Test.main ();\" | " ^ Path.implode (Path.variable ISABELLE_SMLNJ)
Andreas@58039
   426
  in
Andreas@58039
   427
    {files = [(driver_path, driver)], compile_cmd = NONE, run_cmd = cmd, mk_code_file = K code_path}
Andreas@58039
   428
  end
Andreas@58039
   429
wenzelm@58832
   430
fun evaluate_in_smlnj ctxt =
wenzelm@64581
   431
  evaluate mk_driver_smlnj ISABELLE_SMLNJ "SMLNJ executable" smlnjN ctxt
Andreas@58039
   432
wenzelm@64577
   433
wenzelm@64577
   434
(* driver for OCaml *)
Andreas@58039
   435
Andreas@58039
   436
val ocamlN = "OCaml"
Andreas@58039
   437
val ISABELLE_OCAMLC = "ISABELLE_OCAMLC"
Andreas@58039
   438
Andreas@58039
   439
fun mk_driver_ocaml _ path _ value_name =
Andreas@58039
   440
  let
Andreas@58039
   441
    val generatedN = "generated.ml"
Andreas@58039
   442
    val driverN = "driver.ml"
Andreas@58039
   443
Andreas@58039
   444
    val code_path = Path.append path (Path.basic generatedN)
Andreas@58039
   445
    val driver_path = Path.append path (Path.basic driverN)
wenzelm@64577
   446
    val driver =
Andreas@58039
   447
      "let format_term = function\n" ^
wenzelm@64577
   448
      "  | None -> \"\"\n" ^
Andreas@58039
   449
      "  | Some t -> t ();;\n" ^
Andreas@58039
   450
      "let format = function\n" ^
Andreas@58039
   451
      "  | (true, _) -> \"" ^ successN ^ "\\n\"\n" ^
Andreas@58039
   452
      "  | (false, x) -> \"" ^ failureN ^ "\" ^ format_term x ^ \"\\n\";;\n" ^
Andreas@58039
   453
      "let result = " ^ ("Generated." ^ value_name) ^ " ();;\n" ^
Andreas@58039
   454
      "let main x =\n" ^
Andreas@58039
   455
      "  let _ = print_string \"" ^ start_markerN ^ "\" in\n" ^
Andreas@58039
   456
      "  let _ = List.map (fun x -> print_string (format x)) result in\n" ^
Andreas@58039
   457
      "  print_string \"" ^ end_markerN ^ "\";;\n" ^
Andreas@58039
   458
      "main ();;"
Andreas@58039
   459
Andreas@58039
   460
    val compiled_path = Path.append path (Path.basic "test")
Andreas@58039
   461
    val compile_cmd =
Andreas@58039
   462
      Path.implode (Path.variable ISABELLE_OCAMLC) ^ " -w pu -o " ^ Path.implode compiled_path ^
Andreas@58039
   463
      " -I " ^ Path.implode path ^
Andreas@58039
   464
      " nums.cma " ^ Path.implode code_path ^ " " ^ Path.implode driver_path
Andreas@58039
   465
wenzelm@62549
   466
    val run_cmd = File.bash_path compiled_path
Andreas@58039
   467
  in
Andreas@58039
   468
    {files = [(driver_path, driver)],
Andreas@58039
   469
     compile_cmd = SOME compile_cmd, run_cmd = run_cmd, mk_code_file = K code_path}
Andreas@58039
   470
  end
Andreas@58039
   471
wenzelm@58832
   472
fun evaluate_in_ocaml ctxt =
wenzelm@64581
   473
  evaluate mk_driver_ocaml ISABELLE_OCAMLC "ocamlc executable" ocamlN ctxt
Andreas@58039
   474
wenzelm@64577
   475
wenzelm@64577
   476
(* driver for GHC *)
Andreas@58039
   477
Andreas@58039
   478
val ghcN = "GHC"
Andreas@58039
   479
val ISABELLE_GHC = "ISABELLE_GHC"
Andreas@58039
   480
Andreas@58039
   481
val ghc_options = Attrib.setup_config_string @{binding code_test_ghc} (K "")
Andreas@58039
   482
Andreas@58039
   483
fun mk_driver_ghc ctxt path modules value_name =
Andreas@58039
   484
  let
Andreas@58039
   485
    val driverN = "Main.hs"
Andreas@58039
   486
Andreas@58039
   487
    fun mk_code_file name = Path.append path (Path.basic (name ^ ".hs"))
Andreas@58039
   488
    val driver_path = Path.append path (Path.basic driverN)
wenzelm@64577
   489
    val driver =
Andreas@58039
   490
      "module Main where {\n" ^
Andreas@58039
   491
      String.concat (map (fn module => "import qualified " ^ module ^ ";\n") modules) ^
Andreas@58039
   492
      "main = do {\n" ^
Andreas@58039
   493
      "    let {\n" ^
wenzelm@64577
   494
      "      format_term Nothing = \"\";\n" ^
Andreas@58039
   495
      "      format_term (Just t) = t ();\n" ^
Andreas@58039
   496
      "      format (True, _) = \"" ^ successN ^ "\\n\";\n" ^
Andreas@58039
   497
      "      format (False, to) = \"" ^ failureN ^ "\" ++ format_term to ++ \"\\n\";\n" ^
Andreas@58039
   498
      "      result = " ^ value_name ^ " ();\n" ^
Andreas@58039
   499
      "    };\n" ^
Andreas@58039
   500
      "    Prelude.putStr \"" ^ start_markerN ^ "\";\n" ^
Andreas@58039
   501
      "    Prelude.mapM_ (putStr . format) result;\n" ^
Andreas@58039
   502
      "    Prelude.putStr \"" ^ end_markerN ^ "\";\n" ^
Andreas@58039
   503
      "  }\n" ^
Andreas@58039
   504
      "}\n"
Andreas@58039
   505
Andreas@58039
   506
    val compiled_path = Path.append path (Path.basic "test")
Andreas@58039
   507
    val compile_cmd =
Andreas@58039
   508
      Path.implode (Path.variable ISABELLE_GHC) ^ " " ^ Code_Haskell.language_params ^ " " ^
Andreas@58039
   509
      Config.get ctxt ghc_options ^ " -o " ^ Path.implode compiled_path ^ " " ^
Andreas@58039
   510
      Path.implode driver_path ^ " -i" ^ Path.implode path
Andreas@58039
   511
wenzelm@62549
   512
    val run_cmd = File.bash_path compiled_path
Andreas@58039
   513
  in
Andreas@58039
   514
    {files = [(driver_path, driver)],
Andreas@58039
   515
     compile_cmd = SOME compile_cmd, run_cmd = run_cmd, mk_code_file = mk_code_file}
Andreas@58039
   516
  end
Andreas@58039
   517
wenzelm@58832
   518
fun evaluate_in_ghc ctxt =
wenzelm@64581
   519
  evaluate mk_driver_ghc ISABELLE_GHC "GHC executable" ghcN ctxt
Andreas@58039
   520
wenzelm@64577
   521
wenzelm@64577
   522
(* driver for Scala *)
Andreas@58039
   523
Andreas@58039
   524
val scalaN = "Scala"
Andreas@58039
   525
val ISABELLE_SCALA = "ISABELLE_SCALA"
Andreas@58039
   526
Andreas@58039
   527
fun mk_driver_scala _ path _ value_name =
Andreas@58039
   528
  let
Andreas@58039
   529
    val generatedN = "Generated_Code"
Andreas@58039
   530
    val driverN = "Driver.scala"
Andreas@58039
   531
Andreas@58039
   532
    val code_path = Path.append path (Path.basic (generatedN ^ ".scala"))
Andreas@58039
   533
    val driver_path = Path.append path (Path.basic driverN)
wenzelm@64577
   534
    val driver =
Andreas@58039
   535
      "import " ^ generatedN ^ "._\n" ^
Andreas@58039
   536
      "object Test {\n" ^
Andreas@58039
   537
      "  def format_term(x : Option[Unit => String]) : String = x match {\n" ^
Andreas@58039
   538
      "    case None => \"\"\n" ^
Andreas@58039
   539
      "    case Some(x) => x(())\n" ^
Andreas@58039
   540
      "  }\n" ^
Andreas@58039
   541
      "  def format(term : (Boolean, Option[Unit => String])) : String = term match {\n" ^
Andreas@58039
   542
      "      case (true, _) => \"True\\n\"\n" ^
Andreas@58039
   543
      "      case (false, x) => \"False\" + format_term(x) + \"\\n\"\n" ^
Andreas@58039
   544
      "  }\n" ^
Andreas@58039
   545
      "  def main(args:Array[String]) = {\n" ^
Andreas@58039
   546
      "    val result = " ^ value_name ^ "(());\n" ^
Andreas@58039
   547
      "    print(\"" ^ start_markerN ^ "\");\n" ^
Andreas@58039
   548
      "    result.map{test:(Boolean, Option[Unit => String]) => print(format(test))};\n" ^
Andreas@58039
   549
      "    print(\"" ^ end_markerN ^ "\");\n" ^
Andreas@58039
   550
      "  }\n" ^
Andreas@58039
   551
      "}\n"
Andreas@58039
   552
Andreas@58039
   553
    val compile_cmd =
Andreas@58039
   554
      Path.implode (Path.append (Path.variable ISABELLE_SCALA) (Path.basic "scalac")) ^
wenzelm@62549
   555
      " -d " ^ File.bash_path path ^ " -classpath " ^ File.bash_path path ^ " " ^
wenzelm@62549
   556
      File.bash_path code_path ^ " " ^ File.bash_path driver_path
Andreas@58039
   557
Andreas@58039
   558
    val run_cmd =
Andreas@58039
   559
      Path.implode (Path.append (Path.variable ISABELLE_SCALA) (Path.basic "scala")) ^
wenzelm@62549
   560
      " -cp " ^ File.bash_path path ^ " Test"
Andreas@58039
   561
  in
Andreas@58039
   562
    {files = [(driver_path, driver)],
Andreas@58039
   563
     compile_cmd = SOME compile_cmd, run_cmd = run_cmd, mk_code_file = K code_path}
Andreas@58039
   564
  end
Andreas@58039
   565
wenzelm@58832
   566
fun evaluate_in_scala ctxt =
wenzelm@64581
   567
  evaluate mk_driver_scala ISABELLE_SCALA "Scala directory" scalaN ctxt
Andreas@58039
   568
wenzelm@64580
   569
wenzelm@64580
   570
(* command setup *)
Andreas@58039
   571
wenzelm@64577
   572
val _ =
wenzelm@59936
   573
  Outer_Syntax.command @{command_keyword test_code}
Andreas@58039
   574
    "compile test cases to target languages, execute them and report results"
wenzelm@64580
   575
      (Scan.repeat1 Parse.prop -- (@{keyword "in"} |-- Scan.repeat1 Parse.name)
wenzelm@64580
   576
        >> (fn (ts, targets) => Toplevel.keep (test_code_cmd ts targets o Toplevel.context_of)))
Andreas@58039
   577
wenzelm@64580
   578
val _ =
wenzelm@64580
   579
  Theory.setup (fold add_driver
wenzelm@64580
   580
    [(polymlN, (evaluate_in_polyml, Code_ML.target_SML)),
wenzelm@64580
   581
     (mltonN, (evaluate_in_mlton, Code_ML.target_SML)),
wenzelm@64580
   582
     (smlnjN, (evaluate_in_smlnj, Code_ML.target_SML)),
wenzelm@64580
   583
     (ocamlN, (evaluate_in_ocaml, Code_ML.target_OCaml)),
wenzelm@64580
   584
     (ghcN, (evaluate_in_ghc, Code_Haskell.target)),
wenzelm@64580
   585
     (scalaN, (evaluate_in_scala, Code_Scala.target))]
wenzelm@63806
   586
  #> fold (fn target => Value_Command.add_evaluator (target, eval_term target))
wenzelm@64580
   587
      [polymlN, mltonN, smlnjN, ocamlN, ghcN, scalaN])
haftmann@59323
   588
Andreas@58039
   589
end