diff --git a/src/__tests__/exceptions.mjs b/src/__tests__/exceptions.mjs index 5555900..f4b839a 100644 --- a/src/__tests__/exceptions.mjs +++ b/src/__tests__/exceptions.mjs @@ -93,3 +93,17 @@ throws( ".foo !optional", "Unexpected '!'. Escaping special characters with \\ may help.", ); + +// Content between an attribute operator and a quoted value used to be +// silently dropped: `[class=XXX'@{foo}-']` parsed as `[class='@{foo}-']` +// and `[class=~'@{foo}-']` parsed as `[class='@{foo}-']`. +throws( + "unquoted value before a quoted value", + "[class=XXX'@{foo}-']", + "Unexpected string found; an attribute value was already defined.", +); +throws( + "bare tilde before a quoted value", + "[class=~'@{foo}-']", + 'Unexpected "~" found; an operator was already defined.', +); diff --git a/src/parser.js b/src/parser.js index badab9f..7eb118d 100644 --- a/src/parser.js +++ b/src/parser.js @@ -359,6 +359,17 @@ export default class Parser { ) { return this.expected("attribute operator", token[TOKEN.START_POS]); } + if ( + node.operator && + content === "~" && + !(next && next[TOKEN.TYPE] === tokens.equals) + ) { + // A bare `~` after the operator, such as in `[class=~'x']`, + // cannot form an operator and must not be silently dropped. + return this.error('Unexpected "~" found; an operator was already defined.', { + index: token[TOKEN.START_POS], + }); + } if (content === "~" && next && next[TOKEN.TYPE] === tokens.equals) { node.operator = content; lastAdded = "operator"; @@ -470,6 +481,14 @@ export default class Parser { }, ); } + if (node.value !== undefined) { + // A quoted value must not silently overwrite an unquoted value + // that was already read, such as the `XXX` in + // `[class=XXX'@{foo}-']`. + return this.error('Unexpected string found; an attribute value was already defined.', { + index: token[TOKEN.START_POS], + }); + } let { unescaped, quoteMark } = unescapeValue(content); node.value = unescaped; node.quoteMark = quoteMark;