Source

ocaml-shell-dsl / shell_dsl.ml

Full commit
  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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
open Printf;

value ( |> ) x f = f x;
value ( & ) f x = f x;
value ( @> ) f g = fun x -> g (f x);
value ( %< ) f g = fun x -> f (g x);

(*

creating and destructing lists:

$ printf 'SEP="\1"; I="$IFS"; fu_unp () (IFS="$I"; echo "/$1/$2/$3/$4/$5/" ); fu () ( IFS="$SEP"; fu_unp $@ ); cons () { echo "$1$SEP$2"; }; a="  a a  "; b="  b b  "; ab="$(cons "$a" "$b")"; eab="$(cons "echo" "$ab")"; cutlast() { echo "${1%%$SEP*}"; }; head() { echo "${1%%%%$SEP*}"; }; ea="$(cutlast "$eab")"; e="$(head "$eab")"; fu "$e"' | sh -

*)


module Eq
 =
  struct
    type eq 'a 'b = [ Refl of ref (option 'a) and ref (option 'b) ];

    value refl () =
      let r = ref None in
      Refl r r
    ;

    value symm = fun [ Refl a b -> Refl b a ]
    ;

    value apply_eq eq a =
      match eq with
      [ Refl ra rb ->
          let () = ra.val := Some a in
          match rb.val with
          [ None -> assert False
          | Some b ->
              let () = ra.val := None in
              b
          ]
      ]
    ;

    value apply_eq_symm eq b =
      apply_eq (symm eq) b
    ;

  end
;
open Eq
;

module Eqsub
 =
  struct
    type eqsub -'a +'b =
      [ Reflsub of (option 'a -> unit) and (unit -> option 'b) ]
    ;

    value reflsub () =
      let r = ref None in
      Reflsub (fun a -> r.val := a) (fun () -> r.val)
    ;

    value apply_eqsub eq a =
      match eq with
      [ Reflsub put_a get_b_opt ->
          let () = put_a (Some a) in
          let b_opt = get_b_opt () in
          let () = put_a None in
          match b_opt with
          [ None -> assert False
          | Some b -> b
          ]
      ]
    ;

  end
;


type var_name = string;

type sh =
  [ Sh_nop
  | Sh_if of sh_val (* true = sh_val_true = sh_val_ok *)
         and sh
         and sh
  | Sh_cmd of sh_val
  | Sh_seq of sh and sh
  | Sh_var_decl of var_name
  | Sh_var_set of var_name and sh_val
  | Sh_str_func of var_name (* dest *) and list sh_val (* list of argv *)
  ]

and sh_val =
  [ Sh_val_lit of string
  | Sh_val_var of var_name
  | Sh_val_cat of list sh_val
  ]
;


type res = [= `Ok | `Error ];

type t 'a =
  [ Nop of eq res 'a
  | Print of tlist string and eq res 'a
  | With of twith and t 'a and eq res 'a
  | If of t bool
      and t 'a  (* then *)
      and t 'a  (* else *)
  | Let of tlet
       and t 'a
  | Seq of t res and t res and eq res 'a

  | S of string and eq string 'a
  | V of var 'a
  | Getenv of string and string (* default *) and eq string 'a

  | Is_file of t string and eq bool 'a
  | Is_exec of t string and eq bool 'a
  | Is_dir of t string and eq bool 'a

  | Str_eq of t string and t string and eq bool 'a

  | Cmd of tlist string and eq res 'a

  | Res of res and eq res 'a

  | List_strings of 'a and eq (list (t string)) 'a
  | List_append of t 'a and t 'a and eq (list (t string)) 'a

  (* internal: *)
  | Vn of var_name
  ]

and tlet =
  { gen_let_sh : Lazy.t sh
    (* it's not necessary to generate shell code in
       OCaml interpetation, so -- lazy. *)
  }

and var 'a =
  { vname : var_name  (* name for sh, generated *)
  ; vval : t 'a
  }

and twith =
  [ WEnv of env_mod
        and string  (* name *)
        and t string  (* what to set/prepend *)
  | WChdir of t string
  ]

and env_mod =
  [ Env_set
  | Env_prepend
  ]

and env_var_name = string

and tlist 'a = t (list (t 'a))
;



value new_name =
  let n = ref 0 in
  fun () ->
    let r = n.val in
    ( incr n
    ; sprintf "osd%i" r
    )
;



exception Undef;


value nop = Nop (refl ());

value res r = Res r (refl ());

value if_ cond th el = If cond th el;

value print lst = Print lst (refl ());

value with_env_gen env_mod name tval tcont =
  With (WEnv env_mod name tval) tcont (refl ());
value with_env_prepend x = with_env_gen Env_prepend x;
value with_env_set x = with_env_gen Env_set x;

value cmd argv = Cmd argv (refl ());

value seq c1 c2 = Seq c1 c2 (refl ());
value _ = fun () -> seq nop nop;

value getenv ?(default="") name = Getenv name default (refl ());

value is_exec n = Is_exec n (refl ());
value is_file n = Is_file n (refl ());
value is_dir n = Is_dir n (refl ());

value v var = V var;
value s str = S str (refl ());

value make_var vval =
  { vname = new_name ()
  ; vval = vval
  }
;

value of_list
 : list (t string) -> tlist string
 = fun lst ->
     List_strings lst (refl ())
;

value append
 : t (list 'a) -> t (list 'a) -> t (list 'a)
 = fun la lb ->
     List_append la lb (refl ())
;


value _ = fun () ->
  let l1 = of_list [s"a"; s"b"]
  and l2 = of_list [s"c"; s"d"]
  in
  ignore ((append l1 l2) : tlist string)
;


(*************************************)



value let_sh_ref
 : ref < let_sh : !'a . var_name -> t 'a -> sh >
 = ref (object method let_sh : !'a . var_name -> t 'a -> sh
          = fun _ _ -> assert False; end)
;

value let_sh t = let_sh_ref.val#let_sh t
;


value let_
 : t 'a -> (var 'a -> t 'b) -> t 'b
 = fun vval cont ->
     let var = make_var vval in
     Let { gen_let_sh = lazy (let_sh var.vname vval) } (cont var)
;

value with_chdir tdir tcont =
   With (WChdir tdir) tcont (refl ())
;



(*********** compiling to sh ***********)


value rec list_join ~sep lst =
  match lst with
  [ [] -> []
  | [h :: t] ->
      [h :: inner t]
      where rec inner lst =
        match lst with
        [ [] -> []
        | [h :: t] -> [sep :: [h :: inner t]]
        ]
  ]
;


value sh_val_lit s = Sh_val_lit s
and sh_val_var v = Sh_val_var v
;

value sh_val_true = sh_val_lit "0"
and sh_val_false = sh_val_lit "1"
;

value sh_val_ok = sh_val_true
and sh_val_error = sh_val_false
;

value cmd_chdir tdir =
  cmd & of_list [s"cd"; tdir]
;


value rec sh
 : ! 'a . t 'a -> (sh * sh_val)
 = fun t ->
     match t with
     [ Nop _eq -> (Sh_nop, sh_val_ok)

     | Cmd tlst _eq ->
         sh_cmd tlst

     | Print tlst _eq ->
         sh_cmd (append (of_list [s"echo"]) tlst)

     | With twith cont _eq ->
         sh_with twith cont

     | If cond th el ->
         let (cond_sh, cond_res) = sh cond
         and (th_sh, th_res) = sh th
         and (el_sh, el_res) = sh el
         and tmp = new_name () in
         ( sh_seq_list
             [ cond_sh
             ; Sh_var_decl tmp
             ; Sh_if
                 cond_res
                 (Sh_seq th_sh (Sh_var_set tmp th_res))
                 (Sh_seq el_sh (Sh_var_set tmp el_res))
             ]
         , sh_val_var tmp
         )

     | Let binding cont ->
         let (cont_sh, cont_res) = sh cont in
         ( Sh_seq (Lazy.force binding.gen_let_sh) cont_sh
         , cont_res
         )

     | Seq s1 s2 _eq ->
         let (s1_sh, s1_res) = sh s1
         and (s2_sh, s2_res) = sh s2 in
         let tmp = new_name () in
         ( sh_seq_list
             [ Sh_var_decl tmp
             ; s1_sh
             ; Sh_if
                 s1_res
                 (Sh_seq s2_sh (Sh_var_set tmp s2_res))
                 (Sh_var_set tmp s1_res)
             ]
         , sh_val_var tmp
         )

     | S str _eq ->
         (Sh_nop, sh_val_lit str)

     | Getenv name default _eq ->
         sh_getenv name default

     | Is_file tname _eq ->
         sh_cmd_test_unary "-f" tname

     | Is_exec tname _eq ->
         sh_cmd_test_unary "-x" tname

     | Is_dir tname _eq ->
         sh_cmd_test_unary "-d" tname

     | List_strings strs eq ->
         let (lst_str_sh, lst_str_res) =
           apply_eq_symm eq strs |> List.map sh |> List.split
         in
         let (r_sh, r_res) = sh_list_strings_vals lst_str_res in
         ( sh_seq_list
             ( lst_str_sh
             @ [r_sh]
             )
         , r_res
         )

     | List_append tlst1 tlst2 _eq ->
         let (l1_sh, l1_res) = sh tlst1
         and (l2_sh, l2_res) = sh tlst2 in
         let (app_sh, app_res) = sh_append_vals l1_res l2_res in
         ( sh_seq_list
             [ l1_sh
             ; l2_sh
             ; app_sh
             ]
         , app_res
         )

     | Str_eq tstr1 tstr2 _eq ->
         sh_cmd_test_binary tstr1 "=" tstr2

     | V v ->
         sh (Vn v.vname)

     | Vn n ->
         (Sh_nop, sh_val_var n)

     | Res res _eq ->
         ( Sh_nop
         , match res with
           [ `Ok -> sh_val_ok
           | `Error -> sh_val_error
           ]
         )

     ]

and sh_list_strings_vals
 : list sh_val -> (sh * sh_val)
 = fun lst_str_res ->
     let tmp = new_name () in
     ( sh_seq_list
         [ Sh_var_decl tmp
         ; Sh_var_set
             tmp
             (Sh_val_cat
                ( list_join
                    ~sep:(sh_val_var "OSD_LIST_SEP")
                    lst_str_res
                )
             )
         ]
     , sh_val_var tmp
     )

and sh_append_vals
 : sh_val -> sh_val -> (sh * sh_val)
 = fun v1 v2 ->
     let tmp = new_name () in
     ( sh_seq_list
         [ Sh_var_decl tmp
         ; Sh_str_func tmp
             [ sh_val_lit "osd_list_append"
             ; v1
             ; v2
             ]
         ]
     , sh_val_var tmp
     )

and sh_getenv name default : (sh * sh_val) =
  (* todo: 'name' should obey the shell laws *)
  let tmp = new_name () in
  ( sh_seq_list
      [ Sh_var_decl tmp
      ; Sh_var_set tmp (sh_val_lit default)
      ]
  , sh_val_var (sprintf "%s-${%s}" name tmp)
  )

and sh_with_init_deinit twith : (sh * sh_val * sh * sh_val) =
  match twith with
  [ WEnv env_mod name tval ->
      let prev_var = new_name () in
      let (prev_sh, prev_res) =
        sh_getenv name ""
        (* "" to be consistent with OCaml DSL interpretation, where unset
           variable is treated like variable containing empty string. *)
      in
      (
        (* init *)
        let func_name =
          match env_mod with
          [ Env_set -> "osd_env_var_set"
          | Env_prepend -> "osd_env_var_prepend"
          ]
        in
        let (val_sh, val_res) = sh tval in
        sh_seq_list
          [ prev_sh
          ; Sh_var_set prev_var prev_res
          ; val_sh
          ; Sh_str_func name [sh_val_lit func_name; val_res; prev_res]
          ]
      ,
        (* init res *)
        sh_val_ok
      ,
        (* deinit sh *)
        Sh_var_set name (sh_val_var prev_var)
      ,
        (* deinit res *)
        sh_val_ok
      )

  | WChdir tdir ->
      let dir_prev_var_name = new_name () in
      let dir_new_var_name = new_name () in
      let (dir_sh, dir_res) = sh tdir in
      let dir_var_sh =
        sh_seq_list
          [ Sh_var_decl dir_prev_var_name
          ; Sh_var_set dir_prev_var_name (sh_val_var "PWD")

          ; Sh_var_decl dir_new_var_name
          ; dir_sh
          ; Sh_var_set dir_new_var_name dir_res
          ]
      in
      let tdir = Vn dir_new_var_name in
      let (init_sh, init_res) = sh &
        if_ (is_dir tdir)
            (cmd_chdir tdir)
            (res `Error)
      in
      let init_sh = sh_seq_list [dir_var_sh; init_sh] in
      let (deinit_sh, deinit_res) =
        sh & cmd_chdir & Vn dir_prev_var_name in
      (
        init_sh, init_res
      ,
        deinit_sh, deinit_res
      )

  ]

and sh_chdir
 : t string -> (sh * sh_val)
 = fun tdir ->
     sh_cmd (of_list [s"cd"; tdir])

and sh_with
 : ! 'a . twith -> t 'a -> (sh * sh_val)
 = fun twith cont ->
  let (winit_sh, winit_res, wdeinit_sh, wdeinit_res) =
    sh_with_init_deinit twith
  and (cont_sh, cont_res) = sh cont
  and tmp = new_name () in

  ( sh_seq_list
      [ Sh_var_decl tmp
      ; Sh_var_set tmp sh_val_error
      ; winit_sh
      ; Sh_if
          winit_res
          (sh_seq_list
             [ cont_sh
             ; wdeinit_sh
             ; Sh_if
                 wdeinit_res
                 (Sh_var_set tmp cont_res)
                 Sh_nop
             ]
          )
          Sh_nop
      ;
      ]
  ,
    sh_val_var tmp
  )

and sh_set_var vname val =
  Sh_var_set vname val

and sh_seq_list
 : list sh -> sh
 = fun lst ->
     List.fold_left (fun acc s -> Sh_seq acc s) Sh_nop lst

and sh_cmd_vals
 : sh_val -> (sh * sh_val)
 = fun argv ->
     let tmp = new_name () in
     ( sh_seq_list
         [ Sh_var_decl tmp
         ; Sh_cmd argv
         ; Sh_var_set tmp (sh_val_var "?")
         ]
     , sh_val_var tmp
     )

and sh_cmd
 : tlist string -> (sh * sh_val)
 = fun tlst ->
     let (lst_sh, lst_res) = sh tlst in
     let (cmd_sh, cmd_res) = sh_cmd_vals lst_res in
     ( sh_seq_list
         [ lst_sh
         ; cmd_sh
         ]
     , cmd_res
     )

and sh_cmd_test
 : tlist string -> (sh * sh_val)
 = fun test_args ->
     let test_cmd =
       append
         (of_list [s "test"])
         test_args
     in
       sh_cmd test_cmd

and sh_cmd_test_unary opt tstr =
  sh_cmd_test (append (of_list [s opt]) (of_list [tstr]))

and sh_cmd_test_binary tstr1 opt tstr2 =
  sh_cmd_test
    (append
       (of_list [tstr1])
       (append
          (of_list [s opt])
          (of_list [tstr2])
       )
    )

and sh_let_body var_name tbody =
  let (body_sh, body_res) = sh tbody in
  sh_seq_list
    [ Sh_var_decl var_name
    ; body_sh
    ; Sh_var_set var_name body_res
    ]
;


value () =
  let_sh_ref.val :=
    object
      method let_sh
       : !'a . var_name -> t 'a -> sh
       = sh_let_body
      ;
    end
;


type sh_command =
  [ Sc_line of string
  | Sc_seq of list sh_command
  | Sc_if of string and sh_command and sh_command
  ]
;


value linef fmt = ksprintf (fun x -> Sc_line x) fmt
;


value rec commands_of_sh
 : sh -> sh_command
 = fun sh ->
     match sh with
     [ Sh_nop -> Sc_line ":"
     | Sh_if cond th el ->
         Sc_if
           (sprintf "osd_ret_code %s" (string_of_sh_val cond))
           (commands_of_sh th)
           (commands_of_sh el)

     | Sh_cmd argv -> linef "osd_cmd %s" (string_of_sh_val argv)
     | Sh_seq s1 s2 ->
         match (commands_of_sh s1, commands_of_sh s2) with
         [ (Sc_seq l1, Sc_seq l2) -> Sc_seq (l1 @ l2)
         | (Sc_seq l1, (Sc_line _ | Sc_if _ _ _ as i2)) -> Sc_seq (l1 @ [i2])
         | ((Sc_line _ | Sc_if _ _ _ as i1), Sc_seq l2) -> Sc_seq ([i1] @ l2)
         | ( (Sc_line _ | Sc_if _ _ _ as i1)
           , (Sc_line _ | Sc_if _ _ _ as i2)
           ) ->
              Sc_seq [i1; i2]
         ]

     | Sh_var_decl vn -> linef "%s=\"\"" vn
     | Sh_var_set vn vl -> linef "%s=%s" vn (string_of_sh_val vl)
     | Sh_str_func vn argv ->
         linef "%s=\"$(%s)\"" vn
           (String.concat " " & List.map string_of_sh_val argv)
     ]

and string_of_sh_val v =
  sprintf "\"%s\"" (string_of_sh_val_unq v)

and string_of_sh_val_unq v =
  match v with
  [ Sh_val_lit s -> sh_escape_lit s
  | Sh_val_var vn -> sprintf "${%s}" vn
  | Sh_val_cat lst -> String.concat "" & List.map string_of_sh_val_unq lst
  ]

and sh_escape_lit s =
  let len = String.length s in
  let b = Buffer.create len in
  let add c = Buffer.add_char b c in
  let imax = len - 1 in
  let () =
    for i = 0 to imax do
      let c = s.[i] in
      ( match c with
        [ '$' | '`' | '\"' | '\\' | '\n' -> add '\\'
        | _ -> ()
        ]
      ; add c
      )
      done
  in
    Buffer.contents b
;


value rec string_of_sh_commands_d ~depth sh =
  let enprefix s = String.make (2 * depth) ' ' ^ s ^ "\n" in
  match sh with
  [ Sc_line l -> enprefix l
  | Sc_seq lst ->
      lst
      |> List.map
          (string_of_sh_commands_d ~depth)
      |> String.concat ""
  | Sc_if cond_str th el ->
        (enprefix & sprintf "if %s" cond_str)
      ^ (enprefix "then")
      ^ (string_of_sh_commands_d ~depth:(depth + 1) th)
      ^ (enprefix "else")
      ^ (string_of_sh_commands_d ~depth:(depth + 1) el)
      ^ (enprefix "fi")
  ]
;

value string_of_sh_commands = string_of_sh_commands_d ~depth:0
;


value string_of_sh = commands_of_sh @> string_of_sh_commands
;


value script_of_sh (sh, sh_val) = "\
#!/bin/sh\n\
\n\
set -ux\n\
\n\
OSD_LIST_SEP=\"\x01\"\n\
\n\
OSD_PREV_IFS=\"\"\n\
\n\
osd_list_append () { \n\
  if [ -n \"$1\" ]\n\
  then\n\
    if [ -n \"$2\" ]\n\
    then\n\
      echo \"${1}${OSD_LIST_SEP}${2}\"\n\
    else\n\
      echo \"$1\"\n\
    fi\n\
  else\n\
    echo \"$2\"\n\
  fi;\n\
};\n\
\n\
osd_env_var_set () { echo \"$1\"; };\n\
\n\
osd_env_var_prepend () {\n\
  if [ -n \"$2\" ]\n\
  then\n\
    echo \"$1:$2\"\n\
  else\n\
    echo \"$1\"\n\
  fi\n\
};\n\
\n\
osd_ret_code () { return \"$1\"; };\n\
\n\
osd_cmd_unp () { IFS=\"$OSD_PREV_IFS\"; \"$@\"; };\n\
\n\
osd_cmd () { OSD_PREV_IFS=\"$IFS\";\n\
  IFS=\"$OSD_LIST_SEP\"; osd_cmd_unp $@; };\n\
\n\
"
  ^
  (string_of_sh sh)
  ^
  (sprintf "exit %s\n" (string_of_sh_val sh_val))
;


value script = sh @> script_of_sh
;