Skip to content

Commit

Permalink
Split invalid name check for Onig and JS
Browse files Browse the repository at this point in the history
slevithan committed Oct 25, 2024
1 parent d7b9021 commit 102d52e
Showing 4 changed files with 28 additions and 23 deletions.
2 changes: 1 addition & 1 deletion demo/styles.css
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@
margin: 0;
}

html, body, #content {height: 100%}
html, body {height: 100%}

body {
font-family: Calibri, "Helvetica Neue", sans-serif;
28 changes: 14 additions & 14 deletions dist/index.min.js

Large diffs are not rendered by default.

12 changes: 4 additions & 8 deletions src/parse.js
Original file line number Diff line number Diff line change
@@ -467,9 +467,8 @@ function createByGroupKind(token) {

function createCapturingGroup(number, name) {
const hasName = name !== undefined;
if (hasName && !isValidJsGroupName(name)) {
// TODO: Move error to the transformer?
throw new Error(`Group name "${name}" is invalid in JS`);
if (hasName && !isValidGroupNameOniguruma(name)) {
throw new Error(`Group name "${name}" invalid in Oniguruma`);
}
return {
type: AstTypes.CapturingGroup,
@@ -662,11 +661,8 @@ function getOptimizedGroup(node) {
return node;
}

function isValidJsGroupName(name) {
// Oniguruma group name rules are much more permissive than JS, with invalid names seemingly only
// being those matched by `/^(?:[-\d]|$)/`. All of these are also invalid by JS rules
// See <developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers>
return /^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(name);
function isValidGroupNameOniguruma(name) {
return !/^(?:[-\d]|$)/.test(name);
}

// For any intersection classes that contain only a class, swap the parent with its (modded) child
9 changes: 9 additions & 0 deletions src/transform.js
Original file line number Diff line number Diff line change
@@ -127,6 +127,9 @@ const FirstPassVisitor = {

CapturingGroup({node}, {subroutineRefMap}) {
const {name, number} = node;
if (name && !isValidGroupNameJs(name)) {
throw new Error(`Group name "${name}" invalid in JS`);
}
subroutineRefMap.set(name ?? number, node);
},

@@ -587,6 +590,12 @@ function getParentAlternative(node) {
return null;
}

function isValidGroupNameJs(name) {
// JS group names are more restrictive than Oniguruma; see
// <developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers>
return /^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(name);
}

// Returns a single node, either the given node or all nodes wrapped in a noncapturing group
// TODO: Consider moving to `parse` module and dropping assumptions about `parent` props
function parseFragment(pattern, {bypassPropertyNameCheck} = {}) {

0 comments on commit 102d52e

Please sign in to comment.