Fix entity decoding in attribute value; enforce valid Unicode Scalar Value numeric entity refs; update named entities; error messages for CLI; support post-minification empty attributes

This commit is contained in:
Wilson Lin 2019-12-27 00:23:33 +11:00
parent 4ef7574487
commit a76c1f3cd5
9 changed files with 2294 additions and 2216 deletions

View File

@ -48,7 +48,7 @@ They are considered as a single character representing their decoded value. This
If a named entity is an invalid reference as per the [spec](https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references), it is considered malformed and will be interpreted literally.
Numeric character references that reference to numbers below 0x00 or above 0x10FFFF are considered malformed. It will be decoded if it falls within this range, even if it does not refer to a valid Unicode code point.
Numeric character references that do not reference a valid [Unicode Scalar Value](https://www.unicode.org/glossary/#unicode_scalar_value) are considered malformed.
### Attributes

View File

@ -1,5 +1,5 @@
use std::fs::File;
use std::io::{Read, Write};
use std::io::{Read, Write, stderr};
use structopt::StructOpt;
@ -27,9 +27,34 @@ fn main() {
Err((err, pos)) => {
eprintln!("Failed at character {}:", pos);
match err {
// TODO
_ => unimplemented!(),
ErrorType::NoSpaceBeforeAttr => {
eprintln!("Space required before attribute.");
}
ErrorType::UnterminatedCssString => {
eprintln!("Unterminated CSS string.");
}
ErrorType::UnterminatedJsString => {
eprintln!("Unterminated JavaScript string.");
}
ErrorType::CharNotFound { need, got } => {
eprintln!("Expected {} (U+{:X}), got {} (U+{:X}).", need as char, need, got as char, got);
}
ErrorType::MatchNotFound(seq) => {
eprint!("Expected `");
stderr().write_all(seq).expect("failed to write to stderr");
eprintln!("`.");
}
ErrorType::NotFound(exp) => {
eprintln!("Expected {}.", exp);
}
ErrorType::UnexpectedChar(unexp) => {
eprintln!("Unexpected {} (U+{:X}).", unexp as char, unexp);
}
ErrorType::UnexpectedEnd => {
eprintln!("Unexpected end of source code.");
}
};
eprintln!("The output file has not been touched.")
}
};
}

View File

@ -35,7 +35,7 @@ pub enum RequireReason {
ExpectedChar(u8),
}
#[derive(Copy, Clone)]
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Checkpoint {
read_next: usize,
write_next: usize,
@ -70,15 +70,6 @@ pub struct Processor<'d> {
write_next: usize,
}
fn index_of(s: &'static [u8], c: u8, from: usize) -> Option<usize> {
for i in from..s.len() {
if s[i] == c {
return Some(i);
};
};
None
}
impl<'d> Index<ProcessorRange> for Processor<'d> {
type Output = [u8];
@ -383,32 +374,10 @@ impl<'d> Processor<'d> {
self.code[self.write_next..self.write_next + s.len()].copy_from_slice(s);
self.write_next += s.len();
}
/// Does not check if `c` is a valid Unicode code point.
pub fn write_utf8(&mut self, c: u32) -> () {
// TODO Test.
// Don't use char::encode_utf8 as it requires a valid code point,
// and requires passing a [u8, 4] which might be heap-allocated.
if c <= 0x7F {
// Plain ASCII.
self.write(c as u8);
} else if c <= 0x07FF {
// 2-byte UTF-8.
self.write((((c >> 6) & 0x1F) | 0xC0) as u8);
self.write((((c >> 0) & 0x3F) | 0x80) as u8);
} else if c <= 0xFFFF {
// 3-byte UTF-8.
self.write((((c >> 12) & 0x0F) | 0xE0) as u8);
self.write((((c >> 6) & 0x3F) | 0x80) as u8);
self.write((((c >> 0) & 0x3F) | 0x80) as u8);
} else if c <= 0x10FFFF {
// 4-byte UTF-8.
self.write((((c >> 18) & 0x07) | 0xF0) as u8);
self.write((((c >> 12) & 0x3F) | 0x80) as u8);
self.write((((c >> 6) & 0x3F) | 0x80) as u8);
self.write((((c >> 0) & 0x3F) | 0x80) as u8);
} else {
unreachable!();
}
pub fn write_utf8(&mut self, c: char) -> () {
let mut encoded = [0u8, 4];
c.encode_utf8(&mut encoded);
self.write_slice(&encoded);
}
// Shifting characters.

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@ use phf::{phf_set, Set};
use crate::err::ProcessingResult;
use crate::proc::Processor;
use crate::spec::codepoint::is_control;
use crate::unit::attr::value::process_attr_value;
use crate::unit::attr::value::{DelimiterType, process_attr_value, ProcessedAttrValue};
mod value;
@ -41,12 +41,13 @@ pub fn process_attr(proc: &mut Processor) -> ProcessingResult<AttrType> {
Ok(AttrType::NoValue)
} else {
match process_attr_value(proc, should_collapse_and_trim_value_ws)? {
(_, 0) => {
ProcessedAttrValue { empty: true, .. } => {
// Value is empty, which is equivalent to no value, so discard `=` and any quotes.
proc.erase_written(after_name);
Ok(AttrType::NoValue)
}
(attr_type, _) => Ok(attr_type),
ProcessedAttrValue { delimiter: DelimiterType::Unquoted, .. } => Ok(AttrType::Unquoted),
ProcessedAttrValue { delimiter: DelimiterType::Double, .. } | ProcessedAttrValue { delimiter: DelimiterType::Single, .. } => Ok(AttrType::Quoted),
}
}
}

View File

@ -3,8 +3,7 @@ use phf::{Map, phf_map};
use crate::err::ProcessingResult;
use crate::proc::Processor;
use crate::spec::codepoint::is_whitespace;
use crate::unit::attr::AttrType;
use crate::unit::entity::{parse_entity, process_entity};
use crate::unit::entity::{EntityType, maybe_process_entity, ParsedEntity};
pub fn is_double_quote(c: u8) -> bool {
c == b'"'
@ -40,8 +39,7 @@ static ENCODED: Map<u8, &'static [u8]> = phf_map! {
#[derive(Clone, Copy, Eq, PartialEq)]
enum CharType {
End,
MalformedEntity,
DecodedNonAscii,
NonAsciiEntity(ParsedEntity),
// Normal needs associated character to be able to write it.
Normal(u8),
// Whitespace needs associated character to determine cost of encoding it.
@ -63,7 +61,7 @@ impl CharType {
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum DelimiterType {
pub enum DelimiterType {
Double,
Single,
Unquoted,
@ -81,6 +79,7 @@ struct Metrics {
first_char_type: Option<CharType>,
last_char_type: Option<CharType>,
// How many times `collect_char_type` is called. Used to determine first and last characters when writing.
// NOTE: This may not be the same as amount of final characters, as malformed entities are usually multiple chars.
collected_count: usize,
}
@ -162,7 +161,7 @@ impl Metrics {
}
macro_rules! consume_attr_value_chars {
($proc:ident, $should_collapse_and_trim_ws:ident, $delimiter_pred:ident, $entity_processor:ident, $out_char_type:ident, $on_char:block) => {
($proc:ident, $should_collapse_and_trim_ws:ident, $delimiter_pred:ident, $out_char_type:ident, $on_char:block) => {
// Set to true when one or more immediately previous characters were whitespace and deferred for processing after the contiguous whitespace.
// NOTE: Only used if `should_collapse_and_trim_ws`.
let mut currently_in_whitespace = false;
@ -175,9 +174,11 @@ macro_rules! consume_attr_value_chars {
// DO NOT BREAK HERE. More processing is done afterwards upon reaching end.
CharType::End
} else if chain!($proc.match_char(b'&').matched()) {
match $entity_processor($proc)? {
Some(e) => if e <= 0x7f { CharType::from_char(e as u8) } else { CharType::DecodedNonAscii },
None => CharType::MalformedEntity,
let entity = maybe_process_entity($proc)?;
if let EntityType::Ascii(c) = entity.entity() {
CharType::from_char(c)
} else {
CharType::NonAsciiEntity(entity)
}
} else {
CharType::from_char($proc.skip()?)
@ -213,7 +214,12 @@ macro_rules! consume_attr_value_chars {
};
}
pub fn process_attr_value(proc: &mut Processor, should_collapse_and_trim_ws: bool) -> ProcessingResult<(AttrType, usize)> {
pub struct ProcessedAttrValue {
pub delimiter: DelimiterType,
pub empty: bool,
}
pub fn process_attr_value(proc: &mut Processor, should_collapse_and_trim_ws: bool) -> ProcessingResult<ProcessedAttrValue> {
let src_delimiter = chain!(proc.match_pred(is_attr_quote).discard().maybe_char());
let src_delimiter_pred = match src_delimiter {
Some(b'"') => is_double_quote,
@ -234,7 +240,7 @@ pub fn process_attr_value(proc: &mut Processor, should_collapse_and_trim_ws: boo
collected_count: 0,
};
let mut char_type;
consume_attr_value_chars!(proc, should_collapse_and_trim_ws, src_delimiter_pred, parse_entity, char_type, {
consume_attr_value_chars!(proc, should_collapse_and_trim_ws, src_delimiter_pred, char_type, {
metrics.collect_char_type(char_type);
});
@ -253,14 +259,12 @@ pub fn process_attr_value(proc: &mut Processor, should_collapse_and_trim_ws: boo
let mut char_type;
// Used to determine first and last characters.
let mut char_no = 0usize;
consume_attr_value_chars!(proc, should_collapse_and_trim_ws, src_delimiter_pred, process_entity, char_type, {
consume_attr_value_chars!(proc, should_collapse_and_trim_ws, src_delimiter_pred, char_type, {
match char_type {
// This should never happen.
CharType::End => unreachable!(),
// Ignore these; already written by `process_entity`.
CharType::MalformedEntity => {}
CharType::DecodedNonAscii => {}
CharType::NonAsciiEntity(e) => e.keep(proc),
CharType::Normal(c) => proc.write(c),
// If unquoted, encode any whitespace anywhere.
@ -298,10 +302,8 @@ pub fn process_attr_value(proc: &mut Processor, should_collapse_and_trim_ws: boo
proc.write(c);
}
let attr_type = if optimal_delimiter != DelimiterType::Unquoted {
AttrType::Quoted
} else {
AttrType::Unquoted
};
Ok((attr_type, metrics.collected_count))
Ok(ProcessedAttrValue {
delimiter: optimal_delimiter,
empty: metrics.collected_count == 0,
})
}

View File

@ -6,7 +6,7 @@ use crate::spec::tag::formatting::FORMATTING_TAGS;
use crate::spec::tag::wss::WSS_TAGS;
use crate::unit::bang::process_bang;
use crate::unit::comment::process_comment;
use crate::unit::entity::{process_entity, maybe_process_entity};
use crate::unit::entity::{EntityType, maybe_process_entity};
use crate::unit::tag::process_tag;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
@ -92,26 +92,23 @@ pub fn process_content(proc: &mut Processor, parent: Option<ProcessorRange>) ->
loop {
let next_content_type = match ContentType::peek(proc) {
ContentType::Entity => {
let e = maybe_process_entity(proc)?;
// Entity could decode to whitespace.
if e.code_point()
.filter(|c| *c < 0x7f)
.filter(|c| is_whitespace(*c as u8))
.is_some() {
let entity = maybe_process_entity(proc)?;
if let EntityType::Ascii(c) = entity.entity() {
// Skip whitespace char, and mark as whitespace.
ContentType::Whitespace
} else {
// Not whitespace, so decode and write.
e.keep(proc);
entity.keep(proc);
ContentType::Entity
}
},
}
ContentType::Whitespace => {
// This is here to prevent skipping twice from decoded whitespace entity.
// Whitespace is always ignored and then processed afterwards, even if not minifying.
proc.skip().expect("skipping known character");
ContentType::Whitespace
},
}
other_type => other_type,
};

View File

@ -7,7 +7,9 @@
// Based on the data sourced from https://www.w3.org/TR/html5/entities.json as
// of 2019-04-20T04:00:00.000Z:
// - Entity names can have [A-Za-z0-9] characters, and are case sensitive.
// - Some character entity references do not need to end with a semicolon.
// - Some character entity references do not end with a semicolon, but
// spec says all must (https://html.spec.whatwg.org/multipage/syntax.html#character-references).
// - All of these entities also have a corresponding entity with semicolon.
// - The longest name is "CounterClockwiseContourIntegral", with length 31
// (excluding leading ampersand and trailing semicolon).
// - All entity names are at least 2 characters long.
@ -30,65 +32,87 @@
// /&(#(x[0-9a-f]{1-6}|[0-9]{1,7}))|[a-z0-9]{2,31};/i
//
// - If the sequence of characters following an ampersand do not combine to form
// a well formed entity, the ampersand is considered a bare ampersand.
// - A bare ampersand is an ampersand that is interpreted literally and not as
// the start of an entity.
// - hyperbuild looks ahead without consuming to check if the following
// characters would form a well formed entity. If they don't, only the longest
// subsequence that could form a well formed entity is consumed.
// - An entity is considered invalid if it is well formed but represents a
// non-existent Unicode code point or reference name.
// a well formed entity, they are treated literally.
use crate::err::ProcessingResult;
use crate::proc::{Checkpoint, Processor};
use crate::spec::codepoint::{is_digit, is_hex_digit, is_lower_hex_digit, is_upper_hex_digit};
use crate::spec::entity::{ENTITY_REFERENCES, is_valid_entity_reference_name_char};
const MAX_UNICODE_CODE_POINT: u32 = 0x10FFFF;
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
enum Type {
pub enum EntityType {
Malformed,
Name,
Decimal,
Hexadecimal,
Ascii(u8),
// If named or numeric reference refers to ASCII char, Type::Ascii is used instead.
Named(&'static [u8]),
Numeric(char),
}
fn parse_decimal(slice: &[u8]) -> Option<u32> {
let mut val = 0u32;
for c in slice {
val = val * 10 + (c - b'0') as u32;
}
if val > MAX_UNICODE_CODE_POINT {
None
} else {
Some(val)
}
}
fn parse_hexadecimal(slice: &[u8]) -> Option<u32> {
let mut val = 0u32;
for c in slice {
let digit = if is_digit(*c) {
c - b'0'
} else if is_upper_hex_digit(*c) {
c - b'A' + 10
} else if is_lower_hex_digit(*c) {
c - b'a' + 10
} else {
unreachable!();
};
val = val * 16 + digit as u32;
macro_rules! handle_decoded_code_point {
($code_point:ident) => {
match std::char::from_u32($code_point) {
Some(c) => if c.is_ascii() {
EntityType::Ascii(c as u8)
} else {
EntityType::Numeric(c)
},
None => EntityType::Malformed,
}
};
if val > MAX_UNICODE_CODE_POINT {
None
} else {
Some(val)
}
fn parse_decimal(proc: &mut Processor) -> EntityType {
let mut val = 0u32;
// Parse at most seven characters to prevent parsing forever.
for _ in 0..7 {
if let Some(c) = chain!(proc.match_pred(is_digit).discard().maybe_char()) {
val = val * 10 + (c - b'0') as u32;
} else {
break;
}
}
handle_decoded_code_point!(val)
}
fn parse_hexadecimal(proc: &mut Processor) -> EntityType {
let mut val = 0u32;
// Parse at most six characters to prevent parsing forever.
for _ in 0..6 {
if let Some(c) = chain!(proc.match_pred(is_hex_digit).discard().maybe_char()) {
let digit = if is_digit(c) {
c - b'0'
} else if is_upper_hex_digit(c) {
c - b'A' + 10
} else if is_lower_hex_digit(c) {
c - b'a' + 10
} else {
unreachable!();
};
val = val * 16 + digit as u32;
} else {
break;
}
}
handle_decoded_code_point!(val)
}
fn parse_name(proc: &mut Processor) -> EntityType {
let data = chain!(proc.match_while_pred(is_valid_entity_reference_name_char).discard().slice());
match ENTITY_REFERENCES.get(data) {
// In UTF-8, one-byte character encodings are always ASCII.
Some(s) => if s.len() == 1 {
EntityType::Ascii(s[0])
} else {
EntityType::Named(s)
},
None => {
EntityType::Malformed
},
}
}
// This will parse and skip characters. Set a checkpoint to later write skipped, or to ignore results and reset to previous position.
pub fn parse_entity(proc: &mut Processor) -> ProcessingResult<Option<u32>> {
pub fn parse_entity(proc: &mut Processor) -> ProcessingResult<EntityType> {
chain!(proc.match_char(b'&').expect().discard());
// The input can end at any time after initial ampersand.
@ -103,7 +127,7 @@ pub fn parse_entity(proc: &mut Processor) -> ProcessingResult<Option<u32>> {
// characters after the initial ampersand, e.g. "&#", "&#x", "&a".
// 2. Parse the entity data, i.e. the characters between the ampersand
// and semicolon.
// - To avoid parsing forever on malformed entities without
// - TODO To avoid parsing forever on malformed entities without
// semicolons, there is an upper bound on the amount of possible
// characters, based on the type of entity detected from the first
// stage.
@ -111,79 +135,52 @@ pub fn parse_entity(proc: &mut Processor) -> ProcessingResult<Option<u32>> {
// - This simply checks if it refers to a valid Unicode code point or
// entity reference name.
// First stage: determine the type of entity.
let predicate: fn(u8) -> bool;
let mut entity_type: Type;
let min_len: usize;
let max_len: usize;
if chain!(proc.match_seq(b"#x").discard().matched()) {
predicate = is_hex_digit;
entity_type = Type::Hexadecimal;
min_len = 1;
max_len = 6;
// TODO Could optimise.
let entity_type = if chain!(proc.match_seq(b"#x").discard().matched()) {
parse_hexadecimal(proc)
} else if chain!(proc.match_char(b'#').discard().matched()) {
predicate = is_digit;
entity_type = Type::Decimal;
min_len = 1;
max_len = 7;
parse_decimal(proc)
} else if chain!(proc.match_pred(is_valid_entity_reference_name_char).matched()) {
predicate = is_valid_entity_reference_name_char;
entity_type = Type::Name;
min_len = 2;
max_len = 31;
parse_name(proc)
} else {
// At this point, only consumed ampersand.
return Ok(None);
}
// Second stage: try to parse a well formed entity.
// Malformed entity could be last few characters in code, so allow EOF during entity.
let data = chain!(proc.match_while_pred(predicate).discard().slice());
if data.len() < min_len || data.len() > max_len {
entity_type = Type::Malformed;
EntityType::Malformed
};
// Third stage: validate entity and decode if configured to do so.
let res = Ok(match entity_type {
Type::Name => ENTITY_REFERENCES.get(data).map(|r| *r),
Type::Decimal => parse_decimal(data),
Type::Hexadecimal => parse_hexadecimal(data),
Type::Malformed => None,
});
// Consume semicolon after using borrowed data slice.
if entity_type != Type::Malformed && !chain!(proc.match_char(b';').discard().matched()) {
Ok(None)
Ok(if entity_type != EntityType::Malformed && chain!(proc.match_char(b';').discard().matched()) {
entity_type
} else {
res
}
println!("Malformed");
EntityType::Malformed
})
}
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct ParsedEntity {
code_point: Option<u32>,
entity: EntityType,
checkpoint: Checkpoint,
}
impl ParsedEntity {
pub fn code_point(&self) -> Option<u32> {
self.code_point
pub fn entity(&self) -> EntityType {
self.entity
}
pub fn keep(&self, proc: &mut Processor) -> () {
if let Some(cp) = self.code_point {
proc.write_utf8(cp);
} else {
// Write discarded characters that could not form a well formed entity.
proc.write_skipped(self.checkpoint);
match self.entity {
EntityType::Malformed => proc.write_skipped(self.checkpoint),
EntityType::Ascii(c) => proc.write(c),
EntityType::Named(s) => proc.write_slice(s),
EntityType::Numeric(c) => proc.write_utf8(c),
};
}
}
pub fn maybe_process_entity(proc: &mut Processor) -> ProcessingResult<ParsedEntity> {
let checkpoint = proc.checkpoint();
let code_point = parse_entity(proc)?;
let entity = parse_entity(proc)?;
Ok(ParsedEntity { code_point, checkpoint })
Ok(ParsedEntity { entity, checkpoint })
}
/**
@ -192,8 +189,8 @@ pub fn maybe_process_entity(proc: &mut Processor) -> ProcessingResult<ParsedEnti
* @return Unicode code point of the entity, or HB_UNIT_ENTITY_NONE if the
* entity is malformed or invalid
*/
pub fn process_entity(proc: &mut Processor) -> ProcessingResult<Option<u32>> {
let e = maybe_process_entity(proc)?;
e.keep(proc);
Ok(e.code_point())
pub fn process_entity(proc: &mut Processor) -> ProcessingResult<EntityType> {
let entity = maybe_process_entity(proc)?;
entity.keep(proc);
Ok(entity.entity())
}

View File

@ -38,9 +38,7 @@ pub fn process_tag(proc: &mut Processor) -> ProcessingResult<()> {
let mut self_closing = false;
loop {
// At the beginning of this loop, the last parsed unit was
// either the tag name or an attribute (including its value, if
// it had one).
// At the beginning of this loop, the last parsed unit was either the tag name or an attribute (including its value, if it had one).
let ws_accepted = chain!(proc.match_while_pred(is_whitespace).discard().matched());
if chain!(proc.match_char(b'>').keep().matched()) {
@ -60,8 +58,8 @@ pub fn process_tag(proc: &mut Processor) -> ProcessingResult<()> {
// Write space after tag name or unquoted/valueless attribute.
match last_attr_type {
Some(AttrType::Quoted) => {}
_ => proc.write(b' '),
Some(AttrType::Unquoted) | Some(AttrType::NoValue) | None => proc.write(b' '),
_ => {}
};
last_attr_type = Some(process_attr(proc)?);