WPT: 93,88% del corpus del tokenizer, e due difetti veri trovati subito
Il WPT vero non è agganciabile: i suoi test di parsing sono pagine che girano in testharness.js e vogliono DOMParser, createHTMLDocument e un event loop asincrono — cose che il motore non ha. Il corpus `html5lib-tests/tokenizer` è invece la sorgente da cui WPT genera quei test, e misurarlo dà un numero confrontabile invece di un'affermazione. - engine/src/bin/wpt.rs: legge i .test, esegue i casi, confronta i token, stampa percentuali per file e totale; `--min N` fa fallire la CI sotto soglia (93%) - engine/scripts/scarica-corpus.sh: rigenera il corpus (1,7 MB, nel repository perché la CI non deve dipendere dalla rete) Il corpus ha trovato subito due difetti: 1. **Il tokenizer si BLOCCAVA** su `<h/a='b'>`, `<a/\0>` e `<z/0 <>`: nel ciclo degli attributi, una `/` non seguita da `>` produceva un nome vuoto e `j` non avanzava mai. Ora il carattere si scarta e si prosegue (e `<h/a='b'>` vale `<h a='b'>`, come dice la specifica). Un blocco, non un token sbagliato. 2. **Ogni `<!…>` diventava un doctype**, anche `<!>`, `<!ciao>`, `<! `, `<?…>`: doveva essere un **commento spurio**. Era il grosso dei fallimenti in test3. Più: entità HTML nominate complete (2231 voci generate da entities.json del WHATWG, forme legacy e multi-carattere comprese) e DOCTYPE con nome, PUBLIC/SYSTEM e segnalazione degli errori. Numeri: 48,42% al primo giro, 82,09% con le entità, 93,88% con commento spurio e doctype (6247 casi su 6654 eseguibili, 166 saltati). Restano fuori gli stati iniziali diversi da quello dei dati (RCDATA, CDATA, script, PLAINTEXT), lastStartTag e la serializzazione: dichiarati, non nascosti. Effetti collaterali utili: le entità complete migliorano ogni pagina reale con simboli tipografici; il commento spurio rende il parsing di `<![CDATA[` e delle dichiarazioni PHP-like meno sbagliato di prima.
This commit is contained in:
1 parent
36dbc691d9
commit
e2b238d424
28 files changed
+62302
-44
No files matched your search
@@ -0,0 +1,386 @@
|
||||
//! Conformità del tokenizer HTML contro il corpus `html5lib-tests`.
|
||||
//!
|
||||
//! Perché questo e non il WPT: i test di parsing del WPT sono pagine HTML che
|
||||
//! girano dentro `testharness.js` e hanno bisogno di `DOMParser`,
|
||||
//! `createHTMLDocument` e di un event loop con `async_test` — cose che il motore
|
||||
//! non ha. Il corpus `html5lib-tests/tokenizer` è invece **la sorgente** da cui
|
||||
//! WPT genera i propri test di parsing: misurarlo dà un numero vero, confrontabile,
|
||||
//! senza fingere di aver agganciato un harness che non c'è.
|
||||
//!
|
||||
//! Uso: `wpt [--min PERCENTUALE] [--verbose] [cartella]`
|
||||
//! Con `--min`, esce con codice 1 se la percentuale scende sotto la soglia: così
|
||||
//! la CI si accorge di una regressione.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use engine::tokenizer::{tokenize, Token};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Esito {
|
||||
passati: usize,
|
||||
falliti: usize,
|
||||
saltati: usize,
|
||||
fallimenti: Vec<String>,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut soglia: Option<f64> = None;
|
||||
let mut verboso = false;
|
||||
let mut cartella = String::from("cases/html5lib");
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--min" => soglia = args.next().and_then(|v| v.parse().ok()),
|
||||
"--verbose" | "-v" => verboso = true,
|
||||
altro => cartella = altro.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
let percorso = Path::new(&cartella);
|
||||
let mut file: Vec<_> = match std::fs::read_dir(percorso) {
|
||||
Ok(v) => v
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().map(|e| e == "test").unwrap_or(false))
|
||||
.collect(),
|
||||
Err(e) => {
|
||||
eprintln!("cartella {} illeggibile: {}", cartella, e);
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
file.sort();
|
||||
if file.is_empty() {
|
||||
eprintln!("nessun file .test in {}", cartella);
|
||||
std::process::exit(2);
|
||||
}
|
||||
|
||||
let mut totale = Esito::default();
|
||||
let mut per_file: Vec<(String, Esito)> = Vec::new();
|
||||
|
||||
for percorso_file in &file {
|
||||
let testo = match std::fs::read_to_string(percorso_file) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
eprintln!("{}: {}", percorso_file.display(), e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut esito = Esito::default();
|
||||
match serde_json::from_str::<serde_json::Value>(&testo) {
|
||||
Ok(json) => {
|
||||
if let Some(casi) = json.get("tests").and_then(|t| t.as_array()) {
|
||||
for caso in casi {
|
||||
esegui_caso(caso, &mut esito, verboso);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{}: JSON illeggibile: {}", percorso_file.display(), e);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
totale.passati += esito.passati;
|
||||
totale.falliti += esito.falliti;
|
||||
totale.saltati += esito.saltati;
|
||||
per_file.push((
|
||||
percorso_file
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
esito,
|
||||
));
|
||||
}
|
||||
|
||||
println!(
|
||||
"{:<32} {:>6} {:>6} {:>6} {:>7}",
|
||||
"file", "passati", "falliti", "saltati", "esito"
|
||||
);
|
||||
for (nome, e) in &per_file {
|
||||
let fatti = e.passati + e.falliti;
|
||||
let pct = if fatti == 0 {
|
||||
0.0
|
||||
} else {
|
||||
100.0 * e.passati as f64 / fatti as f64
|
||||
};
|
||||
println!(
|
||||
"{:<32} {:>6} {:>6} {:>6} {:>6.1}%",
|
||||
nome, e.passati, e.falliti, e.saltati, pct
|
||||
);
|
||||
}
|
||||
|
||||
let fatti = totale.passati + totale.falliti;
|
||||
let pct = if fatti == 0 {
|
||||
0.0
|
||||
} else {
|
||||
100.0 * totale.passati as f64 / fatti as f64
|
||||
};
|
||||
println!(
|
||||
"\ntotale: {} passati, {} falliti, {} saltati — {:.2}% dei casi eseguibili",
|
||||
totale.passati, totale.falliti, totale.saltati, pct
|
||||
);
|
||||
|
||||
if let Some(minimo) = soglia {
|
||||
if pct + 1e-9 < minimo {
|
||||
eprintln!("conformità sotto la soglia: {:.2}% < {:.2}%", pct, minimo);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn esegui_caso(caso: &serde_json::Value, esito: &mut Esito, verboso: bool) {
|
||||
let descrizione = caso
|
||||
.get("description")
|
||||
.and_then(|d| d.as_str())
|
||||
.unwrap_or("(senza descrizione)");
|
||||
|
||||
// gli stati iniziali diversi da quello dei dati (RCDATA, CDATA, script, ...)
|
||||
// richiedono un tokenizer avviato a metà: fuori ambito, si dichiarano saltati
|
||||
if let Some(stati) = caso.get("initialStates").and_then(|s| s.as_array()) {
|
||||
if !stati.is_empty() {
|
||||
esito.saltati += 1;
|
||||
return;
|
||||
}
|
||||
}
|
||||
// `lastStartTag` cambia il contesto (per esempio dentro un `<title>`): idem
|
||||
if caso.get("lastStartTag").is_some() {
|
||||
esito.saltati += 1;
|
||||
return;
|
||||
}
|
||||
|
||||
let doppio = caso
|
||||
.get("doubleEscaped")
|
||||
.and_then(|d| d.as_bool())
|
||||
.unwrap_or(false);
|
||||
let decodifica = |s: &str| -> String {
|
||||
if doppio {
|
||||
decodifica_escape(s)
|
||||
} else {
|
||||
s.to_string()
|
||||
}
|
||||
};
|
||||
|
||||
let input = decodifica(caso.get("input").and_then(|i| i.as_str()).unwrap_or(""));
|
||||
let attesi = match caso.get("output").and_then(|o| o.as_array()) {
|
||||
Some(o) => o
|
||||
.iter()
|
||||
.filter_map(|t| token_atteso(t, doppio))
|
||||
.collect::<Vec<_>>(),
|
||||
None => {
|
||||
esito.saltati += 1;
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let ottenuti: Vec<String> = tokenize(&input)
|
||||
.into_iter()
|
||||
.filter(|t| !matches!(t, Token::Eof))
|
||||
.map(descrivi)
|
||||
.collect();
|
||||
let attesi = unisci_caratteri(attesi);
|
||||
let ottenuti = unisci_caratteri(ottenuti);
|
||||
|
||||
if attesi == ottenuti {
|
||||
esito.passati += 1;
|
||||
} else {
|
||||
esito.falliti += 1;
|
||||
if verboso {
|
||||
esito.fallimenti.push(format!(
|
||||
"{}\n input: {:?}\n atteso: {:?}\n ottenuto: {:?}",
|
||||
descrizione, input, attesi, ottenuti
|
||||
));
|
||||
eprintln!("FALLITO: {}", esito.fallimenti.last().unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Descrizione normalizzata di un token del corpus, nello stesso formato che
|
||||
/// usiamo per i nostri: così il confronto è fra stringhe.
|
||||
fn token_atteso(t: &serde_json::Value, doppio: bool) -> Option<String> {
|
||||
let elenco = t.as_array()?;
|
||||
let tipo = elenco.first()?.as_str()?;
|
||||
let dec = |v: Option<&serde_json::Value>| -> Option<String> {
|
||||
let s = v?.as_str()?;
|
||||
Some(if doppio {
|
||||
decodifica_escape(s)
|
||||
} else {
|
||||
s.to_string()
|
||||
})
|
||||
};
|
||||
match tipo {
|
||||
"DOCTYPE" => {
|
||||
let nome = elenco
|
||||
.get(1)
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
let pubblico = dec(elenco.get(2));
|
||||
let sistema = dec(elenco.get(3));
|
||||
let corretto = elenco.get(4).and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
Some(format!(
|
||||
"DOCTYPE {:?} {:?} {:?} {}",
|
||||
nome, pubblico, sistema, corretto
|
||||
))
|
||||
}
|
||||
"StartTag" => {
|
||||
let nome = dec(elenco.get(1))?;
|
||||
let attributi = attributi_ordinati(elenco.get(2), doppio);
|
||||
let auto = elenco.get(3).and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
Some(format!("StartTag {} [{}] {}", nome, attributi, auto))
|
||||
}
|
||||
"EndTag" => Some(format!("EndTag {}", dec(elenco.get(1))?)),
|
||||
"Comment" => Some(format!("Comment {:?}", dec(elenco.get(1))?)),
|
||||
"Character" => Some(format!("Character {:?}", dec(elenco.get(1))?)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn attributi_ordinati(v: Option<&serde_json::Value>, doppio: bool) -> String {
|
||||
let mut mappa: BTreeMap<String, String> = BTreeMap::new();
|
||||
if let Some(oggetto) = v.and_then(|v| v.as_object()) {
|
||||
for (nome, valore) in oggetto {
|
||||
let valore = valore.as_str().unwrap_or("");
|
||||
let valore = if doppio {
|
||||
decodifica_escape(valore)
|
||||
} else {
|
||||
valore.to_string()
|
||||
};
|
||||
mappa.insert(nome.clone(), valore);
|
||||
}
|
||||
}
|
||||
mappa
|
||||
.into_iter()
|
||||
.map(|(n, v)| format!("{}=\"{}\"", n, v))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
/// Descrizione di un token prodotto dal motore, nello stesso formato del corpus.
|
||||
fn descrivi(token: Token) -> String {
|
||||
match token {
|
||||
Token::StartTag {
|
||||
name,
|
||||
attrs,
|
||||
self_closing,
|
||||
} => {
|
||||
let mut mappa: BTreeMap<String, String> = BTreeMap::new();
|
||||
for (n, v) in attrs {
|
||||
mappa.insert(n, v);
|
||||
}
|
||||
let attributi = mappa
|
||||
.into_iter()
|
||||
.map(|(n, v)| format!("{}=\"{}\"", n, v))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
format!("StartTag {} [{}] {}", name, attributi, self_closing)
|
||||
}
|
||||
Token::EndTag { name } => format!("EndTag {}", name),
|
||||
Token::Text(testo) => format!("Character {:?}", testo),
|
||||
Token::Comment(testo) => format!("Comment {:?}", testo),
|
||||
Token::Doctype {
|
||||
name,
|
||||
public_id,
|
||||
system_id,
|
||||
corretto,
|
||||
} => format!(
|
||||
"DOCTYPE {:?} {:?} {:?} {}",
|
||||
name, public_id, system_id, corretto
|
||||
),
|
||||
Token::Eof => "EOF".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// I token di carattere consecutivi si confrontano come un testo solo: il corpus
|
||||
/// li spezza come capita, e anche noi emettiamo un testo per sequenza.
|
||||
fn unisci_caratteri(token: Vec<String>) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for t in token {
|
||||
if let Some(resto) = t.strip_prefix("Character ") {
|
||||
if let Some(ultimo) = out.last_mut() {
|
||||
if let Some(precedente) = ultimo.strip_prefix("Character ") {
|
||||
let mut a = testo_da_debug(precedente);
|
||||
a.push_str(&testo_da_debug(resto));
|
||||
*ultimo = format!("Character {:?}", a);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(t);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Interpreta la forma `{:?}` di una stringa (virgolette e sequenze di escape)
|
||||
/// per poterle concatenare.
|
||||
fn testo_da_debug(s: &str) -> String {
|
||||
let senza_virgolette = s.trim_start_matches('"').trim_end_matches('"');
|
||||
let mut out = String::new();
|
||||
let mut iter = senza_virgolette.chars();
|
||||
while let Some(c) = iter.next() {
|
||||
if c != '\\' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
match iter.next() {
|
||||
Some('n') => out.push('\n'),
|
||||
Some('r') => out.push('\r'),
|
||||
Some('t') => out.push('\t'),
|
||||
Some('"') => out.push('"'),
|
||||
Some('\\') => out.push('\\'),
|
||||
Some('u') => {
|
||||
// \u{XXXX}
|
||||
let mut cifre = String::new();
|
||||
for c in iter.by_ref() {
|
||||
if c == '}' {
|
||||
break;
|
||||
}
|
||||
if c != '{' {
|
||||
cifre.push(c);
|
||||
}
|
||||
}
|
||||
if let Ok(n) = u32::from_str_radix(&cifre, 16) {
|
||||
if let Some(c) = char::from_u32(n) {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(altro) => out.push(altro),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Le stringhe marcate `doubleEscaped` sono JSON annidate: `\uXXXX` diventa il
|
||||
/// carattere, e `\\` diventa `\`.
|
||||
fn decodifica_escape(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut iter = s.chars().peekable();
|
||||
while let Some(c) = iter.next() {
|
||||
if c != '\\' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
match iter.next() {
|
||||
Some('u') => {
|
||||
let mut cifre = String::new();
|
||||
for _ in 0..4 {
|
||||
if let Some(&c) = iter.peek() {
|
||||
cifre.push(c);
|
||||
iter.next();
|
||||
}
|
||||
}
|
||||
if let Ok(n) = u32::from_str_radix(&cifre, 16) {
|
||||
if let Some(c) = char::from_u32(n) {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some('n') => out.push('\n'),
|
||||
Some('t') => out.push('\t'),
|
||||
Some('r') => out.push('\r'),
|
||||
Some(altro) => out.push(altro),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -8,6 +8,7 @@ pub mod bidi;
|
||||
pub mod cookie;
|
||||
pub mod css;
|
||||
pub mod dom;
|
||||
mod entita_tabelle;
|
||||
pub mod ffi;
|
||||
pub mod font;
|
||||
pub mod hpack_tabelle;
|
||||
|
||||
+30
-4
@@ -33,6 +33,7 @@ pub enum Cmd {
|
||||
data: Arc<ImageData>,
|
||||
dimensione: crate::style::DimensioneSfondo,
|
||||
ripeti: (bool, bool),
|
||||
posizione: (crate::style::Posizione, crate::style::Posizione),
|
||||
clip: Option<Rect>,
|
||||
},
|
||||
/// Sfondo a gradiente lineare, con il testo CSS originale.
|
||||
@@ -152,7 +153,7 @@ fn walk(
|
||||
let raggio = b.style.border_radius;
|
||||
|
||||
// comodo: applica ritaglio e opacità a un rettangolo
|
||||
let mut rett = |out: &mut Vec<Cmd>, rect: Rect, color: Color, radius: f32| {
|
||||
let rett = |out: &mut Vec<Cmd>, rect: Rect, color: Color, radius: f32| {
|
||||
let Some(rect) = applica_clip(rect, clip) else {
|
||||
return;
|
||||
};
|
||||
@@ -189,6 +190,7 @@ fn walk(
|
||||
data,
|
||||
dimensione: b.style.background_size,
|
||||
ripeti: b.style.background_repeat,
|
||||
posizione: b.style.background_position,
|
||||
clip,
|
||||
});
|
||||
}
|
||||
@@ -383,6 +385,7 @@ pub fn rasterize(cmds: &[Cmd], w: u32, h: u32, scale: f32) -> Vec<u8> {
|
||||
data,
|
||||
dimensione,
|
||||
ripeti,
|
||||
posizione,
|
||||
clip,
|
||||
} => {
|
||||
let ritaglio = clip.map(|c| (c.x * scale, c.y * scale, c.w * scale, c.h * scale));
|
||||
@@ -399,6 +402,7 @@ pub fn rasterize(cmds: &[Cmd], w: u32, h: u32, scale: f32) -> Vec<u8> {
|
||||
data,
|
||||
*dimensione,
|
||||
*ripeti,
|
||||
*posizione,
|
||||
scale,
|
||||
ritaglio,
|
||||
);
|
||||
@@ -1117,10 +1121,11 @@ fn disegna_sfondo(
|
||||
data: &ImageData,
|
||||
dimensione: crate::style::DimensioneSfondo,
|
||||
ripeti: (bool, bool),
|
||||
posizione: (crate::style::Posizione, crate::style::Posizione),
|
||||
scale: f32,
|
||||
ritaglio: Option<(f32, f32, f32, f32)>,
|
||||
) {
|
||||
use crate::style::DimensioneSfondo;
|
||||
use crate::style::{DimensioneSfondo, Posizione};
|
||||
if rect.w <= 0.0 || rect.h <= 0.0 || data.width == 0 || data.height == 0 {
|
||||
return;
|
||||
}
|
||||
@@ -1152,7 +1157,15 @@ fn disegna_sfondo(
|
||||
tw = tw.max(1.0);
|
||||
th = th.max(1.0);
|
||||
|
||||
let mut y = rect.y;
|
||||
// posizione del primo tassello: le percentuali valgono rispetto allo spazio
|
||||
// che avanza (box meno tassello), come nel CSS
|
||||
let offset = |p: Posizione, contenitore: f32, tassello: f32| -> f32 {
|
||||
match p {
|
||||
Posizione::Px(v) => v * scale,
|
||||
Posizione::Pct(v) => (contenitore - tassello) * v / 100.0,
|
||||
}
|
||||
};
|
||||
let mut y = rect.y + offset(posizione.1, rect.h, th);
|
||||
let mut riga = 0;
|
||||
// il tassello si disegna intero e a ritagliarlo pensa `draw_image_clippata`:
|
||||
// limitarlo al box lo schiaccerebbe invece di tagliarlo
|
||||
@@ -1160,8 +1173,21 @@ fn disegna_sfondo(
|
||||
Some((cx, cy, cw, ch)) => Some((cx, cy, cw, ch)),
|
||||
None => Some((rect.x, rect.y, rect.w, rect.h)),
|
||||
};
|
||||
// con `repeat`, il reticolo continua all'indietro fino a coprire il bordo:
|
||||
// un fondo posizionato a metà non lascia un vuoto a sinistra
|
||||
if ripeti.1 {
|
||||
while y > rect.y {
|
||||
y -= th;
|
||||
}
|
||||
}
|
||||
while y < rect.bottom() {
|
||||
let mut x = rect.x;
|
||||
let mut x0 = rect.x + offset(posizione.0, rect.w, tw);
|
||||
if ripeti.0 {
|
||||
while x0 > rect.x {
|
||||
x0 -= tw;
|
||||
}
|
||||
}
|
||||
let mut x = x0;
|
||||
let mut colonna = 0;
|
||||
while x < rect.right() {
|
||||
crate::img::draw_image_clippata(buf, w, h, (x, y, tw, th), data, clip);
|
||||
|
||||
@@ -88,6 +88,19 @@ pub enum Traccia {
|
||||
Auto,
|
||||
}
|
||||
|
||||
/// Una coordinata di `background-position`: px oppure percentuale del box.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Posizione {
|
||||
Px(f32),
|
||||
Pct(f32),
|
||||
}
|
||||
|
||||
impl Default for Posizione {
|
||||
fn default() -> Self {
|
||||
Posizione::Pct(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// `background-size`: come si adatta l'immagine al box.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Default)]
|
||||
pub enum DimensioneSfondo {
|
||||
@@ -239,6 +252,8 @@ pub struct ComputedStyle {
|
||||
pub background_size: DimensioneSfondo,
|
||||
/// `background-repeat`: (orizzontale, verticale). `no-repeat` è (false, false)
|
||||
pub background_repeat: (bool, bool),
|
||||
/// `background-position`, orizzontale e verticale. Il valore iniziale è `0% 0%`
|
||||
pub background_position: (Posizione, Posizione),
|
||||
/// `background-image: linear-gradient(...)`, testo originale
|
||||
pub background_gradient: Option<String>,
|
||||
pub line_height: f32,
|
||||
@@ -312,6 +327,7 @@ impl Default for ComputedStyle {
|
||||
background_image: None,
|
||||
background_size: DimensioneSfondo::Auto,
|
||||
background_repeat: (true, true),
|
||||
background_position: (Posizione::Pct(0.0), Posizione::Pct(0.0)),
|
||||
background_gradient: None,
|
||||
line_height: 19.2,
|
||||
line_height_explicit: false,
|
||||
@@ -841,6 +857,40 @@ fn apply_declaration(st: &mut ComputedStyle, name: &str, value: &str, parent_fon
|
||||
}
|
||||
};
|
||||
}
|
||||
"background-position" => {
|
||||
let parti: Vec<&str> = v.split_whitespace().collect();
|
||||
let orizzontale = parti.first().copied().unwrap_or("0%");
|
||||
let verticale = parti.get(1).copied().unwrap_or_else(|| {
|
||||
// una sola parola: `center` vale per entrambi gli assi, un
|
||||
// valore orizzontale vale `center` in verticale
|
||||
if orizzontale.eq_ignore_ascii_case("center") {
|
||||
"center"
|
||||
} else {
|
||||
"center"
|
||||
}
|
||||
});
|
||||
let asse = |testo: &str, orizzontale: bool| -> Posizione {
|
||||
match testo.to_ascii_lowercase().as_str() {
|
||||
"left" => Posizione::Pct(0.0),
|
||||
"right" => Posizione::Pct(100.0),
|
||||
"top" => Posizione::Pct(0.0),
|
||||
"bottom" => Posizione::Pct(100.0),
|
||||
"center" => Posizione::Pct(50.0),
|
||||
altro => {
|
||||
if let Some(n) = altro.strip_suffix('%') {
|
||||
Posizione::Pct(n.trim().parse().unwrap_or(0.0))
|
||||
} else if let Some(l) = parse_len(altro, st.font_size) {
|
||||
Posizione::Px(l.resolve(st.font_size))
|
||||
} else {
|
||||
// parola non riconosciuta: resta il valore iniziale
|
||||
let _ = orizzontale;
|
||||
Posizione::Pct(0.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
st.background_position = (asse(orizzontale, true), asse(verticale, false));
|
||||
}
|
||||
"background-repeat" => {
|
||||
let minuscolo = v.trim().to_ascii_lowercase();
|
||||
st.background_repeat = match minuscolo.as_str() {
|
||||
|
||||
+196
-33
@@ -13,7 +13,14 @@ pub enum Token {
|
||||
},
|
||||
Text(String),
|
||||
Comment(String),
|
||||
Doctype,
|
||||
/// `<!doctype ...>`: nome e identificatori servono al confronto con la
|
||||
/// specifica; `corretto` è falso se durante la lettura c'è stato un errore
|
||||
Doctype {
|
||||
name: Option<String>,
|
||||
public_id: Option<String>,
|
||||
system_id: Option<String>,
|
||||
corretto: bool,
|
||||
},
|
||||
Eof,
|
||||
}
|
||||
|
||||
@@ -97,13 +104,33 @@ pub fn tokenize(input: &str) -> Vec<Token> {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Doctype o altra dichiarazione
|
||||
// Doctype o commento spurio. `<!` e `<?` non sono per forza una
|
||||
// dichiarazione: se non dicono `doctype` il contenuto è un commento
|
||||
// (è il caso di `<!>`, `<!ciao>`, `<! ` — molti casi del corpus).
|
||||
if b[i..].starts_with(&['<', '!']) || b[i..].starts_with(&['<', '?']) {
|
||||
let mut j = i + 2;
|
||||
let dopo = i + 2;
|
||||
let e_doctype = {
|
||||
let parola = "doctype";
|
||||
b.len() >= dopo + parola.len()
|
||||
&& b[dopo..dopo + parola.len()]
|
||||
.iter()
|
||||
.collect::<String>()
|
||||
.eq_ignore_ascii_case(parola)
|
||||
};
|
||||
if e_doctype {
|
||||
let (token, fine) = leggi_doctype(&b, dopo + "doctype".len());
|
||||
out.push(token);
|
||||
i = fine;
|
||||
continue;
|
||||
}
|
||||
// commento spurio: tutto quello che segue `<!` o `<?` fino a `>`
|
||||
let inizio = dopo;
|
||||
let mut j = inizio;
|
||||
while j < n && b[j] != '>' {
|
||||
j += 1;
|
||||
}
|
||||
out.push(Token::Doctype);
|
||||
let testo: String = b[inizio..j].iter().collect();
|
||||
out.push(Token::Comment(testo));
|
||||
i = (j + 1).min(n);
|
||||
continue;
|
||||
}
|
||||
@@ -160,6 +187,14 @@ pub fn tokenize(input: &str) -> Vec<Token> {
|
||||
while j < n && !b[j].is_whitespace() && b[j] != '=' && b[j] != '>' && b[j] != '/' {
|
||||
j += 1;
|
||||
}
|
||||
// Se il carattere non può iniziare un nome di attributo (per
|
||||
// esempio una `/` non seguita da `>`), si scarta e si prosegue:
|
||||
// senza questo il ciclo non avanza e il tokenizer si blocca.
|
||||
// È il caso di `<h/a='b'>`, che secondo la specifica vale `<h a='b'>`.
|
||||
if j == astart {
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
let aname: String = b[astart..j].iter().collect::<String>().to_ascii_lowercase();
|
||||
while j < n && b[j].is_whitespace() {
|
||||
j += 1;
|
||||
@@ -251,44 +286,80 @@ pub fn unescape(s: &str) -> String {
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
if chars[i] == '&' {
|
||||
let mut j = i + 1;
|
||||
while j < chars.len() && j - i <= 10 && chars[j] != ';' {
|
||||
if chars[i] != '&' {
|
||||
out.push(chars[i]);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// riferimento numerico: `&` oppure `&`
|
||||
if i + 1 < chars.len() && chars[i + 1] == '#' {
|
||||
let mut j = i + 2;
|
||||
let esadecimale = j < chars.len() && (chars[j] == 'x' || chars[j] == 'X');
|
||||
if esadecimale {
|
||||
j += 1;
|
||||
}
|
||||
if j < chars.len() && chars[j] == ';' {
|
||||
let ent: String = chars[i + 1..j].iter().collect();
|
||||
let rep = match ent.as_str() {
|
||||
"amp" => Some('&'),
|
||||
"lt" => Some('<'),
|
||||
"gt" => Some('>'),
|
||||
"quot" => Some('"'),
|
||||
"apos" => Some('\''),
|
||||
"nbsp" => Some('\u{00a0}'),
|
||||
_ => {
|
||||
if let Some(hex) = ent.strip_prefix("#x").or_else(|| ent.strip_prefix("#X"))
|
||||
{
|
||||
u32::from_str_radix(hex, 16).ok().and_then(char::from_u32)
|
||||
} else if let Some(dec) = ent.strip_prefix('#') {
|
||||
dec.parse::<u32>().ok().and_then(char::from_u32)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(r) = rep {
|
||||
out.push(r);
|
||||
i = j + 1;
|
||||
continue;
|
||||
let inizio_cifre = j;
|
||||
while j < chars.len()
|
||||
&& if esadecimale {
|
||||
chars[j].is_ascii_hexdigit()
|
||||
} else {
|
||||
chars[j].is_ascii_digit()
|
||||
}
|
||||
{
|
||||
j += 1;
|
||||
}
|
||||
if j > inizio_cifre {
|
||||
let cifre: String = chars[inizio_cifre..j].iter().collect();
|
||||
let valore =
|
||||
u32::from_str_radix(&cifre, if esadecimale { 16 } else { 10 }).unwrap_or(0);
|
||||
// la specifica sostituisce i valori non validi con U+FFFD
|
||||
out.push(char::from_u32(valore).unwrap_or('\u{fffd}'));
|
||||
// il `;` dopo le cifre fa parte del riferimento e si consuma
|
||||
if j < chars.len() && chars[j] == ';' {
|
||||
j += 1;
|
||||
}
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// entità nominata: si prova la forma più lunga che esiste, con il punto
|
||||
// e virgola prima e senza poi (le forme senza `;` sono quelle "legacy")
|
||||
let massimo = (chars.len() - i - 1).min(32);
|
||||
let mut trovato: Option<(usize, &'static str)> = None;
|
||||
for lunghezza in (1..=massimo).rev() {
|
||||
let candidato: String = chars[i + 1..i + 1 + lunghezza].iter().collect();
|
||||
if let Some(caratteri) = cerca_entita(&candidato) {
|
||||
trovato = Some((lunghezza, caratteri));
|
||||
break;
|
||||
}
|
||||
// con il punto e virgola incluso nella lunghezza si è già provato;
|
||||
// le forme senza `;` esistono solo per 106 nomi, e la tabella le ha
|
||||
}
|
||||
match trovato {
|
||||
Some((lunghezza, caratteri)) => {
|
||||
out.push_str(caratteri);
|
||||
i += 1 + lunghezza;
|
||||
}
|
||||
None => {
|
||||
out.push('&');
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out.push(chars[i]);
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Cerca un'entità nominata nella tabella (ricerca binaria). Il nome include il
|
||||
/// punto e virgola quando c'è: `amp;` e `amp` sono due voci distinte.
|
||||
fn cerca_entita(nome: &str) -> Option<&'static str> {
|
||||
use crate::entita_tabelle::ENTITA;
|
||||
match ENTITA.binary_search_by(|(n, _)| (*n).cmp(nome)) {
|
||||
Ok(posizione) => Some(ENTITA[posizione].1),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -333,3 +404,95 @@ mod tests {
|
||||
assert_eq!(joined, "ab");
|
||||
}
|
||||
}
|
||||
|
||||
/// Legge il resto di un `<!doctype …>`: nome, `PUBLIC`/`SYSTEM` e identificatori.
|
||||
/// `corretto` resta vero solo se la forma è quella della specifica, perché il
|
||||
/// corpus lo confronta (`<!DOCTYPEHtMl>` è un errore, `< !DOCTYPE html>` no).
|
||||
fn leggi_doctype(b: &[char], inizio: usize) -> (Token, usize) {
|
||||
let n = b.len();
|
||||
let mut j = inizio;
|
||||
let mut corretto = true;
|
||||
// deve esserci spazio (o direttamente `>`) dopo `doctype`
|
||||
if j >= n || !b[j].is_whitespace() {
|
||||
corretto = false;
|
||||
}
|
||||
while j < n && b[j].is_whitespace() {
|
||||
j += 1;
|
||||
}
|
||||
let inizio_nome = j;
|
||||
while j < n && !b[j].is_whitespace() && b[j] != '>' {
|
||||
j += 1;
|
||||
}
|
||||
let nome: String = b[inizio_nome..j]
|
||||
.iter()
|
||||
.collect::<String>()
|
||||
.to_ascii_lowercase();
|
||||
let name = if nome.is_empty() { None } else { Some(nome) };
|
||||
|
||||
let mut public_id: Option<String> = None;
|
||||
let mut system_id: Option<String> = None;
|
||||
|
||||
// leggi una stringa fra virgolette, se c'è
|
||||
let leggi_stringa = |j: &mut usize| -> Option<String> {
|
||||
while *j < n && b[*j].is_whitespace() {
|
||||
*j += 1;
|
||||
}
|
||||
if *j >= n || (b[*j] != '"' && b[*j] != '\'') {
|
||||
return None;
|
||||
}
|
||||
let virgoletta = b[*j];
|
||||
*j += 1;
|
||||
let start = *j;
|
||||
while *j < n && b[*j] != virgoletta && b[*j] != '>' {
|
||||
*j += 1;
|
||||
}
|
||||
let valore: String = b[start..*j].iter().collect();
|
||||
if *j < n && b[*j] == virgoletta {
|
||||
*j += 1;
|
||||
}
|
||||
Some(valore)
|
||||
};
|
||||
|
||||
while j < n && b[j].is_whitespace() {
|
||||
j += 1;
|
||||
}
|
||||
let parola = |j: usize, parola: &str| -> bool {
|
||||
b.len() >= j + parola.len()
|
||||
&& b[j..j + parola.len()]
|
||||
.iter()
|
||||
.collect::<String>()
|
||||
.eq_ignore_ascii_case(parola)
|
||||
};
|
||||
if parola(j, "public") {
|
||||
j += "public".len();
|
||||
public_id = leggi_stringa(&mut j);
|
||||
system_id = leggi_stringa(&mut j);
|
||||
} else if parola(j, "system") {
|
||||
j += "system".len();
|
||||
system_id = leggi_stringa(&mut j);
|
||||
}
|
||||
|
||||
while j < n && b[j] != '>' {
|
||||
// caratteri inattesi prima di `>`: errore, si salta
|
||||
corretto = false;
|
||||
j += 1;
|
||||
}
|
||||
if j < n && b[j] == '>' {
|
||||
j += 1;
|
||||
} else {
|
||||
// EOF dentro il doctype
|
||||
corretto = false;
|
||||
}
|
||||
if name.is_none() {
|
||||
corretto = false;
|
||||
}
|
||||
(
|
||||
Token::Doctype {
|
||||
name,
|
||||
public_id,
|
||||
system_id,
|
||||
corretto,
|
||||
},
|
||||
j,
|
||||
)
|
||||
}
|
||||
@@ -43,7 +43,7 @@ pub fn parse(html: &str) -> BuildResult {
|
||||
|
||||
match phase {
|
||||
Phase::BeforeHead => match tok {
|
||||
Token::Doctype | Token::Comment(_) | Token::Eof => {}
|
||||
Token::Doctype { .. } | Token::Comment(_) | Token::Eof => {}
|
||||
Token::Text(t) if t.trim().is_empty() => {}
|
||||
Token::StartTag { name, attrs, .. } if name == "html" => {
|
||||
let n = doc.create_element("html", attrs.clone());
|
||||
@@ -88,7 +88,7 @@ pub fn parse(html: &str) -> BuildResult {
|
||||
phase = Phase::InBody;
|
||||
reprocess = true;
|
||||
}
|
||||
Token::Comment(_) | Token::Doctype | Token::Eof => {}
|
||||
Token::Comment(_) | Token::Doctype { .. } | Token::Eof => {}
|
||||
Token::StartTag {
|
||||
name,
|
||||
attrs,
|
||||
@@ -126,7 +126,7 @@ pub fn parse(html: &str) -> BuildResult {
|
||||
},
|
||||
Phase::AfterHead => match tok {
|
||||
Token::Text(t) if t.trim().is_empty() => {}
|
||||
Token::Comment(_) | Token::Doctype | Token::Eof => {}
|
||||
Token::Comment(_) | Token::Doctype { .. } | Token::Eof => {}
|
||||
Token::StartTag { name, attrs, .. } if name == "body" => {
|
||||
let h = ensure_html(&mut doc, &mut stack, &mut html_node);
|
||||
let n = doc.create_element("body", attrs.clone());
|
||||
@@ -161,7 +161,7 @@ pub fn parse(html: &str) -> BuildResult {
|
||||
let n = doc.create_comment(c);
|
||||
doc.append_child(cur, n);
|
||||
}
|
||||
Token::Doctype | Token::Eof => {}
|
||||
Token::Doctype { .. } | Token::Eof => {}
|
||||
Token::StartTag {
|
||||
name,
|
||||
attrs,
|
||||
|
||||
Reference in new issue
Block a user