Skip to content

fix(generator): escape leading caret in non-negative character class#280

Open
greymoth-jp wants to merge 1 commit into
DmitrySoshnikov:masterfrom
greymoth-jp:fix-leading-caret-char-class
Open

fix(generator): escape leading caret in non-negative character class#280
greymoth-jp wants to merge 1 commit into
DmitrySoshnikov:masterfrom
greymoth-jp:fix-leading-caret-char-class

Conversation

@greymoth-jp

Copy link
Copy Markdown

regexp-tree.optimize('/[a^]/') returns /[^a]/, which inverts the regex: [a^] matches a or ^, while [^a] matches everything except a.

The optimizer's charClassClassrangesMerge sorts character-class members by code point, and ^ (U+005E) sorts before a (U+0061), so the class is reordered to put ^ first. The generator's CharacterClass handler emits the members verbatim, so the reordered class is written as [^a], and a leading ^ in a class is parsed back as negation.

It is more visible when the reordered class is short enough for the optimizer to keep:

optimize('/[a^bcdef]/')   was  /[^a-f]/   (negated, wrong)
                          now  /[\^a-f]/

The same path is reachable through the public generate() API: building or transforming an AST so that a non-negative class starts with a literal ^ produces an inverted regex today.

The fix is in the generator: when a character class is not negative and its first member is an unescaped literal ^, escape it. [a^] then round-trips correctly, and optimize('/[a^]/') returns /[a^]/ again. Genuine negative classes and an already-escaped [\^a] are unaffected.

Tests added for the generator and for the char-class-classranges-merge transform. The full src suite passes.

A non-negative character class whose first element is a literal `^`
was generated as a bare `[^...]`, which parses back as a negated class.
This surfaces through the optimizer: charClassClassrangesMerge sorts class
members by code point, so `/[a^]/` becomes `/[^a]/` (`^` is U+005E, before
`a`), inverting the regex. Calling generate() on a hand-built or otherwise
reordered AST hits the same path.

Escape a leading literal `^` when the class is not negative.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant