Repository navigation
Expand file tree
/
Copy pathregexp.ts
More file actions
152 lines (142 loc) · 5.66 KB
/
Copy pathregexp.ts
File metadata and controls
152 lines (142 loc) · 5.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import type { Builtins } from "../runtime/intrinsics.js"
import { constructor, type Method, methods, prototypeFrom, receiver } from "../runtime/native.js"
import { syntaxError, typeError } from "../runtime/model.js"
import {
define,
defineAccessor,
Arr,
Obj,
RegExpObj,
record,
coerceToNumber,
coerceToString,
type Value,
} from "../runtime/objects.js"
import type { Interpreter } from "../runtime/interpreter.js"
const flagProperties = [
"hasIndices",
"global",
"ignoreCase",
"multiline",
"sticky",
"unicode",
"unicodeSets",
"dotAll",
] as const
const regexFailureReason = (error: unknown): string =>
(error instanceof Error ? error.message : String(error)).replace(/^Invalid regular expression:\s*/i, "")
const escapeRegexHint =
'To match special characters like ( ) [ ] { } + * ? . literally, escape them with a backslash (e.g. "\\\\(") or test for them with String.includes instead.'
/** Runs host regex work on a RegExp argument, sharing its `lastIndex`, or on a pattern string compiled for the call. */
export const withHostRegex = <T>(arg: Value, method: string, extraFlags: string, work: (regex: RegExp) => T): T => {
if (arg instanceof RegExpObj) return arg.use(work)
// Anything else is a pattern string, as `new RegExp(arg)` would read it: undefined is the empty pattern.
const source = arg === undefined ? "" : coerceToString(arg)
return work(compilePattern(source, method, extraFlags))
}
const compilePattern = (source: string, method: string, extraFlags: string): RegExp => {
try {
return new RegExp(source, extraFlags)
} catch (error) {
throw syntaxError(
`String.${method} received the string ${JSON.stringify(source)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`,
)
}
}
export const matchToValue = (builtins: Builtins, match: RegExpMatchArray): Arr => {
const result = new Arr(
builtins.Array,
Array.from(match, (group) => group),
)
if (match.index !== undefined) define(result, "index", match.index)
if (match.input !== undefined) define(result, "input", match.input)
if (match.groups) define(result, "groups", record(builtins.Object, match.groups))
if (match.indices) define(result, "indices", indicesToValue(builtins, match.indices))
return result
}
export const constructRegExp = (builtins: Builtins, args: Array<Value>, proto: Obj = builtins.RegExp): RegExpObj => {
const first = args[0]
const pattern = first instanceof RegExpObj ? first.source : first === undefined ? "" : coerceToString(first)
const flagsArg = args[1]
if (flagsArg !== undefined && typeof flagsArg !== "string") {
throw syntaxError(
`RegExp flags must be a string of flag characters (e.g. "g", "gi"), not ${flagsArg === null ? "null" : typeof flagsArg}.`,
)
}
const flags = flagsArg ?? (first instanceof RegExpObj ? first.flags : "")
try {
return new RegExpObj(proto, pattern, flags)
} catch (error) {
const reason = regexFailureReason(error)
throw syntaxError(
/flag/i.test(reason)
? `new RegExp(...) received invalid flags ${JSON.stringify(flags)} (${reason}). Valid flags are d, g, i, m, s, u, v, and y.`
: `new RegExp(...) received ${JSON.stringify(pattern)}, which is not a valid regular expression pattern (${reason}). ${escapeRegexHint}`,
)
}
}
// RegExp constructs identically with or without new, like JS.
export const regexpGlobal = <R>(ctx: Interpreter<R>) => {
const builtins = ctx.builtins
const proto = builtins.RegExp
const regexp = constructor(builtins, proto, {
name: "RegExp",
length: 2,
call: (_, args) => constructRegExp(builtins, args),
construct: (args, newTarget) => constructRegExp(builtins, args, prototypeFrom(newTarget, proto)),
})
methods(builtins, regexp, [
[
"escape",
1,
(_, args) => {
if (typeof args[0] !== "string") throw typeError("RegExp.escape expects a string.")
return RegExp.escape(args[0])
},
],
])
const self = (thisValue: Value, name: string) => receiver(RegExpObj, thisValue, `RegExp.prototype.${name}`)
defineAccessor(proto, "source", (thisValue) => self(thisValue, "source").source)
defineAccessor(proto, "flags", (thisValue) => self(thisValue, "flags").flags)
// One lastIndex per RegExp, so exec/test and the String methods share one counter.
defineAccessor(
proto,
"lastIndex",
(thisValue) => self(thisValue, "lastIndex").lastIndex,
(thisValue, value) => {
self(thisValue, "lastIndex").lastIndex = coerceToNumber(value)
},
)
for (const name of flagProperties) defineAccessor(proto, name, (thisValue) => self(thisValue, name).regex[name])
const run = (name: "exec" | "test"): Method => [
name,
1,
(thisValue, args) => {
const value = self(thisValue, name)
const input = coerceToString(args[0])
const matched = value.use((regex) => regex.exec(input))
if (name === "test") return matched !== null
return matched === null ? null : matchToValue(builtins, matched)
},
]
methods(builtins, proto, [
run("exec"),
run("test"),
["toString", 0, (thisValue) => coerceToString(self(thisValue, "toString"))],
])
return regexp
}
const indicesToValue = (builtins: Builtins, indices: RegExpIndicesArray): Arr => {
const range = (pair: [number, number] | undefined) =>
pair === undefined ? undefined : new Arr(builtins.Array, [...pair])
const result = new Arr(builtins.Array, Array.from(indices, range))
const groups = indices.groups
define(
result,
"groups",
groups === undefined
? undefined
: record(builtins.Object, Object.fromEntries(Object.entries(groups).map(([key, pair]) => [key, range(pair)]))),
)
return result
}