-
Notifications
You must be signed in to change notification settings - Fork 125
/
dbGen_private.ml
2044 lines (1911 loc) · 91.1 KB
/
dbGen_private.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
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*
Copyright © 2011, 2012 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with Opa. If not, see <http://www.gnu.org/licenses/>.
*)
(**
Private module for DB-Accessors generation.
@author Louis Gesbert
@author Mathieu Barbin (errors report)
@author Quentin Bourgerie
*)
(* depends *)
module Format = Base.Format
module List = BaseList
(* shorthands *)
module Q = QmlAst
module DbAst = QmlAst.Db
module C = DbGen_common
module H = DbGenHelpers
(* alias *)
module AnnotTable = H.AnnotTable
module ExprIdent = Ident
module QC = QmlAstCons.UntypedExpr
module V = Schema_private.V
module E = Schema_private.E
module SchemaGraph = SchemaGraphLib.SchemaGraph
module SchemaGraph0 = SchemaGraphLib.SchemaGraph0
(** the module AnnotTable is in dbGenHelpers *)
#<Debugvar:DBGEN_DEBUG>
let error ?e fmt = AnnotTable.emergency_close();
match e with
| Some e ->
let context = QmlError.Context.expr e in
let context = Schema_private.HacksForPositions.map context in
QmlError.error context fmt
| None ->
let context = QmlError.Context.shame_on_me_i_am_too_lazy "DbGen_private.error" in
QmlError.error context fmt
let debug fmt = OManager.printf ( "@{<magenta>[dbgen]@} "^^fmt^^"@." )
type dbinfo = {
access_fun: Schema_private.vertex -> Q.ident -> Q.expr -> Q.expr;
(* node trans dbpath => expr *)
writer: Schema_private.vertex -> Q.expr -> Q.expr -> Q.expr -> Q.expr;
(* node -> tr -> path -> value -> wr expr *)
default_expr: Schema_private.vertex -> Q.expr;
edge_num_expr: Schema_private.edge -> Q.expr;
(* given an edge in the current schema,
returns the corresponding edge id in the current database *)
db_ident: Q.ident;
(* user-visible (unless no db declarations) ident for this db mount point *)
}
let merge_dbinfo dbinfo1 _dbinfo2 = dbinfo1
let data_root_keylist = [1]
let db_config_keylist = [2]
let db_internal_keylist = [3] (* for the licencing hacks; temporarily unused *)
let config_keys = [`schema, 0; `version, -1]
let (@:) a b = H.(@:) a b
module Default = struct
let rec expr_aux ?select sch n =
H.copy_expr (H.newexpr_annot (expr_for_def ?select sch n) (SchemaGraphLib.type_of_node n))
and expr_for_def ?(select=DbAst.SStar) sch n =
let ty = SchemaGraphLib.type_of_node n in
let _ =
let pos = QmlError.Context.get_pos ((V.label n).C.context) in
H.start_built_pos pos in
let r =
match (V.label n).C.default with
| Some e -> e
| None ->
if Schema_private.has_dflt_in_parents sch n then
let e = SchemaGraphLib.get_parent_edge sch n in
H.make_dot ~ty (expr_aux sch (E.src e)) (SchemaGraphLib.fieldname_of_edge e)
else
match (V.label n).C.nlabel with
| C.Multi ->
begin match select with
| DbAst.SStar | DbAst.SNil ->
begin match SchemaGraphLib.multi_key sch n with
| C.Kint -> H.make_record ["empty", H.make_record []]
| C.Kstring -> H.make_record ["empty", H.make_record []]
| C.Kfields _ -> H.make_record ["empty", H.make_record []]
end
| DbAst.SSlice _ | DbAst.SFlds _ ->
OManager.i_error
"On compute default value unexpected selection on a multi node"
| DbAst.SId (_, select) -> expr_aux ~select sch (SchemaGraph.unique_next sch n)
end
| C.Hidden -> expr_aux sch (SchemaGraph.unique_next sch n)
| C.Sum -> H.convert_case_to_sum ty (expr_aux sch (E.dst (Schema_private.find_nonrec_child_edge sch n)))
| C.Product ->
let selected =
match select with
| DbAst.SFlds flds ->
(fun fld ->
List.find_map
(fun (flds, s) -> if flds = [`string fld] then Some s else None)
flds
)
| _ -> (fun _ -> Some (DbAst.SStar))
in
H.newexpr_annot
(QC.record
(List.fold_right
(fun e acc ->
let fld = SchemaGraphLib.fieldname_of_edge e in
match selected fld with
| None -> acc
| Some s -> (fld, expr_aux ~select:s sch (E.dst e))::acc
) (SchemaGraph0.succ_e sch n) []
))
ty
| C.Leaf C.Leaf_int -> H.const_int 0
| C.Leaf C.Leaf_text -> H.const_string ""
| C.Leaf C.Leaf_binary -> H.const_string ""
| C.Leaf C.Leaf_float -> H.newexpr_annot (QC.const (Q.Float 0.)) ty
in H.end_built_pos ();
r
let expr ?select annotmap sch n =
let () = H.AnnotTable.open_table ~annotmap:(Some annotmap) () in
let e = expr_aux ?select sch n in
(match H.AnnotTable.close_table () with
| None -> assert false
| Some a -> a, e)
end
module CodeGenerator ( Arg : DbGenByPass.S ) = struct
(* aliases *)
module Helpers_gen = H.Helpers_gen (Arg)
module Bypass = Helpers_gen.Bypass
module Db = Schema_private.Db
let typath = Helpers_gen.typath
let tytrans = Helpers_gen.tytrans
let tykey = Helpers_gen.tykey
let tydiff = Helpers_gen.tydiff
let tydbset = Helpers_gen.tydbset
(* -------- DB parameters and access auxiliaries ---------- *)
let make_some e =
H.make_record ["some", e]
(* let ty = AnnotTable.getTypeOfAnnot e.Q.annot in *)
(* H.apply_lambda (expr_some ty) e *)
let debug_in _msg e =
#<If$minlevel 10> debug "Insert run-time debug: %s" _msg #<End>;
#<If> H.make_letin (H.new_ident "_", H.apply_lambda (Bypass.jlog()) (H.const_string _msg)) e
#<Else> e
#<End>
let debugverbose_in _msg e =
#<If$minlevel 20> debug_in _msg e
#<Else> e
#<End>
let match_option_expr e ?(tyval=H.type_inside_option e) fun_some expr_none =
match e with
| Q.Apply (_, Q.Ident (_, id_some), [e]) when id_some = Helpers_gen.id_some() ->
fun_some e
| _ ->
let value = H.new_ident "x" in
H.make_match e
[ H.patt_some_var value tyval, fun_some (value @: tyval);
H.patt_none tyval, expr_none ]
let expr_equals e1 e2 = (* fixme: how to do this in a less verbose way ? *)
let ty = H.type_from_annot e1 in
assert (H.type_from_annot e2 = ty);
H.make_match
(H.apply_lambda' (Bypass.compare ty) [e1;e2])
[ H.patt_const_int 0, H.expr_true();
H.newpatt_annot (QC.patany ()) H.tyint, H.expr_false() ]
let expr_switch e caselist dflt =
let ty1 = H.type_from_annot e in
let ty2 = H.type_from_annot (snd (List.hd caselist)) in
assert (List.for_all (fun (e1,e2) -> H.type_from_annot e1 = ty1 && H.type_from_annot e2 = ty2) caselist);
let id = H.new_ident "switch" in
H.make_letin (id, e)
(List.fold_right
(fun (e1,e2) acc ->
H.make_ifthenelse (expr_equals (id @: ty1) e1) e2 acc)
caselist dflt)
let key_int e = H.apply_lambda (Bypass.key_int()) e
let key_const_int i = key_int (H.const_int i)
let key_string e = H.apply_lambda (Bypass.key_string()) e
let key_const_string s = key_string (H.const_string s)
let rec key_list gamma l_fields e =
let l_fields =
List.sort (fun a b -> String.compare (fst a) (fst b)) l_fields in
let id = H.new_ident "record_key" in
let ty = Q.TypeRecord (Q.TyRow(l_fields,None)) in
let rec key_of (fn,fty) = match fty with
| Q.TypeConst Q.TyInt -> key_int (H.make_dot ~ty:fty (id @: ty) fn)
| Q.TypeConst Q.TyString -> key_string (H.make_dot ~ty:fty (id @: ty) fn)
| Q.TypeRecord (Q.TyRow(l_fields,_)) -> key_list gamma l_fields (H.make_dot ~ty:fty (id @: ty) fn)
| Q.TypeName (tylst,tid) ->
let context = QmlError.Context.expr e in
let fty = Schema_private.get_type_from_name ~context gamma tylst tid in
key_of (fn,fty)
| _ -> error ("Set keys containing fields of type [%a] are not supported yet.") QmlPrint.pp#ty fty in
let l_key = List.map key_of l_fields in
H.make_letin (id, e) (H.apply_lambda (Bypass.key_list()) (Bypass.make_ocaml_list l_key (tykey ())))
let dbpath_add path key = H.apply_lambda' (Bypass.dbpath_add()) [path;key]
let path_of_intkeylist () = List.fold_left (fun acc i -> dbpath_add acc (key_const_int i)) (Bypass.dbpath_root())
let data_root () = path_of_intkeylist () data_root_keylist
let config_key_path k = path_of_intkeylist () (db_config_keylist @ [List.assoc k config_keys])
let leaf_data leaf_t value =
match leaf_t with
| C.Leaf_int -> H.apply_lambda (Bypass.data_int()) value
| C.Leaf_float -> H.apply_lambda (Bypass.data_float()) value
| C.Leaf_text -> H.apply_lambda (Bypass.data_text()) value
| C.Leaf_binary -> H.apply_lambda (Bypass.data_binary()) value
let apply_inside_opt f_expr opt_expr =
let ty2 =
match AnnotTable.getTypeOfAnnot (Q.QAnnot.expr f_expr) with
| Q.TypeArrow ([ty1], ty2) ->
assert
(let ty = AnnotTable.getTypeOfAnnot (Q.QAnnot.expr opt_expr) in
ty = Q.typeNull || ty = H.typeoption ty1 ||
#<If>
debug "apply_inside_opt: %a ~=~ %a"
QmlPrint.pp#ty (H.typeoption ty1)
QmlPrint.pp#ty (AnnotTable.getTypeOfAnnot (Q.QAnnot.expr opt_expr));
false
#<Else> false #<End>);
ty2
| Q.TypeArrow _ -> assert false
| ty when ty = Q.typeNull -> Q.typeNull
| _ -> assert false
in
match_option_expr opt_expr
(fun data -> make_some (H.apply_lambda f_expr data))
(Helpers_gen.expr_none ty2)
let get_code tr path leaf_t =
apply_inside_opt (Bypass.proj_dbtype leaf_t)
(H.apply_lambda' (Bypass.get_opt())
[tr @: (tytrans()); path])
let get_code_noopt tr path leaf_t =
let id = H.new_ident "x" in
let ty = SchemaGraphLib.type_of_leaf leaf_t in
H.make_match
(get_code tr path leaf_t)
[ H.patt_some_var id ty, id @: ty;
H.patt_none ty, H.apply_lambda' (Bypass.fatal_error ty)
[H.const_string "Impossible to read structure data from the database";H.const_string "";H.const_string""] ]
let set_code tr path value leaf_t =
H.apply_lambda' (Bypass.set()) [tr @: (tytrans()); path; leaf_data leaf_t value]
let set_unit_code tr path =
H.apply_lambda' (Bypass.set()) [tr @: (tytrans()); path; H.apply_lambda' (Bypass.data_unit()) []]
let enter_transaction_expr db =
debugverbose_in "ENTER TRANSACTION" (
match_option_expr (H.apply_lambda (Bypass.get_global_transaction_opt()) (db @: C.Db.t ()))
(fun tr -> tr)
(H.apply_lambda (Bypass.trans_start()) (db @: C.Db.t ()))
)
let leave_transaction_expr db tr =
debugverbose_in "LEAVE TRANSACTION" (
match_option_expr (H.apply_lambda (Bypass.get_global_transaction_opt()) (db @: C.Db.t ()))
(fun _ -> H.apply_lambda' (Bypass.set_global_transaction()) [db @: C.Db.t (); tr @: (tytrans())])
(H.apply_lambda' (Bypass.trans_commit()) [tr @: (tytrans())])
)
(* Label of keys inside the edge-map, which is a record containing the
bindings high-level edge -> physical db edge *)
let edge_fld_label edge =
Printf.sprintf "edge_%s_%d" (V.label (E.src edge)).C.nodeid (SchemaGraphLib.fieldid_of_edge edge)
(* --------- Generation functions ----------- *)
let patt_of_node sch node =
match (V.label node).C.nlabel with
| C.Product ->
let fieldmap, fields =
SchemaGraph0.fold_succ_e (
fun e (fieldmap, fields) ->
let f = SchemaGraphLib.fieldname_of_edge e in
let id_f = H.new_ident f in
let fieldmap = (f, id_f) :: fieldmap in
let sub_pat =
H.newpatt_annot (QC.patvar id_f)
(SchemaGraphLib.type_of_node (E.dst e))
in
let fields = (f, sub_pat) :: fields in
fieldmap, fields
)
sch node
([], [])
in
let pat = Q.PatRecord (H.nolabel, fields, `closed) in
fieldmap, H.newpatt_annot pat (SchemaGraphLib.type_of_node node)
| _ -> assert false
let newkey_expr tr path =
key_int
(H.apply_lambda' (Bypass.get_new_key())
[tr; path])
(** From a dbpath pointing to the source of a link edge, returns a dbpath
pointing to the parent of the destination of that link. Links within
elements of a map should be handled correctly. *)
(* The algorithm isn't trivial: we go up then down to find the "shortest" path,
then use the uppath and add_key bypasses to build the corresponding path *)
let dbpath_from_link_expr sch edge_num_from_edge tr edge dbpath =
assert (not (E.label edge).C.is_main); (* edge is a link *)
let fail () =
failwith (Printf.sprintf "Invalid link to %s at %s"
(SchemaGraphLib.string_path_of_node sch (E.dst edge))
(SchemaGraphLib.string_path_of_node sch (E.src edge))) in
let src, dst = E.src edge, E.dst edge in
let rec parents_list acc n = if SchemaGraphLib.is_root n then n::acc
else parents_list (n::acc) (E.src (SchemaGraphLib.get_parent_edge sch n)) in
let up = parents_list [] src in
let down = parents_list [] dst in
let rec find_last_tail a = function
| x::r when x = a -> Some r | _::r -> find_last_tail a r | [] -> None in
let rec find_shortest acc upl downl = match upl with
| x::r -> (match find_last_tail x downl with
| Some down -> (x::acc, down)
| None -> find_shortest (x::acc) r downl)
| [] -> assert false (* a tree's rooted *)
in
let up, down = find_shortest [] (List.rev up) down in
let up_expr =
List.fold_left (fun path _ -> H.apply_lambda' (Bypass.uppath()) [tr @: (tytrans()); path]) dbpath up in
let _, updown_expr =
List.fold_left
(fun (nprev, path) n ->
(n,
match (V.label nprev).C.nlabel with
| C.Multi ->
(match SchemaGraphLib.multi_key sch nprev with
| C.Kint -> dbpath_add path (newkey_expr (tr @: (tytrans())) path)
| C.Kfields _ ->
error "linking to within a set not handled yet" (* todo *)
| C.Kstring -> fail())
| C.Hidden -> dbpath_add path (key_const_int 0)
| C.Sum ->
(* dbpath_add path (key_const_int 0) with override ? *)
error "Unhandled write to a link pointing to a specific case of a sum type"
| C.Product ->
dbpath_add path
(key_int (edge_num_from_edge (SchemaGraph0.find_edge sch nprev n)))
| _ -> fail()))
(List.hd up, up_expr)
down
in
updown_expr
(* ------------------------------------------------------------ *)
(* This module generates the whole database accessors code *)
(* ------------------------------------------------------------ *)
(* GenAccessors generates default values, readers and writers *)
module GenAccessors = struct
(* Idents for default values and accessors *)
module Idents = struct
type t = {
default_idents : (string * ExprIdent.t option) list;
reader_idents : (string * ExprIdent.t option) list;
writer_idents : (string * ExprIdent.t option) list;
generic_reader : (C.leaf * ExprIdent.t) list;
generic_writer : (C.leaf * ExprIdent.t) list;
edge_map_ids : (ExprIdent.t * Q.ty) StringMap.t (* package_name -> edgemap id * its type *)
}
let merge idents1 idents2 =
{
default_idents = idents1.default_idents @ idents2.default_idents;
reader_idents = idents1.reader_idents @ idents2.reader_idents;
writer_idents = idents1.writer_idents @ idents2.writer_idents;
generic_reader = idents1.generic_reader;
generic_writer = idents1.generic_writer;
edge_map_ids =
StringMap.merge
(fun id1 _id2 -> id1)
idents1.edge_map_ids
idents2.edge_map_ids
}
let generate sch =
let default_idents, reader_idents, writer_idents =
SchemaGraph0.fold_vertex
(fun n (d_acc,r_acc,w_acc) -> let nodeid = (V.label n).C.nodeid in
let d,r,w =
match (V.label n).C.nlabel with
| C.Leaf _l -> None, None, None
(* No accessors for leaves, they use the generic ones *)
| C.Multi when SchemaGraphLib.is_node_set sch n ->
None,
(Some (H.new_ident (Printf.sprintf "get_dbset%s" nodeid))),
(Some (H.new_ident (Printf.sprintf "set_dbset%s" nodeid)))
(*
| C.Hidden -> None, None, None
(* No accessors for hidden nodes as well, paths should be
built to access their children directly *)
*)
| C.Product ->
(None, (* Default accessor of product is useless *)
Some (H.new_ident ("get_n"^nodeid)),
Some (H.new_ident ("set_n"^nodeid)))
| _ ->
(Some (H.new_ident ("default_n"^nodeid)),
Some (H.new_ident ("get_n"^nodeid)),
Some (H.new_ident ("set_n"^nodeid)))
in
( (nodeid,d)::d_acc, (nodeid,r)::r_acc, (nodeid,w)::w_acc)
)
sch ([],[],[])
in {
default_idents = default_idents;
reader_idents = reader_idents;
writer_idents = writer_idents;
generic_reader =
(let int = H.new_ident "r_int" in
let binary = H.new_ident "r_binary" in
let text = H.new_ident "r_text" in
let float = H.new_ident "r_float" in
[(C.Leaf_int, int); (C.Leaf_binary, binary);
(C.Leaf_text, text); (C.Leaf_float, float)]
(* function C.Leaf_int -> int | C.Leaf_binary -> binary | C.Leaf_text -> text | C.Leaf_float -> float *));
generic_writer =
(let int = H.new_ident "w_int" in
let binary = H.new_ident "w_binary" in
let text = H.new_ident "w_text" in
let float = H.new_ident "w_float" in
[(C.Leaf_int, int); (C.Leaf_binary, binary);
(C.Leaf_text, text); (C.Leaf_float, float)]
(* function C.Leaf_int -> int | C.Leaf_binary -> binary | C.Leaf_text -> text | C.Leaf_float -> float *));
edge_map_ids =
(let package = ObjectFiles.get_current_package_name() in
let edgemap_edges =
SchemaGraph0.fold_edges_e
(fun e acc ->
if SchemaGraphLib.package_of_node (E.dst e) <> package then acc
else match (E.label e).C.label with
| C.SumCase _ | C.Field _ -> edge_fld_label e :: acc
| _ -> acc)
sch []
in
StringMap.singleton package
(H.new_ident ("edge_map_"^package),
H.tyrecord (List.map (fun lbl -> lbl, H.tyint) edgemap_edges)))
}
let get_default idents n = List.assoc (V.label n).C.nodeid idents.default_idents
let get_reader idents n =
List.assoc (V.label n).C.nodeid idents.reader_idents
let get_writer idents n = List.assoc (V.label n).C.nodeid idents.writer_idents
let get_generic_reader idents lf = List.assoc lf idents.generic_reader
let get_generic_writer idents lf = List.assoc lf idents.generic_writer
end
(* Default values *)
module Default = struct
let rec expr sch idents n = match Idents.get_default idents n with
| Some id -> id @: SchemaGraphLib.type_of_node n
| None -> H.copy_expr (H.newexpr_annot (expr_for_def sch idents n) (SchemaGraphLib.type_of_node n))
and expr_for_def sch idents n =
let ty = SchemaGraphLib.type_of_node n in
let _ =
let pos = QmlError.Context.get_pos ((V.label n).C.context) in
H.start_built_pos pos in
let r =
match (V.label n).C.default with
| Some e -> e
| None ->
if Schema_private.has_dflt_in_parents sch n then
let e = SchemaGraphLib.get_parent_edge sch n in
H.make_dot ~ty (expr sch idents (E.src e)) (SchemaGraphLib.fieldname_of_edge e)
else
match (V.label n).C.nlabel with
| C.Multi -> (match SchemaGraphLib.multi_key sch n with
| C.Kint -> Helpers_gen.expr_intmap_empty ty
| C.Kstring -> Helpers_gen.expr_stringmap_empty ty
| C.Kfields _ -> assert false
(* sets cannot be accessed directly *))
| C.Hidden -> expr sch idents (SchemaGraph.unique_next sch n)
| C.Sum -> H.convert_case_to_sum ty (expr sch idents (E.dst (Schema_private.find_nonrec_child_edge sch n)))
| C.Product ->
H.newexpr_annot
(QC.record
(List.map (fun e -> SchemaGraphLib.fieldname_of_edge e, expr sch idents (E.dst e)) (SchemaGraph0.succ_e sch n)))
ty
| C.Leaf C.Leaf_int -> H.const_int 0
| C.Leaf C.Leaf_text -> H.const_string ""
| C.Leaf C.Leaf_binary -> H.const_string ""
| C.Leaf C.Leaf_float -> H.newexpr_annot (QC.const (Q.Float 0.)) ty
in H.end_built_pos ();
r
let add_valdefs sch idents =
let default_values =
SchemaGraph0.fold_vertex
(fun n acc ->
match Idents.get_default idents n with
| Some id -> (id, expr_for_def sch idents n)::acc
| None -> acc)
sch [] in
let rec aux acc dflt = (* builds nested letand / letin *)
let ids = List.map fst dflt in
match List.partition (fun (_id,e) -> H.are_ids_free_in_expr ids e) dflt with
| [],[] -> acc
| [],_dflt1 -> error "Unsound recursive types in DB definitions"
| dflt0,dflt1 ->
aux (fun e -> acc (
let label = Annot.nolabel "DbGen_private.gen_node_accessors" in
(Q.NewVal (label, dflt0)) :: e)
) dflt1
in aux (fun e -> e) default_values
end
module Type = struct
let generic_reader leaf =
let ty = SchemaGraphLib.type_of_leaf leaf in
H.tyfun [ty; (tytrans()); (typath()); H.over_valpath_ty ty]
(* == ty -> reader *)
let reader n =
H.tyfun [(tytrans()); (typath()); H.over_valpath_ty (SchemaGraphLib.type_of_node n)]
let generic_writer leaf =
let ty = SchemaGraphLib.type_of_leaf leaf in (* == db_writer_type *)
H.tyfun [(tytrans()); (typath()); ty; (tytrans())]
let writer n =
H.tyfun [(tytrans()); (typath()); SchemaGraphLib.type_of_node n; (tytrans())]
end
let make_embedded_path _node tr path =
H.apply_lambda' (Bypass.embedded_path ())
[tr @: (tytrans()); path ]
let edge_map_infos sch db_ident db_diff_id =
(* let oc1 = open_out ("schema") in *)
(* let _ = Schema_io.to_dot sch oc1 in *)
(* let _ = close_out oc1 in *)
let defs = SchemaGraph0.fold_edges_e
(fun e acc ->
if SchemaGraphLib.package_of_node (E.dst e) <> ObjectFiles.get_current_package_name() then acc
else match (E.label e).C.label with
| C.SumCase i | C.Field (_,i) ->
let nodeid = (V.label (E.src e)).C.nodeid in
let edgeid_expr =
if nodeid = "root" then
(* for separated compilation: query the hashtbl initialised during `init *)
H.apply_lambda' (Bypass.get_registered_root_edge())
[ H.const_string (Ident.original_name db_ident);
H.const_string (SchemaGraphLib.package_of_node (E.dst e));
H.const_int i ]
else
H.const_int i
in
(edge_fld_label e,
H.apply_lambda' (Bypass.matching_edge())
[ db_diff_id @: (tydiff ()); H.const_string nodeid; edgeid_expr ])
:: acc
| _ -> acc)
sch [] in
let record = H.make_record defs in
let label = Annot.nolabel "DbGen_private.gen_node_accessors" in
(label, record)
(* For mapping with a pre-existing db, from its embedded schema *)
let def_edge_map (label, record) edge_map_id =
Q.NewVal (label, [edge_map_id, record])
let edge_num_expr edge_map_ids =
(fun edge ->
let package_name = SchemaGraphLib.package_of_node (E.dst edge) in
let edge_map_id, edge_map_ty = StringMap.find package_name edge_map_ids in
H.make_dot ~ty:H.tyint (edge_map_id @: edge_map_ty) (edge_fld_label edge))
let register_root_edge_map db_ident unrenumbered_sch sch =
let defs =
SchemaGraph0.fold_succ_e
(fun e acc ->
match (E.label e).C.label with
| C.Field (fieldname, edgeid) ->
let package_name = SchemaGraphLib.package_of_node (E.dst e) in
let db_name = Ident.original_name db_ident in
let source_edge_id =
match
List.filter
(fun e ->
SchemaGraphLib.package_of_node (E.dst e) = package_name &&
SchemaGraphLib.fieldname_of_edge e = fieldname)
(SchemaGraph0.succ_e unrenumbered_sch (SchemaGraphLib.get_root unrenumbered_sch))
with
| [e] -> SchemaGraphLib.fieldid_of_edge e
| _ -> assert false
in
(H.new_ident "_",
H.apply_lambda' (Bypass.register_root_edge())
[ H.const_string db_name;
H.const_string package_name;
H.const_int source_edge_id;
H.const_int edgeid ])
:: acc
| _ -> assert false)
sch (SchemaGraphLib.get_root sch) [] in
let expr = H.make_letand defs (H.expr_unit()) in
let label = Annot.nolabel "DbGen_private.gen_node_accessors" in
Q.NewVal (label, [H.new_ident "_", expr])
module Reader = struct
module Generic = struct
let expr leaf =
let ty = SchemaGraphLib.type_of_leaf leaf in
let dflt = H.new_ident "default" in
let tr = H.new_ident "tr" in
let path = H.new_ident "curpath" in
H.make_lambda' [dflt, ty; tr, (tytrans()); path, (typath())]
(let res = H.new_ident "res" in
H.make_letin
(res,
get_code tr (path @: (typath())) leaf)
(match_option_expr (res @: H.typeoption ty)
(fun x -> x)
(dflt @: ty)))
end
let expr sch idents n tr path =
match Idents.get_reader idents n with
| Some acc ->
H.apply_lambda' (acc @: Type.reader n) [tr; path]
| None ->
match (V.label n).C.nlabel with
| C.Leaf leaf ->
H.apply_lambda' (Idents.get_generic_reader idents leaf @: Type.generic_reader leaf)
[Default.expr sch idents n; tr; path]
| C.Multi when SchemaGraphLib.is_node_set sch n ->
assert false (* Reader of dbset are generated on idents *)
| _ -> assert false
let get_multi sch idents tr path n ty =
let nextnode = SchemaGraph.unique_next sch n in
let tychld = SchemaGraphLib.type_of_node nextnode in
(* see get_dbset, get_multi should not be called on set node *)
let expr_empty () = match SchemaGraphLib.multi_key sch n with
| C.Kint -> Helpers_gen.expr_intmap_empty ty
| C.Kstring -> Helpers_gen.expr_stringmap_empty ty
| _ -> assert false in
let expr_read =
H.apply_lambda'
(Bypass.fold_children tychld ty)
[
tr @: (tytrans());
path @: (typath());
(let tr, path = H.new_ident "tr", H.new_ident "path" in
H.make_lambda' [tr, (tytrans()); path, (typath())]
(expr sch idents nextnode (tr @: (tytrans())) (path @: (typath()))));
(let acc, key, value = H.new_ident "acc", H.new_ident "key", H.new_ident "value" in
H.make_lambda'
[acc, ty; key, (tykey ()); value, tychld]
(match SchemaGraphLib.multi_key sch n with
| C.Kint ->
H.apply_lambda'
(Helpers_gen.expr_stringmap_add H.tyint tychld)
[ H.apply_lambda (Bypass.key_value_int()) (key @: (tykey ()));
value @: tychld;
acc @: ty ]
| C.Kstring ->
H.apply_lambda'
(Helpers_gen.expr_stringmap_add H.tystring tychld)
[ H.apply_lambda (Bypass.key_value_string()) (key @: (tykey ()));
value @: tychld;
acc @: ty ]
| _ -> assert false));
expr_empty();
]
in
#<If:DBGEN_FLAGS$flag "sharing">
let value = H.new_ident "value" in
H.make_letin (value, expr_read)
(H.make_ifthenelse (expr_equals (value @: ty) (expr_empty())) (* Do not embed data if empty *)
(value @: ty)
(H.apply_lambda'
(Bypass.embed_record_data ty)
[ value @: ty; make_some (make_embedded_path n tr (path @: (typath())))]))
#<Else>
expr_read
#<End>
let get_dbset sch idents tr path node dbsetty =
(* Extract type inside dbset *)
let ty = C.get_dbset_ty dbsetty in
(* The dbset reader is the reader that read a child node *)
let reader =
let child = SchemaGraph.unique_next sch node in
let child = {child with C.ty = C.Db.set ty} in
match Idents.get_reader idents child with
| None -> OManager.i_error "Child reader of a dbset not found"
| Some reader -> reader @: Type.reader child in
let setident = Ident.next "db3set" in
let db3set = H.apply_lambda'
(Bypass.create_dbset ty) [tr @: (tytrans()); path @: (typath()); reader]
in let iterator = H.apply_lambda'
(Helpers_gen.expr_db3set_iterator ty) [setident @: (tydbset ty)]
in let genset = H.apply_lambda'
(Helpers_gen.expr_dbset_genbuild ty) [iterator; setident @: (tydbset ty)]
in H.make_letin (setident, db3set) genset
let def sch idents =
let make_accessor n =
let _ =
let pos = QmlError.Context.get_pos ((V.label n).C.context) in
H.start_built_pos pos in
let ty0 = SchemaGraphLib.type_of_node n in
let ty = H.over_valpath_ty ty0 in
let tr = H.new_ident "tr" in
let path = H.new_ident "curpath" in
let r = H.make_lambda'
[ tr, (tytrans());
path, (typath()) ]
(H.make_coerce ~ty
(match (V.label n).C.nlabel with
| C.Multi when SchemaGraphLib.is_node_set sch n ->
get_dbset sch idents tr path n ty0
| C.Multi -> get_multi sch idents tr path n ty0
| C.Hidden ->
expr sch idents (SchemaGraph.unique_next sch n) (tr @: (tytrans()))
(dbpath_add (path @: (typath())) (key_const_int 0))
| C.Sum ->
expr_switch
(get_code tr (path @: (typath())) C.Leaf_int)
(List.map
(fun e ->
let edgenum() = edge_num_expr idents.Idents.edge_map_ids e in
make_some (edgenum()),
H.make_coerce
(H.convert_case_to_sum
~lazy_param:(Some (make_embedded_path n tr (path @: (typath()))))
ty0
(expr sch idents (E.dst e) (tr @: (tytrans()))
(dbpath_add (path @: (typath())) (key_int (edgenum()))))))
(SchemaGraph0.succ_e sch n))
(Default.expr sch idents n)
| C.Product ->
H.make_coerce
(H.make_lazyrecord
(make_embedded_path n tr (path @: (typath())))
(List.map
(fun e ->
let f = SchemaGraphLib.fieldname_of_edge e in
f,
expr sch idents (E.dst e) (tr @: (tytrans()))
(dbpath_add (path @: (typath())) (key_int (edge_num_expr idents.Idents.edge_map_ids e))))
(SchemaGraph0.succ_e sch n))
ty0)
| C.Leaf _ -> assert false)) (* handled by accessors_generic *)
in H.end_built_pos (); r
in
SchemaGraph0.fold_vertex
(fun n acc ->
match Idents.get_reader idents n with
| None -> acc
| Some id -> (id, make_accessor n)::acc)
sch []
end
module Writer = struct
module Generic = struct
let expr leaf =
let ty = SchemaGraphLib.type_of_leaf leaf in
let tr = H.new_ident "tr" in
let path = H.new_ident "curpath" in
let value = H.new_ident "value" in
H.make_lambda' [tr, (tytrans()); path, (typath()); value, ty]
(set_code tr (path @: (typath())) (value @: ty) leaf)
end
let expr sch idents n =
match Idents.get_writer idents n with
| Some id -> id @: Type.writer n
| None -> match (V.label n).C.nlabel with
| C.Leaf leaf -> Idents.get_generic_writer idents leaf @: Type.generic_writer leaf
| C.Multi when SchemaGraphLib.is_node_set sch n ->
H.apply_lambda (Bypass.error (Type.writer n)) (H.const_string "Writing in a database set node is forbidden. This feature will be available in a future version.")
| _ -> assert false
let apply_writer sch idents node tr path_expr value =
H.apply_lambda'
(expr sch idents node)
[tr @: (tytrans()); path_expr; H.make_coerce (H.newexpr_annot value (SchemaGraphLib.type_of_node node))]
let write_child sch idents tr parent_path key edge value =
let n = E.dst edge in
if (E.label edge).C.is_main then
apply_writer sch idents n tr (dbpath_add (parent_path @: (typath())) key) value
else
(* Write a recursive structure:
(1) create node with new key at the link-to point
-- need to find the path of the map: express the link in terms of ../.. -> this is done by dbpath_from_link_expr
-- append the node to the map, with a fresh key
(2) link to the newly created node
Remark: if we have a 1c path here, maybe we could try & link instead of generating a new key *)
let dbpath_dest = H.new_ident "dbpath_dest"
and newkey = H.new_ident "newkey"
and newpath_dest = H.new_ident "newpath_dest"
and tr1 = H.new_ident "trans1" in
let by_link_or_copy =
#<If:DBGEN_FLAGS$flag "copylink">
(Bypass.set_current_copy())
#<Else> (Bypass.set_link())
#<End>
in
H.make_letin'
[ dbpath_dest,
dbpath_from_link_expr sch (edge_num_expr idents.Idents.edge_map_ids) tr edge (parent_path @: (typath()));
newkey,
newkey_expr (tr @: (tytrans())) (dbpath_dest @: (typath()));
newpath_dest,
dbpath_add (dbpath_dest @: (typath())) (newkey @: (tykey ()));
tr1,
apply_writer sch idents n tr (newpath_dest @: (typath())) value ]
(H.apply_lambda' by_link_or_copy
[ tr1 @: (tytrans());
dbpath_add (parent_path @: (typath())) key;
newpath_dest @: (typath()) ])
let write_multi sch idents tr path n _ty value =
let tykeys, key_make = match SchemaGraphLib.multi_key sch n with
| C.Kint -> H.tyint, key_int
| C.Kstring -> H.tystring, key_string
| C.Kfields _ -> assert false (* todo: implement indexed writing to sets ! *)
in
let edge = SchemaGraph.out_edge sch n in
let tychld = SchemaGraphLib.type_of_node (E.dst edge) in
let tr1 = H.new_ident "loc_trans1" in
let tr2 = H.new_ident "loc_trans2" in
H.make_letin'
[tr2, H.apply_lambda' (Bypass.clear())
(* warn: that would break a link: we should not allow maps as destinations of links in the schema *)
[tr @: (tytrans()); path @: (typath())];
tr1, set_unit_code tr2 (path @: (typath()))]
(* Cleanup the node before re-setting *)
(H.apply_lambda'
(match SchemaGraphLib.multi_key sch n with
| C.Kint -> Helpers_gen.expr_intmap_fold tykeys tychld (tytrans())
| C.Kstring -> Helpers_gen.expr_stringmap_fold tykeys tychld (tytrans())
| _ -> assert false)
[ (let k,x,acc = H.new_ident "k", H.new_ident "x", H.new_ident "trans_acc" in
H.make_lambda' [k, tykeys; x, tychld; acc, (tytrans())]
(write_child sch idents acc path (key_make (k @: tykeys)) edge (QC.ident x)));
value;
tr1 @: (tytrans()) ])
let set_dbset sch idents tr path value node dbsetty =
(* Extract type inside dbset *)
let ty = C.get_dbset_ty dbsetty in
(* The dbset writer is the child writer *)
let writer =
let child = SchemaGraph.unique_next sch node in
let child = {child with C.ty = C.Db.set ty} in
match Idents.get_writer idents child with
| None -> OManager.i_error "Child writer of a dbset not found"
| Some writer -> writer @: Type.writer child in
H.apply_lambda' writer
[tr @: (tytrans()); path @: (typath()); value @: ty]
let def sch idents =
let make_writer n =
let _ =
let pos = QmlError.Context.get_pos ((V.label n).C.context) in
H.start_built_pos pos in
let ty = SchemaGraphLib.type_of_node n in
let value = H.new_ident "cur_value" in
let tr = H.new_ident "trans" in
let path = H.new_ident "path" in
let attempt_to_copy e =
#<If:DBGEN_FLAGS$flag "sharing">
(H.make_match
(H.apply_lambda (Bypass.get_lazy_info_opt ty) (value @: ty))
[ (let ldata = H.new_ident "lazy_data" in
H.patt_some_var ldata (Helpers_gen.ty_lazy_data ()),
debug_in "This data is already in the DB: mark as copy instead of write"
(H.apply_lambda' (Bypass.copy ty)
[ tr @: (tytrans()); ldata @: Helpers_gen.ty_lazy_data (); path @: (typath()) ]));
H.patt_none (C.val_path_ty ty),
debug_in "Marking your data with DB info (for later sharing)"
(let tr = H.new_ident "tr" in
H.make_letin'
[ tr, e;
H.new_ident "_",
(H.apply_lambda' (Bypass.inject_record_data ty)
[ value @: ty;
make_some
(H.apply_lambda' (Bypass.embedded_path ())
[tr @: (tytrans()); path @: (typath())]) ]) ]
(tr @: (tytrans()))) ])
#<Else> e
#<End>
in
let r = H.make_lambda'
[ tr, (tytrans());
path, (typath());
value, ty ]
(* Writes belong to one of three cases:
(1) paths that always lead to a recursive call (eg rectypes == multi with a default case)
these don't access the contents of "value" anyway.
(2) then try to see if we can do a path_copy instead of writing, checking for hidden lazy data
(3) handle actual writes for the remaining cases *)
(
debugverbose_in (Printf.sprintf "Writing node %s (%s)" (V.label n).C.nodeid (SchemaGraphLib.string_path_of_node sch n))
(match (V.label n).C.nlabel with
| C.Multi when SchemaGraphLib.is_node_set sch n ->
set_dbset sch idents tr path value n ty
| C.Multi -> attempt_to_copy (write_multi sch idents tr path n ty (value @: ty))
| C.Hidden ->
(* we don't copy in these cases, which are hidden to the user: no valpath can point here *)
let tr1 = H.new_ident "tr1" in
H.make_letin
(tr1, H.apply_lambda' (Bypass.remove_children()) [tr @: (tytrans()); (path @: (typath()))])
(write_child sch idents tr1 path (key_const_int 0) (SchemaGraph.out_edge sch n) (QC.ident value))
| C.Sum ->
let tr1 = H.new_ident "tr1" in
attempt_to_copy
(H.make_letin
(tr1, H.apply_lambda' (Bypass.remove_children()) [tr @: (tytrans()); (path @: (typath()))])
(H.make_match (value @: ty)
(List.map
(fun e ->
let edgenum() = edge_num_expr idents.Idents.edge_map_ids e in
let fldlist,patt = patt_of_node sch (E.dst e) in
let tr2 = H.new_ident "tr2" in
patt,
H.make_letin
(tr2, set_code tr1 (path @: (typath())) (edgenum()) C.Leaf_int)
(write_child sch idents tr2 path (key_int (edgenum())) e
(* (value @: ty).e *)
(QC.record (* = (value @: ty).e, only useful for typing/conversion *)
(List.map
(fun (fd,id) -> fd, id @: (SchemaGraphLib.type_of_node (E.dst (SchemaGraphLib.find_field_edge sch (E.dst e) fd))))
fldlist))))
(SchemaGraph0.succ_e sch n))))
| C.Product -> attempt_to_copy
(let tr_expr = (* record presence of empty records: *)
if SchemaGraph0.succ_e sch n = []
then set_unit_code tr (path @: (typath()))
else (tr @: (tytrans()))
in