aboutsummaryrefslogtreecommitdiff
path: root/paludis/dep_list/dep_list.cc
blob: 5e4b9248cea0ee671b945f695d8853457d43eb6a (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
/* vim: set sw=4 sts=4 et foldmethod=syntax : */

/*
 * Copyright (c) 2005, 2006 Ciaran McCreesh <ciaranm@ciaranm.org>
 *
 * 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/dep_atom.hh>
#include <paludis/dep_atom_flattener.hh>
#include <paludis/dep_list/dep_list.hh>
#include <paludis/match_package.hh>
#include <paludis/util/collection_concrete.hh>
#include <paludis/util/iterator.hh>
#include <paludis/util/join.hh>
#include <paludis/util/log.hh>
#include <paludis/util/save.hh>
#include <paludis/util/stringify.hh>
#include <paludis/util/tokeniser.hh>

#include <algorithm>
#include <functional>
#include <vector>
#include <set>

using namespace paludis;

#include <paludis/dep_list/dep_list-sr.cc>

DepListError::DepListError(const std::string & m) throw () :
    Exception(m)
{
}

AllMaskedError::AllMaskedError(const std::string & q) throw () :
    DepListError("Error searching for '" + q + "': no available versions"),
    _query(q)
{
}

UseRequirementsNotMetError::UseRequirementsNotMetError(const std::string & q) throw () :
    DepListError("Error searching for '" + q + "': use requirements are not met"),
    _query(q)
{
}

BlockError::BlockError(const std::string & msg) throw () :
    DepListError("Block: " + msg)
{
}

CircularDependencyError::CircularDependencyError(const std::string & msg) throw () :
    DepListError("Circular dependency: " + msg)
{
}

DepListOptions::DepListOptions() :
    reinstall(dl_reinstall_never),
    reinstall_scm(dl_reinstall_scm_never),
    target_type(dl_target_package),
    upgrade(dl_upgrade_always),
    fall_back(dl_fall_back_as_needed_except_targets),
    installed_deps_pre(dl_deps_discard),
    installed_deps_runtime(dl_deps_try_post),
    installed_deps_post(dl_deps_try_post),
    uninstalled_deps_pre(dl_deps_pre),
    uninstalled_deps_runtime(dl_deps_pre_or_post),
    uninstalled_deps_post(dl_deps_post),
    circular(dl_circular_error),
    dependency_tags(false)
{
    /* when changing the above, also see src/paludis/command_line.cc. */
}

namespace paludis
{
    typedef std::list<DepListEntry> MergeList;

    template<>
    struct Implementation<DepList> :
        InternalCounted<Implementation<DepList> >
    {
        const Environment * const env;
        DepListOptions opts;

        MergeList merge_list;
        MergeList::const_iterator current_merge_list_entry;
        MergeList::iterator merge_list_insert_position;
        long merge_list_generation;

        DepAtom::ConstPointer current_top_level_target;

        const PackageDatabaseEntry * current_pde() const
        {
            if (current_merge_list_entry != merge_list.end())
                return &current_merge_list_entry->package;
            return 0;
        }

        Implementation(const Environment * const e, const DepListOptions & o) :
            env(e),
            opts(o),
            current_merge_list_entry(merge_list.end()),
            merge_list_insert_position(merge_list.end()),
            merge_list_generation(0),
            current_top_level_target(0)
        {
        }
    };
}

namespace
{
    struct GenerationGreaterThan
    {
        long g;

        GenerationGreaterThan(long gg) :
            g(gg)
        {
        }

        template <typename T_>
        bool operator() (const T_ & e) const
        {
            return e.generation > g;
        }
    };

    struct RemoveTagsWithGenerationGreaterThan
    {
        long g;

        RemoveTagsWithGenerationGreaterThan(long gg) :
            g(gg)
        {
        }

        void operator() (DepListEntry & e) const
        {
            /* see EffSTL 9 for why this is so painful */
            if (e.tags->empty())
                return;
            DepListEntryTags::Pointer t(new DepListEntryTags::Concrete);
            GenerationGreaterThan pred(g);
            for (DepListEntryTags::Iterator i(e.tags->begin()), i_end(e.tags->end()) ;
                    i != i_end ; ++i)
                if (! pred(*i))
                    t->insert(*i);
            std::swap(e.tags, t);
        }
    };

    class DepListTransaction
    {
        protected:
            MergeList & _list;
            long & _generation;
            int _initial_generation;
            bool _committed;

        public:
            DepListTransaction(MergeList & l, long & g) :
                _list(l),
                _generation(g),
                _initial_generation(g),
                _committed(false)
            {
                ++_generation;
            }

            void commit()
            {
                _committed = true;
            }

            ~DepListTransaction()
            {
                if (! _committed)
                {
                    _list.remove_if(GenerationGreaterThan(_initial_generation));
                    std::for_each(_list.begin(), _list.end(), RemoveTagsWithGenerationGreaterThan(_initial_generation));
                }
            }
    };

    struct MatchDepListEntryAgainstPackageDepAtom
    {
        const Environment * const env;
        const PackageDepAtom * const a;

        MatchDepListEntryAgainstPackageDepAtom(const Environment * const ee,
                const PackageDepAtom * const aa) :
            env(ee),
            a(aa)
        {
        }

        bool operator() (const DepListEntry & e)
        {
            return match_package(env, a, e.package);
        }
    };

    struct IsViableAnyDepAtomChild
    {
        const Environment * const env;
        const PackageDatabaseEntry * const pde;

        IsViableAnyDepAtomChild(const Environment * const e, const PackageDatabaseEntry * const p) :
            env(e),
            pde(p)
        {
        }

        bool operator() (PackageDepAtom::ConstPointer atom)
        {
            const UseDepAtom * const u(atom->as_use_dep_atom());
            if (0 != u)
                return env->query_use(u->flag(), pde) ^ u->inverse();
            else
                return true;
        }
    };
}

struct DepList::QueryVisitor :
    DepAtomVisitorTypes::ConstVisitor
{
    bool result;
    const DepList * const d;

    QueryVisitor(const DepList * const dd) :
        result(true),
        d(dd)
    {
    }

    void visit(const PlainTextDepAtom * const) PALUDIS_ATTRIBUTE((noreturn));
    void visit(const PackageDepAtom * const);
    void visit(const UseDepAtom * const);
    void visit(const AnyDepAtom * const);
    void visit(const BlockDepAtom * const);
    void visit(const AllDepAtom * const);
};

void
DepList::QueryVisitor::visit(const PlainTextDepAtom * const)
{
    throw InternalError(PALUDIS_HERE, "Got PlainTextDepAtom?");
}

void
DepList::QueryVisitor::visit(const PackageDepAtom * const a)
{
    /* a pda matches either if we're already installed, or if we will be installed
     * by the time the current point in the dep list is reached. */

    if (! d->_imp->env->package_database()->query(*a, is_installed_only)->empty())
        result = true;
    else if (d->_imp->merge_list.end() != std::find_if(
                d->_imp->merge_list.begin(),
                d->_imp->merge_list.end(),
                MatchDepListEntryAgainstPackageDepAtom(d->_imp->env, a)))
        result = true;
    else
        result = false;
}

void
DepList::QueryVisitor::visit(const UseDepAtom * const a)
{
    /* for use? ( ) dep atoms, return true if we're not enabled, so that
     * weird || ( ) cases work. */
    if (d->_imp->env->query_use(a->flag(), d->_imp->current_pde()) ^ a->inverse())
    {
        result = true;
        for (CompositeDepAtom::Iterator c(a->begin()), c_end(a->end()) ; c != c_end ; ++c)
        {
            (*c)->accept(this);
            if (! result)
                return;
        }
    }
    else
        result = true;
}

void
DepList::QueryVisitor::visit(const AnyDepAtom * const a)
{
    /* empty || ( ) must resolve to true */
    std::list<DepAtom::ConstPointer> viable_children;
    std::copy(a->begin(), a->end(), filter_inserter(std::back_inserter(viable_children),
                IsViableAnyDepAtomChild(d->_imp->env, d->_imp->current_pde())));

    result = true;
    for (std::list<DepAtom::ConstPointer>::const_iterator c(viable_children.begin()),
            c_end(viable_children.end()) ; c != c_end ; ++c)
    {
        (*c)->accept(this);
        if (result)
            return;
    }
}

void
DepList::QueryVisitor::visit(const BlockDepAtom * const a)
{
    a->blocked_atom()->accept(this);
    result = !result;
}

void
DepList::QueryVisitor::visit(const AllDepAtom * const a)
{
    for (CompositeDepAtom::Iterator c(a->begin()), c_end(a->end()) ; c != c_end ; ++c)
    {
        (*c)->accept(this);
        if (! result)
            return;
    }
}

struct DepList::AddVisitor :
    DepAtomVisitorTypes::ConstVisitor
{
    DepList * const d;

    AddVisitor(DepList * const dd) :
        d(dd)
    {
    }

    void visit(const PlainTextDepAtom * const) PALUDIS_ATTRIBUTE((noreturn));
    void visit(const PackageDepAtom * const);
    void visit(const UseDepAtom * const);
    void visit(const AnyDepAtom * const);
    void visit(const BlockDepAtom * const);
    void visit(const AllDepAtom * const);
};

void
DepList::AddVisitor::visit(const PlainTextDepAtom * const)
{
    throw InternalError(PALUDIS_HERE, "Got PlainTextDepAtom?");
}

void
DepList::AddVisitor::visit(const PackageDepAtom * const a)
{
    Context context("When adding PackageDepAtom '" + stringify(*a) + "':");

    /* find already installed things */
    PackageDatabaseEntryCollection::ConstPointer already_installed(d->_imp->env->package_database()->query(
                *a, is_installed_only));

    /* are we already on the merge list? */
    MergeList::iterator existing_merge_list_entry(std::find_if(d->_imp->merge_list.begin(),
                d->_imp->merge_list.end(), MatchDepListEntryAgainstPackageDepAtom(d->_imp->env, a)));
    if (existing_merge_list_entry != d->_imp->merge_list.end())
    {
        /* tag it */
        if (a->tag())
            existing_merge_list_entry->tags->insert(DepTagEntry::create()
                    .tag(a->tag())
                    .generation(d->_imp->merge_list_generation));

        if (d->_imp->opts.dependency_tags && d->_imp->current_pde())
            existing_merge_list_entry->tags->insert(DepTagEntry::create()
                    .tag(DepTag::Pointer(new DependencyDepTag(*d->_imp->current_pde())))
                    .generation(d->_imp->merge_list_generation));

        /* have our deps been merged already, or is this a circular dep? */
        if (dle_no_deps == existing_merge_list_entry->state)
        {
            /* is a sufficiently good version installed? */
            if (! already_installed->empty())
                return;

            if (d->_imp->opts.circular == dl_circular_discard)
            {
                Log::get_instance()->message(ll_warning, lc_context, "Dropping circular dependency on '"
                        + stringify(existing_merge_list_entry->package) + "'");
                return;
            }
            throw CircularDependencyError("Atom '" + stringify(*a) + "' matched by merge list entry '" +
                    stringify(existing_merge_list_entry->package) + "', which does not yet have its "
                    "dependencies installed");
        }
        else
            return;
    }

    /* find installable candidates, and find the best visible candidate */
    const PackageDatabaseEntry * best_visible_candidate(0);
    PackageDatabaseEntryCollection::ConstPointer installable_candidates(
            d->_imp->env->package_database()->query(*a, is_uninstalled_only));

    for (PackageDatabaseEntryCollection::ReverseIterator p(installable_candidates->rbegin()),
            p_end(installable_candidates->rend()) ; p != p_end ; ++p)
        if (! d->_imp->env->mask_reasons(*p).any())
        {
            best_visible_candidate = &*p;
            break;
        }

    /* no installable candidates. if we're already installed, that's ok (except for top level
     * package targets), otherwise error. */
    if (! best_visible_candidate)
    {
        bool can_fall_back;
        do
        {
            switch (d->_imp->opts.fall_back)
            {
                case dl_fall_back_never:
                    can_fall_back = false;
                    continue;

                case dl_fall_back_as_needed_except_targets:
                    if (! d->_imp->current_pde())
                        can_fall_back = false;
                    else if (already_installed->empty())
                        can_fall_back = true;
                    else
                        can_fall_back = ! d->is_top_level_target(*already_installed->last());

                    continue;

                case dl_fall_back_as_needed:
                    can_fall_back = true;
                    continue;
            }

            throw InternalError(PALUDIS_HERE, "Bad fall_back value '" + stringify(d->_imp->opts.fall_back) + "'");
        } while (false);

        if (already_installed->empty() || ! can_fall_back)
        {
            if (a->use_requirements_ptr() && d->_imp->env->package_database()->query(
                        a->without_use_requirements(), is_either))
                throw UseRequirementsNotMetError(stringify(*a));
            else
                throw AllMaskedError(stringify(*a));
        }
        else
        {
            Log::get_instance()->message(ll_warning, lc_context, "No visible packages matching '"
                    + stringify(*a) + "', falling back to installed package '"
                    + stringify(*already_installed->last()) + "'");
            d->add_already_installed_package(*already_installed->last(), a->tag());
            return;
        }
    }

    SlotName slot(d->_imp->env->package_database()->fetch_repository(best_visible_candidate->repository)->
            version_metadata(best_visible_candidate->name, best_visible_candidate->version)->slot);
    PackageDatabaseEntryCollection::Pointer already_installed_in_same_slot(
            new PackageDatabaseEntryCollection::Concrete);
    for (PackageDatabaseEntryCollection::Iterator aa(already_installed->begin()),
            aa_end(already_installed->end()) ; aa != aa_end ; ++aa)
        if (d->_imp->env->package_database()->fetch_repository(aa->repository)->
                version_metadata(aa->name, aa->version)->slot == slot)
            already_installed_in_same_slot->insert(*aa);

    /* we have an already installed version. do we want to use it? */
    if (! already_installed_in_same_slot->empty())
    {
        if (d->prefer_installed_over_uninstalled(*already_installed_in_same_slot->last(), *best_visible_candidate))
        {
            Log::get_instance()->message(ll_debug, lc_context, "Taking installed package '"
                    + stringify(*already_installed_in_same_slot->last()) + "' over '" + stringify(*best_visible_candidate) + "'");
            d->add_already_installed_package(*already_installed_in_same_slot->last(), a->tag());
            return;
        }
        else
            Log::get_instance()->message(ll_debug, lc_context, "Not taking installed package '"
                    + stringify(*already_installed_in_same_slot->last()) + "' over '" + stringify(*best_visible_candidate) + "'");
    }
    else
        Log::get_instance()->message(ll_debug, lc_context, "No installed packages in SLOT '"
                + stringify(slot) + "', taking uninstalled package '" + stringify(*best_visible_candidate) + "'");

    d->add_package(*best_visible_candidate, a->tag());
}

void
DepList::AddVisitor::visit(const UseDepAtom * const a)
{
    if (d->_imp->env->query_use(a->flag(), d->_imp->current_pde()) ^ a->inverse())
        std::for_each(a->begin(), a->end(), accept_visitor(this));
}

void
DepList::AddVisitor::visit(const AnyDepAtom * const a)
{
    /* annoying requirement: || ( foo? ( ... ) ) resolves to empty if !foo. */
    std::list<DepAtom::ConstPointer> viable_children;
    std::copy(a->begin(), a->end(), filter_inserter(std::back_inserter(viable_children),
                IsViableAnyDepAtomChild(d->_imp->env, d->_imp->current_pde())));

    if (viable_children.empty())
        return;

    /* see if any of our children is already installed. if any is, add it so that
     * any upgrades kick in */
    for (std::list<DepAtom::ConstPointer>::const_iterator c(viable_children.begin()),
            c_end(viable_children.end()) ; c != c_end ; ++c)
    {
        if (d->already_installed(*c))
        {
            d->add(*c);
            return;
        }
    }

    /* install first available viable option */
    for (std::list<DepAtom::ConstPointer>::const_iterator c(viable_children.begin()),
            c_end(viable_children.end()) ; c != c_end ; ++c)
    {
        try
        {
            d->add(*c);
            return;
        }
        catch (const DepListError & e)
        {
        }
    }

    Log::get_instance()->message(ll_warning, lc_context, "No resolvable item in || ( ) block. Using "
            "first item for error message");
    d->add(*viable_children.begin());
}

void
DepList::AddVisitor::visit(const BlockDepAtom * const a)
{
    if (! d->already_installed(a->blocked_atom()))
        return;

    Context context("When checking BlockDepAtom '!" + stringify(*a->blocked_atom()) + "':");

    /* special case: the provider of virtual/blah can DEPEND upon !virtual/blah. */
    /* special case: foo/bar can DEPEND upon !foo/bar. */

    if (d->_imp->current_pde())
    {
        if (d->_imp->current_pde()->name == a->blocked_atom()->package())
        {
            Log::get_instance()->message(ll_debug, lc_context, "Ignoring self block '"
                    + stringify(*a->blocked_atom()) + "' for package '"
                    + stringify(*d->_imp->current_pde()) + "'");
            return;
        }

        VersionMetadata::ConstPointer metadata(d->_imp->env->package_database()->fetch_repository(
                    d->_imp->current_pde()->repository)->version_metadata(d->_imp->current_pde()->name,
                    d->_imp->current_pde()->version));
        if (metadata->get_ebuild_interface())
        {
            bool skip(false);
            DepAtomFlattener f(d->_imp->env, d->_imp->current_pde(), metadata->get_ebuild_interface()->provide());
            for (DepAtomFlattener::Iterator i(f.begin()), i_end(f.end()) ; i != i_end && ! skip ; ++i)
                if ((*i)->text() == stringify(a->blocked_atom()->package()))
                    skip = true;

            if (skip)
            {
                Log::get_instance()->message(ll_debug, lc_context,
                        "Ignoring self block (via PROVIDE) '" + stringify(*a->blocked_atom())
                        + "' for package '" + stringify(*d->_imp->current_pde()) + "'");
                return;
            }
        }
    }

    throw BlockError(stringify(*a->blocked_atom()));
}

void
DepList::AddVisitor::visit(const AllDepAtom * const a)
{
    std::for_each(a->begin(), a->end(), accept_visitor(this));
}

DepList::DepList(const Environment * const e, const DepListOptions & o) :
    PrivateImplementationPattern<DepList>(new Implementation<DepList>(e, o)),
    options(_imp->opts)
{
}

DepList::~DepList()
{
}

void
DepList::clear()
{
    DepListOptions o(options);
    _imp.assign(new Implementation<DepList>(_imp->env, o));
}

void
DepList::add_in_role(DepAtom::ConstPointer atom, const std::string & role)
{
    Context context("When adding " + role + ":");
    add(atom);
}

void
DepList::add(DepAtom::ConstPointer atom)
{
    DepListTransaction transaction(_imp->merge_list, _imp->merge_list_generation);

    Save<DepAtom::ConstPointer> save_current_top_level_target(&_imp->current_top_level_target,
            _imp->current_top_level_target ? _imp->current_top_level_target : atom);

    AddVisitor visitor(this);
    atom->accept(&visitor);
    transaction.commit();
}

void
DepList::add_package(const PackageDatabaseEntry & p, DepTag::ConstPointer tag)
{
    Context context("When adding package '" + stringify(p) + "':");

    Save<MergeList::iterator> save_merge_list_insert_position(&_imp->merge_list_insert_position);

    VersionMetadata::ConstPointer metadata(_imp->env->package_database()->fetch_repository(
                p.repository)->version_metadata(p.name, p.version));

    /* create our merge list entry. insert pre deps before ourself in the list. insert
     * post deps after ourself, and after any provides. */
    MergeList::iterator our_merge_entry_position(
            _imp->merge_list.insert(_imp->merge_list_insert_position,
                DepListEntry::create()
                .package(p)
                .metadata(metadata)
                .generation(_imp->merge_list_generation)
                .state(dle_no_deps)
                .tags(DepListEntryTags::Pointer(new DepListEntryTags::Concrete))
                .skip_install(metadata->get_virtual_interface()))),
        our_merge_entry_post_position(our_merge_entry_position);

    if (tag)
        our_merge_entry_position->tags->insert(DepTagEntry::create()
                .generation(_imp->merge_list_generation)
                .tag(tag));

    if (_imp->opts.dependency_tags && _imp->current_pde())
        our_merge_entry_position->tags->insert(DepTagEntry::create()
                .tag(DepTag::Pointer(new DependencyDepTag(*_imp->current_pde())))
                .generation(_imp->merge_list_generation));

    Save<MergeList::const_iterator> save_current_merge_list_entry(&_imp->current_merge_list_entry,
            our_merge_entry_position);

    _imp->merge_list_insert_position = our_merge_entry_position;

    /* add provides */
    if (metadata->get_ebuild_interface())
    {
        DepAtomFlattener f(_imp->env, _imp->current_pde(), metadata->get_ebuild_interface()->provide());
        for (DepAtomFlattener::Iterator i(f.begin()), i_end(f.end()) ; i != i_end ; ++i)
        {
            PackageDepAtom::Pointer pp(new PackageDepAtom("=" + (*i)->text() + "-" + stringify(p.version)));
            if (_imp->merge_list.end() != std::find_if(_imp->merge_list.begin(),
                        _imp->merge_list.end(), MatchDepListEntryAgainstPackageDepAtom(_imp->env,
                            pp.raw_pointer())))
                continue;

            VersionMetadata::ConstPointer m(0);

            if (_imp->env->package_database()->fetch_repository(RepositoryName("virtuals"))->has_version(
                        QualifiedPackageName((*i)->text()), p.version))
                m = _imp->env->package_database()->fetch_repository(RepositoryName("virtuals"))->version_metadata(
                        QualifiedPackageName((*i)->text()), p.version);
            else
            {
                VersionMetadata::Pointer mm(0);
                mm.assign(new VersionMetadata::Virtual(metadata->deps.parser,
                            PackageDatabaseEntry(p.name, p.version, RepositoryName("virtuals"))));
                mm->slot = metadata->slot;
                m = mm;
            }

            our_merge_entry_post_position = _imp->merge_list.insert(next(our_merge_entry_post_position),
                    DepListEntry(DepListEntry::create()
                        .package(PackageDatabaseEntry((*i)->text(), p.version, RepositoryName("virtuals")))
                        .metadata(m)
                        .generation(_imp->merge_list_generation)
                        .state(dle_has_all_deps)
                        .tags(DepListEntryTags::Pointer(new DepListEntryTags::Concrete))
                        .skip_install(m->get_virtual_interface())));
        }
    }

    /* add pre dependencies */
    add_predeps(metadata->deps.build_depend(), _imp->opts.uninstalled_deps_pre, "build");
    add_predeps(metadata->deps.run_depend(), _imp->opts.uninstalled_deps_runtime, "run");
    add_predeps(metadata->deps.post_depend(), _imp->opts.uninstalled_deps_post, "post");

    our_merge_entry_position->state = dle_has_pre_deps;
    _imp->merge_list_insert_position = next(our_merge_entry_post_position);

    add_postdeps(metadata->deps.build_depend(), _imp->opts.uninstalled_deps_pre, "build");
    add_postdeps(metadata->deps.run_depend(), _imp->opts.uninstalled_deps_runtime, "run");
    add_postdeps(metadata->deps.post_depend(), _imp->opts.uninstalled_deps_post, "post");

    our_merge_entry_position->state = dle_has_all_deps;
}

void
DepList::add_predeps(DepAtom::ConstPointer d, const DepListDepsOption opt, const std::string & s)
{
    if (dl_deps_pre == opt || dl_deps_pre_or_post == opt)
    {
        try
        {
            add_in_role(d, s + " dependencies as pre dependencies");
        }
        catch (const DepListError & e)
        {
            if (dl_deps_pre == opt)
                throw;
            else
                Log::get_instance()->message(ll_warning, lc_context, "Dropping " + s + " dependencies to "
                        "post dependencies because of exception '" + e.message() + "' (" + e.what() + ")");
        }
    }
}

void
DepList::add_postdeps(DepAtom::ConstPointer d, const DepListDepsOption opt, const std::string & s)
{
    if (dl_deps_pre_or_post == opt || dl_deps_post == opt || dl_deps_try_post == opt)
    {
        try
        {
            add_in_role(d, s + " dependencies as post dependencies");
        }
        catch (const DepListError & e)
        {
            if (dl_deps_try_post != opt)
                throw;
            else
                Log::get_instance()->message(ll_warning, lc_context, "Ignoring " + s +
                        " dependencies due to exception '" + e.message() + "' (" + e.what() + ")");
        }
    }
}

void
DepList::add_already_installed_package(const PackageDatabaseEntry & p, DepTag::ConstPointer tag)
{
    Context context("When adding installed package '" + stringify(p) + "':");

    Save<MergeList::iterator> save_merge_list_insert_position(&_imp->merge_list_insert_position);
    VersionMetadata::ConstPointer metadata(_imp->env->package_database()->fetch_repository(
                p.repository)->version_metadata(p.name, p.version));

    MergeList::iterator our_merge_entry(_imp->merge_list.insert(_imp->merge_list_insert_position,
                DepListEntry::create()
                .package(p)
                .metadata(metadata)
                .generation(_imp->merge_list_generation)
                .tags(DepListEntryTags::Pointer(new DepListEntryTags::Concrete))
                .state(dle_has_pre_deps)
                .skip_install(true)));

    if (tag)
        our_merge_entry->tags->insert(DepTagEntry::create()
                .generation(_imp->merge_list_generation)
                .tag(tag));

    if (_imp->opts.dependency_tags && _imp->current_pde())
        our_merge_entry->tags->insert(DepTagEntry::create()
                .tag(DepTag::Pointer(new DependencyDepTag(*_imp->current_pde())))
                .generation(_imp->merge_list_generation));

    Save<MergeList::const_iterator> save_current_merge_list_entry(&_imp->current_merge_list_entry,
            our_merge_entry);

    add_predeps(metadata->deps.build_depend(), _imp->opts.installed_deps_pre, "build");
    add_predeps(metadata->deps.run_depend(), _imp->opts.installed_deps_runtime, "run");
    add_predeps(metadata->deps.post_depend(), _imp->opts.installed_deps_post, "post");

    our_merge_entry->state = dle_has_pre_deps;
    _imp->merge_list_insert_position = next(our_merge_entry);

    add_postdeps(metadata->deps.build_depend(), _imp->opts.installed_deps_pre, "build");
    add_postdeps(metadata->deps.run_depend(), _imp->opts.installed_deps_runtime, "run");
    add_postdeps(metadata->deps.post_depend(), _imp->opts.installed_deps_post, "post");
}

namespace
{
    bool is_scm(const QualifiedPackageName & n)
    {
        std::string pkg(stringify(n.package));
        switch (pkg.length())
        {
            case 0:
            case 1:
            case 2:
            case 3:
                return false;

            default:
                if (0 == pkg.compare(pkg.length() - 5, 5, "-live"))
                    return true;

            case 4:
                if (0 == pkg.compare(pkg.length() - 4, 4, "-cvs"))
                    return true;
                if (0 == pkg.compare(pkg.length() - 4, 4, "-svn"))
                    return true;
                return false;
        }
        return false;
    }
}

bool
DepList::prefer_installed_over_uninstalled(const PackageDatabaseEntry & installed,
        const PackageDatabaseEntry & uninstalled)
{
    do
    {
        switch (_imp->opts.target_type)
        {
            case dl_target_package:
                if (! _imp->current_pde())
                    return false;

                if (is_top_level_target(uninstalled))
                    return false;

                continue;

            case dl_target_set:
                continue;
        }

        throw InternalError(PALUDIS_HERE, "Bad target_type value '" + stringify(_imp->opts.target_type) + "'");
    } while (false);

    if (dl_reinstall_always == _imp->opts.reinstall)
            return false;

    if (dl_upgrade_as_needed == _imp->opts.upgrade)
        return true;

    if (dl_reinstall_scm_never != _imp->opts.reinstall_scm)
        if (uninstalled.version == installed.version &&
                (installed.version.is_scm() || is_scm(installed.name)))
        {
            static time_t current_time(time(0)); /* static to avoid weirdness */
            time_t installed_time(_imp->env->package_database()->fetch_repository(installed.repository
                        )->installed_interface->installed_time(installed.name, installed.version));
            do
            {
                switch (_imp->opts.reinstall_scm)
                {
                    case dl_reinstall_scm_always:
                        return false;

                    case dl_reinstall_scm_daily:
                        if (current_time - installed_time > (24 * 60 * 60))
                            return false;
                        continue;

                    case dl_reinstall_scm_weekly:
                        if (current_time - installed_time > (24 * 60 * 60 * 7))
                            return false;
                        continue;

                    case dl_reinstall_never:
                        ; /* nothing */
                }

                throw InternalError(PALUDIS_HERE, "Bad value for opts.reinstall_scm");
            } while (false);
        }

    /* use != rather than > to correctly force a downgrade when packages are
     * removed. */
    if (uninstalled.version != installed.version)
        return false;

    if (dl_reinstall_if_use_changed == _imp->opts.reinstall)
    {
        const EbuildVersionMetadata * const evm_i(_imp->env->package_database()->fetch_repository(
                    installed.repository)->version_metadata(installed.name, installed.version)->get_ebuild_interface());
        const EbuildVersionMetadata * const evm_u(_imp->env->package_database()->fetch_repository(
                    uninstalled.repository)->version_metadata(uninstalled.name, uninstalled.version)->get_ebuild_interface());

        std::set<std::string> use_i, use_u, use_common;
        if (evm_i)
            WhitespaceTokeniser::get_instance()->tokenise(evm_i->iuse, std::inserter(use_i, use_i.end()));
        if (evm_u)
            WhitespaceTokeniser::get_instance()->tokenise(evm_u->iuse, std::inserter(use_u, use_u.end()));

        std::set_intersection(use_i.begin(), use_i.end(), use_u.begin(), use_u.end(),
                std::inserter(use_common, use_common.end()));

        for (std::set<std::string>::const_iterator f(use_common.begin()), f_end(use_common.end()) ;
                f != f_end ; ++f)
            if (_imp->env->query_use(UseFlagName(*f), &installed) != _imp->env->query_use(UseFlagName(*f), &uninstalled))
                return false;
    }

    return true;
}

bool
DepList::already_installed(DepAtom::ConstPointer atom) const
{
    return already_installed(atom.raw_pointer());
}

bool
DepList::already_installed(const DepAtom * const atom) const
{
    QueryVisitor visitor(this);
    atom->accept(&visitor);
    return visitor.result;
}

DepList::Iterator
DepList::begin() const
{
    return Iterator(_imp->merge_list.begin());
}

DepList::Iterator
DepList::end() const
{
    return Iterator(_imp->merge_list.end());
}

namespace
{
    struct IsTopLevelTarget :
        DepAtomVisitorTypes::ConstVisitor,
        std::unary_function<PackageDatabaseEntry, bool>
    {
        const Environment * const env;
        DepAtom::ConstPointer target;
        const PackageDatabaseEntry * dbe;
        bool matched;

        IsTopLevelTarget(const Environment * const e, DepAtom::ConstPointer t) :
            env(e),
            target(t),
            matched(false)
        {
        }

        bool operator() (const PackageDatabaseEntry & e)
        {
            dbe = &e;
            matched = false;
            target->accept(this);
            return matched;
        }

        void visit(const AllDepAtom * const a)
        {
            if (matched)
                return;

            std::for_each(a->begin(), a->end(), accept_visitor(this));
        }

        void visit(const PackageDepAtom * const a)
        {
            if (matched)
                return;

            if (match_package(env, a, *dbe))
                matched = true;
        }

        void visit(const UseDepAtom * const u)
        {
            if (matched)
                return;

            std::for_each(u->begin(), u->end(), accept_visitor(this));
        }

        void visit(const AnyDepAtom * const a)
        {
            if (matched)
                return;

            std::for_each(a->begin(), a->end(), accept_visitor(this));
        }

        void visit(const BlockDepAtom * const)
        {
        }

        void visit(const PlainTextDepAtom * const) PALUDIS_ATTRIBUTE((noreturn))
        {
            throw InternalError(PALUDIS_HERE, "Got PlainTextDepAtom?");
        }
    };

}

bool
DepList::is_top_level_target(const PackageDatabaseEntry & e) const
{
    if (! _imp->current_top_level_target)
        throw InternalError(PALUDIS_HERE, "current_top_level_target not set?");

    IsTopLevelTarget t(_imp->env, _imp->current_top_level_target);
    return t(e);
}