summary refs log tree commit diff
path: root/src/rustc/middle/tstate/auxiliary.rs
blob: c568d1f0cfee563b1ee401251beb8900e6da22e9 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
import option::*;
import pat_util::*;
import syntax::ast::*;
import syntax::ast_util::*;
import syntax::{visit, codemap};
import codemap::span;
import std::map::{hashmap, int_hash};
import syntax::print::pprust::path_to_str;
import tstate::ann::{pre_and_post, pre_and_post_state, empty_ann, prestate,
                     poststate, precond, postcond,
                     set_prestate, set_poststate, set_in_poststate_,
                     extend_prestate, extend_poststate, set_precondition,
                     set_postcondition, ts_ann,
                     clear_in_postcond,
                     clear_in_poststate_};
import tritv::*;
import bitvectors::promises_;
import driver::session::session;

import syntax::print::pprust::{constr_args_to_str, lit_to_str};

// Used to communicate which operands should be invalidated
// to helper functions
enum oper_type {
    oper_move,
    oper_swap,
    oper_assign,
    oper_assign_op,
    oper_pure,
}

/* logging funs */
fn def_id_to_str(d: def_id) -> str {
    ret int::str(d.crate) + "," + int::str(d.node);
}

fn comma_str(args: [@constr_arg_use]) -> str {
    let mut rslt = "";
    let mut comma = false;
    for a: @constr_arg_use in args {
        if comma { rslt += ", "; } else { comma = true; }
        alt a.node {
          carg_base { rslt += "*"; }
          carg_ident(i) { rslt += i.ident; }
          carg_lit(l) { rslt += lit_to_str(l); }
        }
    }
    ret rslt;
}

fn constraint_to_str(tcx: ty::ctxt, c: sp_constr) -> str {
    alt c.node {
      ninit(id, i) {
        ret #fmt("init(%s id=%d - arising from %s)",
                 i, id, codemap::span_to_str(c.span, tcx.sess.codemap));
      }
      npred(p, _, args) {
          ret #fmt("%s(%s) - arising from %s",
                   path_to_str(p),
                   comma_str(args),
                   codemap::span_to_str(c.span, tcx.sess.codemap));
      }
    }
}

fn tritv_to_str(fcx: fn_ctxt, v: tritv::t) -> str {
    let mut s = "";
    let mut comma = false;
    for p: norm_constraint in constraints(fcx) {
        alt tritv_get(v, p.bit_num) {
          dont_care { }
          tt {
            s +=
                if comma { ", " } else { comma = true; "" } +
                    if tt == tfalse { "!" } else { "" } +
                    constraint_to_str(fcx.ccx.tcx, p.c);
          }
        }
    }
    ret s;
}

fn log_tritv(fcx: fn_ctxt, v: tritv::t) {
    log(debug, tritv_to_str(fcx, v));
}

fn first_difference_string(fcx: fn_ctxt, expected: tritv::t, actual: tritv::t)
   -> str {
    let s: str = "";
    for c: norm_constraint in constraints(fcx) {
        if tritv_get(expected, c.bit_num) == ttrue &&
               tritv_get(actual, c.bit_num) != ttrue {
            ret constraint_to_str(fcx.ccx.tcx, c.c);
        }
    }
    ret s;
}

fn log_tritv_err(fcx: fn_ctxt, v: tritv::t) {
    log(error, tritv_to_str(fcx, v));
}

fn tos(v: [uint]) -> str {
    let mut rslt = "";
    for i: uint in v {
        if i == 0u {
            rslt += "0";
        } else if i == 1u { rslt += "1"; } else { rslt += "?"; }
    }
    ret rslt;
}

fn log_cond(v: [uint]) { log(debug, tos(v)); }

fn log_cond_err(v: [uint]) { log(error, tos(v)); }

fn log_pp(pp: pre_and_post) {
    let p1 = tritv::to_vec(pp.precondition);
    let p2 = tritv::to_vec(pp.postcondition);
    #debug("pre:");
    log_cond(p1);
    #debug("post:");
    log_cond(p2);
}

fn log_pp_err(pp: pre_and_post) {
    let p1 = tritv::to_vec(pp.precondition);
    let p2 = tritv::to_vec(pp.postcondition);
    #error("pre:");
    log_cond_err(p1);
    #error("post:");
    log_cond_err(p2);
}

fn log_states(pp: pre_and_post_state) {
    let p1 = tritv::to_vec(pp.prestate);
    let p2 = tritv::to_vec(pp.poststate);
    #debug("prestate:");
    log_cond(p1);
    #debug("poststate:");
    log_cond(p2);
}

fn log_states_err(pp: pre_and_post_state) {
    let p1 = tritv::to_vec(pp.prestate);
    let p2 = tritv::to_vec(pp.poststate);
    #error("prestate:");
    log_cond_err(p1);
    #error("poststate:");
    log_cond_err(p2);
}

fn print_ident(i: ident) { log(debug, " " + i + " "); }

fn print_idents(&idents: [ident]) {
    if vec::len::<ident>(idents) == 0u { ret; }
    log(debug, "an ident: " + vec::pop::<ident>(idents));
    print_idents(idents);
}


/* data structures */

/**********************************************************************/

/* Two different data structures represent constraints in different
 contexts: constraint and norm_constraint.

constraint gets used to record constraints in a table keyed by def_ids.
cinit constraints represent a single constraint, for the initialization
state of a variable; a cpred constraint, with a single operator and a
list of possible argument lists, could represent several constraints at
once.

norm_constraint, in contrast, gets used when handling an instance
of a constraint rather than a definition of a constraint. It can
also be init or pred (ninit or npred), but the npred case just has
a single argument list.

The representation of constraints, where multiple instances of the
same predicate are collapsed into one entry in the table, makes it
easier to look up a specific instance.

Both types are in constrast with the constraint type defined in
syntax::ast, which is for predicate constraints only, and is what
gets generated by the parser. aux and ast share the same type
to represent predicate *arguments* however. This type
(constr_arg_general) is parameterized (see comments in syntax::ast).

Both types store an ident and span, for error-logging purposes.
*/
type pred_args_ = {args: [@constr_arg_use], bit_num: uint};

type pred_args = spanned<pred_args_>;

// The attached node ID is the *defining* node ID
// for this local.
type constr_arg_use = spanned<constr_arg_general_<inst>>;

enum constraint {
    cinit(uint, span, ident),

    // FIXME: really only want it to be mut during collect_locals.
    // freeze it after that.
    cpred(@path, @mut [pred_args]),
}

// An ninit variant has a node_id because it refers to a local var.
// An npred has a def_id since the definition of the typestate
// predicate need not be local.
// FIXME: would be nice to give both a def_id field,
// and give ninit a constraint saying it's local.
enum tsconstr {
    ninit(node_id, ident),
    npred(@path, def_id, [@constr_arg_use]),
}

type sp_constr = spanned<tsconstr>;

type norm_constraint = {bit_num: uint, c: sp_constr};

type constr_map = std::map::hashmap<def_id, constraint>;

/* Contains stuff that has to be computed up front */
/* For easy access, the fn_info stores two special constraints for each
function.  i_return holds if all control paths in this function terminate
in either a return expression, or an appropriate tail expression.
i_diverge holds if all control paths in this function terminate in a fail
or diverging call.

It might be tempting to use a single constraint C for both properties,
where C represents i_return and !C represents i_diverge. This is
inadvisable, because then the sense of the bit depends on context. If we're
inside a ! function, that reverses the sense of the bit: C would be
i_diverge and !C would be i_return.  That's awkward, because we have to
pass extra context around to functions that shouldn't care.

Okay, suppose C represents i_return and !C represents i_diverge, regardless
of context. Consider this code:

if (foo) { ret; } else { fail; }

C is true in the consequent and false in the alternative. What's T `join`
F, then?  ? doesn't work, because this code should definitely-return if the
context is a returning function (and be definitely-rejected if the context
is a ! function).  F doesn't work, because then the code gets incorrectly
rejected if the context is a returning function. T would work, but it
doesn't make sense for T `join` F to be T (consider init constraints, for
example).;

So we need context. And so it seems clearer to just have separate
constraints.
*/
type fn_info =
    /* list, accumulated during pre/postcondition
    computation, of all local variables that may be
    used */
    // Doesn't seem to work without the @ -- bug
    {constrs: constr_map,
     num_constraints: uint,
     cf: ret_style,
     i_return: tsconstr,
     i_diverge: tsconstr,
     used_vars: @mut [node_id]};

fn tsconstr_to_def_id(t: tsconstr) -> def_id {
    alt t { ninit(id, _) { local_def(id) } npred(_, id, _) { id } }
}

fn tsconstr_to_node_id(t: tsconstr) -> node_id {
    alt t {
      ninit(id, _) { id }
      npred(_, id, _) { fail "tsconstr_to_node_id called on pred constraint" }
    }
}

/* mapping from node ID to typestate annotation */
type node_ann_table = @mut [mut ts_ann];


/* mapping from function name to fn_info map */
type fn_info_map = std::map::hashmap<node_id, fn_info>;

type fn_ctxt =
    {enclosing: fn_info, id: node_id, name: ident, ccx: crate_ctxt};

type crate_ctxt = {tcx: ty::ctxt, node_anns: node_ann_table, fm: fn_info_map};

fn get_fn_info(ccx: crate_ctxt, id: node_id) -> fn_info {
    assert (ccx.fm.contains_key(id));
    ret ccx.fm.get(id);
}

fn add_node(ccx: crate_ctxt, i: node_id, a: ts_ann) {
    let sz = vec::len(*ccx.node_anns);
    if sz <= i as uint {
        vec::grow(*ccx.node_anns, (i as uint) - sz + 1u, empty_ann(0u));
    }
    ccx.node_anns[i] = a;
}

fn get_ts_ann(ccx: crate_ctxt, i: node_id) -> option<ts_ann> {
    if i as uint < vec::len(*ccx.node_anns) {
        ret some::<ts_ann>(ccx.node_anns[i]);
    } else { ret none::<ts_ann>; }
}


/********* utils ********/
fn node_id_to_ts_ann(ccx: crate_ctxt, id: node_id) -> ts_ann {
    alt get_ts_ann(ccx, id) {
      none {
        #error("node_id_to_ts_ann: no ts_ann for node_id %d", id);
        fail;
      }
      some(tt) { ret tt; }
    }
}

fn node_id_to_poststate(ccx: crate_ctxt, id: node_id) -> poststate {
    #debug("node_id_to_poststate");
    ret node_id_to_ts_ann(ccx, id).states.poststate;
}

fn stmt_to_ann(ccx: crate_ctxt, s: stmt) -> ts_ann {
    #debug("stmt_to_ann");
    alt s.node {
      stmt_decl(_, id) | stmt_expr(_, id) | stmt_semi(_, id) {
        ret node_id_to_ts_ann(ccx, id);
      }
    }
}


/* fails if e has no annotation */
fn expr_states(ccx: crate_ctxt, e: @expr) -> pre_and_post_state {
    #debug("expr_states");
    ret node_id_to_ts_ann(ccx, e.id).states;
}


/* fails if e has no annotation */
fn expr_pp(ccx: crate_ctxt, e: @expr) -> pre_and_post {
    #debug("expr_pp");
    ret node_id_to_ts_ann(ccx, e.id).conditions;
}

fn stmt_pp(ccx: crate_ctxt, s: stmt) -> pre_and_post {
    ret stmt_to_ann(ccx, s).conditions;
}


/* fails if b has no annotation */
fn block_pp(ccx: crate_ctxt, b: blk) -> pre_and_post {
    #debug("block_pp");
    ret node_id_to_ts_ann(ccx, b.node.id).conditions;
}

fn clear_pp(pp: pre_and_post) {
    ann::clear(pp.precondition);
    ann::clear(pp.postcondition);
}

fn clear_precond(ccx: crate_ctxt, id: node_id) {
    let pp = node_id_to_ts_ann(ccx, id);
    ann::clear(pp.conditions.precondition);
}

fn block_states(ccx: crate_ctxt, b: blk) -> pre_and_post_state {
    #debug("block_states");
    ret node_id_to_ts_ann(ccx, b.node.id).states;
}

fn stmt_states(ccx: crate_ctxt, s: stmt) -> pre_and_post_state {
    ret stmt_to_ann(ccx, s).states;
}

fn expr_precond(ccx: crate_ctxt, e: @expr) -> precond {
    ret expr_pp(ccx, e).precondition;
}

fn expr_postcond(ccx: crate_ctxt, e: @expr) -> postcond {
    ret expr_pp(ccx, e).postcondition;
}

fn expr_prestate(ccx: crate_ctxt, e: @expr) -> prestate {
    ret expr_states(ccx, e).prestate;
}

fn expr_poststate(ccx: crate_ctxt, e: @expr) -> poststate {
    ret expr_states(ccx, e).poststate;
}

fn stmt_precond(ccx: crate_ctxt, s: stmt) -> precond {
    ret stmt_pp(ccx, s).precondition;
}

fn stmt_postcond(ccx: crate_ctxt, s: stmt) -> postcond {
    ret stmt_pp(ccx, s).postcondition;
}

fn states_to_poststate(ss: pre_and_post_state) -> poststate {
    ret ss.poststate;
}

fn stmt_prestate(ccx: crate_ctxt, s: stmt) -> prestate {
    ret stmt_states(ccx, s).prestate;
}

fn stmt_poststate(ccx: crate_ctxt, s: stmt) -> poststate {
    ret stmt_states(ccx, s).poststate;
}

fn block_precond(ccx: crate_ctxt, b: blk) -> precond {
    ret block_pp(ccx, b).precondition;
}

fn block_postcond(ccx: crate_ctxt, b: blk) -> postcond {
    ret block_pp(ccx, b).postcondition;
}

fn block_prestate(ccx: crate_ctxt, b: blk) -> prestate {
    ret block_states(ccx, b).prestate;
}

fn block_poststate(ccx: crate_ctxt, b: blk) -> poststate {
    ret block_states(ccx, b).poststate;
}

fn set_prestate_ann(ccx: crate_ctxt, id: node_id, pre: prestate) -> bool {
    #debug("set_prestate_ann");
    ret set_prestate(node_id_to_ts_ann(ccx, id), pre);
}

fn extend_prestate_ann(ccx: crate_ctxt, id: node_id, pre: prestate) -> bool {
    #debug("extend_prestate_ann");
    ret extend_prestate(node_id_to_ts_ann(ccx, id).states.prestate, pre);
}

fn set_poststate_ann(ccx: crate_ctxt, id: node_id, post: poststate) -> bool {
    #debug("set_poststate_ann");
    ret set_poststate(node_id_to_ts_ann(ccx, id), post);
}

fn extend_poststate_ann(ccx: crate_ctxt, id: node_id, post: poststate) ->
   bool {
    #debug("extend_poststate_ann");
    ret extend_poststate(node_id_to_ts_ann(ccx, id).states.poststate, post);
}

fn set_pre_and_post(ccx: crate_ctxt, id: node_id, pre: precond,
                    post: postcond) {
    #debug("set_pre_and_post");
    let tt = node_id_to_ts_ann(ccx, id);
    set_precondition(tt, pre);
    set_postcondition(tt, post);
}

fn copy_pre_post(ccx: crate_ctxt, id: node_id, sub: @expr) {
    #debug("set_pre_and_post");
    let p = expr_pp(ccx, sub);
    copy_pre_post_(ccx, id, p.precondition, p.postcondition);
}

fn copy_pre_post_(ccx: crate_ctxt, id: node_id, pre: prestate,
                  post: poststate) {
    #debug("set_pre_and_post");
    let tt = node_id_to_ts_ann(ccx, id);
    set_precondition(tt, pre);
    set_postcondition(tt, post);
}

/* sets all bits to *1* */
fn set_postcond_false(ccx: crate_ctxt, id: node_id) {
    let p = node_id_to_ts_ann(ccx, id);
    ann::set(p.conditions.postcondition);
}

fn pure_exp(ccx: crate_ctxt, id: node_id, p: prestate) -> bool {
    ret set_prestate_ann(ccx, id, p) | set_poststate_ann(ccx, id, p);
}

fn num_constraints(m: fn_info) -> uint { ret m.num_constraints; }

fn new_crate_ctxt(cx: ty::ctxt) -> crate_ctxt {
    let na: [mut ts_ann] = [mut];
    ret {tcx: cx, node_anns: @mut na, fm: int_hash::<fn_info>()};
}

/* Use e's type to determine whether it returns.
 If it has a function type with a ! annotation,
the answer is noreturn. */
fn controlflow_expr(ccx: crate_ctxt, e: @expr) -> ret_style {
    alt ty::get(ty::node_id_to_type(ccx.tcx, e.id)).struct {
      ty::ty_fn(f) { ret f.ret_style; }
      _ { ret return_val; }
    }
}

fn constraints_expr(cx: ty::ctxt, e: @expr) -> [@ty::constr] {
    alt ty::get(ty::node_id_to_type(cx, e.id)).struct {
      ty::ty_fn(f) { ret f.constraints; }
      _ { ret []; }
    }
}

fn node_id_to_def_strict(cx: ty::ctxt, id: node_id) -> def {
    alt cx.def_map.find(id) {
      none {
        #error("node_id_to_def: node_id %d has no def", id);
        fail;
      }
      some(d) { ret d; }
    }
}

fn node_id_to_def(ccx: crate_ctxt, id: node_id) -> option<def> {
    ret ccx.tcx.def_map.find(id);
}

fn norm_a_constraint(id: def_id, c: constraint) -> [norm_constraint] {
    alt c {
      cinit(n, sp, i) {
        ret [{bit_num: n, c: respan(sp, ninit(id.node, i))}];
      }
      cpred(p, descs) {
        let mut rslt: [norm_constraint] = [];
        for pd: pred_args in *descs {
            rslt +=
                [{bit_num: pd.node.bit_num,
                  c: respan(pd.span, npred(p, id, pd.node.args))}];
        }
        ret rslt;
      }
    }
}


// Tried to write this as an iterator, but I got a
// non-exhaustive match in trans.
fn constraints(fcx: fn_ctxt) -> [norm_constraint] {
    let mut rslt: [norm_constraint] = [];
    fcx.enclosing.constrs.items {|key, val|
        rslt += norm_a_constraint(key, val);
    };
    ret rslt;
}

// FIXME
// Would rather take an immutable vec as an argument,
// should freeze it at some earlier point.
fn match_args(fcx: fn_ctxt, occs: @mut [pred_args],
              occ: [@constr_arg_use]) -> uint {
    #debug("match_args: looking at %s",
           constr_args_to_str(fn@(i: inst) -> str { ret i.ident; }, occ));
    for pd: pred_args in *occs {
        log(debug,
                 "match_args: candidate " + pred_args_to_str(pd));
        fn eq(p: inst, q: inst) -> bool { ret p.node == q.node; }
        if ty::args_eq(eq, pd.node.args, occ) { ret pd.node.bit_num; }
    }
    fcx.ccx.tcx.sess.bug("match_args: no match for occurring args");
}

fn def_id_for_constr(tcx: ty::ctxt, t: node_id) -> def_id {
    alt tcx.def_map.find(t) {
      none {
        tcx.sess.bug("node_id_for_constr: bad node_id " + int::str(t));
      }
      some(def_fn(i, _)) { ret i; }
      _ { tcx.sess.bug("node_id_for_constr: pred is not a function"); }
    }
}

fn expr_to_constr_arg(tcx: ty::ctxt, e: @expr) -> @constr_arg_use {
    alt e.node {
      expr_path(p) {
        alt tcx.def_map.find(e.id) {
          some(def_local(nid, _)) | some(def_arg(nid, _)) |
          some(def_binding(nid)) | some(def_upvar(nid, _, _)) {
            ret @respan(p.span,
                        carg_ident({ident: p.node.idents[0], node: nid}));
          }
          some(what) {
              tcx.sess.span_bug(e.span,
                 #fmt("exprs_to_constr_args: non-local variable %? \
                                     as pred arg", what));
          }
          none {
              tcx.sess.span_bug(e.span,
                 "exprs_to_constr_args: unbound id as pred arg");

          }
        }
      }
      expr_lit(l) { ret @respan(e.span, carg_lit(l)); }
      _ {
        tcx.sess.span_fatal(e.span,
                            "arguments to constrained functions must be " +
                                "literals or local variables");
      }
    }
}

fn exprs_to_constr_args(tcx: ty::ctxt, args: [@expr]) -> [@constr_arg_use] {
    let f = bind expr_to_constr_arg(tcx, _);
    let mut rslt: [@constr_arg_use] = [];
    for e: @expr in args { rslt += [f(e)]; }
    rslt
}

fn expr_to_constr(tcx: ty::ctxt, e: @expr) -> sp_constr {
    alt e.node {
      expr_call(operator, args, _) {
        alt operator.node {
          expr_path(p) {
            ret respan(e.span,
                       npred(p, def_id_for_constr(tcx, operator.id),
                             exprs_to_constr_args(tcx, args)));
          }
          _ {
            tcx.sess.span_bug(operator.span,
                              "ill-formed operator in predicate");
          }
        }
      }
      _ {
        tcx.sess.span_bug(e.span, "ill-formed predicate");
      }
    }
}

fn pred_args_to_str(p: pred_args) -> str {
    "<" + uint::str(p.node.bit_num) + ", " +
        constr_args_to_str(fn@(i: inst) -> str { ret i.ident; }, p.node.args)
        + ">"
}

fn substitute_constr_args(cx: ty::ctxt, actuals: [@expr], c: @ty::constr) ->
   tsconstr {
    let mut rslt: [@constr_arg_use] = [];
    for a: @constr_arg in c.node.args {
        rslt += [substitute_arg(cx, actuals, a)];
    }
    ret npred(c.node.path, c.node.id, rslt);
}

fn substitute_arg(cx: ty::ctxt, actuals: [@expr], a: @constr_arg) ->
   @constr_arg_use {
    let num_actuals = vec::len(actuals);
    alt a.node {
      carg_ident(i) {
        if i < num_actuals {
            ret expr_to_constr_arg(cx, actuals[i]);
        } else {
            cx.sess.span_fatal(a.span, "constraint argument out of bounds");
        }
      }
      carg_base { ret @respan(a.span, carg_base); }
      carg_lit(l) { ret @respan(a.span, carg_lit(l)); }
    }
}

fn pred_args_matches(pattern: [constr_arg_general_<inst>], desc: pred_args) ->
   bool {
    let mut i = 0u;
    for c: @constr_arg_use in desc.node.args {
        let n = pattern[i];
        alt c.node {
          carg_ident(p) {
            alt n {
              carg_ident(q) { if p.node != q.node { ret false; } }
              _ { ret false; }
            }
          }
          carg_base { if n != carg_base { ret false; } }
          carg_lit(l) {
            alt n {
              carg_lit(m) { if !const_eval::lit_eq(l, m) { ret false; } }
              _ { ret false; }
            }
          }
        }
        i += 1u;
    }
    ret true;
}

fn find_instance_(pattern: [constr_arg_general_<inst>], descs: [pred_args]) ->
   option<uint> {
    for d: pred_args in descs {
        if pred_args_matches(pattern, d) { ret some(d.node.bit_num); }
    }
    ret none;
}

type inst = {ident: ident, node: node_id};
type subst = [{from: inst, to: inst}];

fn find_instances(_fcx: fn_ctxt, subst: subst, c: constraint) ->
   [{from: uint, to: uint}] {

    let mut rslt = [];
    if vec::len(subst) == 0u { ret rslt; }

    alt c {
      cinit(_, _, _) {/* this is dealt with separately */ }
      cpred(p, descs) {
        for d: pred_args in *descs {
            if args_mention(d.node.args, find_in_subst_bool, subst) {
                let old_bit_num = d.node.bit_num;
                let newv = replace(subst, d);
                alt find_instance_(newv, *descs) {
                  some(d1) { rslt += [{from: old_bit_num, to: d1}]; }
                  _ { }
                }
            }
        }
      }
    }
    rslt
}

fn find_in_subst(id: node_id, s: subst) -> option<inst> {
    for p: {from: inst, to: inst} in s {
        if id == p.from.node { ret some(p.to); }
    }
    ret none;
}

fn find_in_subst_bool(s: subst, id: node_id) -> bool {
    is_some(find_in_subst(id, s))
}

fn insts_to_str(stuff: [constr_arg_general_<inst>]) -> str {
    let mut rslt = "<";
    for i: constr_arg_general_<inst> in stuff {
        rslt +=
            " " +
                alt i {
                  carg_ident(p) { p.ident }
                  carg_base { "*" }
                  carg_lit(_) { "[lit]" }
                } + " ";
    }
    rslt += ">";
    rslt
}

fn replace(subst: subst, d: pred_args) -> [constr_arg_general_<inst>] {
    let mut rslt: [constr_arg_general_<inst>] = [];
    for c: @constr_arg_use in d.node.args {
        alt c.node {
          carg_ident(p) {
            alt find_in_subst(p.node, subst) {
              some(newv) { rslt += [carg_ident(newv)]; }
              _ { rslt += [c.node]; }
            }
          }
          _ {
            //  #error("##");
            rslt += [c.node];
          }
        }
    }

    /*
    for (constr_arg_general_<tup(ident, def_id)> p in rslt) {
        alt (p) {
            case (carg_ident(?p)) {
                log(error, p._0);
            }
            case (_) {}
        }
    }
    */

    ret rslt;
}

enum if_ty { if_check, plain_if, }

fn local_node_id_to_def_id_strict(fcx: fn_ctxt, sp: span, i: node_id) ->
   def_id {
    alt local_node_id_to_def(fcx, i) {
      some(def_local(nid, _)) | some(def_arg(nid, _)) |
      some(def_upvar(nid, _, _)) {
        ret local_def(nid);
      }
      some(_) {
        fcx.ccx.tcx.sess.span_fatal(sp,
                                    "local_node_id_to_def_id: id \
               isn't a local");
      }
      none {
        // should really be bug. span_bug()?
        fcx.ccx.tcx.sess.span_fatal(sp,
                                    "local_node_id_to_def_id: id \
               is unbound");
      }
    }
}

fn local_node_id_to_def(fcx: fn_ctxt, i: node_id) -> option<def> {
    fcx.ccx.tcx.def_map.find(i)
}

fn local_node_id_to_def_id(fcx: fn_ctxt, i: node_id) -> option<def_id> {
    alt local_node_id_to_def(fcx, i) {
      some(def_local(nid, _)) | some(def_arg(nid, _)) |
      some(def_binding(nid)) | some(def_upvar(nid, _, _)) {
        some(local_def(nid))
      }
      _ { none }
    }
}

fn local_node_id_to_local_def_id(fcx: fn_ctxt, i: node_id) ->
   option<node_id> {
    alt local_node_id_to_def_id(fcx, i) {
      some(did) { some(did.node) }
      _ { none }
    }
}

fn copy_in_postcond(fcx: fn_ctxt, parent_exp: node_id, dest: inst, src: inst,
                    ty: oper_type) {
    let post =
        node_id_to_ts_ann(fcx.ccx, parent_exp).conditions.postcondition;
    copy_in_poststate_two(fcx, post, post, dest, src, ty);
}

// FIXME refactor
fn copy_in_poststate(fcx: fn_ctxt, post: poststate, dest: inst, src: inst,
                     ty: oper_type) {
    copy_in_poststate_two(fcx, post, post, dest, src, ty);
}

// In target_post, set the bits corresponding to copies of any
// constraints mentioning src that are set in src_post, with
// dest substituted for src.
// (This doesn't create any new constraints. If a new, substituted
// constraint isn't already in the bit vector, it's ignored.)
fn copy_in_poststate_two(fcx: fn_ctxt, src_post: poststate,
                         target_post: poststate, dest: inst, src: inst,
                         ty: oper_type) {
    let mut subst;
    alt ty {
      oper_swap { subst = [{from: dest, to: src}, {from: src, to: dest}]; }
      oper_assign_op {
        ret; // Don't do any propagation
      }
      _ { subst = [{from: src, to: dest}]; }
    }


    fcx.enclosing.constrs.values {|val|
        // replace any occurrences of the src def_id with the
        // dest def_id
        let insts = find_instances(fcx, subst, val);
        for p: {from: uint, to: uint} in insts {
            if promises_(p.from, src_post) {
                set_in_poststate_(p.to, target_post);
            }
        }
    };
}

/* FIXME should refactor this better */
fn forget_in_postcond(fcx: fn_ctxt, parent_exp: node_id, dead_v: node_id) {
    // In the postcondition given by parent_exp, clear the bits
    // for any constraints mentioning dead_v
    let d = local_node_id_to_local_def_id(fcx, dead_v);
    alt d {
      some(d_id) {
        for c: norm_constraint in constraints(fcx) {
            if constraint_mentions(fcx, c, d_id) {
                #debug("clearing constraint %u %s",
                       c.bit_num,
                       constraint_to_str(fcx.ccx.tcx, c.c));
                clear_in_postcond(c.bit_num,
                                  node_id_to_ts_ann(fcx.ccx,
                                                    parent_exp).conditions);
            }
        }
      }
      _ { }
    }
}

fn forget_in_postcond_still_init(fcx: fn_ctxt, parent_exp: node_id,
                                 dead_v: node_id) {
    // In the postcondition given by parent_exp, clear the bits
    // for any constraints mentioning dead_v
    let d = local_node_id_to_local_def_id(fcx, dead_v);
    alt d {
      some(d_id) {
        for c: norm_constraint in constraints(fcx) {
            if non_init_constraint_mentions(fcx, c, d_id) {
                clear_in_postcond(c.bit_num,
                                  node_id_to_ts_ann(fcx.ccx,
                                                    parent_exp).conditions);
            }
        }
      }
      _ { }
    }
}

fn forget_in_poststate(fcx: fn_ctxt, p: poststate, dead_v: node_id) -> bool {
    // In the poststate given by parent_exp, clear the bits
    // for any constraints mentioning dead_v
    let d = local_node_id_to_local_def_id(fcx, dead_v);
    let mut changed = false;
    alt d {
      some(d_id) {
        for c: norm_constraint in constraints(fcx) {
            if constraint_mentions(fcx, c, d_id) {
                changed |= clear_in_poststate_(c.bit_num, p);
            }
        }
      }
      _ { }
    }
    ret changed;
}

fn forget_in_poststate_still_init(fcx: fn_ctxt, p: poststate, dead_v: node_id)
   -> bool {
    // In the poststate given by parent_exp, clear the bits
    // for any constraints mentioning dead_v
    let d = local_node_id_to_local_def_id(fcx, dead_v);
    let mut changed = false;
    alt d {
      some(d_id) {
        for c: norm_constraint in constraints(fcx) {
            if non_init_constraint_mentions(fcx, c, d_id) {
                changed |= clear_in_poststate_(c.bit_num, p);
            }
        }
      }
      _ { }
    }
    ret changed;
}

fn any_eq(v: [node_id], d: node_id) -> bool {
    for i: node_id in v { if i == d { ret true; } }
    false
}

fn constraint_mentions(_fcx: fn_ctxt, c: norm_constraint, v: node_id) ->
   bool {
    ret alt c.c.node {
          ninit(id, _) { v == id }
          npred(_, _, args) { args_mention(args, any_eq, [v]) }
        };
}

fn non_init_constraint_mentions(_fcx: fn_ctxt, c: norm_constraint, v: node_id)
   -> bool {
    ret alt c.c.node {
          ninit(_, _) { false }
          npred(_, _, args) { args_mention(args, any_eq, [v]) }
        };
}

fn args_mention<T>(args: [@constr_arg_use],
                   q: fn([T], node_id) -> bool,
                   s: [T]) -> bool {
    /*
      FIXME
      The following version causes an assertion in trans to fail
      (something about type_is_tup_like)
    fn mentions<T>(&[T] s, &fn(&[T], def_id) -> bool q,
                            &@constr_arg_use a) -> bool {
        alt (a.node) {
            case (carg_ident(?p1)) {
                auto res = q(s, p1._1);
                log(error, (res));
                res
                    }
            case (_)               { false }
        }
    }
    ret vec::any(bind mentions(s,q,_), args);
    */

    for a: @constr_arg_use in args {
        alt a.node { carg_ident(p1) { if q(s, p1.node) { ret true; } } _ { } }
    }
    ret false;
}

fn use_var(fcx: fn_ctxt, v: node_id) { *fcx.enclosing.used_vars += [v]; }

// FIXME: This should be a function in vec::.
fn vec_contains(v: @mut [node_id], i: node_id) -> bool {
    for d: node_id in *v { if d == i { ret true; } }
    ret false;
}

fn op_to_oper_ty(io: init_op) -> oper_type {
    alt io { init_move { oper_move } _ { oper_assign } }
}

// default function visitor
fn do_nothing<T>(_fk: visit::fn_kind, _decl: fn_decl, _body: blk,
                 _sp: span, _id: node_id,
                 _t: T, _v: visit::vt<T>) {
}


fn args_to_constr_args(tcx: ty::ctxt, args: [arg],
                       indices: [@sp_constr_arg<uint>]) -> [@constr_arg_use] {
    let mut actuals: [@constr_arg_use] = [];
    let num_args = vec::len(args);
    for a: @sp_constr_arg<uint> in indices {
        actuals +=
            [@respan(a.span,
                     alt a.node {
                       carg_base { carg_base }
                       carg_ident(i) {
                         if i < num_args {
                             carg_ident({ident: args[i].ident,
                                         node: args[i].id})
                         } else {
                             tcx.sess.span_bug(a.span,
                                               "index out of bounds in \
                  constraint arg");
                         }
                       }
                       carg_lit(l) { carg_lit(l) }
                     })];
    }
    ret actuals;
}

fn ast_constr_to_ts_constr(tcx: ty::ctxt, args: [arg], c: @constr) ->
   tsconstr {
    let tconstr = ty::ast_constr_to_constr(tcx, c);
    ret npred(tconstr.node.path, tconstr.node.id,
              args_to_constr_args(tcx, args, tconstr.node.args));
}

fn ast_constr_to_sp_constr(tcx: ty::ctxt, args: [arg], c: @constr) ->
   sp_constr {
    let tconstr = ast_constr_to_ts_constr(tcx, args, c);
    ret respan(c.span, tconstr);
}

type binding = {lhs: [inst], rhs: option<initializer>};

fn local_to_bindings(tcx: ty::ctxt, loc: @local) -> binding {
    let mut lhs = [];
    pat_bindings(tcx.def_map, loc.node.pat) {|p_id, _s, name|
        lhs += [{ident: path_to_ident(name), node: p_id}];
    };
    {lhs: lhs, rhs: loc.node.init}
}

fn locals_to_bindings(tcx: ty::ctxt, locals: [@local]) -> [binding] {
    let mut rslt = [];
    for loc in locals { rslt += [local_to_bindings(tcx, loc)]; }
    ret rslt;
}

fn callee_modes(fcx: fn_ctxt, callee: node_id) -> [mode] {
    let ty = ty::type_autoderef(fcx.ccx.tcx,
                                ty::node_id_to_type(fcx.ccx.tcx, callee));
    alt ty::get(ty).struct {
      ty::ty_fn({inputs: args, _}) {
        let mut modes = [];
        for arg: ty::arg in args { modes += [arg.mode]; }
        ret modes;
      }
      _ {
        // Shouldn't happen; callee should be ty_fn.
        fcx.ccx.tcx.sess.bug("non-fn callee type in callee_modes: " +
                                 util::ppaux::ty_to_str(fcx.ccx.tcx, ty));
      }
    }
}

fn callee_arg_init_ops(fcx: fn_ctxt, callee: node_id) -> [init_op] {
    vec::map(callee_modes(fcx, callee)) {|m|
        alt ty::resolved_mode(fcx.ccx.tcx, m) {
          by_move { init_move }
          by_copy | by_ref | by_val | by_mutbl_ref { init_assign }
        }
    }
}

fn anon_bindings(ops: [init_op], es: [@expr]) -> [binding] {
    let mut bindings: [binding] = [];
    let mut i = 0;
    for op: init_op in ops {
        bindings += [{lhs: [], rhs: some({op: op, expr: es[i]})}];
        i += 1;
    }
    ret bindings;
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//