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
|
use html5tokenizer::{
Attribute, Doctype, EndTag, Error, InternalState as State, Reader, StartTag, Token, Tokenizer,
};
use pretty_assertions::assert_eq;
use serde::{de::Error as _, Deserialize};
use std::{collections::BTreeMap, fs::File, io::BufReader, path::Path};
#[cfg(not(feature = "integration-tests"))]
compile_error!(
"integration tests need the integration-tests feature enabled. Run cargo test --all-features"
);
struct ExpectedOutputTokens(Vec<Token<()>>);
impl<'de> Deserialize<'de> for ExpectedOutputTokens {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
// this macro is a horrible way to define a type that deserializes only from a particular
// string. Together with serde(untagged) this gives us really flexible enum tagging with really
// terrible error messages.
macro_rules! def_const {
($str:expr, $ty:ident) => {
#[derive(Deserialize)]
enum $ty {
#[serde(rename = $str)]
$ty,
}
};
}
def_const!("DOCTYPE", DoctypeConst);
def_const!("StartTag", StartTagConst);
def_const!("EndTag", EndTagConst);
def_const!("Comment", CommentConst);
def_const!("Character", CharacterConst);
type Attributes = BTreeMap<String, String>;
#[derive(Deserialize)]
#[serde(untagged)]
enum OutputToken {
// "DOCTYPE", name, public_id, system_id, correctness
Doctype(
DoctypeConst,
Option<String>,
Option<String>,
Option<String>,
bool,
),
// "StartTag", name, attributes, self_closing
StartTag(StartTagConst, String, Attributes),
StartTag2(StartTagConst, String, Attributes, bool),
// "EndTag", name
EndTag(EndTagConst, String),
// "Comment", data
Comment(CommentConst, String),
// "Character", data
Character(CharacterConst, String),
}
Ok(ExpectedOutputTokens(
Vec::deserialize(deserializer)?
.into_iter()
.map(|output_token| match output_token {
OutputToken::Doctype(
_,
name,
public_identifier,
system_identifier,
correctness,
) => Token::Doctype(Doctype {
name: name.unwrap_or_default(),
public_identifier,
system_identifier,
force_quirks: !correctness,
}),
OutputToken::StartTag(_, name, attributes) => Token::StartTag(StartTag {
self_closing: false,
name,
attributes: attributes
.into_iter()
.map(|(k, v)| {
(
k,
Attribute {
value: v,
..Default::default()
},
)
})
.collect(),
name_span: (),
}),
OutputToken::StartTag2(_, name, attributes, self_closing) => {
Token::StartTag(StartTag {
self_closing,
name,
attributes: attributes
.into_iter()
.map(|(k, v)| {
(
k,
Attribute {
value: v,
..Default::default()
},
)
})
.collect(),
name_span: (),
})
}
OutputToken::EndTag(_, name) => Token::EndTag(EndTag {
name,
name_span: (),
}),
OutputToken::Comment(_, data) => Token::Comment(data),
OutputToken::Character(_, data) => Token::String(data),
})
.collect::<Vec<Token<()>>>(),
))
}
}
struct InitialState(State);
impl<'de> Deserialize<'de> for InitialState {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
enum RawInitialState {
#[serde(rename = "Data state")]
Data,
#[serde(rename = "PLAINTEXT state")]
PlainText,
#[serde(rename = "RCDATA state")]
RcData,
#[serde(rename = "RAWTEXT state")]
RawText,
#[serde(rename = "Script data state")]
ScriptData,
#[serde(rename = "CDATA section state")]
CdataSection,
}
Ok(Self(match RawInitialState::deserialize(deserializer)? {
RawInitialState::Data => State::Data,
RawInitialState::PlainText => State::PlainText,
RawInitialState::RcData => State::RcData,
RawInitialState::RawText => State::RawText,
RawInitialState::ScriptData => State::ScriptData,
RawInitialState::CdataSection => State::CdataSection,
}))
}
}
fn initial_states_default() -> Vec<InitialState> {
vec![InitialState(State::Data)]
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Test {
description: String,
input: String,
output: ExpectedOutputTokens,
#[serde(default = "initial_states_default")]
initial_states: Vec<InitialState>,
#[serde(default)]
double_escaped: bool,
#[serde(default)]
last_start_tag: Option<String>,
#[serde(default)]
errors: Vec<ParseError>,
}
#[derive(Debug, Eq, PartialEq)]
struct ParseErrorInner(Error);
impl<'de> Deserialize<'de> for ParseErrorInner {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let str_err = String::deserialize(deserializer)?;
let err: Error = str_err
.parse()
.map_err(|_| D::Error::custom(&format!("failed to deserialize error: {}", str_err)))?;
Ok(ParseErrorInner(err))
}
}
#[derive(Deserialize, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
struct ParseError {
code: ParseErrorInner,
// TODO: lineno and column?
}
#[derive(Deserialize)]
struct Tests {
tests: Vec<Test>,
}
/// Path to a local checkout of [html5lib-tests], relative to the
/// directory containing the `Cargo.toml` file of the current crate.
///
/// [html5lib-tests]: https://github.com/html5lib/html5lib-tests
const HTML5LIB_TESTS_PATH: &str = "tests/html5lib-tests";
// FUTURE: it would be nice to assert that HTML5LIB_TESTS_PATH matches the path defined in .gitmodules
// but this is currently blocked by:
// * Cargo not setting CARGO_WORKSPACE_DIR (see https://github.com/rust-lang/cargo/issues/3946)
// * gix-config having more dependencies than I'd want to add for this
#[test]
fn tokenizer() {
// TODO: use a custom test harness with e.g. libtest-mimic
let test_dir = format!("{HTML5LIB_TESTS_PATH}/tokenizer");
let mut test_paths = glob::glob(&format!("{test_dir}/*.test"))
.unwrap()
.peekable();
if test_paths.peek().is_none() {
panic!(
"could not find any .test files in {}, maybe try `git submodule update --init`",
test_dir
);
}
for test_path in test_paths {
let test_path = test_path.unwrap();
test_tokenizer_file(&test_path);
}
}
fn test_tokenizer_file(path: &Path) {
let fname = path.file_name().unwrap().to_str().unwrap();
if matches!(
fname,
// We don't implement "Coercing an HTML DOM into an infoset" section
"xmlViolation.test" |
// Our parser does not operate on bytes, the input isn't valid Rust &str
"unicodeCharsProblematic.test"
) {
return;
}
let f = File::open(path).unwrap();
let bf = BufReader::new(f);
let tests: Tests = serde_json::from_reader(bf).unwrap();
for (i, test) in tests.tests.into_iter().enumerate() {
run_test(fname, i, test);
}
}
fn run_test(fname: &str, test_i: usize, mut test: Test) {
test.input = if test.double_escaped {
unescape(&test.input)
} else {
test.input
};
test.output = if test.double_escaped {
ExpectedOutputTokens(
test.output
.0
.into_iter()
.map(|token| match token {
Token::String(x) => Token::String(unescape(&x)),
Token::Comment(x) => Token::Comment(unescape(&x)),
token => token,
})
.collect(),
)
} else {
ExpectedOutputTokens(test.output.0)
};
for state in &test.initial_states {
run_test_inner(
fname,
test_i,
&test,
state.0,
Tokenizer::new(&test.input),
"string",
);
run_test_inner(
fname,
test_i,
&test,
state.0,
Tokenizer::new(BufReader::new(test.input.as_bytes())),
"bufread",
);
}
}
fn run_test_inner<R: Reader>(
fname: &str,
test_i: usize,
test: &Test,
state: State,
mut tokenizer: Tokenizer<R>,
tokenizer_info: &str,
) {
println!(
"==== FILE {}, TEST {}, STATE {:?}, TOKENIZER {} ====",
fname, test_i, state, tokenizer_info,
);
println!("description: {}", test.description);
tokenizer.set_internal_state(state);
tokenizer.set_last_start_tag(test.last_start_tag.as_ref().map(String::as_str));
let mut actual_tokens = Vec::new();
let mut actual_errors = Vec::new();
for token in tokenizer {
let token = token.unwrap();
if let Token::Error { error, .. } = token {
actual_errors.push(ParseError {
code: ParseErrorInner(error),
});
} else {
actual_tokens.push(token);
}
}
assert_eq!(test.output.0, actual_tokens);
if !matches!(
(fname, test_i),
// TODO: html5lib-tests bug?
("test3.test", 79)
) {
assert_eq!(test.errors, actual_errors);
}
}
/// Implements the escape sequences described in the tokenizer tests of html5lib-tests (and nothing
/// more)
fn unescape(data: &str) -> String {
let mut stream = data.chars();
let mut rv = String::new();
loop {
match stream.next() {
Some('\\') => (),
Some(x) => {
rv.push(x);
continue;
}
None => break,
}
match stream.next() {
Some('u') => (),
x => panic!("unexpected escape: {:?}", x),
}
let orig_len = rv.len();
for _ in 0..4 {
rv.push(match stream.next() {
Some(x) => x,
None => panic!("unexpected eof after \\u"),
});
}
let c = u32::from_str_radix(&rv[orig_len..], 16).expect("failed to parse as hex");
let c = char::from_u32(c).expect("bad character");
rv.truncate(orig_len);
rv.push(c);
}
rv
}
|