selectors/
ir.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
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use fidl_fuchsia_diagnostics as fdiagnostics;
use std::borrow::Cow;
use std::fmt::Debug;

#[derive(Debug, Eq, PartialEq)]
pub enum Segment<'a> {
    ExactMatch(Cow<'a, str>),
    Pattern(Cow<'a, str>),
}

fn contains_unescaped(s: &str, unescaped_char: char) -> bool {
    let mut iter = s.chars();
    while let Some(c) = iter.next() {
        match c {
            c2 if c2 == unescaped_char => return true,
            '\\' => {
                // skip escaped characters
                let _ = iter.next();
            }
            _ => {}
        }
    }
    false
}

impl<'a> From<&'a str> for Segment<'a> {
    fn from(s: &'a str) -> Segment<'a> {
        if contains_unescaped(s, '*') {
            return Segment::Pattern(Cow::Owned(unescape(s, &['*'])));
        }
        if !s.contains('\\') {
            return Segment::ExactMatch(Cow::from(s));
        }
        Segment::ExactMatch(Cow::Owned(unescape(s, &[])))
    }
}

#[derive(Debug, Eq, PartialEq)]
pub enum TreeNames<'a> {
    Some(Vec<Cow<'a, str>>),
    All,
}

impl<'a> From<Vec<&'a str>> for TreeNames<'a> {
    fn from(vec: Vec<&'a str>) -> TreeNames<'a> {
        let mut payload = vec![];
        for name in vec {
            if name.contains('\\') {
                payload.push(Cow::Owned(unescape(name, &[])));
            } else {
                payload.push(Cow::Borrowed(name));
            }
        }
        TreeNames::Some(payload)
    }
}

// Given a escaped string, removes all the escaped characters (`\\`) and returns a new string
// without them. It'll keep characters present in the `except` list escaped.
fn unescape(value: &str, except: &[char]) -> String {
    let mut result = String::with_capacity(value.len());
    let mut iter = value.chars();
    while let Some(c) = iter.next() {
        match c {
            '\\' => {
                // push unescaped character since we are constructing an exact match.
                if let Some(c) = iter.next() {
                    if except.contains(&c) {
                        result.push('\\')
                    }
                    result.push(c);
                }
            }
            c => result.push(c),
        }
    }
    result
}

#[derive(Debug, Eq, PartialEq)]
pub struct TreeSelector<'a> {
    pub node: Vec<Segment<'a>>,
    pub property: Option<Segment<'a>>,
    pub tree_names: Option<TreeNames<'a>>,
}

#[derive(Debug, Eq, PartialEq)]
pub struct ComponentSelector<'a> {
    pub segments: Vec<Segment<'a>>,
}

#[derive(Debug, Eq, PartialEq)]
pub struct Selector<'a> {
    pub component: ComponentSelector<'a>,
    pub tree: TreeSelector<'a>,
}

impl From<Selector<'_>> for fdiagnostics::Selector {
    fn from(mut selector: Selector<'_>) -> fdiagnostics::Selector {
        let tree_names = selector.tree.tree_names.take();
        fdiagnostics::Selector {
            component_selector: Some(selector.component.into()),
            tree_selector: Some(selector.tree.into()),
            tree_names: tree_names.map(|names| names.into()),
            ..Default::default()
        }
    }
}

impl From<ComponentSelector<'_>> for fdiagnostics::ComponentSelector {
    fn from(component_selector: ComponentSelector<'_>) -> fdiagnostics::ComponentSelector {
        fdiagnostics::ComponentSelector {
            moniker_segments: Some(
                component_selector.segments.into_iter().map(|segment| segment.into()).collect(),
            ),
            ..Default::default()
        }
    }
}

impl From<TreeSelector<'_>> for fdiagnostics::TreeSelector {
    fn from(tree_selector: TreeSelector<'_>) -> fdiagnostics::TreeSelector {
        let node_path = tree_selector.node.into_iter().map(|s| s.into()).collect();
        match tree_selector.property {
            None => fdiagnostics::TreeSelector::SubtreeSelector(fdiagnostics::SubtreeSelector {
                node_path,
            }),
            Some(property) => {
                fdiagnostics::TreeSelector::PropertySelector(fdiagnostics::PropertySelector {
                    node_path,
                    target_properties: property.into(),
                })
            }
        }
    }
}

impl From<TreeNames<'_>> for fdiagnostics::TreeNames {
    fn from(tree_names: TreeNames<'_>) -> fdiagnostics::TreeNames {
        match tree_names {
            TreeNames::All => fdiagnostics::TreeNames::All(fdiagnostics::All {}),
            TreeNames::Some(names) => {
                fdiagnostics::TreeNames::Some(names.iter().map(|n| n.to_string()).collect())
            }
        }
    }
}

impl From<Segment<'_>> for fdiagnostics::StringSelector {
    fn from(segment: Segment<'_>) -> fdiagnostics::StringSelector {
        match segment {
            Segment::ExactMatch(s) => fdiagnostics::StringSelector::ExactMatch(s.into_owned()),
            Segment::Pattern(s) => fdiagnostics::StringSelector::StringPattern(s.into_owned()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[fuchsia::test]
    fn convert_string_to_segment() {
        assert_eq!(Segment::ExactMatch(Cow::Borrowed("abc")), "abc".into());
        assert_eq!(Segment::Pattern("a*c".into()), "a*c".into());
        assert_eq!(Segment::ExactMatch(Cow::Owned("ac*".into())), "ac\\*".into());
        assert_eq!(Segment::Pattern("a\\*c*".into()), "a\\*c*".into());
    }
}