forge_fmt/
string.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
//! Helpers for dealing with quoted strings

/// The state of a character in a string with quotable components
/// This is a simplified version of the
/// [actual parser](https://docs.soliditylang.org/en/v0.8.15/grammar.html#a4.SolidityLexer.EscapeSequence)
/// as we don't care about hex or other character meanings
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum QuoteState {
    /// Not currently in quoted string
    #[default]
    None,
    /// The opening character of a quoted string
    Opening(char),
    /// A character in a quoted string
    String(char),
    /// The `\` in an escape sequence `"\n"`
    Escaping(char),
    /// The escaped character e.g. `n` in `"\n"`
    Escaped(char),
    /// The closing character
    Closing(char),
}

/// An iterator over characters and indices in a string slice with information about quoted string
/// states
pub struct QuoteStateCharIndices<'a> {
    iter: std::str::CharIndices<'a>,
    state: QuoteState,
}

impl<'a> QuoteStateCharIndices<'a> {
    fn new(string: &'a str) -> Self {
        Self { iter: string.char_indices(), state: QuoteState::None }
    }
    pub fn with_state(mut self, state: QuoteState) -> Self {
        self.state = state;
        self
    }
}

impl Iterator for QuoteStateCharIndices<'_> {
    type Item = (QuoteState, usize, char);
    fn next(&mut self) -> Option<Self::Item> {
        let (idx, ch) = self.iter.next()?;
        match self.state {
            QuoteState::None | QuoteState::Closing(_) => {
                if ch == '\'' || ch == '"' {
                    self.state = QuoteState::Opening(ch);
                } else {
                    self.state = QuoteState::None
                }
            }
            QuoteState::String(quote) | QuoteState::Opening(quote) | QuoteState::Escaped(quote) => {
                if ch == quote {
                    self.state = QuoteState::Closing(quote)
                } else if ch == '\\' {
                    self.state = QuoteState::Escaping(quote)
                } else {
                    self.state = QuoteState::String(quote)
                }
            }
            QuoteState::Escaping(quote) => self.state = QuoteState::Escaped(quote),
        }
        Some((self.state, idx, ch))
    }
}

/// An iterator over the indices of quoted string locations
pub struct QuotedRanges<'a>(QuoteStateCharIndices<'a>);

impl QuotedRanges<'_> {
    pub fn with_state(mut self, state: QuoteState) -> Self {
        self.0 = self.0.with_state(state);
        self
    }
}

impl Iterator for QuotedRanges<'_> {
    type Item = (char, usize, usize);
    fn next(&mut self) -> Option<Self::Item> {
        let (quote, start) = loop {
            let (state, idx, _) = self.0.next()?;
            match state {
                QuoteState::Opening(quote) |
                QuoteState::Escaping(quote) |
                QuoteState::Escaped(quote) |
                QuoteState::String(quote) => break (quote, idx),
                QuoteState::Closing(quote) => return Some((quote, idx, idx)),
                QuoteState::None => {}
            }
        };
        for (state, idx, _) in self.0.by_ref() {
            if matches!(state, QuoteState::Closing(_)) {
                return Some((quote, start, idx))
            }
        }
        None
    }
}

/// Helpers for iterating over quoted strings
pub trait QuotedStringExt {
    /// Returns an iterator of characters, indices and their quoted string state.
    fn quote_state_char_indices(&self) -> QuoteStateCharIndices<'_>;

    /// Returns an iterator of quoted string ranges.
    fn quoted_ranges(&self) -> QuotedRanges<'_> {
        QuotedRanges(self.quote_state_char_indices())
    }

    /// Check to see if a string is quoted. This will return true if the first character
    /// is a quote and the last character is a quote with no non-quoted sections in between.
    fn is_quoted(&self) -> bool {
        let mut iter = self.quote_state_char_indices();
        if !matches!(iter.next(), Some((QuoteState::Opening(_), _, _))) {
            return false
        }
        while let Some((state, _, _)) = iter.next() {
            if matches!(state, QuoteState::Closing(_)) {
                return iter.next().is_none()
            }
        }
        false
    }
}

impl<T> QuotedStringExt for T
where
    T: AsRef<str>,
{
    fn quote_state_char_indices(&self) -> QuoteStateCharIndices<'_> {
        QuoteStateCharIndices::new(self.as_ref())
    }
}

impl QuotedStringExt for str {
    fn quote_state_char_indices(&self) -> QuoteStateCharIndices<'_> {
        QuoteStateCharIndices::new(self)
    }
}

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

    #[test]
    fn quote_state_char_indices() {
        assert_eq!(
            r#"a'a"\'\"\n\\'a"#.quote_state_char_indices().collect::<Vec<_>>(),
            vec![
                (QuoteState::None, 0, 'a'),
                (QuoteState::Opening('\''), 1, '\''),
                (QuoteState::String('\''), 2, 'a'),
                (QuoteState::String('\''), 3, '"'),
                (QuoteState::Escaping('\''), 4, '\\'),
                (QuoteState::Escaped('\''), 5, '\''),
                (QuoteState::Escaping('\''), 6, '\\'),
                (QuoteState::Escaped('\''), 7, '"'),
                (QuoteState::Escaping('\''), 8, '\\'),
                (QuoteState::Escaped('\''), 9, 'n'),
                (QuoteState::Escaping('\''), 10, '\\'),
                (QuoteState::Escaped('\''), 11, '\\'),
                (QuoteState::Closing('\''), 12, '\''),
                (QuoteState::None, 13, 'a'),
            ]
        );
    }

    #[test]
    fn quoted_ranges() {
        let string = r#"testing "double quoted" and 'single quoted' strings"#;
        assert_eq!(
            string
                .quoted_ranges()
                .map(|(quote, start, end)| (quote, &string[start..=end]))
                .collect::<Vec<_>>(),
            vec![('"', r#""double quoted""#), ('\'', "'single quoted'")]
        );
    }
}