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
/*<LICENSE>
    This file is part of Memthol.

    Copyright (C) 2020 OCamlPro.

    Memthol is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Memthol 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 Memthol.  If not, see <https://www.gnu.org/licenses/>.
*/

//! UID types for charts, filters and subfilters.
//!
//! All UID types implement serialize and deserialize.
//!
//! Types [`Chart`], [`Filter`] and [`SubFilter`] are the straightforward UIDs. This module also has
//! a [`Line`] type which augments [`Filter`] with two additional variants:
//!
//! - the "catch-all filter", which is the filter that catches everything the other filters do not
//!   catch;
//! - the "everything filter", which is the filter that catches **all** allocations, independently
//!   of the user-defined filters.
//!
//! [`Chart`]: Chart (The Chart struct)
//! [`Filter`]: Filter (The Filter struct)
//! [`Line`]: Line (The Line enum)
//! [`SubFilter`]: SubFilter (The SubFilter struct)

use std::fmt;

/// Creates UID-related types and a factory for UIDs.
macro_rules! new_uids {
    () => {};
    (
        mod $mod_name:ident {
            $(#[$uid_meta:meta])*
            $uid_type_name:ident
            $(
                ,
                $(#[$map_meta:meta])*
                map: $map_name:ident with iter: $iter_name:ident
            )?
            $(
                ,
                fresh_fn: $fresh_name:ident
            )?
            $(,)?
        }
        $($tail:tt)*
    ) => {
        pub use $mod_name::{
            $uid_type_name,
            $($map_name)?
        };
        mod $mod_name {
            safe_index::new! {
                $(#[$uid_meta])*
                $uid_type_name,
                $(
                    $(#[$map_meta])*
                    map: $map_name
                )?
            }

            impl serde::Serialize for $uid_type_name {
                fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
                where
                    S: serde::Serializer,
                {
                    serializer.serialize_str(&self.to_string())
                }
            }
            struct UidVisitor;
            impl<'de> serde::de::Visitor<'de> for UidVisitor {
                type Value = $uid_type_name;

                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                    formatter.write_str("a UID (usize)")
                }

                fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
                where E: serde::de::Error {
                    use std::str::FromStr;
                    usize::from_str(value).map(|index| $uid_type_name::from(index)).map_err(
                        |e| E::custom(e.to_string())
                    )
                }
            }
            impl<'de> serde::Deserialize<'de> for $uid_type_name {
                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where
                    D: serde::Deserializer<'de>,
                {
                    deserializer.deserialize_str(UidVisitor)
                }
            }

            $(
                $crate::prelude::lazy_static! {
                    /// Uid factory.
                    static ref COUNTER: std::sync::Mutex<usize> = std::sync::Mutex::new(0);
                }

                impl $uid_type_name {
                    /// Yields a fresh UID.
                    pub fn $fresh_name() -> $uid_type_name {
                        let mut factory = COUNTER.lock().unwrap_or_else(|e| {
                            panic!(
                                "[sync] unable to access UID factory for `{}`: {}",
                                stringify!($uid_type_name),
                                e
                            )
                        });
                        let uid = *factory;
                        *factory += 1;
                        uid.into()
                    }
                }
            )?
        }

        new_uids! { $($tail)* }
    };
}

new_uids! {
    mod alloc_uid {
        /// Allocation UID.
        Alloc,
        /// Map from allocation UIDs to something.
        map: AllocMap with iter: AllocIter,
    }

    mod chart_uid {
        /// Chart UID.
        Chart,
        fresh_fn: fresh,
    }

    mod filter_uid {
        /// Filter UID.
        Filter,
        fresh_fn: fresh,
    }

    mod sub_filter_uid {
        /// Sub-filter UID.
        SubFilter,
        fresh_fn: fresh,
    }
}

implement! {
    impl From for Alloc {
        from u64 => |n| {
            use std::convert::TryFrom;
            usize::try_from(n).unwrap_or_else(
                |e| panic!(
                    "`{}_u64` is not a valid `usize`, cannot construct allocation UID:\n{}", n, e
                )
            ).into()
        }
    }
}

/// A UID for a line in the chart.
///
/// A line in the chart is either an actual filter, or the "catch-all" line, or the "everything"
/// line.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub enum Line {
    /// An actual filter.
    Filter(Filter),
    /// The catch-all filter.
    CatchAll,
    /// The everything filter.
    Everything,
}

impl From<Filter> for Line {
    fn from(uid: Filter) -> Line {
        Self::Filter(uid)
    }
}

impl Line {
    /// The filter UID, if any.
    pub fn filter_uid(self) -> Option<Filter> {
        match self {
            Self::Filter(uid) => Some(uid),
            Self::CatchAll | Self::Everything => None,
        }
    }

    /// True if the filter is the `everything` filter.
    pub fn is_everything(self) -> bool {
        self == Self::Everything
    }
    /// True if the filter is the `catch_all` filter.
    pub fn is_catch_all(self) -> bool {
        self == Self::CatchAll
    }

    /// Y-axis key representation.
    pub fn y_axis_key(self) -> String {
        match self {
            Self::Filter(uid) => format!("y_{}", uid),
            Self::CatchAll => "y_catch_all".into(),
            Self::Everything => "y".into(),
        }
    }
}

impl fmt::Display for Line {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Filter(uid) => uid.fmt(fmt),
            Self::CatchAll => line_uid::CATCH_ALL_STR.fmt(fmt),
            Self::Everything => line_uid::EVERYTHING_STR.fmt(fmt),
        }
    }
}

mod line_uid {
    use super::*;

    /// String representing the `CatchAll` variant of `Line`.
    pub const CATCH_ALL_STR: &str = "catch_all";
    /// String representing the `Everything` variant of `Line`.
    pub const EVERYTHING_STR: &str = "everything";

    impl serde::Serialize for Line {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
        {
            serializer.serialize_str(&self.to_string())
        }
    }
    struct UidVisitor;
    impl<'de> serde::de::Visitor<'de> for UidVisitor {
        type Value = Line;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("a UID (usize), or `catch_all`, or `everything`")
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            use std::str::FromStr;
            if value == CATCH_ALL_STR {
                Ok(Line::CatchAll)
            } else if value == EVERYTHING_STR {
                Ok(Line::Everything)
            } else {
                usize::from_str(value)
                    .map(|index| Line::Filter(Filter::from(index)))
                    .map_err(|e| E::custom(e.to_string()))
            }
        }
    }
    impl<'de> serde::Deserialize<'de> for Line {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            deserializer.deserialize_str(UidVisitor)
        }
    }
}