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

//! Location filters.

prelude! {}

use filter::{string_like, FilterExt};

/// A location filter.
pub type LocFilter = string_like::StringLikeFilter<LocSpec>;

/// A location list predicate.
pub type LocPred = string_like::Pred;

/// An update for a location filter.
pub type LocUpdate = string_like::Update;

/// A line specification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum LineSpec {
    /// Matches a precise line.
    Value(usize),
    /// Matches a range of lines.
    ///
    /// If `lb.is_none()` and `ub.is_none()`, the range matches any line at all.
    Range {
        /// Lower bound.
        lb: Option<usize>,
        /// Upper bound.
        ub: Option<usize>,
    },
}
impl LineSpec {
    /// Matches any line at all.
    pub fn any() -> Self {
        Self::Range { lb: None, ub: None }
    }
    /// Matches a precise line.
    pub fn line(line: usize) -> Self {
        Self::Value(line)
    }
    /// Matches a range of lines.
    pub fn range(lb: Option<usize>, ub: Option<usize>) -> Self {
        Self::Range { lb, ub }
    }

    /// Constructor, from a string.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use charts::filter::loc::*;
    /// let line_spec = LineSpec::new("_").unwrap();
    /// assert_eq!(line_spec, LineSpec::any());
    ///
    /// let line_spec = LineSpec::new("79").unwrap();
    /// assert_eq!(line_spec, LineSpec::line(79));
    ///
    /// let line_spec = LineSpec::new("[79, 105]").unwrap();
    /// assert_eq!(line_spec, LineSpec::range(Some(79), Some(105)));
    ///
    /// let line_spec = LineSpec::new(" [ 79  , 105  ]  ").unwrap();
    /// assert_eq!(line_spec, LineSpec::range(Some(79), Some(105)));
    ///
    /// let line_spec = LineSpec::new(" [ _  , 105  ]  ").unwrap();
    /// assert_eq!(line_spec, LineSpec::range(None, Some(105)));
    ///
    /// let line_spec = LineSpec::new(" [ 105, _  ]  ").unwrap();
    /// assert_eq!(line_spec, LineSpec::range(Some(105), None));
    /// ```
    pub fn new(str: impl AsRef<str>) -> Res<Self> {
        let mut s = str.as_ref();
        macro_rules! s_do {
            (trim) => {
                s = s.trim()
            };
            (sub $lb:expr) => {
                s = &s[$lb..];
                s_do!(trim)
            };
            (bail) => {
                bail!(s_do!(bail msg))
            };
            (bail if $cond:expr) => {
                if $cond {
                    s_do!(bail)
                }
            };
            (bail msg) => {
                format!("`{}` is not a legal line specification", str.as_ref())
            }
        }

        s_do!(trim);
        if s.is_empty() {
            return Ok(Self::any());
        }
        // `s` is not empty now.

        if &s[0..1] == "[" {
            s_do!(sub 1);
            s_do!(bail if s.is_empty());

            let mut subs = s.split(",");

            let lb = if let Some(mut lb) = subs.next() {
                lb = lb.trim();
                if lb == "_" {
                    None
                } else {
                    let lb = usize::from_str(lb).chain_err(|| s_do!(bail msg))?;
                    Some(lb)
                }
            } else {
                s_do!(bail)
            };

            let ub = if let Some(mut ub) = subs.next() {
                ub = ub.trim();
                s_do!(bail if
                    ub.is_empty() || &ub[ub.len() - 1..ub.len()] != "]"
                );
                ub = ub[0..ub.len() - 1].trim();
                if ub == "_" {
                    None
                } else {
                    let ub = usize::from_str(ub).chain_err(|| s_do!(bail msg))?;
                    Some(ub)
                }
            } else {
                s_do!(bail)
            };

            Ok(Self::range(lb, ub))
        } else if s == "_" {
            Ok(Self::any())
        } else {
            let line = usize::from_str(s).chain_err(|| s_do!(bail msg))?;
            Ok(Self::line(line))
        }
    }

    /// True if the line specification matches anything.
    pub fn matches_anything(&self) -> bool {
        match self {
            Self::Value(_) => false,
            Self::Range { lb: None, ub: None } => true,
            Self::Range { .. } => false,
        }
    }
}
impl FilterExt<usize> for LineSpec {
    fn apply(&self, line: &usize) -> bool {
        match self {
            Self::Value(l) => l == line,
            Self::Range { lb, ub } => {
                lb.map(|lb| lb <= *line).unwrap_or(true) && ub.map(|ub| *line <= ub).unwrap_or(true)
            }
        }
    }
}
impl fmt::Display for LineSpec {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Value(line) => line.fmt(fmt),
            Self::Range { lb: None, ub: None } => "_".fmt(fmt),
            Self::Range { lb, ub } => {
                "[".fmt(fmt)?;
                if let Some(lb) = lb {
                    lb.fmt(fmt)?
                } else {
                    "_".fmt(fmt)?
                }
                write!(fmt, ", ")?;
                if let Some(ub) = ub {
                    ub.fmt(fmt)?
                } else {
                    "_".fmt(fmt)?
                }
                "]".fmt(fmt)
            }
        }
    }
}

/// Loc specification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LocSpec {
    /// Matches a sequence of arbitrary locations.
    Anything,
    /// An actualy location value.
    Value {
        /// Location string.
        value: String,
        /// Location line.
        line: LineSpec,
    },
    /// A regular expression.
    Regex {
        /// Location regex.
        #[serde(with = "serde_regex")]
        regex: Regex,
        /// Location line.
        line: LineSpec,
    },
}
impl std::cmp::Eq for LocSpec {}
impl std::cmp::PartialEq for LocSpec {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Anything, Self::Anything) => true,
            (
                Self::Value {
                    value: lft_value,
                    line: lft_line,
                },
                Self::Value {
                    value: rgt_value,
                    line: rgt_line,
                },
            ) => lft_value == rgt_value && lft_line == rgt_line,
            (
                Self::Regex {
                    regex: lft_regex,
                    line: lft_line,
                },
                Self::Regex {
                    regex: rgt_regex,
                    line: rgt_line,
                },
            ) => lft_regex.as_str() == rgt_regex.as_str() && lft_line == rgt_line,
            (Self::Anything, _) | (Self::Value { .. }, _) | (Self::Regex { .. }, _) => false,
        }
    }
}

impl FilterExt<alloc::CLoc> for LocSpec {
    fn apply(&self, alloc::CLoc { loc, .. }: &alloc::CLoc) -> bool {
        match self {
            LocSpec::Anything => true,
            LocSpec::Value { value, line } => &loc.file == value && line.apply(&loc.line),
            LocSpec::Regex { regex, line } => {
                loc.file.str_do(|s| regex.is_match(s)) && line.apply(&loc.line)
            }
        }
    }
}

impl string_like::SpecExt for LocSpec {
    type Data = alloc::CLoc;
    const DATA_DESC: &'static str = "label";

    fn from_string(s: impl Into<String>) -> Res<Self> {
        Self::new(s)
    }

    /// True if the spec is an empty label.
    fn is_empty(&self) -> bool {
        match self {
            LocSpec::Value { value, line } => value == "" && line.matches_anything(),
            LocSpec::Regex { .. } => false,
            LocSpec::Anything => false,
        }
    }

    fn data_of_alloc(alloc: &Alloc) -> Arc<Vec<Self::Data>> {
        alloc.trace()
    }

    /// True if the input data is a match for this specification.
    fn matches(&self, data: &Self::Data) -> bool {
        self.apply(data)
    }

    /// True if the specification matches a repetition of anything.
    fn matches_anything(&self) -> bool {
        match self {
            Self::Anything => true,
            Self::Value { .. } => false,
            Self::Regex { .. } => false,
        }
    }
}

impl fmt::Display for LocSpec {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Value { value, line } => {
                write!(fmt, "{}", value)?;
                if !line.matches_anything() {
                    write!(fmt, " : {}", line)?
                }
                Ok(())
            }
            Self::Regex { regex, line } => {
                write!(fmt, "#\"{}\"#", regex)?;
                if !line.matches_anything() {
                    write!(fmt, " : {}", line)?
                }
                Ok(())
            }
            Self::Anything => write!(fmt, "**"),
        }
    }
}

impl Default for LocSpec {
    fn default() -> LocSpec {
        Self::new("path/to/my_file.ml:[55, _]").unwrap()
    }
}

impl LocSpec {
    /// Constructor from strings.
    pub fn new(s: impl Into<String>) -> Res<Self> {
        let loc = s.into();
        macro_rules! illegal {
            () => {{
                let err: err::Error = format!("illegal regex `{}`", loc).into();
                err
            }};
        }

        if loc == "**" {
            return Ok(Self::Anything);
        }

        let (file, line) = {
            let mut subs = loc.split(':');
            if let Some(file) = subs.next() {
                let file = file.trim();
                if let Some(line) = subs.next() {
                    if subs.next().is_some() {
                        bail!(
                            illegal!().chain_err(|| "found more than one `:` file/line separators")
                        )
                    }
                    (file, Some(line.trim()))
                } else {
                    (file, None)
                }
            } else {
                // Unreachable.
                bail!(illegal!().chain_err(|| "entered unreachable code"))
            }
        };

        let line = line
            .map(|s| LineSpec::new(s))
            .unwrap_or_else(|| Ok(LineSpec::any()));

        if file.len() > 2 && &file[0..2] == "#\"" {
            if &file[file.len() - 2..file.len()] != "\"#" {
                bail!(illegal!().chain_err(|| "a regex must end with `\"#`"))
            }

            let regex = Regex::new(&file[2..file.len() - 2])
                .map_err(|e| illegal!().chain_err(|| format!("{}", e)))?;
            Ok(Self::Regex { regex, line: line? })
        } else {
            Ok(Self::Value {
                value: file.into(),
                line: line?,
            })
        }
    }

    /// True if the spec matches anything.
    pub fn matches_anything(&self) -> bool {
        match self {
            Self::Anything => true,
            Self::Value { .. } => false,
            Self::Regex { .. } => false,
        }
    }
}

impl Default for string_like::StringLikeFilter<LocSpec> {
    fn default() -> Self {
        Self::new(
            string_like::Pred::Contain,
            vec![LocSpec::Anything, LocSpec::default(), LocSpec::Anything],
        )
    }
}