aboutsummaryrefslogtreecommitdiff
path: root/paludis/resolver/decider.cc
blob: 809e305b3c1483512253248d1206b98fdd30232c (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
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
/* vim: set sw=4 sts=4 et foldmethod=syntax : */

/*
 * Copyright (c) 2009, 2010 Ciaran McCreesh
 *
 * This file is part of the Paludis package manager. Paludis is free software;
 * you can redistribute it and/or modify it under the terms of the GNU General
 * Public License version 2, as published by the Free Software Foundation.
 *
 * Paludis 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 General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <paludis/resolver/decider.hh>
#include <paludis/resolver/resolver_functions.hh>
#include <paludis/resolver/spec_rewriter.hh>
#include <paludis/resolver/resolvent.hh>
#include <paludis/resolver/resolution.hh>
#include <paludis/resolver/constraint.hh>
#include <paludis/resolver/decision.hh>
#include <paludis/resolver/destination.hh>
#include <paludis/resolver/resolutions_by_resolvent.hh>
#include <paludis/resolver/suggest_restart.hh>
#include <paludis/resolver/reason.hh>
#include <paludis/resolver/unsuitable_candidates.hh>
#include <paludis/resolver/resolver.hh>
#include <paludis/resolver/required_confirmations.hh>
#include <paludis/util/exception.hh>
#include <paludis/util/stringify.hh>
#include <paludis/util/make_named_values.hh>
#include <paludis/util/make_shared_ptr.hh>
#include <paludis/util/wrapped_forward_iterator.hh>
#include <paludis/util/wrapped_output_iterator.hh>
#include <paludis/util/enum_iterator.hh>
#include <paludis/util/indirect_iterator-impl.hh>
#include <paludis/util/tribool.hh>
#include <paludis/environment.hh>
#include <paludis/notifier_callback.hh>
#include <paludis/repository.hh>
#include <paludis/filtered_generator.hh>
#include <paludis/package_database.hh>
#include <paludis/metadata_key.hh>
#include <paludis/generator.hh>
#include <paludis/selection.hh>
#include <paludis/filter.hh>
#include <paludis/match_package.hh>
#include <paludis/version_requirements.hh>
#include <paludis/slot_requirement.hh>
#include <paludis/choice.hh>
#include <paludis/action.hh>
#include <paludis/elike_slot_requirement.hh>

#include <paludis/util/private_implementation_pattern-impl.hh>

#include <algorithm>
#include <map>
#include <set>

using namespace paludis;
using namespace paludis::resolver;

namespace paludis
{
    template <>
    struct Implementation<Decider>
    {
        const Environment * const env;
        const ResolverFunctions fns;
        SpecRewriter rewriter;

        const std::tr1::shared_ptr<ResolutionsByResolvent> resolutions_by_resolvent;

        Implementation(const Environment * const e, const ResolverFunctions & f,
                const std::tr1::shared_ptr<ResolutionsByResolvent> & l) :
            env(e),
            fns(f),
            rewriter(env),
            resolutions_by_resolvent(l)
        {
        }
    };
}

Decider::Decider(const Environment * const e, const ResolverFunctions & f,
        const std::tr1::shared_ptr<ResolutionsByResolvent> & l) :
    PrivateImplementationPattern<Decider>(new Implementation<Decider>(e, f, l))
{
}

Decider::~Decider()
{
}

void
Decider::_resolve_decide_with_dependencies()
{
    Context context("When resolving and adding dependencies recursively:");

    enum State { deciding_non_suggestions, deciding_suggestions, finished } state = deciding_non_suggestions;
    bool changed(true);
    while (true)
    {
        if (! changed)
            state = State(state + 1);
        if (state == finished)
            break;

        changed = false;
        for (ResolutionsByResolvent::ConstIterator i(_imp->resolutions_by_resolvent->begin()),
                i_end(_imp->resolutions_by_resolvent->end()) ;
                i != i_end ; ++i)
        {
            /* we've already decided */
            if ((*i)->decision())
                continue;

            /* we're only being suggested. don't do this on the first pass, so
             * we don't have to do restarts for suggestions later becoming hard
             * deps. */
            if (state == deciding_non_suggestions && (*i)->constraints()->all_untaken())
                continue;

            _imp->env->trigger_notifier_callback(NotifierCallbackResolverStepEvent());

            changed = true;
            _decide(*i);

            _add_dependencies_if_necessary(*i);
        }
    }
}

bool
Decider::_resolve_dependents()
{
    Context context("When finding dependents:");

    bool changed(false);
    const std::pair<
        std::tr1::shared_ptr<const PackageIDSequence>,
        std::tr1::shared_ptr<const PackageIDSequence> > changing(_collect_changing());

    if (changing.first->empty())
        return false;

    const std::tr1::shared_ptr<const PackageIDSequence> staying(_collect_staying(changing.first));

    for (PackageIDSequence::ConstIterator s(staying->begin()), s_end(staying->end()) ;
            s != s_end ; ++s)
    {
        _imp->env->trigger_notifier_callback(NotifierCallbackResolverStepEvent());

        const std::tr1::shared_ptr<const PackageIDSequence> dependent_upon(_dependent_upon(
                    *s, changing.first, changing.second));
        if (dependent_upon->empty())
            continue;

        Resolvent resolvent(*s, dt_install_to_slash);
        bool remove(_remove_if_dependent(*s));

        /* we've changed things if we've not already done anything for this
         * resolvent, but only if we're going to remove it rather than mark it
         * as broken */
        if (remove && _imp->resolutions_by_resolvent->end() == _imp->resolutions_by_resolvent->find(resolvent))
            changed = true;

        const std::tr1::shared_ptr<Resolution> resolution(_resolution_for_resolvent(resolvent, true));
        const std::tr1::shared_ptr<const ConstraintSequence> constraints(_make_constraints_for_dependent(
                    resolution, *s, dependent_upon));
        for (ConstraintSequence::ConstIterator c(constraints->begin()), c_end(constraints->end()) ;
                c != c_end ; ++c)
            _apply_resolution_constraint(resolution, *c);

        if ((! remove) && (! resolution->decision()))
            resolution->decision() = make_shared_ptr(new BreakDecision(
                        resolvent,
                        *s,
                        true));
    }

    return changed;
}

const std::tr1::shared_ptr<ConstraintSequence>
Decider::_make_constraints_for_dependent(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const std::tr1::shared_ptr<const PackageID> & id,
        const std::tr1::shared_ptr<const PackageIDSequence> & r) const
{
    return _imp->fns.get_constraints_for_dependent_fn()(resolution, id, r);
}

namespace
{
    struct DependentChecker
    {
        const Environment * const env;
        const std::tr1::shared_ptr<const PackageIDSequence> going_away;
        const std::tr1::shared_ptr<const PackageIDSequence> newly_available;
        const std::tr1::shared_ptr<PackageIDSequence> result;

        DependentChecker(
                const Environment * const e,
                const std::tr1::shared_ptr<const PackageIDSequence> & g,
                const std::tr1::shared_ptr<const PackageIDSequence> & n) :
            env(e),
            going_away(g),
            newly_available(n),
            result(new PackageIDSequence)
        {
        }

        void visit(const DependencySpecTree::NodeType<NamedSetDepSpec>::Type & s)
        {
            const std::tr1::shared_ptr<const SetSpecTree> set(env->set(s.spec()->name()));
            set->root()->accept(*this);
        }

        void visit(const DependencySpecTree::NodeType<PackageDepSpec>::Type & s)
        {
            for (PackageIDSequence::ConstIterator g(going_away->begin()), g_end(going_away->end()) ;
                    g != g_end ; ++g)
            {
                if (! match_package(*env, *s.spec(), **g, MatchPackageOptions()))
                    continue;

                if (indirect_iterator(newly_available->end()) == std::find_if(
                            indirect_iterator(newly_available->begin()), indirect_iterator(newly_available->end()),
                            std::tr1::bind(&match_package, std::tr1::cref(*env), std::tr1::cref(*s.spec()),
                                std::tr1::placeholders::_1, MatchPackageOptions())))
                    result->push_back(*g);
            }
        }

        void visit(const DependencySpecTree::NodeType<BlockDepSpec>::Type &)
        {
        }

        void visit(const DependencySpecTree::NodeType<ConditionalDepSpec>::Type & s)
        {
            if (s.spec()->condition_met())
                std::for_each(indirect_iterator(s.begin()), indirect_iterator(s.end()),
                        accept_visitor(*this));
        }

        void visit(const DependencySpecTree::NodeType<AnyDepSpec>::Type & s)
        {
            std::for_each(indirect_iterator(s.begin()), indirect_iterator(s.end()),
                    accept_visitor(*this));
        }

        void visit(const DependencySpecTree::NodeType<AllDepSpec>::Type & s)
        {
            std::for_each(indirect_iterator(s.begin()), indirect_iterator(s.end()),
                    accept_visitor(*this));
        }

        void visit(const DependencySpecTree::NodeType<DependenciesLabelsDepSpec>::Type &)
        {
        }
    };
}

const std::tr1::shared_ptr<const PackageIDSequence>
Decider::_dependent_upon(
        const std::tr1::shared_ptr<const PackageID> & id,
        const std::tr1::shared_ptr<const PackageIDSequence> & going_away,
        const std::tr1::shared_ptr<const PackageIDSequence> & staying) const
{
    DependentChecker c(_imp->env, going_away, staying);
    if (id->dependencies_key())
        id->dependencies_key()->value()->root()->accept(c);
    else
    {
        if (id->build_dependencies_key())
            id->build_dependencies_key()->value()->root()->accept(c);
        if (id->run_dependencies_key())
            id->run_dependencies_key()->value()->root()->accept(c);
        if (id->post_dependencies_key())
            id->post_dependencies_key()->value()->root()->accept(c);
        if (id->suggested_dependencies_key())
            id->suggested_dependencies_key()->value()->root()->accept(c);
    }

    return c.result;
}

namespace
{
    struct ChangingCollector
    {
        std::tr1::shared_ptr<PackageIDSequence> going_away;
        std::tr1::shared_ptr<PackageIDSequence> newly_available;

        ChangingCollector() :
            going_away(new PackageIDSequence),
            newly_available(new PackageIDSequence)
        {
        }

        void visit(const NothingNoChangeDecision &)
        {
        }

        void visit(const ExistingNoChangeDecision &)
        {
        }

        void visit(const RemoveDecision & d)
        {
            std::copy(d.ids()->begin(), d.ids()->end(), going_away->back_inserter());
        }

        void visit(const ChangesToMakeDecision & d)
        {
            std::copy(d.destination()->replacing()->begin(), d.destination()->replacing()->end(),
                    going_away->back_inserter());
            newly_available->push_back(d.origin_id());
        }

        void visit(const UnableToMakeDecision &)
        {
        }

        void visit(const BreakDecision &)
        {
        }
    };
}

const std::pair<
    std::tr1::shared_ptr<const PackageIDSequence>,
    std::tr1::shared_ptr<const PackageIDSequence> >
Decider::_collect_changing() const
{
    ChangingCollector c;

    for (ResolutionsByResolvent::ConstIterator i(_imp->resolutions_by_resolvent->begin()),
            i_end(_imp->resolutions_by_resolvent->end()) ;
            i != i_end ; ++i)
        if ((*i)->decision())
            (*i)->decision()->accept(c);

    return std::make_pair(c.going_away, c.newly_available);
}

const std::tr1::shared_ptr<const PackageIDSequence>
Decider::_collect_staying(const std::tr1::shared_ptr<const PackageIDSequence> & going_away) const
{
    const std::tr1::shared_ptr<const PackageIDSequence> existing((*_imp->env)[selection::AllVersionsUnsorted(
                generator::All() | filter::InstalledAtRoot(FSEntry("/")))]);

    const std::tr1::shared_ptr<PackageIDSequence> result(new PackageIDSequence);
    for (PackageIDSequence::ConstIterator x(existing->begin()), x_end(existing->end()) ;
            x != x_end ; ++x)
        if (indirect_iterator(going_away->end()) == std::find(indirect_iterator(going_away->begin()),
                    indirect_iterator(going_away->end()), **x))
            result->push_back(*x);

    return result;
}

void
Decider::_resolve_confirmations()
{
    Context context("When resolving confirmations:");

    for (ResolutionsByResolvent::ConstIterator i(_imp->resolutions_by_resolvent->begin()),
            i_end(_imp->resolutions_by_resolvent->end()) ;
            i != i_end ; ++i)
        _confirm(*i);
}

void
Decider::_fixup_changes_to_make_decision(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        ChangesToMakeDecision & decision) const
{
    decision.set_destination(_make_destination_for(resolution, decision));
    decision.set_change_type(_make_change_type_for(resolution, decision));
}

const std::tr1::shared_ptr<Destination>
Decider::_make_destination_for(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const ChangesToMakeDecision & decision) const
{
    const std::tr1::shared_ptr<const Repository> repo(_find_repository_for(resolution, decision));
    if ((! repo->destination_interface()) ||
            (! repo->destination_interface()->is_suitable_destination_for(*decision.origin_id())))
        throw InternalError(PALUDIS_HERE, stringify(repo->name()) + " is not a suitable destination for "
                + stringify(*decision.origin_id()));

    return make_shared_ptr(new Destination(make_named_values<Destination>(
                    n::replacing() = _find_replacing(decision.origin_id(), repo),
                    n::repository() = repo->name()
                    )));
}

const ChangeType
Decider::_make_change_type_for(
        const std::tr1::shared_ptr<const Resolution> &,
        const ChangesToMakeDecision & decision) const
{
    if (decision.destination()->replacing()->empty())
    {
        const std::tr1::shared_ptr<const PackageIDSequence> others((*_imp->env)[selection::SomeArbitraryVersion(
                    generator::Package(decision.origin_id()->name()) &
                    generator::InRepository(decision.destination()->repository())
                    )]);
        if (others->empty())
            return ct_new;
        else
            return ct_slot_new;
    }
    else
    {
        /* we pick the worst, so replacing 1 and 3 with 2 requires permission to
         * downgrade */
        ChangeType result(last_ct);
        for (PackageIDSequence::ConstIterator i(decision.destination()->replacing()->begin()),
                i_end(decision.destination()->replacing()->end()) ;
                i != i_end ; ++i)
        {
            if ((*i)->version() == decision.origin_id()->version())
                result = std::min(result, ct_reinstall);
            else if ((*i)->version() < decision.origin_id()->version())
                result = std::min(result, ct_upgrade);
            else if ((*i)->version() > decision.origin_id()->version())
                result = std::min(result, ct_downgrade);
        }

        return result;
    }
}

const std::tr1::shared_ptr<const Repository>
Decider::_find_repository_for(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const ChangesToMakeDecision & decision) const
{
    return _imp->fns.find_repository_for_fn()(resolution, decision);
}

FilteredGenerator
Decider::_make_destination_filtered_generator(const Generator & g, const Resolvent & resolvent) const
{
    return _imp->fns.make_destination_filtered_generator_fn()(g, resolvent);
}

const std::tr1::shared_ptr<const PackageIDSequence>
Decider::_find_replacing(
        const std::tr1::shared_ptr<const PackageID> & id,
        const std::tr1::shared_ptr<const Repository> & repo) const
{
    Context context("When working out what is replaced by '" + stringify(*id) +
            "' when it is installed to '" + stringify(repo->name()) + "':");

    std::set<RepositoryName> repos;

    if (repo->installed_root_key())
    {
        for (PackageDatabase::RepositoryConstIterator r(_imp->env->package_database()->begin_repositories()),
                r_end(_imp->env->package_database()->end_repositories()) ;
                r != r_end ; ++r)
            if ((*r)->installed_root_key() &&
                    (*r)->installed_root_key()->value() == repo->installed_root_key()->value())
                repos.insert((*r)->name());
    }
    else
        repos.insert(repo->name());

    std::tr1::shared_ptr<PackageIDSequence> result(new PackageIDSequence);
    for (std::set<RepositoryName>::const_iterator r(repos.begin()),
            r_end(repos.end()) ;
            r != r_end ; ++r)
    {
        std::tr1::shared_ptr<const PackageIDSequence> ids((*_imp->env)[selection::AllVersionsUnsorted(
                    generator::Package(id->name()) & generator::InRepository(*r))]);
        for (PackageIDSequence::ConstIterator i(ids->begin()), i_end(ids->end()) ;
                i != i_end ; ++i)
        {
            if ((*i)->version() == id->version() || _same_slot(*i, id))
                result->push_back(*i);
        }
    }

    return result;
}

bool
Decider::_same_slot(const std::tr1::shared_ptr<const PackageID> & a,
        const std::tr1::shared_ptr<const PackageID> & b) const
{
    if (a->slot_key())
        return b->slot_key() && a->slot_key()->value() == b->slot_key()->value();
    else
        return ! b->slot_key();
}

const std::tr1::shared_ptr<Resolution>
Decider::_create_resolution_for_resolvent(const Resolvent & r) const
{
    return make_shared_ptr(new Resolution(make_named_values<Resolution>(
                    n::constraints() = _initial_constraints_for(r),
                    n::decision() = make_null_shared_ptr(),
                    n::resolvent() = r
                    )));
}

const std::tr1::shared_ptr<Resolution>
Decider::_resolution_for_resolvent(const Resolvent & r, const bool create)
{
    ResolutionsByResolvent::ConstIterator i(_imp->resolutions_by_resolvent->find(r));
    if (_imp->resolutions_by_resolvent->end() == i)
    {
        if (create)
        {
            std::tr1::shared_ptr<Resolution> resolution(_create_resolution_for_resolvent(r));
            i = _imp->resolutions_by_resolvent->insert_new(resolution);
        }
        else
            throw InternalError(PALUDIS_HERE, "resolver bug: expected resolution for "
                    + stringify(r) + " to exist, but it doesn't");
    }

    return *i;
}

const std::tr1::shared_ptr<ConstraintSequence>
Decider::_make_constraints_from_target(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const PackageOrBlockDepSpec & spec,
        const std::tr1::shared_ptr<const Reason> & reason) const
{
    if (spec.if_package())
    {
        const std::tr1::shared_ptr<ConstraintSequence> result(new ConstraintSequence);
        result->push_back(make_shared_ptr(new Constraint(make_named_values<Constraint>(
                            n::destination_type() = resolution->resolvent().destination_type(),
                            n::nothing_is_fine_too() = false,
                            n::reason() = reason,
                            n::spec() = spec,
                            n::untaken() = false,
                            n::use_existing() = _imp->fns.get_use_existing_fn()(resolution, *spec.if_package(), reason)
                            ))));
        return result;
    }
    else if (spec.if_block())
        return _make_constraints_from_blocker(resolution, *spec.if_block(), reason);
    else
        throw InternalError(PALUDIS_HERE, "resolver bug: huh? it's not a block and it's not a package");
}

const std::tr1::shared_ptr<ConstraintSequence>
Decider::_make_constraints_from_dependency(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const SanitisedDependency & dep,
        const std::tr1::shared_ptr<const Reason> & reason,
        const SpecInterest interest) const
{
    if (dep.spec().if_package())
    {
        const std::tr1::shared_ptr<ConstraintSequence> result(new ConstraintSequence);
        result->push_back(make_shared_ptr(new Constraint(make_named_values<Constraint>(
                            n::destination_type() = resolution->resolvent().destination_type(),
                            n::nothing_is_fine_too() = false,
                            n::reason() = reason,
                            n::spec() = *dep.spec().if_package(),
                            n::untaken() = si_untaken == interest,
                            n::use_existing() = _imp->fns.get_use_existing_fn()(resolution, *dep.spec().if_package(), reason)
                            ))));
        return result;
    }
    else if (dep.spec().if_block())
        return _make_constraints_from_blocker(resolution, *dep.spec().if_block(), reason);
    else
        throw InternalError(PALUDIS_HERE, "resolver bug: huh? it's not a block and it's not a package");
}

const std::tr1::shared_ptr<ConstraintSequence>
Decider::_make_constraints_from_blocker(
        const std::tr1::shared_ptr<const Resolution> &,
        const BlockDepSpec & spec,
        const std::tr1::shared_ptr<const Reason> & reason) const
{
    const std::tr1::shared_ptr<ConstraintSequence> result(new ConstraintSequence);

    DestinationTypes destination_types(_get_destination_types_for_blocker(spec));
    for (EnumIterator<DestinationType> t, t_end(last_dt) ; t != t_end ; ++t)
        if (destination_types[*t])
            result->push_back(make_shared_ptr(new Constraint(make_named_values<Constraint>(
                                n::destination_type() = *t,
                                n::nothing_is_fine_too() = true,
                                n::reason() = reason,
                                n::spec() = spec,
                                n::untaken() = false,
                                n::use_existing() = ue_if_possible
                                ))));

    return result;
}

void
Decider::_apply_resolution_constraint(
        const std::tr1::shared_ptr<Resolution> & resolution,
        const std::tr1::shared_ptr<const Constraint> & constraint)
{
    if (resolution->decision())
        if (! _verify_new_constraint(resolution, constraint))
            _made_wrong_decision(resolution, constraint);

    resolution->constraints()->add(constraint);
}

namespace
{
    struct CheckConstraintVisitor
    {
        const Environment * const env;
        const Constraint constraint;

        CheckConstraintVisitor(const Environment * const e, const Constraint & c) :
            env(e),
            constraint(c)
        {
        }

        bool ok(const std::tr1::shared_ptr<const PackageID> & chosen_id) const
        {
            if (constraint.spec().if_package())
            {
                if (! match_package(*env, *constraint.spec().if_package(), *chosen_id, MatchPackageOptions()))
                    return false;
            }
            else
            {
                if (match_package(*env, constraint.spec().if_block()->blocking(),
                            *chosen_id, MatchPackageOptions()))
                    return false;
            }

            return true;
        }

        bool visit(const ChangesToMakeDecision & decision) const
        {
            return ok(decision.origin_id());
        }

        bool visit(const ExistingNoChangeDecision & decision) const
        {
            return ok(decision.existing_id());
        }

        bool visit(const NothingNoChangeDecision &) const
        {
            return constraint.nothing_is_fine_too();
        }

        bool visit(const UnableToMakeDecision &) const
        {
            return true;
        }

        bool visit(const RemoveDecision &) const
        {
            return constraint.nothing_is_fine_too();
        }

        bool visit(const BreakDecision &) const
        {
            return true;
        }
    };

    struct CheckUseExistingVisitor
    {
        const std::tr1::shared_ptr<const Constraint> constraint;

        CheckUseExistingVisitor(const std::tr1::shared_ptr<const Constraint> & c) :
            constraint(c)
        {
        }

        bool visit(const ExistingNoChangeDecision & decision) const
        {
            switch (constraint->use_existing())
            {
                case ue_if_possible:
                    break;

                case ue_only_if_transient:
                    if (! decision.is_transient())
                        return false;
                    break;

                case ue_if_same:
                    if (! decision.is_same())
                        return false;
                    break;

                case ue_if_same_version:
                    if (! decision.is_same_version())
                        return false;
                    break;

                case ue_never:
                case last_ue:
                    return false;
            }

            return true;
        }

        bool visit(const NothingNoChangeDecision &) const
        {
            return true;
        }

        bool visit(const UnableToMakeDecision &) const
        {
            return true;
        }

        bool visit(const ChangesToMakeDecision &) const
        {
            return true;
        }

        bool visit(const RemoveDecision &) const
        {
            return true;
        }

        bool visit(const BreakDecision &) const
        {
            return true;
        }
    };
}

bool
Decider::_check_constraint(
        const std::tr1::shared_ptr<const Constraint> & constraint,
        const std::tr1::shared_ptr<const Decision> & decision) const
{
    if (! decision->accept_returning<bool>(CheckConstraintVisitor(_imp->env, *constraint)))
        return false;

    if (! decision->accept_returning<bool>(CheckUseExistingVisitor(constraint)))
        return false;

    if (! constraint->untaken())
    {
        if (! decision->taken())
            return false;
    }

    return true;
}

bool
Decider::_verify_new_constraint(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const std::tr1::shared_ptr<const Constraint> & constraint)
{
    return _check_constraint(constraint, resolution->decision());
}

namespace
{
    struct WrongDecisionVisitor
    {
        std::tr1::function<void ()> restart;

        WrongDecisionVisitor(const std::tr1::function<void ()> & r) :
            restart(r)
        {
        }

        void visit(const NothingNoChangeDecision &) const
        {
            /* going from nothing to something is fine */
        }

        void visit(const RemoveDecision &) const
        {
            restart();
        }

        void visit(const UnableToMakeDecision &) const
        {
            restart();
        }

        void visit(const ChangesToMakeDecision &) const
        {
            restart();
        }

        void visit(const ExistingNoChangeDecision &) const
        {
            restart();
        }

        void visit(const BreakDecision &) const PALUDIS_ATTRIBUTE((noreturn))
        {
            throw InternalError(PALUDIS_HERE, "why are we trying to go from a BreakDecision to something else?");
        }
    };
}

void
Decider::_made_wrong_decision(
        const std::tr1::shared_ptr<Resolution> & resolution,
        const std::tr1::shared_ptr<const Constraint> & constraint)
{
    /* can we find a resolution that works for all our constraints? */
    std::tr1::shared_ptr<Resolution> adapted_resolution(make_shared_ptr(new Resolution(*resolution)));
    adapted_resolution->constraints()->add(constraint);

    const std::tr1::shared_ptr<Decision> decision(_try_to_find_decision_for(adapted_resolution));
    if (decision)
    {
        resolution->decision()->accept(WrongDecisionVisitor(std::tr1::bind(
                        &Decider::_suggest_restart_with, this, resolution, constraint, decision)));
        resolution->decision() = decision;
    }
    else
        resolution->decision() = _cannot_decide_for(adapted_resolution);
}

void
Decider::_suggest_restart_with(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const std::tr1::shared_ptr<const Constraint> & constraint,
        const std::tr1::shared_ptr<const Decision> & decision) const
{
    throw SuggestRestart(resolution->resolvent(), resolution->decision(), constraint, decision,
            _make_constraint_for_preloading(decision, constraint));
}

const std::tr1::shared_ptr<const Constraint>
Decider::_make_constraint_for_preloading(
        const std::tr1::shared_ptr<const Decision> &,
        const std::tr1::shared_ptr<const Constraint> & c) const
{
    const std::tr1::shared_ptr<Constraint> result(new Constraint(*c));

    const std::tr1::shared_ptr<PresetReason> reason(new PresetReason("restarted because of", c->reason()));
    result->reason() = reason;

    if (result->spec().if_package())
    {
        PackageDepSpec s(_make_spec_for_preloading(*result->spec().if_package()));
        result->spec().if_package() = make_shared_ptr(new PackageDepSpec(s));
    }
    else
    {
        PackageDepSpec s(_make_spec_for_preloading(result->spec().if_block()->blocking()));
        result->spec().if_block() = make_shared_ptr(new BlockDepSpec(
                    "!" + stringify(s),
                    s,
                    result->spec().if_block()->strong()));
    }

    return result;
}

const PackageDepSpec
Decider::_make_spec_for_preloading(const PackageDepSpec & spec) const
{
    PartiallyMadePackageDepSpec result(spec);

    /* we don't want to copy use deps from the constraint, since things like
     * [foo?] start to get weird when there's no longer an associated ID. */
    result.clear_additional_requirements();

    return result;
}

void
Decider::_decide(const std::tr1::shared_ptr<Resolution> & resolution)
{
    Context context("When deciding upon an origin ID to use for '" + stringify(resolution->resolvent()) + "':");

    std::tr1::shared_ptr<Decision> decision(_try_to_find_decision_for(resolution));
    if (decision)
        resolution->decision() = decision;
    else
        resolution->decision() = _cannot_decide_for(resolution);
}

namespace
{
    struct DependenciesNecessityVisitor
    {
        const std::tr1::shared_ptr<const PackageID> visit(const NothingNoChangeDecision &) const
        {
            return make_null_shared_ptr();
        }

        const std::tr1::shared_ptr<const PackageID> visit(const RemoveDecision &) const
        {
            return make_null_shared_ptr();
        }

        const std::tr1::shared_ptr<const PackageID> visit(const UnableToMakeDecision &) const
        {
            return make_null_shared_ptr();
        }

        const std::tr1::shared_ptr<const PackageID> visit(const ExistingNoChangeDecision & decision) const
        {
            if (decision.taken())
                return decision.existing_id();
            else
                return make_null_shared_ptr();
        }

        const std::tr1::shared_ptr<const PackageID> visit(const ChangesToMakeDecision & decision) const
        {
            if (decision.taken())
                return decision.origin_id();
            else
                return make_null_shared_ptr();
        }

        const std::tr1::shared_ptr<const PackageID> visit(const BreakDecision &) const
        {
            return make_null_shared_ptr();
        }
    };
}

void
Decider::_add_dependencies_if_necessary(
        const std::tr1::shared_ptr<Resolution> & our_resolution)
{
    const std::tr1::shared_ptr<const PackageID> package_id(
            our_resolution->decision()->accept_returning<std::tr1::shared_ptr<const PackageID> >(
                DependenciesNecessityVisitor()));
    if (! package_id)
        return;

    Context context("When adding dependencies for '" + stringify(our_resolution->resolvent()) + "' with '"
            + stringify(*package_id) + "':");

    const std::tr1::shared_ptr<SanitisedDependencies> deps(new SanitisedDependencies);
    deps->populate(_imp->env, *this, our_resolution, package_id);

    for (SanitisedDependencies::ConstIterator s(deps->begin()), s_end(deps->end()) ;
            s != s_end ; ++s)
    {
        Context context_2("When handling dependency '" + stringify(s->spec()) + "':");

        SpecInterest interest(_interest_in_spec(our_resolution, *s));

        switch (interest)
        {
            case si_ignore:
                continue;

            case si_untaken:
            case si_take:
            case last_si:
                break;
        }

        const std::tr1::shared_ptr<DependencyReason> reason(new DependencyReason(
                    package_id, our_resolution->resolvent(), *s, _already_met(*s)));

        std::tr1::shared_ptr<const Resolvents> resolvents;

        if (s->spec().if_package())
            resolvents = _get_resolvents_for(*s->spec().if_package(), reason);
        else
            resolvents = _get_resolvents_for_blocker(*s->spec().if_block());

        if (resolvents->empty())
        {
            if (s->spec().if_package())
                resolvents = _get_error_resolvents_for(*s->spec().if_package(), reason);
            else
            {
                /* blocking on something that doesn't exist is fine */
            }
        }

        for (Resolvents::ConstIterator r(resolvents->begin()), r_end(resolvents->end()) ;
                r != r_end ; ++r)
        {
            const std::tr1::shared_ptr<Resolution> dep_resolution(_resolution_for_resolvent(*r, true));
            const std::tr1::shared_ptr<ConstraintSequence> constraints(_make_constraints_from_dependency(our_resolution, *s, reason, interest));

            for (ConstraintSequence::ConstIterator c(constraints->begin()), c_end(constraints->end()) ;
                    c != c_end ; ++c)
                _apply_resolution_constraint(dep_resolution, *c);
        }
    }
}

SpecInterest
Decider::_interest_in_spec(const std::tr1::shared_ptr<const Resolution> & resolution, const SanitisedDependency & dep) const
{
    return _imp->fns.interest_in_spec_fn()(resolution, dep);
}

const std::tr1::shared_ptr<Constraints>
Decider::_initial_constraints_for(const Resolvent & r) const
{
    return _imp->fns.get_initial_constraints_for_fn()(r);
}

std::pair<AnyChildScore, OperatorScore>
Decider::find_any_score(
        const std::tr1::shared_ptr<const Resolution> & our_resolution,
        const std::tr1::shared_ptr<const PackageID> & our_id,
        const SanitisedDependency & dep) const
{
    Context context("When working out whether we'd like '" + stringify(dep.spec()) + "' because of '"
            + stringify(our_resolution->resolvent()) + "':");

    if (dep.spec().if_block())
        throw InternalError(PALUDIS_HERE, "unimplemented: blockers inside || blocks are horrid");

    const PackageDepSpec & spec(*dep.spec().if_package());

    // note: make sure the worst_score declaration in
    // AnyDepSpecChildHandler::commit in satitised_dependencies.cc
    // matches this logic
    OperatorScore operator_bias(os_worse_than_worst);
    if (spec.version_requirements_ptr() && ! spec.version_requirements_ptr()->empty())
    {
        OperatorScore score(os_worse_than_worst);
        for (VersionRequirements::ConstIterator v(spec.version_requirements_ptr()->begin()),
                v_end(spec.version_requirements_ptr()->end()) ;
                v != v_end ; ++v)
        {
            OperatorScore local_score(os_worse_than_worst);

            switch (v->version_operator().value())
            {
                case vo_greater:
                case vo_greater_equal:
                    local_score = os_greater_or_none;
                    break;

                case vo_equal:
                case vo_tilde:
                case vo_nice_equal_star:
                case vo_stupid_equal_star:
                case vo_tilde_greater:
                    local_score = os_equal;
                    break;

                case vo_less_equal:
                case vo_less:
                    local_score = os_less;
                    break;

                case last_vo:
                    local_score = os_less;
                    break;
            }

            if (score == os_worse_than_worst)
                score = local_score;
            else
                switch (spec.version_requirements_mode())
                {
                    case vr_and:
                        score = std::min(score, local_score);
                        break;

                    case vr_or:
                        score = std::max(score, local_score);
                        break;

                    case last_vr:
                        break;
                }
        }
        operator_bias = score;
    }
    else
    {
        /* don't bias no operator over a >= operator, so || ( >=foo-2 bar )
         * still likes foo. */
        operator_bias = os_greater_or_none;
    }

    /* explicit preferences come first */
    if (spec.package_ptr())
    {
        Tribool prefer_or_avoid(_imp->fns.prefer_or_avoid_fn()(*spec.package_ptr()));
        if (prefer_or_avoid.is_true())
            return std::make_pair(acs_prefer, operator_bias);
        else if (prefer_or_avoid.is_false())
            return std::make_pair(acs_avoid, operator_bias);
    }

    /* best: already installed */
    {
        const std::tr1::shared_ptr<const PackageIDSequence> installed_ids((*_imp->env)[selection::BestVersionOnly(
                    generator::Matches(spec, MatchPackageOptions()) |
                    filter::InstalledAtRoot(FSEntry("/")))]);
        if (! installed_ids->empty())
            return std::make_pair(acs_already_installed, operator_bias);
    }

    /* next: already installed, except with the wrong options */
    if (spec.additional_requirements_ptr())
    {
        const std::tr1::shared_ptr<const PackageIDSequence> installed_ids((*_imp->env)[selection::BestVersionOnly(
                    generator::Matches(spec, MatchPackageOptions() + mpo_ignore_additional_requirements) |
                    filter::InstalledAtRoot(FSEntry("/")))]);
        if (! installed_ids->empty())
            return std::make_pair(acs_wrong_options_installed, operator_bias);
    }

    const std::tr1::shared_ptr<DependencyReason> reason(new DependencyReason(
                our_id, our_resolution->resolvent(), dep, _already_met(dep)));
    const std::tr1::shared_ptr<const Resolvents> resolvents(_get_resolvents_for(spec, reason));

    /* next: will already be installing */
    {
        for (Resolvents::ConstIterator r(resolvents->begin()), r_end(resolvents->end()) ;
                r != r_end ; ++r)
        {
            ResolutionsByResolvent::ConstIterator i(_imp->resolutions_by_resolvent->find(*r));
            if (i != _imp->resolutions_by_resolvent->end())
                return std::make_pair(acs_will_be_installing, operator_bias);
        }
    }

    /* next: could install */
    {
        for (Resolvents::ConstIterator r(resolvents->begin()), r_end(resolvents->end()) ;
                r != r_end ; ++r)
        {
            const std::tr1::shared_ptr<Resolution> resolution(_create_resolution_for_resolvent(*r));
            const std::tr1::shared_ptr<ConstraintSequence> constraints(_make_constraints_from_dependency(
                        our_resolution, dep, reason, si_take));
            for (ConstraintSequence::ConstIterator c(constraints->begin()), c_end(constraints->end()) ;
                    c != c_end ; ++c)
                resolution->constraints()->add(*c);
            const std::tr1::shared_ptr<Decision> decision(_try_to_find_decision_for(resolution));
            if (decision)
                return std::make_pair(acs_could_install, operator_bias);
        }
    }

    /* next: exists */
    {
        const std::tr1::shared_ptr<const PackageIDSequence> ids((*_imp->env)[selection::BestVersionOnly(
                    generator::Matches(spec, MatchPackageOptions() + mpo_ignore_additional_requirements)
                    )]);
        if (! ids->empty())
            return std::make_pair(acs_exists, operator_bias);
    }

    /* yay, people are depping upon packages that don't exist again. I SMELL A LESSPIPE. */
    return std::make_pair(acs_hate_hate_hate, operator_bias);
}

namespace
{
    struct SlotNameFinder
    {
        std::tr1::shared_ptr<SlotName> visit(const SlotExactRequirement & s)
        {
            return make_shared_ptr(new SlotName(s.slot()));
        }

        std::tr1::shared_ptr<SlotName> visit(const SlotAnyUnlockedRequirement &)
        {
            return make_null_shared_ptr();
        }

        std::tr1::shared_ptr<SlotName> visit(const SlotAnyLockedRequirement &)
        {
            return make_null_shared_ptr();
        }
    };
}

const std::tr1::shared_ptr<const Resolvents>
Decider::_get_resolvents_for_blocker(const BlockDepSpec & spec) const
{
    Context context("When finding slots for '" + stringify(spec) + "':");

    std::tr1::shared_ptr<SlotName> exact_slot;
    if (spec.blocking().slot_requirement_ptr())
    {
        SlotNameFinder f;
        exact_slot = spec.blocking().slot_requirement_ptr()->accept_returning<std::tr1::shared_ptr<SlotName> >(f);
    }

    DestinationTypes destination_types(_get_destination_types_for_blocker(spec));
    std::tr1::shared_ptr<Resolvents> result(new Resolvents);
    if (exact_slot)
    {
        for (EnumIterator<DestinationType> t, t_end(last_dt) ; t != t_end ; ++t)
            if (destination_types[*t])
                result->push_back(Resolvent(spec.blocking(), *exact_slot, *t));
    }
    else
    {
        const std::tr1::shared_ptr<const PackageIDSequence> ids((*_imp->env)[selection::BestVersionInEachSlot(
                    generator::Package(*spec.blocking().package_ptr())
                    )]);
        for (PackageIDSequence::ConstIterator i(ids->begin()), i_end(ids->end()) ;
                i != i_end ; ++i)
            for (EnumIterator<DestinationType> t, t_end(last_dt) ; t != t_end ; ++t)
                if (destination_types[*t])
                    result->push_back(Resolvent(*i, *t));
    }

    return result;
}

const DestinationTypes
Decider::_get_destination_types_for_blocker(const BlockDepSpec &) const
{
    return DestinationTypes() + dt_install_to_slash;
}

const std::tr1::shared_ptr<const Resolvents>
Decider::_get_resolvents_for(
        const PackageDepSpec & spec,
        const std::tr1::shared_ptr<const Reason> & reason) const
{
    Context context("When finding slots for '" + stringify(spec) + "':");

    std::tr1::shared_ptr<SlotName> exact_slot;

    if (spec.slot_requirement_ptr())
    {
        SlotNameFinder f;
        exact_slot = spec.slot_requirement_ptr()->accept_returning<std::tr1::shared_ptr<SlotName> >(f);
    }

    return _imp->fns.get_resolvents_for_fn()(spec, exact_slot, reason);
}

const DestinationTypes
Decider::_get_destination_types_for(
        const PackageDepSpec & spec,
        const std::tr1::shared_ptr<const PackageID> & id,
        const std::tr1::shared_ptr<const Reason> & reason) const
{
    return _imp->fns.get_destination_types_for_fn()(spec, id, reason);
}

const std::tr1::shared_ptr<const Resolvents>
Decider::_get_error_resolvents_for(
        const PackageDepSpec & spec,
        const std::tr1::shared_ptr<const Reason> & reason) const
{
    Context context("When finding slots for '" + stringify(spec) + "', which can't be found the normal way:");

    std::tr1::shared_ptr<Resolvents> result(new Resolvents);
    DestinationTypes destination_types(_get_destination_types_for(spec, make_null_shared_ptr(), reason));
    for (EnumIterator<DestinationType> t, t_end(last_dt) ; t != t_end ; ++t)
        if (destination_types[*t])
            result->push_back(Resolvent(spec, true, *t));
    return result;
}

const std::tr1::shared_ptr<Decision>
Decider::_try_to_find_decision_for(
        const std::tr1::shared_ptr<const Resolution> & resolution) const
{
    const std::tr1::shared_ptr<const PackageID> existing_id(_find_existing_id_for(resolution));
    std::pair<const std::tr1::shared_ptr<const PackageID>, bool> installable_id_best(_find_installable_id_for(resolution));
    const std::tr1::shared_ptr<const PackageID> installable_id(installable_id_best.first);
    bool best(installable_id_best.second);

    if (resolution->constraints()->nothing_is_fine_too())
    {
        const std::tr1::shared_ptr<const PackageIDSequence> existing_resolvent_ids(_installed_ids(resolution->resolvent()));
        if (existing_resolvent_ids->empty())
        {
            /* nothing existing, but nothing's ok */
            return make_shared_ptr(new NothingNoChangeDecision(
                        resolution->resolvent(),
                        ! resolution->constraints()->all_untaken()
                        ));
        }
    }

    if (installable_id && ! existing_id)
    {
        /* there's nothing suitable existing. */
        return make_shared_ptr(new ChangesToMakeDecision(
                    resolution->resolvent(),
                    installable_id,
                    best,
                    last_ct,
                    ! resolution->constraints()->all_untaken(),
                    make_null_shared_ptr(),
                    std::tr1::bind(&Decider::_fixup_changes_to_make_decision, this, resolution, std::tr1::placeholders::_1)
                    ));
    }
    else if (existing_id && ! installable_id)
    {
        /* there's nothing installable. this may or may not be ok. */
        bool is_transient(existing_id->behaviours_key() && existing_id->behaviours_key()->value()->end() !=
                existing_id->behaviours_key()->value()->find("transient"));

        switch (resolution->constraints()->strictest_use_existing())
        {
            case ue_if_possible:
                break;

            case ue_only_if_transient:
            case ue_if_same:
            case ue_if_same_version:
                if (! is_transient)
                    return make_null_shared_ptr();
                break;

            case ue_never:
                return make_null_shared_ptr();

            case last_ue:
                break;
        }

        return make_shared_ptr(new ExistingNoChangeDecision(
                    resolution->resolvent(),
                    existing_id,
                    true,
                    true,
                    is_transient,
                    ! resolution->constraints()->all_untaken()
                    ));
    }
    else if ((! existing_id) && (! installable_id))
    {
        /* we can't stick with our existing id, if there is one, and we can't
         * fix it by installing things. this might be an error, or we might be
         * able to remove things. */
        if (resolution->constraints()->nothing_is_fine_too() && _installed_but_allowed_to_remove(resolution))
            return make_shared_ptr(new RemoveDecision(
                        resolution->resolvent(),
                        _installed_ids(resolution->resolvent()),
                        ! resolution->constraints()->all_untaken()
                        ));
        else
            return make_null_shared_ptr();
    }
    else if (existing_id && installable_id)
    {
        bool is_same_version(existing_id->version() == installable_id->version());
        bool is_same(false);

        if (is_same_version)
        {
            is_same = true;

            std::set<ChoiceNameWithPrefix> common;
            if (existing_id->choices_key() && installable_id->choices_key())
            {
                std::set<ChoiceNameWithPrefix> i_common, u_common;
                for (Choices::ConstIterator k(installable_id->choices_key()->value()->begin()),
                        k_end(installable_id->choices_key()->value()->end()) ;
                        k != k_end ; ++k)
                {
                    if (! (*k)->consider_added_or_changed())
                        continue;

                    for (Choice::ConstIterator i((*k)->begin()), i_end((*k)->end()) ;
                            i != i_end ; ++i)
                        if ((*i)->explicitly_listed())
                            i_common.insert((*i)->name_with_prefix());
                }

                for (Choices::ConstIterator k(existing_id->choices_key()->value()->begin()),
                        k_end(existing_id->choices_key()->value()->end()) ;
                        k != k_end ; ++k)
                {
                    if (! (*k)->consider_added_or_changed())
                        continue;

                    for (Choice::ConstIterator i((*k)->begin()), i_end((*k)->end()) ;
                            i != i_end ; ++i)
                        if ((*i)->explicitly_listed())
                            u_common.insert((*i)->name_with_prefix());
                }

                std::set_intersection(
                        i_common.begin(), i_common.end(),
                        u_common.begin(), u_common.end(),
                        std::inserter(common, common.begin()));
            }

            for (std::set<ChoiceNameWithPrefix>::const_iterator f(common.begin()), f_end(common.end()) ;
                    f != f_end ; ++f)
                if (installable_id->choices_key()->value()->find_by_name_with_prefix(*f)->enabled() !=
                        existing_id->choices_key()->value()->find_by_name_with_prefix(*f)->enabled())
                {
                    is_same = false;
                    break;
                }
        }

        bool is_transient(existing_id->behaviours_key() && existing_id->behaviours_key()->value()->end() !=
                existing_id->behaviours_key()->value()->find("transient"));

        /* we've got existing and installable. do we have any reason not to pick the existing id? */
        const std::tr1::shared_ptr<Decision> existing(new ExistingNoChangeDecision(
                    resolution->resolvent(),
                    existing_id,
                    is_same,
                    is_same_version,
                    is_transient,
                    ! resolution->constraints()->all_untaken()
                    ));
        const std::tr1::shared_ptr<Decision> changes_to_make(new ChangesToMakeDecision(
                    resolution->resolvent(),
                    installable_id,
                    best,
                    last_ct,
                    ! resolution->constraints()->all_untaken(),
                    make_null_shared_ptr(),
                    std::tr1::bind(&Decider::_fixup_changes_to_make_decision, this, resolution, std::tr1::placeholders::_1)
                    ));

        switch (resolution->constraints()->strictest_use_existing())
        {
            case ue_only_if_transient:
            case ue_never:
                return changes_to_make;

            case ue_if_same:
                if (is_same)
                    return existing;
                else
                    return changes_to_make;

            case ue_if_same_version:
                if (is_same_version)
                    return existing;
                else
                    return changes_to_make;

            case ue_if_possible:
                return existing;

            case last_ue:
                break;
        }
    }

    throw InternalError(PALUDIS_HERE, "resolver bug: shouldn't be reached");
}

const std::tr1::shared_ptr<Decision>
Decider::_cannot_decide_for(
        const std::tr1::shared_ptr<const Resolution> & resolution) const
{
    const std::tr1::shared_ptr<UnsuitableCandidates> unsuitable_candidates(new UnsuitableCandidates);

    const std::tr1::shared_ptr<const PackageID> existing_id(_find_existing_id_for(resolution));
    if (existing_id)
        unsuitable_candidates->push_back(_make_unsuitable_candidate(resolution, existing_id, true));

    const std::tr1::shared_ptr<const PackageIDSequence> installable_ids(_find_installable_id_candidates_for(resolution, true));
    for (PackageIDSequence::ConstIterator i(installable_ids->begin()), i_end(installable_ids->end()) ;
            i != i_end ; ++i)
        unsuitable_candidates->push_back(_make_unsuitable_candidate(resolution, *i, false));

    return make_shared_ptr(new UnableToMakeDecision(
                resolution->resolvent(),
                unsuitable_candidates,
                ! resolution->constraints()->all_untaken()
                ));
}

UnsuitableCandidate
Decider::_make_unsuitable_candidate(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const std::tr1::shared_ptr<const PackageID> & id,
        const bool existing) const
{
    return make_named_values<UnsuitableCandidate>(
            n::package_id() = id,
            n::unmet_constraints() = _get_unmatching_constraints(resolution, id, existing)
            );
}

const std::tr1::shared_ptr<const PackageID>
Decider::_find_existing_id_for(const std::tr1::shared_ptr<const Resolution> & resolution) const
{
    const std::tr1::shared_ptr<const PackageIDSequence> ids(_installed_ids(resolution->resolvent()));
    return _find_id_for_from(resolution, ids).first;
}

bool
Decider::_installed_but_allowed_to_remove(const std::tr1::shared_ptr<const Resolution> & resolution) const
{
    const std::tr1::shared_ptr<const PackageIDSequence> ids(_installed_ids(resolution->resolvent()));
    if (ids->empty())
        return false;

    return ids->end() == std::find_if(ids->begin(), ids->end(),
            std::tr1::bind(std::logical_not<bool>(), std::tr1::bind(&Decider::_allowed_to_remove,
                    this, resolution, std::tr1::placeholders::_1)));
}

bool
Decider::_allowed_to_remove(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const std::tr1::shared_ptr<const PackageID> & id) const
{
    return id->supports_action(SupportsActionTest<UninstallAction>()) && _imp->fns.allowed_to_remove_fn()(resolution, id);
}

bool
Decider::_remove_if_dependent(const std::tr1::shared_ptr<const PackageID> & id) const
{
    return _imp->fns.remove_if_dependent_fn()(id);
}

const std::tr1::shared_ptr<const PackageIDSequence>
Decider::_installed_ids(const Resolvent & resolvent) const
{
    return (*_imp->env)[selection::AllVersionsSorted(
            _make_destination_filtered_generator(generator::Package(resolvent.package()), resolvent) |
            make_slot_filter(resolvent)
            )];
}

const std::tr1::shared_ptr<const PackageIDSequence>
Decider::_find_installable_id_candidates_for(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const bool include_errors) const
{
    return (*_imp->env)[selection::AllVersionsSorted(
            generator::Package(resolution->resolvent().package()) |
            make_slot_filter(resolution->resolvent()) |
            filter::SupportsAction<InstallAction>() |
            ((! include_errors) ? Filter(filter::NotMasked()) : Filter(filter::All()))
            )];
}

const std::pair<const std::tr1::shared_ptr<const PackageID>, bool>
Decider::_find_installable_id_for(const std::tr1::shared_ptr<const Resolution> & resolution) const
{
    return _find_id_for_from(resolution, _find_installable_id_candidates_for(resolution, false));
}

const std::pair<const std::tr1::shared_ptr<const PackageID>, bool>
Decider::_find_id_for_from(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const std::tr1::shared_ptr<const PackageIDSequence> & ids) const
{
    std::tr1::shared_ptr<const PackageID> best_version;
    for (PackageIDSequence::ReverseConstIterator i(ids->rbegin()), i_end(ids->rend()) ;
            i != i_end ; ++i)
    {
        if (! best_version)
            best_version = *i;

        bool ok(true);
        for (Constraints::ConstIterator c(resolution->constraints()->begin()),
                c_end(resolution->constraints()->end()) ;
                c != c_end ; ++c)
        {
            if ((*c)->spec().if_package())
                ok = ok && match_package(*_imp->env, *(*c)->spec().if_package(), **i, MatchPackageOptions());
            else
                ok = ok && ! match_package(*_imp->env, (*c)->spec().if_block()->blocking(), **i, MatchPackageOptions());

            if (! ok)
                break;
        }

        if (ok)
            return std::make_pair(*i, (*i)->version() == best_version->version());
    }

    return std::make_pair(make_null_shared_ptr(), false);
}

const std::tr1::shared_ptr<const Constraints>
Decider::_get_unmatching_constraints(
        const std::tr1::shared_ptr<const Resolution> & resolution,
        const std::tr1::shared_ptr<const PackageID> & id,
        const bool existing) const
{
    const std::tr1::shared_ptr<Constraints> result(new Constraints);

    for (Constraints::ConstIterator c(resolution->constraints()->begin()),
            c_end(resolution->constraints()->end()) ;
            c != c_end ; ++c)
    {
        std::tr1::shared_ptr<Decision> decision;

        if (existing)
        {
            bool is_transient(id->behaviours_key() && id->behaviours_key()->value()->end() !=
                    id->behaviours_key()->value()->find("transient"));
            decision.reset(new ExistingNoChangeDecision(
                        resolution->resolvent(),
                        id,
                        true,
                        true,
                        is_transient,
                        ! (*c)->untaken()
                        ));
        }
        else
            decision.reset(new ChangesToMakeDecision(
                        resolution->resolvent(),
                        id,
                        false,
                        last_ct,
                        ! (*c)->untaken(),
                        make_null_shared_ptr(),
                        std::tr1::bind(&Decider::_fixup_changes_to_make_decision, this, resolution, std::tr1::placeholders::_1)
                        ));
        if (! _check_constraint(*c, decision))
            result->add(*c);
    }

    return result;
}

const std::tr1::shared_ptr<const RewrittenSpec>
Decider::rewrite_if_special(
        const PackageOrBlockDepSpec & spec,
        const std::tr1::shared_ptr<const Resolvent> & maybe_from) const
{
    return _imp->rewriter.rewrite_if_special(spec, maybe_from);
}

void
Decider::add_target_with_reason(const PackageOrBlockDepSpec & spec, const std::tr1::shared_ptr<const Reason> & reason)
{
    Context context("When adding target '" + stringify(spec) + "':");

    _imp->env->trigger_notifier_callback(NotifierCallbackResolverStepEvent());

    const std::tr1::shared_ptr<const RewrittenSpec> if_rewritten(rewrite_if_special(spec, make_null_shared_ptr()));
    if (if_rewritten)
    {
        for (Sequence<PackageOrBlockDepSpec>::ConstIterator i(if_rewritten->specs()->begin()), i_end(if_rewritten->specs()->end()) ;
                i != i_end ; ++i)
            add_target_with_reason(*i, reason);
    }
    else
    {
        PackageDepSpec base_spec(spec.if_package() ? *spec.if_package() : spec.if_block()->blocking());
        std::tr1::shared_ptr<const Resolvents> resolvents(_get_resolvents_for(base_spec, reason));
        if (resolvents->empty())
        {
            if (spec.if_package())
                resolvents = _get_error_resolvents_for(*spec.if_package(), reason);
            else
            {
                /* blocking on something that doesn't exist is fine */
            }
        }

        for (Resolvents::ConstIterator r(resolvents->begin()), r_end(resolvents->end()) ;
                r != r_end ; ++r)
        {
            Context context_2("When adding constraints from target '" + stringify(spec) + "' to resolvent '"
                    + stringify(*r) + "':");

            const std::tr1::shared_ptr<Resolution> dep_resolution(_resolution_for_resolvent(*r, true));
            const std::tr1::shared_ptr<ConstraintSequence> constraints(_make_constraints_from_target(dep_resolution, spec, reason));

            for (ConstraintSequence::ConstIterator c(constraints->begin()), c_end(constraints->end()) ;
                    c != c_end ; ++c)
                _apply_resolution_constraint(dep_resolution, *c);
        }
    }
}

void
Decider::resolve()
{
    while (true)
    {
        _imp->env->trigger_notifier_callback(NotifierCallbackResolverStageEvent("Deciding"));
        _resolve_decide_with_dependencies();
        _imp->env->trigger_notifier_callback(NotifierCallbackResolverStageEvent("Finding Dependents"));
        if (! _resolve_dependents())
            break;
    }

    _imp->env->trigger_notifier_callback(NotifierCallbackResolverStageEvent("Confirming"));
    _resolve_confirmations();
}

bool
Decider::_already_met(const SanitisedDependency & dep) const
{
    const std::tr1::shared_ptr<const PackageIDSequence> installed_ids((*_imp->env)[selection::BestVersionOnly(
                generator::Matches(dep.spec().if_package() ?
                    *dep.spec().if_package() :
                    dep.spec().if_block()->blocking(),
                    MatchPackageOptions()) |
                filter::InstalledAtRoot(FSEntry("/")))]);
    if (installed_ids->empty())
        return dep.spec().if_block();
    else
        return dep.spec().if_package();
}

namespace
{
    struct ConfirmVisitor
    {
        const Environment * const env;
        const ResolverFunctions & fns;
        const std::tr1::shared_ptr<const Resolution> resolution;

        ConfirmVisitor(
                const Environment * const e,
                const ResolverFunctions & f,
                const std::tr1::shared_ptr<const Resolution> & r) :
            env(e),
            fns(f),
            resolution(r)
        {
        }

        void visit(ChangesToMakeDecision & changes_to_make_decision) const
        {
            if (! changes_to_make_decision.best())
            {
                const std::tr1::shared_ptr<RequiredConfirmation> c(new NotBestConfirmation);
                if (! fns.confirm_fn()(resolution, c))
                    changes_to_make_decision.add_required_confirmation(c);
            }

            if (ct_downgrade == changes_to_make_decision.change_type())
            {
                const std::tr1::shared_ptr<DowngradeConfirmation> c(new DowngradeConfirmation);
                if (! fns.confirm_fn()(resolution, c))
                    changes_to_make_decision.add_required_confirmation(c);
            }
        }

        void visit(BreakDecision & break_decision) const
        {
            const std::tr1::shared_ptr<BreakConfirmation> c(new BreakConfirmation);
            if (! fns.confirm_fn()(resolution, c))
                break_decision.add_required_confirmation(c);
        }

        void visit(UnableToMakeDecision &) const
        {
        }

        void visit(ExistingNoChangeDecision &) const
        {
        }

        void visit(NothingNoChangeDecision &) const
        {
        }

        void visit(RemoveDecision & remove_decision) const
        {
            /* we do BreakConfirmation elsewhere */
            bool is_system(false);
            for (PackageIDSequence::ConstIterator i(remove_decision.ids()->begin()), i_end(remove_decision.ids()->end()) ;
                    i != i_end && ! is_system ; ++i)
                if (match_package_in_set(*env, *env->set(SetName("system")), **i, MatchPackageOptions()))
                    is_system = true;

            if (is_system)
            {
                const std::tr1::shared_ptr<RemoveSystemPackageConfirmation> c(new RemoveSystemPackageConfirmation);
                if (! fns.confirm_fn()(resolution, c))
                    remove_decision.add_required_confirmation(c);
            }
        }
    };
}

void
Decider::_confirm(
        const std::tr1::shared_ptr<const Resolution> & resolution)
{
    resolution->decision()->accept(ConfirmVisitor(_imp->env, _imp->fns, resolution));
}