summaryrefslogtreecommitdiff
path: root/src/tokenizer.rs
blob: 7768ee486845e935d77560321f6042c1da044d21 (plain)
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
use crate::machine;
use crate::reader::{IntoReader, Reader};
use crate::utils::{
    control_pat, noncharacter_pat, surrogate_pat, ControlToken, State as InternalState,
};
use crate::{DefaultEmitter, Emitter, Error};

// this is a stack that can hold 0 to 2 Ts
#[derive(Debug, Default, Clone, Copy)]
struct Stack2<T: Copy>(Option<(T, Option<T>)>);

impl<T: Copy> Stack2<T> {
    #[inline]
    fn push(&mut self, c: T) {
        self.0 = match self.0 {
            None => Some((c, None)),
            Some((c1, None)) => Some((c1, Some(c))),
            Some((_c1, Some(_c2))) => panic!("stack full!"),
        }
    }

    #[inline]
    fn pop(&mut self) -> Option<T> {
        let (new_self, rv) = match self.0 {
            Some((c1, Some(c2))) => (Some((c1, None)), Some(c2)),
            Some((c1, None)) => (None, Some(c1)),
            None => (None, None),
        };
        self.0 = new_self;
        rv
    }
}

/// A HTML tokenizer. See crate-level docs for basic usage.
pub struct Tokenizer<R: Reader, E: Emitter<R> = DefaultEmitter<R, ()>> {
    eof: bool,
    pub(crate) state: InternalState,
    pub(crate) emitter: E,
    pub(crate) temporary_buffer: String,
    pub(crate) reader: R,
    to_reconsume: Stack2<Option<char>>,
    pub(crate) character_reference_code: u32,
    pub(crate) return_state: Option<InternalState>,
    current_tag_name: String,
    last_start_tag_name: String,
    is_start_tag: bool,
}

impl<R: Reader, E: Emitter<R>> Tokenizer<R, E> {
    /// Creates a new tokenizer from some input and an emitter.
    ///
    /// TODO: add warning about you needing to do the state switching
    pub fn new<'a>(reader: impl IntoReader<'a, Reader = R>, emitter: E) -> Self {
        Tokenizer {
            reader: reader.into_reader(),
            emitter,
            state: InternalState::Data,
            to_reconsume: Stack2::default(),
            return_state: None,
            temporary_buffer: String::new(),
            character_reference_code: 0,
            eof: false,
            current_tag_name: String::new(),
            last_start_tag_name: String::new(),
            is_start_tag: false,
        }
    }
}

/// The states you can set the tokenizer to.
#[derive(Debug)]
#[non_exhaustive]
pub enum State {
    /// The [Data state](https://html.spec.whatwg.org/#data-state).
    Data,
    /// The [PLAINTEXT state](https://html.spec.whatwg.org/#plaintext-state).
    PlainText,
    /// The [RCDATA state](https://html.spec.whatwg.org/#rcdata-state).
    RcData,
    /// The [RAWTEXT state](https://html.spec.whatwg.org/#rawtext-state).
    RawText,
    /// The [Script data state](https://html.spec.whatwg.org/#script-data-state).
    ScriptData,
    /// The [Script data escaped state](https://html.spec.whatwg.org/#script-data-escaped-state).
    ScriptDataEscaped,
    /// The [Script data double escaped state](https://html.spec.whatwg.org/#script-data-double-escaped-state).
    ScriptDataDoubleEscaped,
}

impl From<State> for InternalState {
    fn from(state: State) -> Self {
        match state {
            State::Data => InternalState::Data,
            State::PlainText => InternalState::PlainText,
            State::RcData => InternalState::RcData,
            State::RawText => InternalState::RawText,
            State::ScriptData => InternalState::ScriptData,
            State::ScriptDataEscaped => InternalState::ScriptDataEscaped,
            State::ScriptDataDoubleEscaped => InternalState::ScriptDataDoubleEscaped,
        }
    }
}

impl<R: Reader, E: Emitter<R>> Tokenizer<R, E> {
    /// Test-internal function to override internal state.
    ///
    /// Only available with the `integration-tests` feature which is not public API.
    #[cfg(feature = "integration-tests")]
    pub fn set_internal_state(&mut self, state: InternalState) {
        self.state = state;
    }

    /// Set the statemachine to start/continue in the given state.
    pub fn set_state(&mut self, state: State) {
        self.state = state.into();
    }

    /// Just a helper method for the machine.
    #[inline]
    pub(crate) fn emit_error(&mut self, error: Error) {
        self.emitter.emit_error(error, &self.reader);
    }

    /// Assuming the _current token_ is an end tag, return true if all of these hold. Return false otherwise.
    ///
    /// * the _last start tag_ exists
    /// * the current end tag token's name equals to the last start tag's name.
    ///
    /// See also [WHATWG's definition of "appropriate end tag
    /// token"](https://html.spec.whatwg.org/#appropriate-end-tag-token).
    #[inline]
    pub(crate) fn current_end_tag_is_appropriate(&mut self) -> bool {
        self.current_tag_name == self.last_start_tag_name
    }

    #[inline]
    pub(crate) fn init_start_tag(&mut self) {
        self.emitter.init_start_tag(&self.reader);
        self.current_tag_name.clear();
        self.is_start_tag = true;
    }

    #[inline]
    pub(crate) fn init_end_tag(&mut self) {
        self.emitter.init_end_tag(&self.reader);
        self.current_tag_name.clear();
        self.is_start_tag = false;
    }

    #[inline]
    pub(crate) fn push_tag_name(&mut self, s: &str) {
        self.emitter.push_tag_name(s);
        self.current_tag_name.push_str(s);
    }

    #[inline]
    pub(crate) fn emit_current_tag(&mut self) {
        self.emitter.emit_current_tag();
        if self.is_start_tag {
            std::mem::swap(&mut self.last_start_tag_name, &mut self.current_tag_name);
        }
    }

    #[inline]
    pub(crate) fn unread_char(&mut self, c: Option<char>) {
        self.to_reconsume.push(c);
    }

    #[inline]
    fn validate_char(&mut self, c: char) {
        match c as u32 {
            surrogate_pat!() => {
                self.emit_error(Error::SurrogateInInputStream);
            }
            noncharacter_pat!() => {
                self.emit_error(Error::NoncharacterInInputStream);
            }
            // control without whitespace or nul
            x @ control_pat!()
                if !matches!(x, 0x0000 | 0x0009 | 0x000a | 0x000c | 0x000d | 0x0020) =>
            {
                self.emit_error(Error::ControlCharacterInInputStream);
            }
            _ => (),
        }
    }

    pub(crate) fn read_char(&mut self) -> Result<Option<char>, R::Error> {
        let (c_res, reconsumed) = match self.to_reconsume.pop() {
            Some(c) => (Ok(c), true),
            None => (self.reader.read_char(), false),
        };

        let mut c = match c_res {
            Ok(Some(c)) => c,
            res => return res,
        };

        if c == '\r' {
            c = '\n';
            let c2 = self.reader.read_char()?;
            if c2 != Some('\n') {
                self.unread_char(c2);
            }
        }

        if !reconsumed {
            self.validate_char(c);
        }

        Ok(Some(c))
    }

    #[inline]
    pub(crate) fn try_read_string(
        &mut self,
        mut s: &str,
        case_sensitive: bool,
    ) -> Result<bool, R::Error> {
        debug_assert!(!s.is_empty());

        let to_reconsume_bak = self.to_reconsume;
        let mut chars = s.chars();
        while let Some(c) = self.to_reconsume.pop() {
            if let (Some(x), Some(x2)) = (c, chars.next()) {
                if x == x2 || (!case_sensitive && x.to_ascii_lowercase() == x2.to_ascii_lowercase())
                {
                    s = &s[x.len_utf8()..];
                    continue;
                }
            }

            self.to_reconsume = to_reconsume_bak;
            return Ok(false);
        }

        self.reader.try_read_string(s, case_sensitive)
    }

    pub(crate) fn is_consumed_as_part_of_an_attribute(&self) -> bool {
        matches!(
            self.return_state,
            Some(
                InternalState::AttributeValueDoubleQuoted
                    | InternalState::AttributeValueSingleQuoted
                    | InternalState::AttributeValueUnquoted
            )
        )
    }

    pub(crate) fn flush_code_points_consumed_as_character_reference(&mut self) {
        if self.is_consumed_as_part_of_an_attribute() {
            self.emitter.push_attribute_value(&self.temporary_buffer);
            self.temporary_buffer.clear();
        } else {
            self.flush_buffer_characters();
        }
    }

    pub(crate) fn next_input_character(&mut self) -> Result<Option<char>, R::Error> {
        let rv = self.read_char()?;
        self.unread_char(rv);
        Ok(rv)
    }

    pub(crate) fn flush_buffer_characters(&mut self) {
        self.emitter.emit_string(&self.temporary_buffer);
        self.temporary_buffer.clear();
    }
}

impl<R: Reader, E: Emitter<R>> Iterator for Tokenizer<R, E> {
    type Item = Result<E::Token, R::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(token) = self.emitter.pop_token() {
                break Some(Ok(token));
            } else if !self.eof {
                match machine::consume(self) {
                    Ok(ControlToken::Continue) => (),
                    Ok(ControlToken::Eof) => {
                        self.eof = true;
                        self.emitter.emit_eof();
                    }
                    Err(e) => break Some(Err(e)),
                }
            } else {
                break None;
            }
        }
    }
}

impl<R: Reader, E: Emitter<R>> Tokenizer<R, E> {
    /// Test-internal function to override internal state.
    ///
    /// Only available with the `integration-tests` feature which is not public API.
    #[cfg(feature = "integration-tests")]
    pub fn set_last_start_tag(&mut self, last_start_tag: &str) {
        self.last_start_tag_name.clear();
        self.last_start_tag_name.push_str(last_start_tag);
    }
}