diff --git a/src/index.ts b/src/index.ts index 8ab848d..b227119 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,7 @@ export { str_equals, str_starts_with, str_index_of, + css_unescape, } from './string-helpers' // Advanced/class-based API diff --git a/src/parse-atrule-prelude.ts b/src/parse-atrule-prelude.ts index 6d3a2a8..4a71f12 100644 --- a/src/parse-atrule-prelude.ts +++ b/src/parse-atrule-prelude.ts @@ -29,6 +29,7 @@ import { } from './token-types' import { str_equals_range, + css_unescape, is_and_or_not_range, strip_vendor_prefix, CHAR_PERIOD, @@ -83,7 +84,7 @@ export class AtRulePreludeParser { // Dispatch to appropriate parser based on at-rule type private parse_prelude_dispatch(at_rule_name: string): number[] { // Strip vendor prefix to treat @-webkit-keyframes same as @keyframes - const normalized_name = strip_vendor_prefix(at_rule_name).toLowerCase() + const normalized_name = strip_vendor_prefix(css_unescape(at_rule_name)).toLowerCase() switch (normalized_name) { case 'media': diff --git a/src/parse-escapes.test.ts b/src/parse-escapes.test.ts index a7d5de6..0de19cc 100644 --- a/src/parse-escapes.test.ts +++ b/src/parse-escapes.test.ts @@ -3,7 +3,8 @@ import { parse } from './parse' import { parse_selector } from './parse-selector' import { ID_SELECTOR, AT_RULE, DIMENSION, IDENTIFIER } from './constants' import { parse_value } from './parse-value' -import type { Atrule, Dimension } from './node-types' +import type { Atrule, Declaration, Dimension, Rule } from './node-types' +import { css_unescape, str_equals } from './string-helpers' test('escaped quote in selector', () => { expect(parse('.a{color:red} .x-\\"{color:red} .b{color:blue}').children.length).toBe(3) @@ -68,3 +69,72 @@ test.each(['.-\\31 x', '.-\\31', '#-\\31 x'])('selector %s with hyphen and escap expect(root.children.length).toBe(1) expect(root.first_child!.text).toBe(selector) }) + +test.each([ + ['\\31 23', '123'], + ['\\:', ':'], + ['a\\:b', 'a:b'], + ['\\6d edia', 'media'], + ['\\00006dedia', 'media'], + ['\\6D edia', 'media'], + ['\\1F600 x', '😀x'], + ['\\0', '�'], + ['\\D800 ', '�'], + ['\\110000 ', '�'], + ['a\\\nb', 'a\\\nb'], + ['a\\', 'a\\'], + ['plain', 'plain'], +])('css_unescape(%j) is %j', (input, expected) => { + expect(css_unescape(input)).toBe(expected) +}) + +test('str_equals decodes escapes', () => { + expect(str_equals('media', '\\6d edia')).toBe(true) + expect(str_equals('media', '\\4d edia')).toBe(true) + expect(str_equals('media', 'm\\65 dia')).toBe(true) + expect(str_equals('media', '\\6d edia2')).toBe(false) + expect(str_equals('media', '\\6d ed')).toBe(false) + expect(str_equals('a-b', 'a\\-b')).toBe(true) + expect(str_equals('media', 'screen')).toBe(false) +}) + +test.each([ + ['@\\6d edia (min-width:1px){}', 'MediaQuery'], + ['@\\6c ayer a,b;', 'Layer'], + ['@\\73 upports (display:grid){}', 'SupportsQuery'], + ['@\\63 ontainer (min-width:1px){}', 'ContainerQuery'], + ['@\\6b eyframes a{}', 'Identifier'], + ['@\\73 cope (.a) to (.b){}', 'PreludeSelectorList'], + ['@\\69 mport "a";', 'Url'], + ['@-webkit-\\6b eyframes a{}', 'Identifier'], +])('escaped at-rule name in %s dispatches to the right prelude parser', (css, type_name) => { + const atrule = parse(css).first_child as Atrule + expect(atrule.prelude?.first_child?.type_name ?? atrule.prelude?.type_name).toBe(type_name) +}) + +test('escaped at-rule name keeps declarations in the block', () => { + const atrule = parse('@\\66 ont-face{color:red}').first_child as Atrule + expect(atrule.block?.first_child?.type_name).toBe('Declaration') +}) + +test.each([ + [':\\6e ot(.a)', 'SelectorList'], + [':\\69 s(.a)', 'SelectorList'], + [':\\68 as(> a)', 'SelectorList'], + [':\\6e th-child(2n+1)', 'Nth'], + [':\\6c ang(en)', 'Lang'], +])('escaped pseudo-class name in %s is parsed like the plain name', (selector, type_name) => { + const pseudo = parse_selector(selector).first_child! + expect(pseudo.first_child!.type_name).toBe(type_name) +}) + +test('escaped function names in values', () => { + expect(parse_value('\\75 rl(a.png)').first_child!.type_name).toBe('Url') + expect(parse_value('\\76 ar(--a)').first_child!.first_child!.type_name).toBe('Identifier') +}) + +test('escaped !important is flagged', () => { + const rule = parse('a{color:red !\\69 mportant}').first_child as Rule + const decl = rule.block!.first_child as Declaration + expect(decl.is_important).toBe(true) +}) diff --git a/src/parse-selector.ts b/src/parse-selector.ts index 88bc9b9..6080b27 100644 --- a/src/parse-selector.ts +++ b/src/parse-selector.ts @@ -46,6 +46,7 @@ import { import { is_whitespace, str_equals_range, + css_unescape, CHAR_PLUS, CHAR_TILDE, CHAR_GREATER_THAN, @@ -824,7 +825,9 @@ export class SelectorParser { func_column + content_start - func_name_start, ) } else if ( - SELECTOR_PSEUDOS.has(this.source.substring(func_name_start, func_name_end).toLowerCase()) + SELECTOR_PSEUDOS.has( + css_unescape(this.source.substring(func_name_start, func_name_end)).toLowerCase(), + ) ) { // Parse as selector (for :is(), :where(), :has(), etc.) // Save current lexer state and selector_end diff --git a/src/parse.ts b/src/parse.ts index 1e59790..f1ba6e6 100644 --- a/src/parse.ts +++ b/src/parse.ts @@ -45,6 +45,7 @@ import { CHAR_TILDE, CHAR_AMPERSAND, CHAR_LEFT_BRACE, + css_unescape, } from './string-utils' export interface ParserOptions { @@ -584,7 +585,7 @@ export class Parser { // Determine if an at-rule contains declarations or nested rules private atrule_has_declarations(name: string): boolean { - return DECLARATION_AT_RULES.has(name.toLowerCase()) + return DECLARATION_AT_RULES.has(css_unescape(name).toLowerCase()) } } diff --git a/src/string-helpers.ts b/src/string-helpers.ts index ebea2ad..ed91f92 100644 --- a/src/string-helpers.ts +++ b/src/string-helpers.ts @@ -9,4 +9,5 @@ export { str_equals, str_starts_with, str_index_of, + css_unescape, } from './string-utils' diff --git a/src/string-utils.ts b/src/string-utils.ts index dcbb0f2..3404e17 100644 --- a/src/string-utils.ts +++ b/src/string-utils.ts @@ -1,3 +1,5 @@ +import { is_hex_digit } from './char-types' + // String utility functions for CSS parsing // Character constants (exported for use in parsers) @@ -49,30 +51,125 @@ export function is_digit(ch: number): boolean { return ch >= 0x30 && ch <= 0x39 // 0-9 } -/** Case-insensitive ASCII equality without allocations. `a` MUST be lowercase. */ -export function str_equals(a: string, b: string): boolean { - if (a.length !== b.length) { - return false +/** True if `source[start, end)` contains a backslash. */ +function has_backslash(source: string, start: number, end: number): boolean { + for (let i = start; i < end; i++) { + if (source.charCodeAt(i) === CHAR_BACKSLASH) return true } + return false +} - for (let i = 0; i < a.length; i++) { - const ca = a.charCodeAt(i) - let cb = b.charCodeAt(i) +/** + * Read one CSS escape starting at the backslash at `source[i]`, within `[i, end)`. + * Returns the decoded code point, or -1 for a backslash that isn't a valid escape (at the end or + * before a newline). The index after the escape is left in `escape_next`, which avoids allocating a result. + */ +let escape_next = 0 +function read_escape(source: string, i: number, end: number): number { + const next = i + 1 + if (next >= end) { + escape_next = next + return -1 + } + const ch = source.charCodeAt(next) + if (ch === CHAR_NEWLINE || ch === CHAR_CARRIAGE_RETURN || ch === CHAR_FORM_FEED) { + escape_next = next + return -1 + } + if (!is_hex_digit(ch)) { + escape_next = next + 1 + return ch + } + let cp = 0 + let pos = next + for (let n = 0; n < 6 && pos < end; n++) { + const h = source.charCodeAt(pos) + if (!is_hex_digit(h)) break + cp = cp * 16 + (h <= 0x39 ? h - 0x30 : (h | 32) - 0x61 + 10) + pos++ + } + // A single whitespace after a hex escape belongs to the escape (CRLF counts as one) + if (pos < end) { + const ws = source.charCodeAt(pos) + if (ws === CHAR_CARRIAGE_RETURN && source.charCodeAt(pos + 1) === CHAR_NEWLINE) { + pos += 2 + } else if (is_whitespace(ws)) { + pos++ + } + } + escape_next = pos + // Per CSS Syntax: NULL, surrogates and out-of-range code points become U+FFFD + if (cp === 0 || (cp >= 0xd800 && cp <= 0xdfff) || cp > 0x10ffff) return 0xfffd + return cp +} - // normalize ASCII uppercase A-Z → a-z - cb |= 32 +/** + * Decode CSS escapes (`\31 23` -> `123`, `\:` -> `:`), per CSS Syntax "consume an escaped code point". + * A backslash followed by a newline or at the end of the input is not an escape and is kept as is. + * Returns the input unchanged (no allocation) when it has no backslash. + */ +export function css_unescape(text: string): string { + if (!has_backslash(text, 0, text.length)) return text + let result = '' + let i = 0 + const end = text.length + while (i < end) { + const ch = text.charCodeAt(i) + if (ch !== CHAR_BACKSLASH) { + result += text[i] + i++ + continue + } + const cp = read_escape(text, i, end) + if (cp === -1) { + result += '\\' + i++ + } else { + result += String.fromCodePoint(cp) + i = escape_next + } + } + return result +} - if (ca !== cb) { - return false +/** + * Case-insensitive equality between the decoded `source[start, end)` (escapes resolved) and `literal`, + * without allocating. `literal` MUST be lowercase ASCII. + */ +function escaped_equals(source: string, start: number, end: number, literal: string): boolean { + let j = 0 + let i = start + while (i < end) { + if (j >= literal.length) return false + let cp = source.charCodeAt(i) + if (cp === CHAR_BACKSLASH) { + cp = read_escape(source, i, end) + i = cp === -1 ? i + 1 : escape_next + if (cp === -1) cp = CHAR_BACKSLASH + } else { + i++ } + // normalize ASCII uppercase A-Z -> a-z + if (cp < 128) cp |= 32 + if (cp !== literal.charCodeAt(j)) return false + j++ } + return j === literal.length +} - return true +/** + * Case-insensitive ASCII equality without allocations. `a` MUST be lowercase. + * Escapes in `b` are decoded: `str_equals('media', '\\6dedia')` is true. + */ +export function str_equals(a: string, b: string): boolean { + return str_equals_range(b, 0, b.length, a) } /** * Case-insensitive equality between `source[start, end)` and `literal`, without allocating a substring first. * Same semantics as `str_equals(literal, source.substring(start, end))`. `literal` MUST be lowercase. + * Escapes in the source are decoded (`\6dedia` equals `media`); an escape is always longer than the + * character it encodes, so only a longer source can be an escaped match. */ export function str_equals_range( source: string, @@ -80,10 +177,15 @@ export function str_equals_range( end: number, literal: string, ): boolean { - if (end - start !== literal.length) { + const length = end - start + if (length < literal.length) { return false } + if (length > literal.length) { + return has_backslash(source, start, end) && escaped_equals(source, start, end, literal) + } + for (let i = 0; i < literal.length; i++) { let ch = source.charCodeAt(start + i) // normalize ASCII uppercase A-Z → a-z