hakari/explain/
mod.rs

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
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Information about why a dependency is in the workspace-hack.
//!
//! [`HakariExplain`] instances are produced by [`Hakari::explain`]. The current API is limited
//! to displaying these instances if the `cli-support` feature is enabled.

#[cfg(feature = "cli-support")]
mod display;
mod simplify;

#[cfg(feature = "cli-support")]
pub use display::HakariExplainDisplay;

use crate::{explain::simplify::*, Hakari};
use guppy::{
    graph::{cargo::BuildPlatform, feature::StandardFeatures, PackageGraph, PackageMetadata},
    PackageId,
};
use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Arc,
};
use target_spec::Platform;

/// The result of a Hakari explain query.
///
/// Generated by [`Hakari::explain`].
#[derive(Clone, Debug)]
pub struct HakariExplain<'g, 'a> {
    #[cfg_attr(not(feature = "cli-support"), allow(dead_code))]
    graph: &'g PackageGraph,
    metadata: PackageMetadata<'g>,
    #[cfg_attr(not(feature = "cli-support"), allow(dead_code))]
    platforms: &'a [Arc<Platform>],
    target_map: ExplainMap<'g, 'a>,
    host_map: ExplainMap<'g, 'a>,
}

type ExplainMap<'g, 'a> = BTreeMap<&'a BTreeSet<&'g str>, ExplainInner<'g>>;

#[derive(Clone, Debug, Default)]
struct ExplainInner<'g> {
    #[cfg_attr(not(feature = "cli-support"), allow(dead_code))]
    workspace_packages: BTreeMap<&'g PackageId, ExplainInnerValue<'g>>,
    #[cfg_attr(not(feature = "cli-support"), allow(dead_code))]
    fixup_platforms: Vec<Simple<Option<usize>>>,
}

#[derive(Clone, Debug)]
#[allow(clippy::type_complexity)]
struct ExplainInnerValue<'g> {
    #[cfg_attr(not(feature = "cli-support"), allow(dead_code))]
    metadata: PackageMetadata<'g>,
    #[cfg_attr(not(feature = "cli-support"), allow(dead_code))]
    sets: Vec<(
        Simple<bool>,
        Simple<StandardFeatures>,
        Simple<Option<usize>>,
    )>,
}

impl<'g, 'a> HakariExplain<'g, 'a> {
    pub(crate) fn new(hakari: &'a Hakari<'g>, dep_id: &PackageId) -> Result<Self, guppy::Error> {
        let graph = hakari.builder.graph();
        let metadata = hakari.builder.graph().metadata(dep_id)?;
        let intermediate = ExplainIntermediate::new(hakari, metadata.id())?;

        let target_map = Self::simplify_map(hakari, intermediate.target_map);
        let host_map = Self::simplify_map(hakari, intermediate.host_map);

        Ok(Self {
            graph,
            metadata,
            platforms: &hakari.builder.platforms,
            target_map,
            host_map,
        })
    }

    fn simplify_map(hakari: &'a Hakari<'g>, map: IntermediateMap<'g, 'a>) -> ExplainMap<'g, 'a> {
        const STANDARD_FEATURES_COUNT: usize = 3;
        const INCLUDE_DEV_COUNT: usize = 2;
        // +1 for the None case
        let platform_count = hakari.builder.platforms.len() + 1;

        map.into_iter()
            .map(|(features, inner)| {
                let workspace_packages = inner
                    .workspace_packages
                    .into_iter()
                    .map(|(package_id, IntermediateInnerValue { metadata, sets })| {
                        let sets = simplify3(
                            &sets,
                            (INCLUDE_DEV_COUNT, STANDARD_FEATURES_COUNT, platform_count),
                        );
                        (package_id, ExplainInnerValue { metadata, sets })
                    })
                    .collect();
                let fixup_platforms = simplify1(&inner.fixup_platforms, platform_count);
                (
                    features,
                    ExplainInner {
                        workspace_packages,
                        fixup_platforms,
                    },
                )
            })
            .collect()
    }

    /// Returns [`PackageMetadata`] for the dependency associated with this `HakariExplain`
    /// instance.
    pub fn dependency(&self) -> PackageMetadata<'g> {
        self.metadata
    }

    /// Returns a displayer for the output.
    #[cfg(feature = "cli-support")]
    pub fn display<'explain>(&'explain self) -> HakariExplainDisplay<'g, 'a, 'explain> {
        HakariExplainDisplay::new(self)
    }

    // Used by the display module.
    #[allow(dead_code)]
    fn explain_maps(&self) -> [(BuildPlatform, &ExplainMap<'g, 'a>); 2] {
        [
            (BuildPlatform::Target, &self.target_map),
            (BuildPlatform::Host, &self.host_map),
        ]
    }
}

/// Pre-simplification map.
#[derive(Debug)]
struct ExplainIntermediate<'g, 'a> {
    target_map: IntermediateMap<'g, 'a>,
    host_map: IntermediateMap<'g, 'a>,
}

type IntermediateMap<'g, 'a> = BTreeMap<&'a BTreeSet<&'g str>, IntermediateInner<'g>>;

#[derive(Debug, Default)]
struct IntermediateInner<'g> {
    workspace_packages: BTreeMap<&'g PackageId, IntermediateInnerValue<'g>>,
    fixup_platforms: BTreeSet<Option<usize>>,
}

#[derive(Debug)]
struct IntermediateInnerValue<'g> {
    metadata: PackageMetadata<'g>,
    sets: BTreeSet<(bool, StandardFeatures, Option<usize>)>,
}

impl<'g, 'a> ExplainIntermediate<'g, 'a> {
    fn new(hakari: &'a Hakari<'g>, dep_id: &'g PackageId) -> Result<Self, guppy::Error> {
        let mut target_map: IntermediateMap<'g, 'a> = BTreeMap::new();
        let mut host_map: IntermediateMap<'g, 'a> = BTreeMap::new();

        // Look at the computed map to figure out which packages are built.
        let platform_idxs =
            std::iter::once(None).chain((0..=hakari.builder.platforms.len()).map(Some));
        let map_keys = platform_idxs.map(|idx| (idx, dep_id));

        for (platform, package_id) in map_keys {
            let computed_value = match hakari.computed_map.get(&(platform, package_id)) {
                Some(v) => v,
                None => continue,
            };

            for (build_platform, inner_map) in computed_value.inner_maps() {
                let map = match build_platform {
                    BuildPlatform::Target => &mut target_map,
                    BuildPlatform::Host => &mut host_map,
                };

                for (features, inner_value) in inner_map {
                    for &(workspace_package, standard_features, include_dev) in
                        &inner_value.workspace_packages
                    {
                        map.entry(features)
                            .or_default()
                            .workspace_packages
                            .entry(workspace_package.id())
                            .or_insert_with(|| IntermediateInnerValue {
                                metadata: workspace_package,
                                sets: BTreeSet::new(),
                            })
                            .sets
                            .insert((include_dev, standard_features, platform));
                    }

                    if inner_value.fixed_up {
                        map.entry(features)
                            .or_default()
                            .fixup_platforms
                            .insert(platform);
                    }
                }
            }
        }

        if target_map.is_empty() && host_map.is_empty() {
            return Err(guppy::Error::UnknownPackageId(dep_id.clone()));
        }

        Ok(Self {
            target_map,
            host_map,
        })
    }
}