FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

JavaScript: recognize regex literals after `=>` and `...` by ekanshul · Pull Request #3266 · pygments/pygments · GitHub

JavaScript: recognize regex literals after => and ... - #3266

Open
ekanshul wants to merge 1 commit into
pygments:masterfrom
ekanshul:fix-js-regex-after-arrow
Open

JavaScript: recognize regex literals after => and ...#3266
ekanshul wants to merge 1 commit into
pygments:masterfrom
ekanshul:fix-js-regex-after-arrow

Conversation

Copy link
Copy Markdown

The JavaScript root state matched => and ... as punctuation without entering the slashstartsregex state, so a regex literal right after an arrow (a very common shape, e.g. const isUrl = s => /^https?:\/\//.test(s)) was lexed as two division operators, and every backslash inside it became an Error token. The same happens after a spread.

Both tokens are always followed by an expression, so a slash after them can only start a regular expression literal. This change makes both rules push slashstartsregex, like the other operators do. It applies to all lexers derived from JavascriptLexer (TypeScript, JSX, TSX, ...).

Found by lexing real-world code (gitea's web_src) and looking for Error tokens; for example gitea/web_src/js/utils/url.ts:

export const urlRawRegex = () => /\bhttps?:\/\/[^\s<>[\]]+/gi;

A snippet test is added covering an arrow with a block-less body, an arrow followed by a method call on the regex, and a spread.

The root state matched `=>` and `...` as punctuation without entering
the slashstartsregex state, so `x => /re/` lexed the regex as two
division operators and emitted Error tokens for any backslash inside
it. Both tokens are always followed by an expression, so a slash after
them starts a regular expression literal.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

Copy link
Copy Markdown
Author

Data point: with this change, lexing all 4,346 .ts files of gitea's web_src plus a Next.js monorepo produces zero Error tokens (the TypeScript lexer inherits the rule). Before, a single .filter((line) => /^[a-z0-9]+: '/.test(line)) desynchronized the lexer for the remaining ~800 lines of the file because the regex was read as division and the ' inside it opened a string.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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


Back | FazBrowse Home | New Git URL