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
/*<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/>.
*/

//! Types and parsers for memthol's dump structures.
//!
//! These types are used by memthol's client when loading up memthol diffs.
//!
//! Generally speaking, all the types in this crate are parsed, not created from scratch. There is
//! no [`Uid`] factory for instance, since we will not have to generate fresh `Uid`s. We will only
//! parse them, the fact that they're unique must be guaranteed by whoever generated them.
//!
//! The entry point in terms of parsing is [`Diff`], since (currently) the only way the client can
//! build the other types is when parsing a `Diff`.
//!
//! # Dealing With Time
//!
//! There are two types to handle time: [`Date`] and [`SinceStart`]. The former encodes an absolute
//! date, while the latter is a only a duration. Memthol's init file specifies the `Date` at which
//! the program we're profiling started. After that, all the allocation data relies on `SinceStart`
//! to refer to point in times relative to the start date.
//!
//! [`Diff`]: Diff (The Diff struct)
//! [`Uid`]: base::uid::Alloc (The Alloc struct)
//! [`Date`]: base::time::Date (The Date struct)
//! [`SinceStart`]: base::time::SinceStart (The SinceStart struct)

#![deny(missing_docs)]
pub use error_chain::bail;
pub use num_bigint::BigUint;

#[macro_use]
pub mod prelude;

#[macro_use]
pub mod mem;

pub mod parser;

mod fmt;

prelude! {}

/// Errors, handled by `error_chain`.
pub mod err {
    pub use base::err::*;
}

/// Some tests, only active in `test` mode.
#[cfg(test)]
mod test;

/// A byte-span.
pub type Span = base::Range<usize>;

/// A location.
///
/// # Construction From String Slices
///
/// ```rust
/// # alloc_data::prelude! {}
/// let s = "`blah/stuff/file.ml`:325:7-38";
/// let loc = Loc::parse(s).unwrap();
/// # println!("loc: {}", loc);
/// assert_eq! { format!("{}", loc), s }
/// assert_eq! { loc.file, "blah/stuff/file.ml" }
/// assert_eq! { loc.line, 325 }
/// assert_eq! { loc.span, (7, 38).into() }
/// ```
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Loc {
    /// File the location is for.
    pub file: Str,
    /// Line in the file.
    pub line: usize,
    /// Column span at that line in the file.
    pub span: Span,
}
impl Loc {
    /// Constructor.
    pub fn new(file: Str, line: usize, span: impl Into<Span>) -> Self {
        Self {
            file,
            line,
            span: span.into(),
        }
    }
}

/// A counted location.
///
/// Used in callstacks to represent a repetition of locations.
///
/// # Construction From String Slices
///
/// ```rust
/// # alloc_data::prelude! {}
/// let s = "`blah/stuff/file.ml`:325:7-38#5";
/// let CLoc { loc, cnt } = CLoc::parse(s).unwrap();
/// # println!("loc_count: {}#{}", loc, cnt);
/// assert_eq! { format!("{}", loc), s[0..s.len()-2] }
/// assert_eq! { loc.file, "blah/stuff/file.ml" }
/// assert_eq! { loc.line, 325 }
/// assert_eq! { loc.span, (7, 38).into() }
/// assert_eq! { cnt, 5 }
/// ```
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct CLoc {
    /// Location.
    pub loc: Loc,
    /// Number of times the location is repeated.
    pub cnt: usize,
}
impl CLoc {
    /// Constructor.
    pub fn new(loc: Loc, cnt: usize) -> Self {
        Self { loc, cnt }
    }
}

/// A kind of allocation.
///
/// # Construction From String Slices
///
/// ```rust
/// # alloc_data::prelude! {}
/// let s_list = [
///     ("Minor", AllocKind::Minor),
///     ("Major", AllocKind::Major),
///     ("MajorPostponed", AllocKind::MajorPostponed),
///     ("Serialized", AllocKind::Serialized),
/// ];
/// for (s, exp) in &s_list {
///     let kind = AllocKind::parse(*s).unwrap();
///     assert_eq! { kind, *exp }
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AllocKind {
    /// Minor allocation.
    Minor,
    /// Major allocation.
    Major,
    /// Major postponed.
    MajorPostponed,
    /// Serialized.
    Serialized,
    /// Unknown allocation.
    Unknown,
}

impl AllocKind {
    /// String representation of an allocation kind.
    pub fn as_str(&self) -> &'static str {
        use AllocKind::*;
        match self {
            Minor => "Minor",
            Major => "Major",
            MajorPostponed => "MajorPostponed",
            Serialized => "Serialized",
            Unknown => "_",
        }
    }
}

/// An allocation builder.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Builder {
    /// UID hint.
    pub uid_hint: Option<uid::Alloc>,
    /// Allocation kind.
    pub kind: AllocKind,
    /// Size of the allocation.
    pub size: u32,
    /// Sample count.
    pub nsamples: u32,
    /// Allocation-site callstack.
    trace: Trace,
    /// User-defined labels.
    labels: Labels,
    /// Time of creation.
    pub toc: time::SinceStart,
    /// Time of death.
    pub tod: Option<time::SinceStart>,
}
impl Builder {
    /// Constructor.
    pub fn new(
        uid_hint: Option<uid::Alloc>,
        kind: AllocKind,
        size: u32,
        trace: Trace,
        labels: Labels,
        toc: time::SinceStart,
        tod: Option<time::SinceStart>,
    ) -> Self { 
        Self {
            uid_hint,
            kind,
            size,
            nsamples: size,
            trace,
            labels,
            toc,
            tod,
        }
    }

    /// Sets the number of samples.
    pub fn nsamples(mut self, nsamples: u32) -> Self {
        self.nsamples = nsamples;
        self
    }

    /// Builds an `Alloc`.
    pub fn build(self, sample_rate: &SampleRate, uid: uid::Alloc) -> Res<Alloc> {
        let Self {
            uid_hint,
            kind,
            size,
            nsamples,
            trace,
            labels,
            toc,
            tod,
        } = self;
        let real_size = sample_rate.real_size_of(nsamples);
        match uid_hint {
            None => (),
            Some(hint) if uid == hint => (),
            Some(hint) => bail!(
                "failed alloc UID check: expected {}, but hint says {}",
                uid,
                hint,
            ),
        }
        Ok(Alloc {
            uid,
            kind,
            size,
            real_size,
            nsamples,
            trace,
            labels,
            toc,
            tod,
        })
    }
}

/// Some allocation information.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Alloc {
    /// Uid of the allocation.
    pub uid: uid::Alloc,
    /// Allocation kind.
    pub kind: AllocKind,
    /// Size of the allocation.
    pub size: u32,
    /// Real size of the allocation.
    pub real_size: u32,
    /// Sample count.
    pub nsamples: u32,
    /// Allocation-site callstack.
    trace: Trace,
    /// User-defined labels.
    labels: Labels,
    /// Time of creation.
    pub toc: time::SinceStart,
    /// Time of death.
    pub tod: Option<time::SinceStart>,
}

impl Alloc {
    /// Constructor.
    pub fn new(
        sample_rate: &base::SampleRate,
        uid: impl Into<uid::Alloc>,
        kind: AllocKind,
        size: u32,
        trace: Trace,
        labels: Labels,
        toc: time::SinceStart,
        tod: Option<time::SinceStart>,
    ) -> Self {
        let uid = uid.into();
        let nsamples = size;
        let real_size = sample_rate.real_size_of(nsamples);
        Self {
            uid,
            kind,
            size,
            real_size,
            nsamples: size,
            trace,
            labels,
            toc,
            tod,
        }
    }

    /// Sets the number of samples.
    pub fn nsamples(mut self, nsamples: u32) -> Self {
        self.nsamples = nsamples;
        self
    }

    /// Sets the time of death.
    ///
    /// Bails if a time of death is already registered.
    pub fn set_tod(&mut self, tod: time::SinceStart) -> Result<(), String> {
        if self.tod.is_some() {
            Err("\
                 trying to set the time of death, \
                 but a tod is already registered for this allocation\
                 "
            .into())
        } else {
            self.tod = Some(tod);
            Ok(())
        }
    }

    /// Sets the time of creation.
    pub fn set_toc(&mut self, toc: time::SinceStart) {
        self.toc = toc
    }

    /// UID accessor.
    pub fn uid(&self) -> &uid::Alloc {
        &self.uid
    }
    /// Kind accessor.
    pub fn kind(&self) -> &AllocKind {
        &self.kind
    }
    /// Size accessor (in machine words).
    pub fn size(&self) -> u32 {
        self.size
    }

    /// Trace accessor.
    pub fn trace(&self) -> Arc<Vec<CLoc>> {
        self.trace.get()
    }
    /// Allocation-site of the allocation.
    pub fn alloc_site_do<Res>(&self, action: impl FnOnce(Option<&CLoc>) -> Res) -> Res {
        let trace = self.trace();
        action(trace.last())
    }

    /// Labels accessor.
    pub fn labels(&self) -> Arc<Vec<Str>> {
        self.labels.get()
    }
    /// Time of creation accessor.
    pub fn toc(&self) -> time::SinceStart {
        self.toc
    }
    /// Time of death accessor.
    pub fn tod(&self) -> Option<time::SinceStart> {
        self.tod
    }
}

/// A diff.
///
/// **NB:** `Display` for this type is multi-line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Diff {
    /// Timestamp.
    pub time: time::SinceStart,
    /// New allocations in this diff.
    pub new: Vec<Builder>,
    /// Data freed in this diff.
    pub dead: Vec<(uid::Alloc, time::SinceStart)>,
}

impl Diff {
    /// Constructor.
    pub fn new(
        time: time::SinceStart,
        new: Vec<Builder>,
        dead: Vec<(uid::Alloc, time::SinceStart)>,
    ) -> Self {
        Self { time, new, dead }
    }
}

/// Data from a memthol init file.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Init {
    /// The start time of the run: an absolute date.
    pub start_time: time::Date,
    /// Optional end time.
    pub end_time: Option<time::SinceStart>,
    /// Size of machine words in bytes.
    pub word_size: usize,
    /// True if the callstack go from `main` to allocation site, called *reversed order*.
    pub callstack_is_rev: bool,
    /// Sampling rate.
    pub sample_rate: base::SampleRate,
}

impl Default for Init {
    fn default() -> Self {
        Self {
            start_time: time::Date::from_timestamp(0, 0),
            end_time: None,
            word_size: 8,
            callstack_is_rev: false,
            sample_rate: SampleRate::new(1.0, 8),
        }
    }
}

impl Init {
    /// Constructor.
    pub fn new(
        start_time: time::Date,
        end_time: Option<time::SinceStart>,
        word_size: usize,
        callstack_is_rev: bool,
    ) -> Self {
        Self {
            start_time,
            end_time,
            word_size,
            callstack_is_rev,
            sample_rate: SampleRate::new(1.0, convert(word_size, "Init::new, word_size")),
        }
    }

    /// Sets the sampling rate.
    pub fn sample_rate(mut self, rate: f64) -> Self {
        self.sample_rate = SampleRate::new(
            rate,
            convert(self.word_size, "Init::sample_rate, word_size"),
        );
        self
    }
}