regex-explain 0.0.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +275 -1
- package/dist/cjs/compiler.d.ts +34 -0
- package/dist/cjs/compiler.js +160 -0
- package/dist/cjs/explainer.d.ts +123 -0
- package/dist/cjs/explainer.js +628 -0
- package/dist/cjs/extlinks.d.ts +21 -0
- package/dist/cjs/extlinks.js +25 -0
- package/dist/cjs/index.d.ts +22 -0
- package/dist/cjs/index.js +22 -0
- package/dist/cjs/locator.d.ts +80 -0
- package/dist/cjs/locator.js +341 -0
- package/dist/cjs/matches.d.ts +133 -0
- package/dist/cjs/matches.js +238 -0
- package/dist/cjs/render.d.ts +120 -0
- package/dist/cjs/render.js +238 -0
- package/dist/cjs/strings.d.ts +39 -0
- package/dist/cjs/strings.js +85 -0
- package/dist/cjs/text.d.ts +49 -0
- package/dist/cjs/text.js +109 -0
- package/dist/esm/index.mjs +1207 -0
- package/package.json +62 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,277 @@
|
|
|
1
1
|
# regex-explain
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Explains ECMAScript regular expressions in plain English, as a tree of steps that follows the
|
|
4
|
+
pattern's structure. It also reports how long a match can be and warns about catastrophic
|
|
5
|
+
backtracking (ReDoS), suggesting an equivalent safe pattern when one exists. It can also find the
|
|
6
|
+
regexes in source code in several languages, and run a regex over text to list its matches by line.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install regex-explain
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The package ships CommonJS and ES module builds with TypeScript types, and needs Node.js 18 or
|
|
13
|
+
later. Finding regexes in source code also needs the optional peer dependency
|
|
14
|
+
[`@vscode/tree-sitter-wasm`](https://www.npmjs.com/package/@vscode/tree-sitter-wasm):
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npm install @vscode/tree-sitter-wasm
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { ExplanationRenderer, explainRegex } from "regex-explain";
|
|
24
|
+
|
|
25
|
+
const result = explainRegex("^\\d{3}-\\d{4}$");
|
|
26
|
+
console.log(new ExplanationRenderer(result).text());
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```text
|
|
30
|
+
^ Assert position is at the start of the input
|
|
31
|
+
\d{3} Match a digit (0-9), exactly 3 times
|
|
32
|
+
- Match the character "-"
|
|
33
|
+
\d{4} Match a digit (0-9), exactly 4 times
|
|
34
|
+
$ Assert position is at the end of the input
|
|
35
|
+
|
|
36
|
+
Matches exactly 8 characters.
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`markdownTable()` renders the same result as Markdown:
|
|
40
|
+
|
|
41
|
+
<!-- prettier-ignore -->
|
|
42
|
+
```md
|
|
43
|
+
| Code Point | Explanation |
|
|
44
|
+
| ---------- | ----------- |
|
|
45
|
+
| `^` | Assert position is at the start of the input |
|
|
46
|
+
| `\d{3}` | Match a digit (0-9), exactly 3 times |
|
|
47
|
+
| `-` | Match the character `-` |
|
|
48
|
+
| `\d{4}` | Match a digit (0-9), exactly 4 times |
|
|
49
|
+
| `$` | Assert position is at the end of the input |
|
|
50
|
+
|
|
51
|
+
*Matches exactly 8 characters.*
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Use `model()` or walk `result.nodes` to build your own output. Each node carries the source it
|
|
55
|
+
explains and its offsets in the pattern, so you can highlight it:
|
|
56
|
+
|
|
57
|
+
```json
|
|
58
|
+
{
|
|
59
|
+
"raw": "\\d{3}",
|
|
60
|
+
"start": 1,
|
|
61
|
+
"end": 6,
|
|
62
|
+
"description": "Match a digit (0-9), exactly 3 times",
|
|
63
|
+
"children": []
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## API
|
|
68
|
+
|
|
69
|
+
### `explainRegex(pattern, flags?, options?)`
|
|
70
|
+
|
|
71
|
+
Explains `pattern` (without slashes, as passed to `new RegExp()`) compiled with `flags`. Returns an
|
|
72
|
+
`ExplainResult`; it does not throw for invalid patterns.
|
|
73
|
+
|
|
74
|
+
- `ExplainOptions`: `{ checkBacktracking?: boolean }`. The backtracking check is on by default.
|
|
75
|
+
- `ExplainResult`: either a `RegexExplanation` (`ok: true`) or a `RegexExplanationError`
|
|
76
|
+
(`ok: false`, with `message` and, when known, the `index` of the error in the pattern).
|
|
77
|
+
- `RegexExplanation` has:
|
|
78
|
+
- `nodes`: the top-level `ExplanationNode` steps. Each node has `raw`, `start`, `end`,
|
|
79
|
+
`description`, and `children`. Descriptions may contain Markdown code spans.
|
|
80
|
+
- `flagExplanations`: one `FlagExplanation` (`flag`, `name`, `description`) per flag.
|
|
81
|
+
- `length`: a `LengthSummary` with the `min` and `max` characters a match consumes. `max` is
|
|
82
|
+
`Infinity` when unbounded.
|
|
83
|
+
- `warnings`: `BacktrackingWarning` entries with the quantifier's `raw`, `start`, and `end`,
|
|
84
|
+
whether the backtracking is `exponential`, an `attackCharacter` that triggers it when repeated,
|
|
85
|
+
a `description`, and a `fix` (`pattern` and `flags`) when an equivalent safe pattern exists.
|
|
86
|
+
- `multiline`: whether `^` and `$` match at line breaks anywhere in the pattern, through the `m`
|
|
87
|
+
flag or a group such as `(?m:...)`. `explainRegex("(?m:^a)").multiline` is `true`.
|
|
88
|
+
|
|
89
|
+
### `parseRegexInput(text)` and `isRegexSource(value)`
|
|
90
|
+
|
|
91
|
+
`parseRegexInput` reads text a user typed or selected as a `RegexSource` (`{ pattern, flags }`, as
|
|
92
|
+
`new RegExp()` takes them): a literal such as `/ab+c/gi`, optionally surrounded by whitespace, is
|
|
93
|
+
split into its pattern and flags, and anything else is a bare pattern with no flags.
|
|
94
|
+
`parseRegexInput("/ab+c/gi")` returns `{ pattern: "ab+c", flags: "gi" }` and
|
|
95
|
+
`parseRegexInput("ab+c")` returns `{ pattern: "ab+c", flags: "" }`. It does not validate the
|
|
96
|
+
pattern. Results, located regexes, and match requests all extend `RegexSource`. `isRegexSource` is a
|
|
97
|
+
type guard that tells whether an untyped value, such as a command argument, has string `pattern` and
|
|
98
|
+
`flags` properties.
|
|
99
|
+
|
|
100
|
+
### `ExplanationRenderer`
|
|
101
|
+
|
|
102
|
+
`new ExplanationRenderer(result)` renders an `ExplainResult` in several formats:
|
|
103
|
+
|
|
104
|
+
- `markdownList(options?)`: a nested Markdown list, as in hovers.
|
|
105
|
+
- `markdownTable(options?)`: a Markdown table with Code Point and Explanation columns. Nested steps
|
|
106
|
+
are indented with ` `.
|
|
107
|
+
- `text(options?)`: aligned plain text, with code spans shown in double quotes.
|
|
108
|
+
- `model()`: everything a view shows, as an `ExplanationModel`, which the other formats render from:
|
|
109
|
+
the regex as a `literal` (`/pattern/flags`), the `error` (`ErrorModel`: `message`, `pattern`,
|
|
110
|
+
`index`, and a `caret` line such as `" ^"` to print under the pattern) for an invalid pattern,
|
|
111
|
+
`warnings` (`WarningModel`: the `fix` as a literal), the steps as `rows` (`ExplanationRow`: `raw`
|
|
112
|
+
and nesting `depth`), the `length` sentence such as "Matches 2 to 4 characters.", `flags`
|
|
113
|
+
(`FlagModel`: `flag` and `name`), and whether the pattern is `multiline`. Each warning, row, and
|
|
114
|
+
flag has a `description`, which may contain Markdown code spans, and the same text as `parts`:
|
|
115
|
+
`TextPart`s with the `text` and whether it is `code`, so that HTML or other UIs render it without
|
|
116
|
+
a Markdown parser. For an invalid pattern, the model has only the `literal` and `error`; its lists
|
|
117
|
+
are empty.
|
|
118
|
+
|
|
119
|
+
The Markdown and text formats put warnings first, then the steps, the match length, and the flags.
|
|
120
|
+
Invalid patterns render the error with a caret under its position. `RenderOptions`:
|
|
121
|
+
`{ title?: boolean }` starts the output with the whole regex (under a heading in Markdown).
|
|
122
|
+
|
|
123
|
+
### `describeCount(min, max)`
|
|
124
|
+
|
|
125
|
+
Words a repetition count ("one or more times"), for callers that build their own output.
|
|
126
|
+
|
|
127
|
+
### `RegexFinder` and `findRegexAt(regexes, offset)`
|
|
128
|
+
|
|
129
|
+
`new RegexFinder(wasmDir)` finds regexes in source code with tree-sitter: regex literals, and string
|
|
130
|
+
literals passed to regex APIs such as `new RegExp()`, Python's `re.compile()`, or Java's
|
|
131
|
+
`Pattern.compile()`. `wasmDir` is a directory or URL holding `tree-sitter.wasm` and the grammar
|
|
132
|
+
files; in Node, pass the `wasm` directory of `@vscode/tree-sitter-wasm`. The runtime and each
|
|
133
|
+
grammar load on first use. `find` returns no regexes for a source longer than 1,000,000 characters,
|
|
134
|
+
since parsing generated or minified files on every change is slow.
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import { createRequire } from "module";
|
|
138
|
+
import * as path from "path";
|
|
139
|
+
import { RegexFinder, findRegexAt } from "regex-explain";
|
|
140
|
+
|
|
141
|
+
const require = createRequire(import.meta.url);
|
|
142
|
+
const finder = new RegexFinder(path.dirname(require.resolve("@vscode/tree-sitter-wasm")));
|
|
143
|
+
const source = 'import re\nDATE = re.compile(r"(\\d{4})-(\\d{2})")\n';
|
|
144
|
+
const regexes = await finder.find(source, "python"); // in an ES module
|
|
145
|
+
// [ { pattern: '(\\d{4})-(\\d{2})', flags: '', start: 28, end: 46 } ]
|
|
146
|
+
findRegexAt(regexes, 30); // the same regex, which covers offset 30
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
- `find(source, languageId)` resolves to `LocatedRegex`es (`pattern`, `flags`, `start`, and `end`
|
|
150
|
+
offsets in UTF-16 code units), in order. String escapes are decoded, so `"\\d"` in source becomes
|
|
151
|
+
`\d`, and flags are translated to JavaScript, such as Ruby's `m` to `s`. Strings built at run
|
|
152
|
+
time, such as interpolations, are skipped. Unsupported languages give `[]`.
|
|
153
|
+
- `supports(languageId)` tells whether a language is supported.
|
|
154
|
+
- `SUPPORTED_LANGUAGE_IDS` lists the language IDs, which are VS Code's: `javascript`,
|
|
155
|
+
`javascriptreact`, `typescript`, `typescriptreact`, `vue`, `svelte` (both inside `<script>` blocks
|
|
156
|
+
only), `python`, `go`, `rust`, `java`, `csharp`, `ruby`, and `php`. The
|
|
157
|
+
[extension README](https://github.com/awalsh128/vscode-regex-explain/tree/main/packages/vscode-regex-explain#readme)
|
|
158
|
+
lists the calls recognized in each.
|
|
159
|
+
- `GRAMMARS` lists the grammar names, for copying `tree-sitter-<grammar>.wasm` files when bundling.
|
|
160
|
+
|
|
161
|
+
### `findMatches(request)`
|
|
162
|
+
|
|
163
|
+
Runs a `MatchRequest` (`pattern`, `flags`, `text`, a match `limit`, and optionally `entries`) with
|
|
164
|
+
JavaScript's `RegExp`, adding `g` if missing. It returns a `MatchResponse`: the `matches`, whether
|
|
165
|
+
they were `truncated` at the limit, and an `error` if the pattern does not compile. `findMatches`
|
|
166
|
+
never sets `timedOut`; it is there for callers that stop matching from outside, such as a worker
|
|
167
|
+
with a time limit. Each `FoundMatch` has `start` and `end` offsets, the matched `text`, the 1-based
|
|
168
|
+
`startLine` and `endLine`, the numbered `groups`, and the `named` groups.
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
findMatches({
|
|
172
|
+
pattern: "(\\d{4})-(\\d{2})",
|
|
173
|
+
flags: "",
|
|
174
|
+
text: "due 2024-05\nor 2025-01",
|
|
175
|
+
limit: 100,
|
|
176
|
+
});
|
|
177
|
+
// matches[0]: { start: 4, end: 11, text: "2024-05", startLine: 1, endLine: 1,
|
|
178
|
+
// groups: ["2024", "05"], named: {} }
|
|
179
|
+
// matches[1]: { start: 15, end: 22, text: "2025-01", startLine: 2, endLine: 2, ... }
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
With `entries: true`, each line is a separate entry, matched on its own: `^` and `$` match at its
|
|
183
|
+
ends and no match spans lines. A line break at the end of the text does not start another entry. The
|
|
184
|
+
response then also has the `entries` (`MatchEntry`: the 1-based `line`, its `start` and `end`
|
|
185
|
+
offsets without the line break, and its `text`). Match offsets and lines are still in the whole
|
|
186
|
+
text. When matching stops at the limit, entries after the one holding the last match are left out.
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
findMatches({
|
|
190
|
+
pattern: "^\\d{4}-\\d{2}$",
|
|
191
|
+
flags: "",
|
|
192
|
+
text: "2024-05\nsoon\n2025-01",
|
|
193
|
+
limit: 100,
|
|
194
|
+
entries: true,
|
|
195
|
+
});
|
|
196
|
+
// matches: "2024-05" (start 0, startLine 1) and "2025-01" (start 13, startLine 3)
|
|
197
|
+
// entries: [ { line: 1, start: 0, end: 7, text: "2024-05" },
|
|
198
|
+
// { line: 2, start: 8, end: 12, text: "soon" },
|
|
199
|
+
// { line: 3, start: 13, end: 20, text: "2025-01" } ]
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
A pattern that backtracks catastrophically can run for a very long time; run untrusted patterns
|
|
203
|
+
where they can be stopped, such as a worker thread.
|
|
204
|
+
|
|
205
|
+
### `describeMatches(response)`
|
|
206
|
+
|
|
207
|
+
Words a `MatchResponse` for display, returning a `MatchesModel`: a one-sentence `summary` such as "2
|
|
208
|
+
matches." or why the regex could not run, whether it reports a `problem` (an `error` or `timedOut`),
|
|
209
|
+
and the `matches` (`MatchModel`). Each has the `start` and `end` offsets, `lines` such as `L1` or
|
|
210
|
+
`L1–2`, the `text` ("(empty)" for an empty match), and `groups` (`MatchGroupModel`: the `name`,
|
|
211
|
+
which is `$1`, `$2`, and so on or the group's name, the `value` ("(no match)" if the group did not
|
|
212
|
+
take part), and whether it `matched`).
|
|
213
|
+
|
|
214
|
+
For a response with `entries`, the summary counts entries instead, such as "2 of 3 entries match."
|
|
215
|
+
or "No entries.", and the model also has the `entries` (`EntryModel`: the `line` such as `L2`, its
|
|
216
|
+
`start` and `end`, its `text` ("(empty)" for an empty line), whether it `matched`, and its
|
|
217
|
+
`matches`). For the entries example above, they are `L1` "2024-05" (matched, 1 match), `L2` "soon"
|
|
218
|
+
(not matched), and `L3` "2025-01" (matched, 1 match).
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
const model = describeMatches(
|
|
222
|
+
findMatches({
|
|
223
|
+
pattern: "(?<year>\\d{4})-(\\d{2})",
|
|
224
|
+
flags: "",
|
|
225
|
+
text: "due 2024-05\nor 2025-01",
|
|
226
|
+
limit: 100,
|
|
227
|
+
})
|
|
228
|
+
);
|
|
229
|
+
// model.summary: "2 matches." model.problem: false model.matches[1].lines: "L2"
|
|
230
|
+
// model.matches[0]: { start: 4, end: 11, lines: "L1", text: "2024-05",
|
|
231
|
+
// groups: [ { name: "$1", value: "2024", matched: true },
|
|
232
|
+
// { name: "$2", value: "05", matched: true },
|
|
233
|
+
// { name: "year", value: "2024", matched: true } ] }
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
### `regex101Url(source, testString?)`
|
|
237
|
+
|
|
238
|
+
Builds a [regex101](https://regex101.com) link that opens a `RegexSource` in the JavaScript flavor,
|
|
239
|
+
prefilled through the query string as the
|
|
240
|
+
[regex101 FAQ](https://github.com/firasdib/Regex101/wiki/FAQ#how-to-prefill-the-fields-on-the-interface-via-url)
|
|
241
|
+
describes. Values are percent-encoded, and the test string is left out when empty.
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
regex101Url({ pattern: "a+b", flags: "gi" });
|
|
245
|
+
// "https://regex101.com/?regex=a%2Bb&flags=gi&flavor=javascript"
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### Migrating from `renderMarkdown` and `renderText`
|
|
249
|
+
|
|
250
|
+
`renderMarkdown(result, options)`, `renderText(result, options)`, and `describeLength(result)` were
|
|
251
|
+
replaced by `new ExplanationRenderer(result).markdownList(options)`, `.text(options)`, and
|
|
252
|
+
`.model().length`.
|
|
253
|
+
|
|
254
|
+
## Semantics and limitations
|
|
255
|
+
|
|
256
|
+
Patterns follow **JavaScript** semantics up to ES2025: named and duplicate named groups, lookbehind,
|
|
257
|
+
Unicode property escapes, the `v` flag's set operations and `\q{...}`, and inline modifiers such as
|
|
258
|
+
`(?i:...)`. Constructs specific to other engines are reported as syntax errors.
|
|
259
|
+
|
|
260
|
+
The backtracking check omits patterns that are slow only because the engine retries them at every
|
|
261
|
+
input position (for example `/a+b/`); those are too common to be useful as warnings. Fixes are not
|
|
262
|
+
offered when a rewrite would change what a capture group holds.
|
|
263
|
+
|
|
264
|
+
## How it works
|
|
265
|
+
|
|
266
|
+
Parsing uses [`@eslint-community/regexpp`](https://github.com/eslint-community/regexpp), the parser
|
|
267
|
+
behind ESLint's regex rules. Character sets, case folding, and match lengths come from
|
|
268
|
+
[`regexp-ast-analysis`](https://github.com/RunDevelopment/regexp-ast-analysis), and backtracking
|
|
269
|
+
analysis from [`scslre`](https://github.com/RunDevelopment/scslre), the libraries used by
|
|
270
|
+
[`eslint-plugin-regexp`](https://github.com/ota-meshi/eslint-plugin-regexp). This package walks the
|
|
271
|
+
parsed tree and words the results. Finding regexes in source code uses tree-sitter grammars from
|
|
272
|
+
[`@vscode/tree-sitter-wasm`](https://github.com/microsoft/vscode-tree-sitter-wasm) with one query
|
|
273
|
+
per language.
|
|
274
|
+
|
|
275
|
+
## License
|
|
276
|
+
|
|
277
|
+
Apache-2.0
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where regexes appear in each supported language, as tree-sitter queries over the grammars in
|
|
3
|
+
* `@vscode/tree-sitter-wasm`. Adding a language means adding an entry here; the locator and the
|
|
4
|
+
* bundle script read this table.
|
|
5
|
+
*
|
|
6
|
+
* Capture names tell the locator how to read a match:
|
|
7
|
+
*
|
|
8
|
+
* - `@regex`: the whole regex expression. The hover covers it; without it, the hover covers the
|
|
9
|
+
* pattern capture.
|
|
10
|
+
* - `@pattern` and `@flags`: nodes whose source text is the pattern or flags as written.
|
|
11
|
+
* - `@literal`: a regex literal whose first and last children are its delimiters, with the flags
|
|
12
|
+
* after the closing delimiter, such as Ruby's `/a+/i` or `%r{a+}i`.
|
|
13
|
+
* - `@pattern.string` and `@flags.string`: string literals whose values are the pattern or flags.
|
|
14
|
+
* - `@pattern.delimited`: a string literal whose value is a delimited pattern such as `/a+/i`.
|
|
15
|
+
*
|
|
16
|
+
* Captures starting with `_` exist only for predicates.
|
|
17
|
+
*/
|
|
18
|
+
/** How to find regexes in one language. */
|
|
19
|
+
export interface LanguageSpec {
|
|
20
|
+
/** The grammar, loaded from `tree-sitter-<grammar>.wasm`. */
|
|
21
|
+
readonly grammar: string;
|
|
22
|
+
/** A tree-sitter query using the capture names described in this module. */
|
|
23
|
+
readonly query: string;
|
|
24
|
+
/** Flags that mean something else in JavaScript, for `translateFlags`. */
|
|
25
|
+
readonly flags?: Readonly<Record<string, string>>;
|
|
26
|
+
/** Parse only the `<script>` blocks, for single-file component formats. */
|
|
27
|
+
readonly scriptBlocks?: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** Supported languages, keyed by VS Code language ID. */
|
|
30
|
+
export declare const LANGUAGES: Readonly<Record<string, LanguageSpec>>;
|
|
31
|
+
/** VS Code language IDs that have a {@link LanguageSpec}, in table order. */
|
|
32
|
+
export declare const SUPPORTED_LANGUAGE_IDS: readonly string[];
|
|
33
|
+
/** Grammar names used by {@link LANGUAGES}, each once. */
|
|
34
|
+
export declare const GRAMMARS: readonly string[];
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Where regexes appear in each supported language, as tree-sitter queries over the grammars in
|
|
4
|
+
* `@vscode/tree-sitter-wasm`. Adding a language means adding an entry here; the locator and the
|
|
5
|
+
* bundle script read this table.
|
|
6
|
+
*
|
|
7
|
+
* Capture names tell the locator how to read a match:
|
|
8
|
+
*
|
|
9
|
+
* - `@regex`: the whole regex expression. The hover covers it; without it, the hover covers the
|
|
10
|
+
* pattern capture.
|
|
11
|
+
* - `@pattern` and `@flags`: nodes whose source text is the pattern or flags as written.
|
|
12
|
+
* - `@literal`: a regex literal whose first and last children are its delimiters, with the flags
|
|
13
|
+
* after the closing delimiter, such as Ruby's `/a+/i` or `%r{a+}i`.
|
|
14
|
+
* - `@pattern.string` and `@flags.string`: string literals whose values are the pattern or flags.
|
|
15
|
+
* - `@pattern.delimited`: a string literal whose value is a delimited pattern such as `/a+/i`.
|
|
16
|
+
*
|
|
17
|
+
* Captures starting with `_` exist only for predicates.
|
|
18
|
+
*/
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.GRAMMARS = exports.SUPPORTED_LANGUAGE_IDS = exports.LANGUAGES = void 0;
|
|
21
|
+
/** JavaScript string literals, with or without template syntax. */
|
|
22
|
+
const JS_STRING = "[(string) (template_string)]";
|
|
23
|
+
/** Regex literals and `RegExp` constructor calls, shared by the JavaScript-family grammars. */
|
|
24
|
+
const JS_QUERY = `
|
|
25
|
+
(regex pattern: (regex_pattern) @pattern flags: (regex_flags)? @flags) @regex
|
|
26
|
+
(new_expression
|
|
27
|
+
constructor: (identifier) @_constructor
|
|
28
|
+
arguments: (arguments . ${JS_STRING} @pattern.string . ${JS_STRING}? @flags.string)
|
|
29
|
+
(#eq? @_constructor "RegExp"))
|
|
30
|
+
(call_expression
|
|
31
|
+
function: (identifier) @_constructor
|
|
32
|
+
arguments: (arguments . ${JS_STRING} @pattern.string . ${JS_STRING}? @flags.string)
|
|
33
|
+
(#eq? @_constructor "RegExp"))
|
|
34
|
+
`;
|
|
35
|
+
/** C# string literals that hold a pattern on one line. */
|
|
36
|
+
const CS_STRING = "[(string_literal) (verbatim_string_literal) (raw_string_literal)]";
|
|
37
|
+
/** Ruby flags: `m` is JavaScript's `s`; `o` and the encoding flags do not change what matches. */
|
|
38
|
+
const RUBY_FLAGS = { m: "s", o: "", n: "", e: "", s: "", u: "" };
|
|
39
|
+
/**
|
|
40
|
+
* PHP (PCRE) flags: `u` and `S` do not change what matches for patterns JavaScript can parse.
|
|
41
|
+
* Others, such as `x`, are kept so that the explainer reports them.
|
|
42
|
+
*/
|
|
43
|
+
const PHP_FLAGS = { u: "", S: "" };
|
|
44
|
+
/** Supported languages, keyed by VS Code language ID. */
|
|
45
|
+
exports.LANGUAGES = {
|
|
46
|
+
javascript: { grammar: "javascript", query: JS_QUERY },
|
|
47
|
+
javascriptreact: { grammar: "javascript", query: JS_QUERY },
|
|
48
|
+
typescript: { grammar: "typescript", query: JS_QUERY },
|
|
49
|
+
typescriptreact: { grammar: "tsx", query: JS_QUERY },
|
|
50
|
+
vue: { grammar: "typescript", query: JS_QUERY, scriptBlocks: true },
|
|
51
|
+
svelte: { grammar: "typescript", query: JS_QUERY, scriptBlocks: true },
|
|
52
|
+
python: {
|
|
53
|
+
grammar: "python",
|
|
54
|
+
query: `
|
|
55
|
+
(call
|
|
56
|
+
function: (attribute object: (identifier) @_module attribute: (identifier) @_function)
|
|
57
|
+
arguments: (argument_list . (string) @pattern.string)
|
|
58
|
+
(#any-of? @_module "re" "regex")
|
|
59
|
+
(#any-of? @_function
|
|
60
|
+
"compile" "search" "match" "fullmatch" "split" "findall" "finditer" "sub" "subn"))
|
|
61
|
+
`,
|
|
62
|
+
},
|
|
63
|
+
go: {
|
|
64
|
+
grammar: "go",
|
|
65
|
+
query: `
|
|
66
|
+
(call_expression
|
|
67
|
+
function: (selector_expression operand: (identifier) @_package field: (field_identifier) @_function)
|
|
68
|
+
arguments: (argument_list
|
|
69
|
+
. [(raw_string_literal) (interpreted_string_literal)] @pattern.string)
|
|
70
|
+
(#eq? @_package "regexp")
|
|
71
|
+
(#any-of? @_function
|
|
72
|
+
"Compile" "CompilePOSIX" "MustCompile" "MustCompilePOSIX" "Match" "MatchReader" "MatchString"))
|
|
73
|
+
`,
|
|
74
|
+
},
|
|
75
|
+
rust: {
|
|
76
|
+
grammar: "rust",
|
|
77
|
+
query: `
|
|
78
|
+
(call_expression
|
|
79
|
+
function: (scoped_identifier path: (_) @_type name: (identifier) @_function)
|
|
80
|
+
arguments: (arguments . [(string_literal) (raw_string_literal)] @pattern.string)
|
|
81
|
+
(#match? @_type "(^|::)(Regex|RegexBuilder)$")
|
|
82
|
+
(#eq? @_function "new"))
|
|
83
|
+
`,
|
|
84
|
+
},
|
|
85
|
+
java: {
|
|
86
|
+
// Text blocks ("""...""") strip indentation, which the decoder does not model.
|
|
87
|
+
grammar: "java",
|
|
88
|
+
query: `
|
|
89
|
+
(method_invocation
|
|
90
|
+
object: (identifier) @_class
|
|
91
|
+
name: (identifier) @_method
|
|
92
|
+
arguments: (argument_list . (string_literal) @pattern.string)
|
|
93
|
+
(#eq? @_class "Pattern")
|
|
94
|
+
(#eq? @_method "compile")
|
|
95
|
+
(#not-match? @pattern.string "^\\"\\"\\""))
|
|
96
|
+
(method_invocation
|
|
97
|
+
name: (identifier) @_method
|
|
98
|
+
arguments: (argument_list . (string_literal) @pattern.string)
|
|
99
|
+
(#any-of? @_method "matches" "split")
|
|
100
|
+
(#not-match? @pattern.string "^\\"\\"\\""))
|
|
101
|
+
(method_invocation
|
|
102
|
+
name: (identifier) @_method
|
|
103
|
+
arguments: (argument_list . (string_literal) @pattern.string . (_))
|
|
104
|
+
(#any-of? @_method "replaceAll" "replaceFirst")
|
|
105
|
+
(#not-match? @pattern.string "^\\"\\"\\""))
|
|
106
|
+
`,
|
|
107
|
+
},
|
|
108
|
+
csharp: {
|
|
109
|
+
// Multi-line raw strings strip indentation, which the decoder does not model.
|
|
110
|
+
grammar: "c-sharp",
|
|
111
|
+
query: `
|
|
112
|
+
(object_creation_expression
|
|
113
|
+
type: (_) @_type
|
|
114
|
+
arguments: (argument_list . (argument ${CS_STRING} @pattern.string))
|
|
115
|
+
(#match? @_type "(^|\\\\.)Regex$")
|
|
116
|
+
(#not-match? @pattern.string "^\\"\\"\\"+\\\\s*\\n"))
|
|
117
|
+
(invocation_expression
|
|
118
|
+
function: (member_access_expression expression: (_) @_type name: (identifier) @_method)
|
|
119
|
+
arguments: (argument_list . (argument) . (argument ${CS_STRING} @pattern.string))
|
|
120
|
+
(#match? @_type "(^|\\\\.)Regex$")
|
|
121
|
+
(#any-of? @_method "Count" "EnumerateMatches" "IsMatch" "Match" "Matches" "Replace" "Split")
|
|
122
|
+
(#not-match? @pattern.string "^\\"\\"\\"+\\\\s*\\n"))
|
|
123
|
+
(attribute
|
|
124
|
+
name: (identifier) @_attribute
|
|
125
|
+
(attribute_argument_list . (attribute_argument ${CS_STRING} @pattern.string))
|
|
126
|
+
(#eq? @_attribute "GeneratedRegex")
|
|
127
|
+
(#not-match? @pattern.string "^\\"\\"\\"+\\\\s*\\n"))
|
|
128
|
+
`,
|
|
129
|
+
},
|
|
130
|
+
ruby: {
|
|
131
|
+
grammar: "ruby",
|
|
132
|
+
flags: RUBY_FLAGS,
|
|
133
|
+
query: `
|
|
134
|
+
(regex) @literal
|
|
135
|
+
(call
|
|
136
|
+
receiver: (constant) @_class
|
|
137
|
+
method: (identifier) @_method
|
|
138
|
+
arguments: (argument_list . (string) @pattern.string)
|
|
139
|
+
(#eq? @_class "Regexp")
|
|
140
|
+
(#any-of? @_method "new" "compile"))
|
|
141
|
+
`,
|
|
142
|
+
},
|
|
143
|
+
php: {
|
|
144
|
+
grammar: "php",
|
|
145
|
+
flags: PHP_FLAGS,
|
|
146
|
+
query: `
|
|
147
|
+
(function_call_expression
|
|
148
|
+
function: (name) @_function
|
|
149
|
+
arguments: (arguments . (argument [(string) (encapsed_string)] @pattern.delimited))
|
|
150
|
+
(#match? @_function "^preg_(filter|grep|match|match_all|replace|replace_callback|split)$"))
|
|
151
|
+
`,
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
/** VS Code language IDs that have a {@link LanguageSpec}, in table order. */
|
|
155
|
+
exports.SUPPORTED_LANGUAGE_IDS = Object.keys(exports.LANGUAGES);
|
|
156
|
+
/** Grammar names used by {@link LANGUAGES}, each once. */
|
|
157
|
+
exports.GRAMMARS = [
|
|
158
|
+
...new Set(Object.values(exports.LANGUAGES).map((spec) => spec.grammar)),
|
|
159
|
+
];
|
|
160
|
+
//# sourceMappingURL=compiler.js.map
|