backburn 0.1.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.
Files changed (185) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/Makefile +50 -0
  4. data/README.md +520 -0
  5. data/docs/cli-and-outputs.md +226 -0
  6. data/docs/technical-spec.md +656 -0
  7. data/exe/backburn +8 -0
  8. data/ext/backburn/extconf.rb +31 -0
  9. data/ext/backburn/prism/COMMIT +1 -0
  10. data/ext/backburn/prism/LICENSE.md +7 -0
  11. data/ext/backburn/prism/Makefile +213 -0
  12. data/ext/backburn/prism/include/prism/arena.h +45 -0
  13. data/ext/backburn/prism/include/prism/arena.hpp +42 -0
  14. data/ext/backburn/prism/include/prism/ast.h +10395 -0
  15. data/ext/backburn/prism/include/prism/ast.hpp +641 -0
  16. data/ext/backburn/prism/include/prism/buffer.h +60 -0
  17. data/ext/backburn/prism/include/prism/buffer.hpp +55 -0
  18. data/ext/backburn/prism/include/prism/comments.h +72 -0
  19. data/ext/backburn/prism/include/prism/compiler/accel.h +26 -0
  20. data/ext/backburn/prism/include/prism/compiler/align.h +36 -0
  21. data/ext/backburn/prism/include/prism/compiler/assume.h +25 -0
  22. data/ext/backburn/prism/include/prism/compiler/branch.h +26 -0
  23. data/ext/backburn/prism/include/prism/compiler/bswap.h +46 -0
  24. data/ext/backburn/prism/include/prism/compiler/cplusplus.hpp +16 -0
  25. data/ext/backburn/prism/include/prism/compiler/endianness.h +34 -0
  26. data/ext/backburn/prism/include/prism/compiler/exceptions.hpp +17 -0
  27. data/ext/backburn/prism/include/prism/compiler/exported.h +24 -0
  28. data/ext/backburn/prism/include/prism/compiler/fallthrough.h +22 -0
  29. data/ext/backburn/prism/include/prism/compiler/filesystem.h +32 -0
  30. data/ext/backburn/prism/include/prism/compiler/flex_array.h +19 -0
  31. data/ext/backburn/prism/include/prism/compiler/force_inline.h +21 -0
  32. data/ext/backburn/prism/include/prism/compiler/format.h +27 -0
  33. data/ext/backburn/prism/include/prism/compiler/inline.h +17 -0
  34. data/ext/backburn/prism/include/prism/compiler/lifetimebound.hpp +25 -0
  35. data/ext/backburn/prism/include/prism/compiler/nodiscard.h +22 -0
  36. data/ext/backburn/prism/include/prism/compiler/nonnull.h +18 -0
  37. data/ext/backburn/prism/include/prism/compiler/noreturn.h +24 -0
  38. data/ext/backburn/prism/include/prism/compiler/stack.h +60 -0
  39. data/ext/backburn/prism/include/prism/compiler/unused.h +18 -0
  40. data/ext/backburn/prism/include/prism/constant_pool.h +112 -0
  41. data/ext/backburn/prism/include/prism/diagnostic.h +121 -0
  42. data/ext/backburn/prism/include/prism/errors_format.h +63 -0
  43. data/ext/backburn/prism/include/prism/excludes.h +29 -0
  44. data/ext/backburn/prism/include/prism/integer.h +79 -0
  45. data/ext/backburn/prism/include/prism/internal/allocator.h +68 -0
  46. data/ext/backburn/prism/include/prism/internal/allocator_debug.h +88 -0
  47. data/ext/backburn/prism/include/prism/internal/arena.h +223 -0
  48. data/ext/backburn/prism/include/prism/internal/assert.h +14 -0
  49. data/ext/backburn/prism/include/prism/internal/bignum.h +239 -0
  50. data/ext/backburn/prism/include/prism/internal/bit.h +66 -0
  51. data/ext/backburn/prism/include/prism/internal/buffer.h +104 -0
  52. data/ext/backburn/prism/include/prism/internal/char.h +145 -0
  53. data/ext/backburn/prism/include/prism/internal/comments.h +54 -0
  54. data/ext/backburn/prism/include/prism/internal/constant_pool.h +155 -0
  55. data/ext/backburn/prism/include/prism/internal/diagnostic.h +392 -0
  56. data/ext/backburn/prism/include/prism/internal/double.h +19 -0
  57. data/ext/backburn/prism/include/prism/internal/encoding.h +326 -0
  58. data/ext/backburn/prism/include/prism/internal/integer.h +66 -0
  59. data/ext/backburn/prism/include/prism/internal/isinf.h +16 -0
  60. data/ext/backburn/prism/include/prism/internal/line_offset_list.h +50 -0
  61. data/ext/backburn/prism/include/prism/internal/list.h +62 -0
  62. data/ext/backburn/prism/include/prism/internal/magic_comments.h +23 -0
  63. data/ext/backburn/prism/include/prism/internal/memchr.h +15 -0
  64. data/ext/backburn/prism/include/prism/internal/node.h +197 -0
  65. data/ext/backburn/prism/include/prism/internal/oom.h +16 -0
  66. data/ext/backburn/prism/include/prism/internal/options.h +248 -0
  67. data/ext/backburn/prism/include/prism/internal/parser.h +1170 -0
  68. data/ext/backburn/prism/include/prism/internal/regexp.h +70 -0
  69. data/ext/backburn/prism/include/prism/internal/serialize.h +39 -0
  70. data/ext/backburn/prism/include/prism/internal/source.h +72 -0
  71. data/ext/backburn/prism/include/prism/internal/static_literals.h +60 -0
  72. data/ext/backburn/prism/include/prism/internal/stringy.h +37 -0
  73. data/ext/backburn/prism/include/prism/internal/strncasecmp.h +18 -0
  74. data/ext/backburn/prism/include/prism/internal/strpbrk.h +61 -0
  75. data/ext/backburn/prism/include/prism/internal/tokens.h +11 -0
  76. data/ext/backburn/prism/include/prism/internal/xxh3.h +16 -0
  77. data/ext/backburn/prism/include/prism/json.h +40 -0
  78. data/ext/backburn/prism/include/prism/line_offset_list.h +69 -0
  79. data/ext/backburn/prism/include/prism/magic_comments.h +53 -0
  80. data/ext/backburn/prism/include/prism/node.h +139 -0
  81. data/ext/backburn/prism/include/prism/node.hpp +272 -0
  82. data/ext/backburn/prism/include/prism/node_type.hpp +38 -0
  83. data/ext/backburn/prism/include/prism/options.h +393 -0
  84. data/ext/backburn/prism/include/prism/options.hpp +43 -0
  85. data/ext/backburn/prism/include/prism/parser.h +433 -0
  86. data/ext/backburn/prism/include/prism/parser.hpp +274 -0
  87. data/ext/backburn/prism/include/prism/prettyprint.h +39 -0
  88. data/ext/backburn/prism/include/prism/serialize.h +123 -0
  89. data/ext/backburn/prism/include/prism/source.h +163 -0
  90. data/ext/backburn/prism/include/prism/stream.h +36 -0
  91. data/ext/backburn/prism/include/prism/string_query.h +97 -0
  92. data/ext/backburn/prism/include/prism/stringy.h +61 -0
  93. data/ext/backburn/prism/include/prism/stringy.hpp +31 -0
  94. data/ext/backburn/prism/include/prism/version.h +46 -0
  95. data/ext/backburn/prism/include/prism.h +123 -0
  96. data/ext/backburn/prism/include/prism.hpp +24 -0
  97. data/ext/backburn/prism/src/arena.c +200 -0
  98. data/ext/backburn/prism/src/bignum.c +399 -0
  99. data/ext/backburn/prism/src/buffer.c +405 -0
  100. data/ext/backburn/prism/src/char.c +289 -0
  101. data/ext/backburn/prism/src/comments.c +455 -0
  102. data/ext/backburn/prism/src/constant_pool.c +410 -0
  103. data/ext/backburn/prism/src/diagnostic.c +918 -0
  104. data/ext/backburn/prism/src/double.c +394 -0
  105. data/ext/backburn/prism/src/encoding.c +1701 -0
  106. data/ext/backburn/prism/src/errors_format.c +650 -0
  107. data/ext/backburn/prism/src/integer.c +675 -0
  108. data/ext/backburn/prism/src/json.c +5745 -0
  109. data/ext/backburn/prism/src/line_offset_list.c +99 -0
  110. data/ext/backburn/prism/src/list.c +24 -0
  111. data/ext/backburn/prism/src/memchr.c +37 -0
  112. data/ext/backburn/prism/src/node.c +4464 -0
  113. data/ext/backburn/prism/src/options.c +475 -0
  114. data/ext/backburn/prism/src/parser.c +371 -0
  115. data/ext/backburn/prism/src/prettyprint.c +9038 -0
  116. data/ext/backburn/prism/src/prism.c +23615 -0
  117. data/ext/backburn/prism/src/regexp.c +3833 -0
  118. data/ext/backburn/prism/src/serialize.c +2656 -0
  119. data/ext/backburn/prism/src/source.c +525 -0
  120. data/ext/backburn/prism/src/static_literals.c +562 -0
  121. data/ext/backburn/prism/src/string_query.c +195 -0
  122. data/ext/backburn/prism/src/stringy.c +77 -0
  123. data/ext/backburn/prism/src/strncasecmp.c +37 -0
  124. data/ext/backburn/prism/src/strpbrk.c +465 -0
  125. data/ext/backburn/prism/src/tokens.c +724 -0
  126. data/ext/backburn/prism/src/xxh3.c +292 -0
  127. data/lib/backburn/version.rb +7 -0
  128. data/presets/devise.roots +11 -0
  129. data/presets/fast-mcp.roots +5 -0
  130. data/presets/graphql.roots +6 -0
  131. data/presets/phlex.roots +7 -0
  132. data/presets/pundit.roots +3 -0
  133. data/presets/rails-framework.roots +10 -0
  134. data/presets/rails.roots +83 -0
  135. data/presets/sidekiq.roots +4 -0
  136. data/presets/thor.roots +3 -0
  137. data/rails.roots +99 -0
  138. data/scripts/embed-presets.sh +13 -0
  139. data/scripts/version-h.sh +7 -0
  140. data/src/analysis/analysis.c +95 -0
  141. data/src/analysis/analysis.h +24 -0
  142. data/src/analysis/batches.c +127 -0
  143. data/src/analysis/batches.h +17 -0
  144. data/src/analysis/graph.c +238 -0
  145. data/src/analysis/graph.h +34 -0
  146. data/src/analysis/mark.c +300 -0
  147. data/src/analysis/mark.h +21 -0
  148. data/src/analysis/roots.c +229 -0
  149. data/src/analysis/roots.h +29 -0
  150. data/src/cli/cli.c +237 -0
  151. data/src/cli/cli.h +9 -0
  152. data/src/cli/config.c +112 -0
  153. data/src/cli/config.h +14 -0
  154. data/src/cli/options.c +17 -0
  155. data/src/cli/options.h +35 -0
  156. data/src/commands/commands.h +11 -0
  157. data/src/commands/explain.c +255 -0
  158. data/src/commands/gemfile.c +126 -0
  159. data/src/commands/gemfile.h +27 -0
  160. data/src/commands/gems.c +408 -0
  161. data/src/commands/init.c +92 -0
  162. data/src/commands/roots.c +82 -0
  163. data/src/commands/scan.c +91 -0
  164. data/src/core/intern.c +94 -0
  165. data/src/core/intern.h +40 -0
  166. data/src/core/json.c +17 -0
  167. data/src/core/json.h +9 -0
  168. data/src/core/model.c +25 -0
  169. data/src/core/model.h +85 -0
  170. data/src/core/util.c +116 -0
  171. data/src/core/util.h +48 -0
  172. data/src/index/erb.c +40 -0
  173. data/src/index/erb.h +9 -0
  174. data/src/index/haml.c +334 -0
  175. data/src/index/haml.h +10 -0
  176. data/src/index/indexer.c +702 -0
  177. data/src/index/indexer.h +19 -0
  178. data/src/index/walk.c +144 -0
  179. data/src/index/walk.h +14 -0
  180. data/src/main.c +81 -0
  181. data/src/output/baseline.c +101 -0
  182. data/src/output/baseline.h +15 -0
  183. data/src/output/report.c +440 -0
  184. data/src/output/report.h +28 -0
  185. metadata +231 -0
@@ -0,0 +1,3833 @@
1
+ #include "prism/internal/regexp.h"
2
+
3
+ #include "prism/compiler/align.h"
4
+ #include "prism/compiler/inline.h"
5
+ #include "prism/compiler/fallthrough.h"
6
+ #include "prism/internal/arena.h"
7
+ #include "prism/internal/assert.h"
8
+ #include "prism/internal/buffer.h"
9
+ #include "prism/internal/char.h"
10
+ #include "prism/internal/diagnostic.h"
11
+ #include "prism/internal/encoding.h"
12
+ #include "prism/internal/memchr.h"
13
+ #include "prism/internal/node.h"
14
+ #include "prism/internal/options.h"
15
+ #include "prism/internal/parser.h"
16
+ #include "prism/internal/stringy.h"
17
+ #include "prism/internal/strncasecmp.h"
18
+ #include "prism/internal/xxh3.h"
19
+
20
+ #include <string.h>
21
+
22
+ /** The maximum depth of nested groups allowed in a regular expression. */
23
+ #define PM_REGEXP_PARSE_DEPTH_MAX 4096
24
+
25
+ /**
26
+ * Whether an ASCII byte is written as it is when a regular expression is
27
+ * quoted. That is a printable character other than the slash.
28
+ */
29
+ static PRISM_INLINE bool
30
+ pm_regexp_format_verbatim_p(uint8_t byte) {
31
+ return byte >= 0x20 && byte < 0x7F && byte != '/';
32
+ }
33
+
34
+ /**
35
+ * Whether the content of a regular expression can be quoted as it is. That is
36
+ * when every ASCII character is written as it is and every other character is
37
+ * valid UTF-8, since messages are in UTF-8.
38
+ */
39
+ static bool
40
+ pm_regexp_format_verbatim_content_p(const pm_encoding_t *encoding, const uint8_t *cursor, const uint8_t *end) {
41
+ while (cursor < end) {
42
+ if (*cursor < 0x80) {
43
+ if (!pm_regexp_format_verbatim_p(*cursor)) return false;
44
+ cursor++;
45
+ } else {
46
+ if (encoding != PM_ENCODING_UTF_8_ENTRY) return false;
47
+
48
+ size_t width = pm_encoding_char_width(encoding, cursor, end - cursor);
49
+ if (width == 0) return false;
50
+ cursor += width;
51
+ }
52
+ }
53
+
54
+ return true;
55
+ }
56
+
57
+ /**
58
+ * Write the content of a regular expression the way Ruby quotes it in an
59
+ * error. Content that can be quoted as it is gets written unchanged. Otherwise
60
+ * each character is written like this:
61
+ *
62
+ * - a backslash and the character after it, unchanged, as in \n;
63
+ * - a slash as \/;
64
+ * - printable ASCII and whitespace, unchanged;
65
+ * - other ASCII as \xHH, as in \x01;
66
+ * - a byte that is not part of a valid character as \xHH;
67
+ * - a UTF-8 or CESU-8 character as \uHHHH, or \u{HHHHH} past U+FFFF;
68
+ * - any other character as \xHH, or as \x{HHHH} with all of its bytes.
69
+ */
70
+ static void
71
+ pm_regexp_format_for_error(pm_buffer_t *buffer, const pm_encoding_t *encoding, const uint8_t *source, size_t length) {
72
+ const uint8_t *cursor = source;
73
+ const uint8_t *end = source + length;
74
+
75
+ if (pm_regexp_format_verbatim_content_p(encoding, cursor, end)) {
76
+ pm_buffer_append_string(buffer, (const char *) source, length);
77
+ return;
78
+ }
79
+
80
+ while (cursor < end) {
81
+ uint8_t byte = *cursor;
82
+
83
+ if (byte == '\\' && cursor + 1 < end) {
84
+ size_t width = pm_encoding_char_width(encoding, cursor + 1, end - cursor - 1);
85
+ if (width == 0) width = 1;
86
+
87
+ pm_buffer_append_string(buffer, (const char *) cursor, width + 1);
88
+ cursor += width + 1;
89
+ } else if (byte >= 0x80) {
90
+ size_t width = pm_encoding_char_width(encoding, cursor, end - cursor);
91
+
92
+ if (width == 0) {
93
+ pm_buffer_append_format(buffer, "\\x%02X", byte);
94
+ cursor++;
95
+ continue;
96
+ }
97
+
98
+ int32_t codepoint = pm_encoding_unicode_codepoint(encoding, cursor, width);
99
+ if (codepoint >= 0x10000) {
100
+ pm_buffer_append_format(buffer, "\\u{%X}", (unsigned int) codepoint);
101
+ } else if (codepoint >= 0) {
102
+ pm_buffer_append_format(buffer, "\\u%04X", (unsigned int) codepoint);
103
+ } else if (width == 1) {
104
+ pm_buffer_append_format(buffer, "\\x%02X", byte);
105
+ } else {
106
+ pm_buffer_append_string(buffer, "\\x{", 3);
107
+ for (size_t index = 0; index < width; index++) pm_buffer_append_format(buffer, "%02X", cursor[index]);
108
+ pm_buffer_append_byte(buffer, '}');
109
+ }
110
+
111
+ cursor += width;
112
+ } else if (byte == '/') {
113
+ pm_buffer_append_string(buffer, "\\/", 2);
114
+ cursor++;
115
+ } else if (pm_regexp_format_verbatim_p(byte) || pm_char_is_whitespace(byte)) {
116
+ pm_buffer_append_byte(buffer, byte);
117
+ cursor++;
118
+ } else {
119
+ pm_buffer_append_format(buffer, "\\x%02X", byte);
120
+ cursor++;
121
+ }
122
+ }
123
+ }
124
+
125
+ /**
126
+ * A regular expression as it is validated: its content, its options, and the
127
+ * place in the source of the errors that are about it as a whole.
128
+ */
129
+ typedef struct {
130
+ /** The parser that the regular expression is in. */
131
+ pm_parser_t *parser;
132
+
133
+ /**
134
+ * The content, in which the lexer keeps the escapes that the regular
135
+ * expression engine reads as their text.
136
+ */
137
+ const uint8_t *source;
138
+
139
+ /** The length of the content. */
140
+ size_t size;
141
+
142
+ /**
143
+ * The encoding that the content is in. This is the source encoding,
144
+ * except for content joined from strings in another encoding.
145
+ */
146
+ const pm_encoding_t *encoding;
147
+
148
+ /** The flags of the regular expression, which hold its options. */
149
+ pm_node_flags_t flags;
150
+
151
+ /** Where errors about the regular expression as a whole are reported. */
152
+ pm_location_t location;
153
+
154
+ /**
155
+ * Whether the content holds characters that the lexer did not check, as
156
+ * the values of strings joined into it do, so that an invalid character is
157
+ * an error once its escapes are read rather than one that was reported
158
+ * where it was lexed.
159
+ */
160
+ bool unlexed;
161
+ } pm_regexp_t;
162
+
163
+ /**
164
+ * Write the letters of the options that an error shows after the quoted
165
+ * regular expression, the way Ruby writes them: m, i, and x, in that order. The
166
+ * encoding options are not shown.
167
+ */
168
+ static void
169
+ pm_regexp_option_letters(pm_node_flags_t flags, char letters[4]) {
170
+ size_t index = 0;
171
+ if (flags & PM_REGULAR_EXPRESSION_FLAGS_MULTI_LINE) letters[index++] = 'm';
172
+ if (flags & PM_REGULAR_EXPRESSION_FLAGS_IGNORE_CASE) letters[index++] = 'i';
173
+ if (flags & PM_REGULAR_EXPRESSION_FLAGS_EXTENDED) letters[index++] = 'x';
174
+ letters[index] = '\0';
175
+ }
176
+
177
+ /**
178
+ * The name of a named group, in the pattern.
179
+ */
180
+ typedef struct {
181
+ /** The start of the name. */
182
+ const uint8_t *start;
183
+
184
+ /** The length of the name. */
185
+ size_t length;
186
+ } pm_regexp_name_t;
187
+
188
+ /** A name's binding, with a one-based index into the capture list. */
189
+ typedef struct {
190
+ uint64_t hash;
191
+ uint32_t capture;
192
+ uint32_t count;
193
+ } pm_regexp_name_binding_t;
194
+
195
+ /**
196
+ * A list of the names of named groups.
197
+ */
198
+ typedef struct {
199
+ /** The names, which the list owns in the scratch arena. */
200
+ pm_regexp_name_t *values;
201
+
202
+ /** The number of names in the list. */
203
+ size_t size;
204
+
205
+ /** The number of names the list has room for. */
206
+ size_t capacity;
207
+
208
+ /** Bindings built when a reference needs to search a larger list. */
209
+ pm_regexp_name_binding_t *bindings;
210
+
211
+ /** The number of distinct names in the bindings. */
212
+ size_t bindings_size;
213
+
214
+ /** The number of slots in the bindings, always a power of two when used. */
215
+ size_t bindings_capacity;
216
+ } pm_regexp_names_t;
217
+
218
+ /**
219
+ * The kinds of references to groups that are checked once the whole pattern is
220
+ * parsed, as the regular expression engine checks them when it compiles it.
221
+ */
222
+ typedef enum {
223
+ /** A backreference by number, as in \1 or \k<1>. */
224
+ PM_REGEXP_DEFERRED_NUMBER,
225
+
226
+ /** A condition by number, as in (?(1)a). */
227
+ PM_REGEXP_DEFERRED_CONDITION_NUMBER,
228
+
229
+ /**
230
+ * A condition with a number in the form of a name, as in (?(<1>)a), which
231
+ * the engine treats as a reference by name, so it may be used alongside
232
+ * named groups.
233
+ */
234
+ PM_REGEXP_DEFERRED_NAMED_NUMBER,
235
+
236
+ /** A call by number, as in \g<1>. */
237
+ PM_REGEXP_DEFERRED_CALL_NUMBER,
238
+
239
+ /** A call by name, as in \g<n>. */
240
+ PM_REGEXP_DEFERRED_CALL_NAME
241
+ } pm_regexp_deferred_type_t;
242
+
243
+ /**
244
+ * A reference to a group that is checked once the whole pattern is parsed.
245
+ */
246
+ typedef struct {
247
+ /** The kind of reference. */
248
+ pm_regexp_deferred_type_t type;
249
+
250
+ /** The start of the reference as it is written. */
251
+ const uint8_t *start;
252
+
253
+ /** The end of the reference as it is written. */
254
+ const uint8_t *end;
255
+
256
+ /** The number of the group, for a reference by number. */
257
+ int64_t number;
258
+ } pm_regexp_deferred_t;
259
+
260
+ /**
261
+ * A list of the references to groups that are checked once the whole pattern
262
+ * is parsed.
263
+ */
264
+ typedef struct {
265
+ /** The references, which the list owns in the scratch arena. */
266
+ pm_regexp_deferred_t *values;
267
+
268
+ /** The number of references in the list. */
269
+ size_t size;
270
+
271
+ /** The number of references the list has room for. */
272
+ size_t capacity;
273
+ } pm_regexp_deferreds_t;
274
+
275
+ /**
276
+ * This is the parser that is going to handle parsing regular expressions.
277
+ */
278
+ typedef struct {
279
+ /** The parser that is currently being used. */
280
+ pm_parser_t *parser;
281
+
282
+ /** The regular expression that is being validated, which errors quote. */
283
+ const pm_regexp_t *regexp;
284
+
285
+ /** A pointer to the start of the pattern that we are parsing. */
286
+ const uint8_t *start;
287
+
288
+ /** A pointer to the current position in the pattern. */
289
+ const uint8_t *cursor;
290
+
291
+ /** A pointer to the end of the pattern that we are parsing. */
292
+ const uint8_t *end;
293
+
294
+ /**
295
+ * Where the pattern stops lining up with the content, or NULL if it is the
296
+ * content itself.
297
+ */
298
+ const pm_regexp_offsets_t *pattern_offsets;
299
+
300
+ /**
301
+ * Where the content stops lining up with the source, for reporting errors
302
+ * at their place in the source. NULL when the content does not line up with
303
+ * the source at all, as when it is joined from several parts, in which case
304
+ * errors are reported at the location of the whole regular expression.
305
+ */
306
+ const pm_regexp_offsets_t *offsets;
307
+
308
+ /** The offset in the source of the start of the content. */
309
+ uint32_t source_start;
310
+
311
+ /** The location of the whole regular expression. */
312
+ pm_location_t location;
313
+
314
+ /** The encoding of the source. */
315
+ const pm_encoding_t *encoding;
316
+
317
+ /**
318
+ * Pointer to the first non-POSIX property name (for /n error messages).
319
+ * POSIX properties (Alnum, Alpha, etc.) work in all encodings.
320
+ * Script properties (Hiragana, Katakana, etc.) work in /e, /s, /u.
321
+ * Unicode-only properties (L, Ll, etc.) work only in /u.
322
+ */
323
+ const uint8_t *property_name;
324
+
325
+ /** Length of the first non-POSIX property name found. */
326
+ size_t property_name_length;
327
+
328
+ /**
329
+ * Pointer to the first Unicode-only property name (for /e, /s error
330
+ * messages). NULL if only POSIX or script properties have been seen.
331
+ */
332
+ const uint8_t *unicode_property_name;
333
+
334
+ /** Length of the first Unicode-only property name found. */
335
+ size_t unicode_property_name_length;
336
+
337
+ /**
338
+ * Whether or not the regular expression currently being parsed is in
339
+ * extended mode, wherein whitespace is ignored and comments are allowed.
340
+ */
341
+ bool extended_mode;
342
+
343
+ /** Whether the encoding has changed from the default. */
344
+ bool encoding_changed;
345
+
346
+ /** Number of syntax diagnostics that have quoted the complete pattern. */
347
+ uint8_t quoted_errors;
348
+
349
+ /**
350
+ * The number of capturing groups opened so far, plain and named. A group
351
+ * counts from its (, before its body, as in the regular expression engine.
352
+ */
353
+ uint32_t groups;
354
+
355
+ /**
356
+ * The names of the named groups opened so far, for the references that
357
+ * need a name to be defined already.
358
+ */
359
+ pm_regexp_names_t names;
360
+
361
+ /**
362
+ * The references to groups that are checked once the whole pattern is
363
+ * parsed.
364
+ */
365
+ pm_regexp_deferreds_t deferreds;
366
+ } pm_regexp_parser_t;
367
+
368
+ /** Find the binding for a name, or its empty slot. */
369
+ static pm_regexp_name_binding_t *
370
+ pm_regexp_name_binding(const pm_regexp_names_t *names, pm_regexp_name_t name, uint64_t hash) {
371
+ size_t mask = names->bindings_capacity - 1;
372
+ size_t index = (size_t) hash & mask;
373
+
374
+ while (names->bindings[index].capture != 0) {
375
+ pm_regexp_name_binding_t *binding = &names->bindings[index];
376
+ const pm_regexp_name_t *capture = &names->values[binding->capture - 1];
377
+ if (binding->hash == hash && capture->length == name.length && memcmp(capture->start, name.start, name.length) == 0) return binding;
378
+ index = (index + 1) & mask;
379
+ }
380
+
381
+ return &names->bindings[index];
382
+ }
383
+
384
+ /** Update a name's binding when another capture with that name is opened. */
385
+ static void
386
+ pm_regexp_name_bind(pm_arena_t *arena, pm_regexp_names_t *names, size_t capture) {
387
+ const pm_regexp_name_binding_t *previous = names->bindings;
388
+ if (previous == NULL || names->bindings_size >= names->bindings_capacity / 4 * 3) {
389
+ size_t capacity = previous == NULL ? 16 : names->bindings_capacity * 2;
390
+ size_t mask = capacity - 1;
391
+ pm_regexp_name_binding_t *bindings = PM_ARENA_ZALLOC_ARRAY(arena, pm_regexp_name_binding_t, capacity);
392
+
393
+ if (previous != NULL) {
394
+ for (size_t index = 0; index < names->bindings_capacity; index++) {
395
+ pm_regexp_name_binding_t binding = previous[index];
396
+ if (binding.capture == 0) continue;
397
+
398
+ size_t slot = (size_t) binding.hash & mask;
399
+ while (bindings[slot].capture != 0) slot = (slot + 1) & mask;
400
+ bindings[slot] = binding;
401
+ }
402
+ }
403
+
404
+ names->bindings = bindings;
405
+ names->bindings_capacity = capacity;
406
+ }
407
+
408
+ pm_regexp_name_t name = names->values[capture];
409
+ uint64_t hash = pm_xxh3(name.start, name.length);
410
+ pm_regexp_name_binding_t *binding = pm_regexp_name_binding(names, name, hash);
411
+ if (binding->capture == 0) {
412
+ binding->hash = hash;
413
+ binding->capture = (uint32_t) (capture + 1);
414
+ names->bindings_size++;
415
+ }
416
+ binding->count++;
417
+ }
418
+
419
+ /**
420
+ * Append a name to the names of the named groups opened so far, growing the
421
+ * list in the scratch arena.
422
+ */
423
+ static void
424
+ pm_regexp_names_append(pm_regexp_parser_t *parser, pm_regexp_name_t name) {
425
+ pm_regexp_names_t *names = &parser->names;
426
+
427
+ if (names->size == names->capacity) {
428
+ size_t capacity = names->capacity == 0 ? 4 : names->capacity * 2;
429
+ pm_regexp_name_t *values = (pm_regexp_name_t *) pm_arena_alloc(&parser->parser->scratch_arena, capacity * sizeof(pm_regexp_name_t), PRISM_ALIGNOF(pm_regexp_name_t));
430
+
431
+ if (names->size > 0) memcpy(values, names->values, names->size * sizeof(pm_regexp_name_t));
432
+ names->values = values;
433
+ names->capacity = capacity;
434
+ }
435
+
436
+ names->values[names->size++] = name;
437
+ if (names->bindings != NULL) pm_regexp_name_bind(&parser->parser->scratch_arena, names, names->size - 1);
438
+ }
439
+
440
+ /**
441
+ * Keep a reference to a group to check once the whole pattern is parsed,
442
+ * growing the list in the scratch arena.
443
+ */
444
+ static void
445
+ pm_regexp_defer(pm_regexp_parser_t *parser, pm_regexp_deferred_type_t type, const uint8_t *start, const uint8_t *end, int64_t number) {
446
+ pm_regexp_deferreds_t *deferreds = &parser->deferreds;
447
+
448
+ if (deferreds->size == deferreds->capacity) {
449
+ size_t capacity = deferreds->capacity == 0 ? 4 : deferreds->capacity * 2;
450
+ pm_regexp_deferred_t *values = (pm_regexp_deferred_t *) pm_arena_alloc(&parser->parser->scratch_arena, capacity * sizeof(pm_regexp_deferred_t), PRISM_ALIGNOF(pm_regexp_deferred_t));
451
+
452
+ if (deferreds->size > 0) memcpy(values, deferreds->values, deferreds->size * sizeof(pm_regexp_deferred_t));
453
+ deferreds->values = values;
454
+ deferreds->capacity = capacity;
455
+ }
456
+
457
+ deferreds->values[deferreds->size++] = (pm_regexp_deferred_t) { .type = type, .start = start, .end = end, .number = number };
458
+ }
459
+
460
+ /**
461
+ * Append a place to a list of places, growing the list in the scratch arena.
462
+ */
463
+ void
464
+ pm_regexp_offsets_append(pm_parser_t *parser, pm_regexp_offsets_t *offsets, pm_regexp_offset_t offset) {
465
+ pm_regexp_offset_t *values = offsets->values;
466
+ if (values == NULL || offsets->size == offsets->capacity) {
467
+ size_t capacity = values == NULL ? 4 : offsets->capacity * 2;
468
+ pm_regexp_offset_t *grown = PM_ARENA_ALLOC_ARRAY(&parser->scratch_arena, pm_regexp_offset_t, capacity);
469
+
470
+ if (values != NULL) memcpy(grown, values, offsets->size * sizeof(pm_regexp_offset_t));
471
+ offsets->values = grown;
472
+ offsets->capacity = capacity;
473
+ values = grown;
474
+ }
475
+
476
+ values[offsets->size++] = offset;
477
+ }
478
+
479
+ /**
480
+ * Map an offset in the content to an offset in the source, through the places
481
+ * where the two stop lining up. The base is the offset in the source of the
482
+ * start of the content.
483
+ *
484
+ * Each byte after a place is at the same distance from it in the source as in
485
+ * the content. A byte in text written in place of an escape maps to somewhere
486
+ * within that escape. The start flag says whether the offset starts a range or
487
+ * ends one. At a place, the escape before it wrote nothing at that offset, so
488
+ * a range that starts there starts at the escape, and one that ends there ends
489
+ * after it.
490
+ */
491
+ static uint32_t
492
+ pm_regexp_offsets_map(const pm_regexp_offsets_t *offsets, uint32_t base, uint32_t content, bool start) {
493
+ const pm_regexp_offset_t *values = offsets->values;
494
+ size_t size = offsets->size;
495
+
496
+ /* Find the number of places at or before the position. */
497
+ size_t low = 0;
498
+ size_t high = size;
499
+
500
+ while (low < high) {
501
+ size_t middle = low + (high - low) / 2;
502
+
503
+ if (values[middle].content <= content) {
504
+ low = middle + 1;
505
+ } else {
506
+ high = middle;
507
+ }
508
+ }
509
+
510
+ /* The place that the position is measured from, which for the start of a
511
+ * range at a recorded place is the one before it. */
512
+ size_t from = low;
513
+ if (start && from > 0 && values[from - 1].content == content) from--;
514
+
515
+ uint32_t source = (from == 0) ? (base + content) : (values[from - 1].source + (content - values[from - 1].content));
516
+ if (from < size && source > values[from].source) source = values[from].source;
517
+
518
+ return source;
519
+ }
520
+
521
+ /**
522
+ * Return the offset in the source of the given position in the pattern, as the
523
+ * start (or else the end) of a range. The pattern maps to the content first,
524
+ * and the content then maps to the source.
525
+ *
526
+ * In the pattern, text written in place of an escape lines up with the escape
527
+ * at both ends, so it maps the same way whether it starts or ends a range.
528
+ */
529
+ static uint32_t
530
+ pm_regexp_source_offset(const pm_regexp_parser_t *parser, const uint8_t *position, bool start) {
531
+ if (parser->offsets == NULL) {
532
+ return start ? parser->location.start : (parser->location.start + parser->location.length);
533
+ }
534
+
535
+ uint32_t content = (uint32_t) (position - parser->start);
536
+ if (parser->pattern_offsets != NULL) content = pm_regexp_offsets_map(parser->pattern_offsets, 0, content, false);
537
+
538
+ return pm_regexp_offsets_map(parser->offsets, parser->source_start, content, start);
539
+ }
540
+
541
+ /**
542
+ * Append a syntax error to the parser's error list, at the place in the source
543
+ * of the given range of the content. The first eight messages are followed by
544
+ * the quoted regular expression and its options, as in "unmatched close
545
+ * parenthesis: /a)/i".
546
+ */
547
+ static void
548
+ pm_regexp_parse_error(pm_regexp_parser_t *regexp_parser, const uint8_t *start, const uint8_t *end, const char *message) {
549
+ pm_parser_t *parser = regexp_parser->parser;
550
+ const pm_regexp_t *regexp = regexp_parser->regexp;
551
+
552
+ uint32_t source_start = pm_regexp_source_offset(regexp_parser, start, true);
553
+ uint32_t source_end = pm_regexp_source_offset(regexp_parser, end, false);
554
+
555
+ /* Recovery can report an error for every byte of the pattern. Limit how
556
+ * many diagnostics copy it so the total message size remains linear. */
557
+ if (regexp_parser->quoted_errors == 8) {
558
+ pm_diagnostic_list_append_format(&parser->metadata_arena, &parser->error_list, source_start, source_end - source_start, PM_ERR_REGEXP_PARSE_ERROR, message);
559
+ } else {
560
+ regexp_parser->quoted_errors++;
561
+
562
+ char letters[4];
563
+ pm_regexp_option_letters(regexp->flags, letters);
564
+
565
+ pm_buffer_t buffer = { 0 };
566
+ pm_buffer_append_string(&buffer, message, strlen(message));
567
+ pm_buffer_append_string(&buffer, ": /", 3);
568
+ pm_regexp_format_for_error(&buffer, regexp->encoding, regexp->source, regexp->size);
569
+ pm_buffer_append_byte(&buffer, '/');
570
+ pm_buffer_append_string(&buffer, letters, strlen(letters));
571
+ pm_buffer_append_byte(&buffer, '\0');
572
+
573
+ pm_diagnostic_list_append_format(&parser->metadata_arena, &parser->error_list, source_start, source_end - source_start, PM_ERR_REGEXP_PARSE_ERROR, pm_buffer_value(&buffer));
574
+ pm_buffer_cleanup(&buffer);
575
+ }
576
+ }
577
+
578
+ /**
579
+ * Report that the stack budget was used up while parsing the regular
580
+ * expression.
581
+ */
582
+ static void
583
+ pm_regexp_parse_stack_exhausted(pm_regexp_parser_t *regexp_parser) {
584
+ uint32_t source_start = pm_regexp_source_offset(regexp_parser, regexp_parser->start, true);
585
+ uint32_t source_end = pm_regexp_source_offset(regexp_parser, regexp_parser->end, false);
586
+ pm_parser_err_stack_exhausted(regexp_parser->parser, source_start, source_end - source_start);
587
+ }
588
+
589
+ /**
590
+ * Returns true if the next character is the end of the source.
591
+ */
592
+ static PRISM_INLINE bool
593
+ pm_regexp_char_is_eof(pm_regexp_parser_t *parser) {
594
+ return parser->cursor >= parser->end;
595
+ }
596
+
597
+ /**
598
+ * Optionally accept a char and consume it if it exists.
599
+ */
600
+ static PRISM_INLINE bool
601
+ pm_regexp_char_accept(pm_regexp_parser_t *parser, uint8_t value) {
602
+ if (!pm_regexp_char_is_eof(parser) && *parser->cursor == value) {
603
+ parser->cursor++;
604
+ return true;
605
+ }
606
+ return false;
607
+ }
608
+
609
+ /**
610
+ * Expect a character to be present and consume it.
611
+ */
612
+ static PRISM_INLINE bool
613
+ pm_regexp_char_expect(pm_regexp_parser_t *parser, uint8_t value) {
614
+ if (!pm_regexp_char_is_eof(parser) && *parser->cursor == value) {
615
+ parser->cursor++;
616
+ return true;
617
+ }
618
+ return false;
619
+ }
620
+
621
+ /**
622
+ * Skip the whitespace that extended mode ignores outside of a character class:
623
+ * a space, tab, newline, carriage return, or form feed. Each place that reads
624
+ * the next part of the pattern skips it first, so in /( *)/x the * has nothing
625
+ * to repeat.
626
+ */
627
+ static PRISM_INLINE void
628
+ pm_regexp_skip_extended_whitespace(pm_regexp_parser_t *parser) {
629
+ if (!parser->extended_mode) return;
630
+
631
+ while (parser->cursor < parser->end) {
632
+ switch (*parser->cursor) {
633
+ case ' ':
634
+ case '\t':
635
+ case '\n':
636
+ case '\r':
637
+ case '\f':
638
+ parser->cursor++;
639
+ break;
640
+ default:
641
+ return;
642
+ }
643
+ }
644
+ }
645
+
646
+ /**
647
+ * Advance past the character at the cursor, reading it whole in the encoding of
648
+ * the regular expression. An invalid character, which the lexer has already
649
+ * reported, is skipped a byte at a time.
650
+ */
651
+ static void
652
+ pm_regexp_skip_char(pm_regexp_parser_t *parser) {
653
+ ptrdiff_t remaining = parser->end - parser->cursor;
654
+ size_t width = parser->encoding_changed ? pm_encoding_char_width(parser->encoding, parser->cursor, remaining) : pm_encoding_utf_8_char_width(parser->cursor, remaining);
655
+ parser->cursor += (width == 0) ? 1 : width;
656
+ }
657
+
658
+ /**
659
+ * This advances the current token to the next instance of the given character.
660
+ */
661
+ static bool
662
+ pm_regexp_char_find(pm_regexp_parser_t *parser, uint8_t value) {
663
+ if (pm_regexp_char_is_eof(parser)) {
664
+ return false;
665
+ }
666
+
667
+ const uint8_t *end = (const uint8_t *) pm_memchr(parser->cursor, value, (size_t) (parser->end - parser->cursor), parser->encoding_changed, parser->encoding);
668
+ if (end == NULL) {
669
+ return false;
670
+ }
671
+
672
+ parser->cursor = end + 1;
673
+ return true;
674
+ }
675
+
676
+ /**
677
+ * Parse a hex digit character and return its value, or -1 if not a hex digit.
678
+ */
679
+ static PRISM_INLINE int
680
+ pm_regexp_hex_digit_value(uint8_t byte) {
681
+ if (byte >= '0' && byte <= '9') return byte - '0';
682
+ if (byte >= 'a' && byte <= 'f') return byte - 'a' + 10;
683
+ if (byte >= 'A' && byte <= 'F') return byte - 'A' + 10;
684
+ return -1;
685
+ }
686
+
687
+ /**
688
+ * Return the value of the digits at the cursor in the given base, reading at
689
+ * most maximum of them, and set length to how many were read.
690
+ */
691
+ static uint32_t
692
+ pm_regexp_scan_digits(const uint8_t *cursor, const uint8_t *end, uint32_t maximum, uint32_t base, uint32_t *length) {
693
+ uint32_t value = 0;
694
+ uint32_t index = 0;
695
+
696
+ while (index < maximum && cursor + index < end) {
697
+ int digit = pm_regexp_hex_digit_value(cursor[index]);
698
+ if (digit < 0 || (uint32_t) digit >= base) break;
699
+
700
+ value = value * base + (uint32_t) digit;
701
+ index++;
702
+ }
703
+
704
+ *length = index;
705
+ return value;
706
+ }
707
+
708
+ /**
709
+ * Read the decimal digit at the cursor the way the regular expression engine
710
+ * reads one, setting its width and value. Returns false if there is no digit.
711
+ *
712
+ * The engine reads each digit's value as its code point minus that of 0. That
713
+ * is right for 0 through 9. In an encoding whose characters are Unicode code
714
+ * points, other digits count too, with much bigger values, so even two
715
+ * fullwidth digits make a number that is too big for an interval.
716
+ */
717
+ static bool
718
+ pm_regexp_digit(const pm_regexp_parser_t *parser, const uint8_t *cursor, size_t *width, uint32_t *value) {
719
+ if (pm_char_is_decimal_digit(*cursor)) {
720
+ *width = 1;
721
+ *value = (uint32_t) (*cursor - '0');
722
+ return true;
723
+ }
724
+
725
+ if (*cursor < 0x80) return false;
726
+
727
+ *width = pm_encoding_char_width(parser->encoding, cursor, (ptrdiff_t) (parser->end - cursor));
728
+ if (*width == 0) return false;
729
+
730
+ int32_t codepoint = pm_encoding_unicode_codepoint(parser->encoding, cursor, *width);
731
+ if (codepoint < 0 || !pm_encoding_unicode_digit_p((uint32_t) codepoint, parser->parser->version)) return false;
732
+
733
+ *value = (uint32_t) codepoint - '0';
734
+ return true;
735
+ }
736
+
737
+ /**
738
+ * Add a digit to a number the way the regular expression engine does, which
739
+ * gives up as soon as the number would overflow an int. Returns false then.
740
+ */
741
+ static PRISM_INLINE bool
742
+ pm_regexp_number_append(uint32_t *number, uint32_t digit) {
743
+ if ((INT32_MAX - digit) / 10 < *number) return false;
744
+ *number = *number * 10 + digit;
745
+ return true;
746
+ }
747
+
748
+ /** The largest bound of an interval, like the 3 in a{3}. */
749
+ #define PM_REGEXP_INTERVAL_MAXIMUM 100000
750
+
751
+ /**
752
+ * Read the bound of an interval at the cursor, like the 3 in a{3}, and advance
753
+ * the cursor past its digits. Returns false if the bound is too big.
754
+ */
755
+ static bool
756
+ pm_regexp_parse_interval_bound(const pm_regexp_parser_t *parser, const uint8_t **cursor, uint32_t *bound) {
757
+ uint32_t value = 0;
758
+
759
+ while (*cursor < parser->end) {
760
+ size_t width;
761
+ uint32_t digit;
762
+
763
+ if (!pm_regexp_digit(parser, *cursor, &width, &digit)) break;
764
+ if (!pm_regexp_number_append(&value, digit)) return false;
765
+
766
+ *cursor += width;
767
+ }
768
+
769
+ *bound = value;
770
+ return value <= PM_REGEXP_INTERVAL_MAXIMUM;
771
+ }
772
+
773
+ /**
774
+ * The results of reading an interval.
775
+ */
776
+ typedef enum {
777
+ /** The interval is invalid, which has been reported. */
778
+ PM_REGEXP_INTERVAL_INVALID,
779
+
780
+ /** The { does not start an interval, so it is a character. */
781
+ PM_REGEXP_INTERVAL_NONE,
782
+
783
+ /** The interval is valid, and the cursor is past it. */
784
+ PM_REGEXP_INTERVAL_VALID
785
+ } pm_regexp_interval_t;
786
+
787
+ /**
788
+ * Read an interval, like {3}, {3,}, {,5}, or {3,5}. The cursor is just past its
789
+ * {. A bound that is too big is an error, even if the interval never closes. So
790
+ * is an upper bound below the lower one. Anything else that is not an interval,
791
+ * like {x} or {,}, is not an error: its { is just a character.
792
+ */
793
+ static pm_regexp_interval_t
794
+ pm_regexp_parse_interval(pm_regexp_parser_t *parser) {
795
+ const uint8_t *start = parser->cursor - 1;
796
+ const uint8_t *cursor = parser->cursor;
797
+ const uint8_t *end = parser->end;
798
+
799
+ uint32_t lower;
800
+ if (!pm_regexp_parse_interval_bound(parser, &cursor, &lower)) {
801
+ pm_regexp_parse_error(parser, start, cursor, "too big number for repeat range");
802
+ return PM_REGEXP_INTERVAL_INVALID;
803
+ }
804
+
805
+ bool has_lower = cursor != parser->cursor;
806
+ bool has_upper = true;
807
+ uint32_t upper = lower;
808
+
809
+ if (cursor < end && *cursor == ',') {
810
+ const uint8_t *digits = ++cursor;
811
+ if (!pm_regexp_parse_interval_bound(parser, &cursor, &upper)) {
812
+ pm_regexp_parse_error(parser, start, cursor, "too big number for repeat range");
813
+ return PM_REGEXP_INTERVAL_INVALID;
814
+ }
815
+
816
+ /* {,} has neither bound. */
817
+ if (cursor == digits) {
818
+ if (!has_lower) return PM_REGEXP_INTERVAL_NONE;
819
+ has_upper = false;
820
+ }
821
+ } else if (!has_lower) {
822
+ return PM_REGEXP_INTERVAL_NONE;
823
+ }
824
+
825
+ if (cursor == end || *cursor != '}') return PM_REGEXP_INTERVAL_NONE;
826
+ cursor++;
827
+
828
+ if (has_upper && lower > upper) {
829
+ pm_regexp_parse_error(parser, start, cursor, "upper is smaller than lower in repeat range");
830
+ return PM_REGEXP_INTERVAL_INVALID;
831
+ }
832
+
833
+ parser->cursor = cursor;
834
+ return PM_REGEXP_INTERVAL_VALID;
835
+ }
836
+
837
+ /**
838
+ * quantifier : star-quantifier
839
+ * | plus-quantifier
840
+ * | optional-quantifier
841
+ * | interval
842
+ * | <empty>
843
+ * ;
844
+ */
845
+ static bool
846
+ pm_regexp_parse_quantifier(pm_regexp_parser_t *parser) {
847
+ while (true) {
848
+ pm_regexp_skip_extended_whitespace(parser);
849
+ if (pm_regexp_char_is_eof(parser)) return true;
850
+
851
+ switch (*parser->cursor) {
852
+ case '*':
853
+ case '+':
854
+ case '?':
855
+ parser->cursor++;
856
+ break;
857
+ case '{':
858
+ parser->cursor++;
859
+ switch (pm_regexp_parse_interval(parser)) {
860
+ case PM_REGEXP_INTERVAL_INVALID:
861
+ return false;
862
+ case PM_REGEXP_INTERVAL_NONE:
863
+ /* The { is a character, which starts the next item. */
864
+ parser->cursor--;
865
+ return true;
866
+ case PM_REGEXP_INTERVAL_VALID:
867
+ break;
868
+ }
869
+ break;
870
+ default:
871
+ return true;
872
+ }
873
+ }
874
+ }
875
+
876
+ /**
877
+ * Property escape classification. Onigmo supports three tiers of property
878
+ * names depending on the encoding:
879
+ *
880
+ * - POSIX properties (Alnum, Alpha, ASCII, Blank, Cntrl, Digit, Graph, Lower,
881
+ * Print, Punct, Space, Upper, XDigit, Word): valid in all encodings.
882
+ * - Script properties (Hiragana, Katakana, Han, Latin, Greek, Cyrillic): valid
883
+ * in EUC-JP (/e), Windows-31J (/s), and UTF-8 (/u), but not ASCII-8BIT (/n).
884
+ * - Unicode-only properties (general categories like L, Ll, Lu, etc., plus
885
+ * Any, Assigned): valid only in UTF-8 (/u).
886
+ */
887
+ typedef enum {
888
+ PM_REGEXP_PROPERTY_POSIX,
889
+ PM_REGEXP_PROPERTY_SCRIPT,
890
+ PM_REGEXP_PROPERTY_UNICODE
891
+ } pm_regexp_property_type_t;
892
+
893
+ /**
894
+ * Classify a property name. The name may start with '^' for negation, which
895
+ * is skipped before matching.
896
+ */
897
+ static pm_regexp_property_type_t
898
+ pm_regexp_classify_property(const uint8_t *name, size_t length) {
899
+ // Skip leading '^' for negated properties like \p{^Hiragana}.
900
+ if (length > 0 && name[0] == '^') {
901
+ name++;
902
+ length--;
903
+ }
904
+
905
+ #define PM_REGEXP_CASECMP(str_) (pm_strncasecmp(name, (const uint8_t *) (str_), length) == 0)
906
+
907
+ switch (length) {
908
+ case 3:
909
+ if (PM_REGEXP_CASECMP("Han")) return PM_REGEXP_PROPERTY_SCRIPT;
910
+ break;
911
+ case 4:
912
+ if (PM_REGEXP_CASECMP("Word")) return PM_REGEXP_PROPERTY_POSIX;
913
+ break;
914
+ case 5:
915
+ /* Most properties are length 5, so dispatch on first character. */
916
+ switch (name[0] | 0x20) {
917
+ case 'a':
918
+ if (PM_REGEXP_CASECMP("Alnum")) return PM_REGEXP_PROPERTY_POSIX;
919
+ if (PM_REGEXP_CASECMP("Alpha")) return PM_REGEXP_PROPERTY_POSIX;
920
+ if (PM_REGEXP_CASECMP("ASCII")) return PM_REGEXP_PROPERTY_POSIX;
921
+ break;
922
+ case 'b':
923
+ if (PM_REGEXP_CASECMP("Blank")) return PM_REGEXP_PROPERTY_POSIX;
924
+ break;
925
+ case 'c':
926
+ if (PM_REGEXP_CASECMP("Cntrl")) return PM_REGEXP_PROPERTY_POSIX;
927
+ break;
928
+ case 'd':
929
+ if (PM_REGEXP_CASECMP("Digit")) return PM_REGEXP_PROPERTY_POSIX;
930
+ break;
931
+ case 'g':
932
+ if (PM_REGEXP_CASECMP("Graph")) return PM_REGEXP_PROPERTY_POSIX;
933
+ if (PM_REGEXP_CASECMP("Greek")) return PM_REGEXP_PROPERTY_SCRIPT;
934
+ break;
935
+ case 'l':
936
+ if (PM_REGEXP_CASECMP("Lower")) return PM_REGEXP_PROPERTY_POSIX;
937
+ if (PM_REGEXP_CASECMP("Latin")) return PM_REGEXP_PROPERTY_SCRIPT;
938
+ break;
939
+ case 'p':
940
+ if (PM_REGEXP_CASECMP("Print")) return PM_REGEXP_PROPERTY_POSIX;
941
+ if (PM_REGEXP_CASECMP("Punct")) return PM_REGEXP_PROPERTY_POSIX;
942
+ break;
943
+ case 's':
944
+ if (PM_REGEXP_CASECMP("Space")) return PM_REGEXP_PROPERTY_POSIX;
945
+ break;
946
+ case 'u':
947
+ if (PM_REGEXP_CASECMP("Upper")) return PM_REGEXP_PROPERTY_POSIX;
948
+ break;
949
+ }
950
+ break;
951
+ case 6:
952
+ if (PM_REGEXP_CASECMP("XDigit")) return PM_REGEXP_PROPERTY_POSIX;
953
+ break;
954
+ case 8:
955
+ if (PM_REGEXP_CASECMP("Hiragana")) return PM_REGEXP_PROPERTY_SCRIPT;
956
+ if (PM_REGEXP_CASECMP("Katakana")) return PM_REGEXP_PROPERTY_SCRIPT;
957
+ if (PM_REGEXP_CASECMP("Cyrillic")) return PM_REGEXP_PROPERTY_SCRIPT;
958
+ break;
959
+ }
960
+
961
+ #undef PM_REGEXP_CASECMP
962
+
963
+ // Everything else is Unicode-only (general categories, other scripts, etc.).
964
+ return PM_REGEXP_PROPERTY_UNICODE;
965
+ }
966
+
967
+ /**
968
+ * Check for and skip a `\p{...}` or `\P{...}` Unicode property escape. The
969
+ * cursor should be pointing at 'p' or 'P' when this is called. If a property
970
+ * escape is found, record it on the regexp parser and advance past the closing
971
+ * '}'.
972
+ *
973
+ * Properties are classified into three tiers (POSIX, script, Unicode-only) to
974
+ * determine which encoding modifiers they are valid with.
975
+ */
976
+ static bool
977
+ pm_regexp_parse_property_escape(pm_regexp_parser_t *parser) {
978
+ PRISM_ASSERT(*parser->cursor == 'p' || *parser->cursor == 'P');
979
+
980
+ if (parser->cursor + 1 >= parser->end || parser->cursor[1] != '{') {
981
+ // Not a property escape, just skip the single character after '\'.
982
+ parser->cursor++;
983
+ return false;
984
+ }
985
+
986
+ /* Read the name the way Onigmo's fetch_char_property_to_ctype does: up to
987
+ * a }, after the ^ that negates the property. A (, ), {, or | stops the
988
+ * name, and so does the end of the pattern, after which the name is
989
+ * quoted without the last character read. An empty name is no property. */
990
+ parser->cursor += 2;
991
+ if (parser->cursor < parser->end && *parser->cursor == '^') parser->cursor++;
992
+
993
+ const uint8_t *name_start = parser->cursor;
994
+ const uint8_t *previous = parser->cursor;
995
+
996
+ while (parser->cursor < parser->end) {
997
+ previous = parser->cursor;
998
+ uint8_t byte = *parser->cursor;
999
+ pm_regexp_skip_char(parser);
1000
+
1001
+ if (byte == '}') {
1002
+ size_t name_length = (size_t) (previous - name_start);
1003
+ if (name_length == 0) break;
1004
+
1005
+ pm_regexp_property_type_t type = pm_regexp_classify_property(name_start, name_length);
1006
+
1007
+ // Track the first non-POSIX property name (for /n error messages).
1008
+ if (type >= PM_REGEXP_PROPERTY_SCRIPT && parser->property_name == NULL) {
1009
+ parser->property_name = name_start;
1010
+ parser->property_name_length = name_length;
1011
+ }
1012
+
1013
+ // Track the first Unicode-only property name (for /e, /s error messages).
1014
+ if (type == PM_REGEXP_PROPERTY_UNICODE && parser->unicode_property_name == NULL) {
1015
+ parser->unicode_property_name = name_start;
1016
+ parser->unicode_property_name_length = name_length;
1017
+ }
1018
+
1019
+ return true;
1020
+ }
1021
+
1022
+ if (byte == '(' || byte == ')' || byte == '{' || byte == '|') break;
1023
+ }
1024
+
1025
+ pm_buffer_t buffer = { 0 };
1026
+ const char *message = "invalid character property name {";
1027
+ pm_buffer_append_string(&buffer, message, strlen(message));
1028
+ pm_buffer_append_string(&buffer, (const char *) name_start, (size_t) (previous - name_start));
1029
+ pm_buffer_append_byte(&buffer, '}');
1030
+ pm_buffer_append_byte(&buffer, '\0');
1031
+
1032
+ pm_regexp_parse_error(parser, name_start, previous, pm_buffer_value(&buffer));
1033
+ pm_buffer_cleanup(&buffer);
1034
+
1035
+ return true;
1036
+ }
1037
+
1038
+ /**
1039
+ * Skip a \u escape, in either its \uHHHH or its \u{...} form. The cursor should
1040
+ * be pointing at the character after the 'u' when this is called. Its code
1041
+ * points were checked when the escapes of the content were read, before the
1042
+ * pattern is parsed, so this only finds where the escape ends.
1043
+ */
1044
+ static void
1045
+ pm_regexp_parse_unicode_escape(pm_regexp_parser_t *parser) {
1046
+ if (pm_regexp_char_accept(parser, '{')) {
1047
+ while (!pm_regexp_char_is_eof(parser) && *parser->cursor != '}') parser->cursor++;
1048
+ pm_regexp_char_accept(parser, '}');
1049
+ } else {
1050
+ for (int index = 0; index < 4 && !pm_regexp_char_is_eof(parser) && pm_char_is_hexadecimal_digit(*parser->cursor); index++) {
1051
+ parser->cursor++;
1052
+ }
1053
+ }
1054
+ }
1055
+
1056
+ /**
1057
+ * Skip the digits of a \x escape, of which there are at most two. The cursor
1058
+ * should be pointing at the character after 'x'.
1059
+ */
1060
+ static void
1061
+ pm_regexp_parse_hex_escape(pm_regexp_parser_t *parser) {
1062
+ for (int index = 0; index < 2 && !pm_regexp_char_is_eof(parser) && pm_char_is_hexadecimal_digit(*parser->cursor); index++) {
1063
+ parser->cursor++;
1064
+ }
1065
+ }
1066
+
1067
+ /**
1068
+ * Report an error about the name of a group, like "invalid group name <1x>",
1069
+ * that quotes the name, which runs from start to end.
1070
+ */
1071
+ static void
1072
+ pm_regexp_parse_name_error(pm_regexp_parser_t *parser, const uint8_t *start, const uint8_t *end, const char *message) {
1073
+ pm_buffer_t buffer = { 0 };
1074
+ pm_buffer_append_string(&buffer, message, strlen(message));
1075
+ pm_buffer_append_string(&buffer, " <", 2);
1076
+ pm_buffer_append_string(&buffer, (const char *) start, (size_t) (end - start));
1077
+ pm_buffer_append_byte(&buffer, '>');
1078
+ pm_buffer_append_byte(&buffer, '\0');
1079
+
1080
+ pm_regexp_parse_error(parser, start, end, pm_buffer_value(&buffer));
1081
+ pm_buffer_cleanup(&buffer);
1082
+ }
1083
+
1084
+ /**
1085
+ * A reference to a group, by its number or its name, as in \k<1>, \k<n>, \g<n>,
1086
+ * or the condition of (?(1)a|b).
1087
+ */
1088
+ typedef struct {
1089
+ /** The start of the number or name as it is written. */
1090
+ const uint8_t *start;
1091
+
1092
+ /** The end of the number or name as it is written. */
1093
+ const uint8_t *end;
1094
+
1095
+ /**
1096
+ * The number of the group, which is negative when it counts back from the
1097
+ * reference, as in \k<-1>, or 0 when the group is named.
1098
+ */
1099
+ int32_t number;
1100
+ } pm_regexp_reference_t;
1101
+
1102
+ /**
1103
+ * Whether the character at the cursor is a word character, for the messages
1104
+ * about the characters of a group number. Any character that is not ASCII
1105
+ * counts as one. That is exact for the encodings that are not Unicode, while in
1106
+ * UTF-8 a symbol that is not a word character gets the message of one.
1107
+ */
1108
+ static bool
1109
+ pm_regexp_word_char_p(const pm_regexp_parser_t *parser) {
1110
+ uint8_t byte = *parser->cursor;
1111
+ return byte >= 0x80 || pm_encoding_ascii_alnum_p(byte) || byte == '_';
1112
+ }
1113
+
1114
+ /**
1115
+ * Read the number that the digits from start to end spell, the way the engine
1116
+ * reads them. Returns false if the number would overflow an int.
1117
+ */
1118
+ static bool
1119
+ pm_regexp_reference_number(const pm_regexp_parser_t *parser, const uint8_t *start, const uint8_t *end, uint32_t *number) {
1120
+ *number = 0;
1121
+
1122
+ while (start < end) {
1123
+ size_t width;
1124
+ uint32_t digit;
1125
+ if (!pm_regexp_digit(parser, start, &width, &digit)) break;
1126
+ if (!pm_regexp_number_append(number, digit)) return false;
1127
+ start += width;
1128
+ }
1129
+
1130
+ return true;
1131
+ }
1132
+
1133
+ /**
1134
+ * Parse a reference to a group by its number or its name, with the cursor after
1135
+ * the character that opens it, the way Onigmo's fetch_name reads a reference,
1136
+ * and consume the close character that ends it. This reads the group of a
1137
+ * call, as in \g<n>, and the number of the condition of a conditional group,
1138
+ * as in (?(1)a|b), whose close character is the ). A number must be all
1139
+ * digits, after an optional -, and must not be 0. Returns false after an
1140
+ * error.
1141
+ */
1142
+ static bool
1143
+ pm_regexp_parse_reference(pm_regexp_parser_t *parser, uint8_t close, pm_regexp_reference_t *reference) {
1144
+ const uint8_t *start = parser->cursor;
1145
+
1146
+ if (parser->cursor >= parser->end || *parser->cursor == close) {
1147
+ pm_regexp_parse_error(parser, start, parser->cursor, "group name is empty");
1148
+ return false;
1149
+ }
1150
+
1151
+ /* Whether the reference is a name, a number, or a - that no digit has
1152
+ * followed yet. */
1153
+ enum { NAME, NUMBER, SIGN } kind = NAME;
1154
+ const uint8_t *digits = start;
1155
+
1156
+ size_t width;
1157
+ uint32_t digit;
1158
+ if (pm_regexp_digit(parser, parser->cursor, &width, &digit)) {
1159
+ kind = NUMBER;
1160
+ } else if (*parser->cursor == '-') {
1161
+ kind = SIGN;
1162
+ digits = parser->cursor + 1;
1163
+ }
1164
+
1165
+ pm_regexp_skip_char(parser);
1166
+
1167
+ const uint8_t *name_end = parser->end;
1168
+ const char *message = NULL;
1169
+ bool closed = false;
1170
+
1171
+ while (parser->cursor < parser->end) {
1172
+ name_end = parser->cursor;
1173
+ uint8_t byte = *parser->cursor;
1174
+
1175
+ if (byte == close || byte == ')') {
1176
+ pm_regexp_skip_char(parser);
1177
+
1178
+ if (kind == SIGN) {
1179
+ message = "invalid group name";
1180
+ } else {
1181
+ closed = (byte == close);
1182
+ }
1183
+ break;
1184
+ }
1185
+
1186
+ if (kind != NAME) {
1187
+ if (pm_regexp_digit(parser, parser->cursor, &width, &digit)) {
1188
+ kind = NUMBER;
1189
+ parser->cursor += width;
1190
+ continue;
1191
+ }
1192
+
1193
+ message = pm_regexp_word_char_p(parser) ? "invalid group name" : "invalid char in group name";
1194
+ pm_regexp_skip_char(parser);
1195
+ break;
1196
+ }
1197
+
1198
+ pm_regexp_skip_char(parser);
1199
+ }
1200
+
1201
+ if (message != NULL) {
1202
+ /* After an error, the engine still looks for the character that would
1203
+ * end the name, to quote the name up to it, or to the end of the
1204
+ * pattern when the name runs there. */
1205
+ while (parser->cursor < parser->end) {
1206
+ name_end = parser->cursor;
1207
+ uint8_t byte = *parser->cursor;
1208
+ pm_regexp_skip_char(parser);
1209
+ if (byte == close || byte == ')') break;
1210
+ }
1211
+
1212
+ if (parser->cursor >= parser->end) name_end = parser->end;
1213
+ pm_regexp_parse_name_error(parser, start, name_end, message);
1214
+ return false;
1215
+ }
1216
+
1217
+ if (!closed) {
1218
+ pm_regexp_parse_name_error(parser, start, parser->end, "invalid group name");
1219
+ return false;
1220
+ }
1221
+
1222
+ uint32_t number = 0;
1223
+ if (kind != NAME) {
1224
+ if (!pm_regexp_reference_number(parser, digits, name_end, &number)) {
1225
+ pm_regexp_parse_error(parser, start, name_end, "too big number");
1226
+ return false;
1227
+ }
1228
+
1229
+ if (number == 0) {
1230
+ pm_regexp_parse_name_error(parser, start, name_end, "invalid group name");
1231
+ return false;
1232
+ }
1233
+ }
1234
+
1235
+ reference->start = start;
1236
+ reference->end = name_end;
1237
+ reference->number = (kind == SIGN || *start == '-') ? -((int32_t) number) : (int32_t) number;
1238
+ return true;
1239
+ }
1240
+
1241
+ /**
1242
+ * Parse a reference to a group by its number or its name, with the cursor after
1243
+ * the < or ' that opens it, the way Onigmo's fetch_name_with_level reads it,
1244
+ * and consume the close character that ends it. This reads the group of a
1245
+ * backreference, as in \k<n>, and the name of the condition of a conditional
1246
+ * group, as in (?(<n>)a|b). A reference can end with a level of recursion, as
1247
+ * in \k<n+1>. Returns false after an error.
1248
+ */
1249
+ static bool
1250
+ pm_regexp_parse_reference_with_level(pm_regexp_parser_t *parser, uint8_t close, pm_regexp_reference_t *reference) {
1251
+ const uint8_t *start = parser->cursor;
1252
+
1253
+ if (parser->cursor >= parser->end || *parser->cursor == close) {
1254
+ pm_regexp_parse_error(parser, start, parser->cursor, "group name is empty");
1255
+ return false;
1256
+ }
1257
+
1258
+ /* Whether the reference is a name, a number, or a - that no digit has
1259
+ * followed yet. */
1260
+ enum { NAME, NUMBER, SIGN } kind = NAME;
1261
+ const uint8_t *digits = start;
1262
+
1263
+ size_t width;
1264
+ uint32_t digit;
1265
+ if (pm_regexp_digit(parser, parser->cursor, &width, &digit)) {
1266
+ kind = NUMBER;
1267
+ } else if (*parser->cursor == '-') {
1268
+ kind = SIGN;
1269
+ digits = parser->cursor + 1;
1270
+ }
1271
+
1272
+ bool negative = (kind == SIGN);
1273
+ pm_regexp_skip_char(parser);
1274
+
1275
+ const uint8_t *name_end = parser->end;
1276
+ const char *message = NULL;
1277
+ uint8_t terminator = 0;
1278
+
1279
+ while (parser->cursor < parser->end) {
1280
+ name_end = parser->cursor;
1281
+ uint8_t byte = *parser->cursor;
1282
+
1283
+ if (byte == close || byte == ')' || byte == '+' || byte == '-') {
1284
+ pm_regexp_skip_char(parser);
1285
+ terminator = byte;
1286
+ if (kind == SIGN) message = "invalid group name";
1287
+ break;
1288
+ }
1289
+
1290
+ if (kind != NAME) {
1291
+ if (pm_regexp_digit(parser, parser->cursor, &width, &digit)) {
1292
+ kind = NUMBER;
1293
+ parser->cursor += width;
1294
+ continue;
1295
+ }
1296
+
1297
+ /* The rest of the name is still read, as a name. */
1298
+ message = "invalid group name";
1299
+ kind = NAME;
1300
+ }
1301
+
1302
+ pm_regexp_skip_char(parser);
1303
+ }
1304
+
1305
+ if (message == NULL && terminator != close) {
1306
+ bool valid = false;
1307
+
1308
+ if (terminator == '+' || terminator == '-') {
1309
+ if (parser->cursor >= parser->end) {
1310
+ pm_regexp_parse_name_error(parser, start, name_end, "invalid char in group name");
1311
+ return false;
1312
+ }
1313
+
1314
+ if (pm_regexp_digit(parser, parser->cursor, &width, &digit)) {
1315
+ uint32_t level = 0;
1316
+
1317
+ while (parser->cursor < parser->end && pm_regexp_digit(parser, parser->cursor, &width, &digit)) {
1318
+ if (!pm_regexp_number_append(&level, digit)) {
1319
+ pm_regexp_parse_error(parser, start, parser->cursor, "too big number");
1320
+ return false;
1321
+ }
1322
+ parser->cursor += width;
1323
+ }
1324
+
1325
+ if (parser->cursor < parser->end) {
1326
+ uint8_t byte = *parser->cursor;
1327
+ pm_regexp_skip_char(parser);
1328
+ valid = (byte == close);
1329
+ }
1330
+ }
1331
+ }
1332
+
1333
+ if (!valid) {
1334
+ pm_regexp_parse_name_error(parser, start, parser->end, "invalid group name");
1335
+ return false;
1336
+ }
1337
+ }
1338
+
1339
+ if (message != NULL) {
1340
+ pm_regexp_parse_name_error(parser, start, name_end, message);
1341
+ return false;
1342
+ }
1343
+
1344
+ uint32_t number = 0;
1345
+ if (kind == NUMBER) {
1346
+ if (!pm_regexp_reference_number(parser, digits, name_end, &number)) {
1347
+ pm_regexp_parse_error(parser, start, name_end, "too big number");
1348
+ return false;
1349
+ }
1350
+
1351
+ if (number == 0) {
1352
+ pm_regexp_parse_name_error(parser, start, parser->end, "invalid group name");
1353
+ return false;
1354
+ }
1355
+ }
1356
+
1357
+ reference->start = start;
1358
+ reference->end = name_end;
1359
+ reference->number = negative ? -((int32_t) number) : (int32_t) number;
1360
+ return true;
1361
+ }
1362
+
1363
+ /**
1364
+ * Count the groups with this name that have been opened so far.
1365
+ */
1366
+ static size_t
1367
+ pm_regexp_name_count(pm_regexp_parser_t *parser, const uint8_t *start, const uint8_t *end) {
1368
+ pm_regexp_names_t *names = &parser->names;
1369
+ size_t length = (size_t) (end - start);
1370
+
1371
+ /* Small capture lists are cheaper to scan than to index. */
1372
+ if (names->size < 8) {
1373
+ size_t count = 0;
1374
+ for (size_t index = 0; index < names->size; index++) {
1375
+ const pm_regexp_name_t *name = &names->values[index];
1376
+ if (name->length == length && memcmp(name->start, start, length) == 0) count++;
1377
+ }
1378
+ return count;
1379
+ }
1380
+
1381
+ if (names->bindings == NULL) {
1382
+ pm_arena_t *arena = &parser->parser->scratch_arena;
1383
+ for (size_t index = 0; index < names->size; index++) {
1384
+ pm_regexp_name_bind(arena, names, index);
1385
+ }
1386
+ }
1387
+
1388
+ pm_regexp_name_t name = { .start = start, .length = length };
1389
+ return pm_regexp_name_binding(names, name, pm_xxh3(start, length))->count;
1390
+ }
1391
+
1392
+ /**
1393
+ * Check a reference that the engine resolves while it parses, against the
1394
+ * groups opened so far. A name must already be defined, as in (?<n>a)\k<n>,
1395
+ * and a number that counts back, as in (a)\k<-1>, must land on a group. A
1396
+ * number that counts forward is checked once the pattern is parsed. Returns
1397
+ * false after an error.
1398
+ */
1399
+ static bool
1400
+ pm_regexp_check_reference(pm_regexp_parser_t *parser, const pm_regexp_reference_t *reference) {
1401
+ if (reference->number == 0) {
1402
+ if (pm_regexp_name_count(parser, reference->start, reference->end) > 0) return true;
1403
+
1404
+ pm_buffer_t buffer = { 0 };
1405
+ pm_buffer_append_string(&buffer, "undefined name <", 16);
1406
+ pm_buffer_append_string(&buffer, (const char *) reference->start, (size_t) (reference->end - reference->start));
1407
+ pm_buffer_append_string(&buffer, "> reference", 11);
1408
+ pm_buffer_append_byte(&buffer, '\0');
1409
+
1410
+ pm_regexp_parse_error(parser, reference->start, reference->end, pm_buffer_value(&buffer));
1411
+ pm_buffer_cleanup(&buffer);
1412
+ return false;
1413
+ }
1414
+
1415
+ if (reference->number < 0 && (int64_t) parser->groups + 1 + reference->number <= 0) {
1416
+ pm_regexp_parse_error(parser, reference->start, reference->end, "invalid backref number/name");
1417
+ return false;
1418
+ }
1419
+
1420
+ return true;
1421
+ }
1422
+
1423
+ /**
1424
+ * Check a call of a group that counts, as in \g<-1> or \g<+1>, against the
1425
+ * groups opened so far, the way the engine does while it parses. A call that
1426
+ * counts back must land on a group. Returns false after an error.
1427
+ */
1428
+ static bool
1429
+ pm_regexp_check_relative_call(pm_regexp_parser_t *parser, const pm_regexp_reference_t *reference, bool forward) {
1430
+ if (reference->number >= 0 && !forward) return true;
1431
+
1432
+ int64_t number = reference->number > 0 ? reference->number - 1 : reference->number;
1433
+ if ((int64_t) parser->groups + 1 + number > 0) return true;
1434
+
1435
+ pm_regexp_parse_error(parser, reference->start, reference->end, "invalid backref number/name");
1436
+ return false;
1437
+ }
1438
+
1439
+ /**
1440
+ * Keep a backreference or condition by number to check once the whole pattern
1441
+ * is parsed. One that counts back, as in \k<-1>, is to the group that many
1442
+ * before the groups opened so far. A reference by name was already checked.
1443
+ */
1444
+ static void
1445
+ pm_regexp_defer_reference(pm_regexp_parser_t *parser, const pm_regexp_reference_t *reference, pm_regexp_deferred_type_t type) {
1446
+ if (reference->number == 0) return;
1447
+
1448
+ int64_t number = reference->number;
1449
+ if (number < 0) number += (int64_t) parser->groups + 1;
1450
+ pm_regexp_defer(parser, type, reference->start, reference->end, number);
1451
+ }
1452
+
1453
+ /**
1454
+ * Report an error that quotes a name, like "undefined group <2> reference",
1455
+ * with the given text before and after the name.
1456
+ */
1457
+ static void
1458
+ pm_regexp_parse_quoted_error(pm_regexp_parser_t *parser, const uint8_t *start, const uint8_t *end, const char *before, const char *after) {
1459
+ pm_buffer_t buffer = { 0 };
1460
+ pm_buffer_append_string(&buffer, before, strlen(before));
1461
+ pm_buffer_append_string(&buffer, (const char *) start, (size_t) (end - start));
1462
+ pm_buffer_append_string(&buffer, after, strlen(after));
1463
+ pm_buffer_append_byte(&buffer, '\0');
1464
+
1465
+ pm_regexp_parse_error(parser, start, end, pm_buffer_value(&buffer));
1466
+ pm_buffer_cleanup(&buffer);
1467
+ }
1468
+
1469
+ /**
1470
+ * Check the references to groups that wait for the end of the pattern, the way
1471
+ * the engine checks them when it compiles the pattern. Numbered references
1472
+ * and calls are restricted when named groups are present, and numbers must
1473
+ * refer to existing groups. A call by name must name exactly one group.
1474
+ */
1475
+ static void
1476
+ pm_regexp_check_deferreds(pm_regexp_parser_t *parser) {
1477
+ bool named = parser->names.size > 0;
1478
+
1479
+ for (size_t index = 0; index < parser->deferreds.size; index++) {
1480
+ const pm_regexp_deferred_t *deferred = &parser->deferreds.values[index];
1481
+
1482
+ switch (deferred->type) {
1483
+ case PM_REGEXP_DEFERRED_NUMBER:
1484
+ case PM_REGEXP_DEFERRED_CONDITION_NUMBER: {
1485
+ bool out_of_range = deferred->number > (int64_t) parser->groups;
1486
+ /* With both named and unnamed captures, Onigmo checks
1487
+ * condition bounds while renumbering the groups, before
1488
+ * rejecting numbered conditions. */
1489
+ bool remap_error = deferred->type == PM_REGEXP_DEFERRED_CONDITION_NUMBER &&
1490
+ parser->groups > parser->names.size && out_of_range;
1491
+ if (named && !remap_error) {
1492
+ pm_regexp_parse_error(parser, deferred->start, deferred->end, "numbered backref/call is not allowed. (use name)");
1493
+ } else if (out_of_range) {
1494
+ pm_regexp_parse_error(parser, deferred->start, deferred->end, "invalid backref number/name");
1495
+ }
1496
+ break;
1497
+ }
1498
+ case PM_REGEXP_DEFERRED_NAMED_NUMBER:
1499
+ if (deferred->number > (int64_t) parser->groups) {
1500
+ pm_regexp_parse_error(parser, deferred->start, deferred->end, "invalid backref number/name");
1501
+ }
1502
+ break;
1503
+ case PM_REGEXP_DEFERRED_CALL_NUMBER:
1504
+ if (named) {
1505
+ pm_regexp_parse_error(parser, deferred->start, deferred->end, "numbered backref/call is not allowed. (use name)");
1506
+ } else if (deferred->number > (int64_t) parser->groups) {
1507
+ pm_regexp_parse_quoted_error(parser, deferred->start, deferred->end, "undefined group <", "> reference");
1508
+ }
1509
+ break;
1510
+ case PM_REGEXP_DEFERRED_CALL_NAME: {
1511
+ size_t count = pm_regexp_name_count(parser, deferred->start, deferred->end);
1512
+
1513
+ if (count == 0) {
1514
+ pm_regexp_parse_quoted_error(parser, deferred->start, deferred->end, "undefined name <", "> reference");
1515
+ } else if (count > 1) {
1516
+ pm_regexp_parse_quoted_error(parser, deferred->start, deferred->end, "multiplex definition name <", "> call");
1517
+ }
1518
+ break;
1519
+ }
1520
+ }
1521
+ }
1522
+ }
1523
+
1524
+ /** The largest number of a backreference written as a backslash and digits. */
1525
+ #define PM_REGEXP_BACKREF_MAXIMUM 1000
1526
+
1527
+ /**
1528
+ * Parse a backslash followed by a digit from 1 to 9, with the cursor on the
1529
+ * digit, the way Onigmo's fetch_token reads it. The digits are a backreference
1530
+ * when their number is at most 9 or at most the number of groups opened so
1531
+ * far, as in (a)\1. Otherwise an 8 or 9 is that character, and other digits
1532
+ * start an octal escape of up to three digits.
1533
+ */
1534
+ static void
1535
+ pm_regexp_parse_numbered_backref(pm_regexp_parser_t *parser) {
1536
+ const uint8_t *start = parser->cursor;
1537
+ uint32_t number = 0;
1538
+ bool too_big = false;
1539
+
1540
+ while (parser->cursor < parser->end) {
1541
+ size_t width;
1542
+ uint32_t digit;
1543
+ if (!pm_regexp_digit(parser, parser->cursor, &width, &digit)) break;
1544
+ if (!pm_regexp_number_append(&number, digit)) too_big = true;
1545
+ parser->cursor += width;
1546
+ }
1547
+
1548
+ if (!too_big && number <= PM_REGEXP_BACKREF_MAXIMUM && (number <= 9 || number <= parser->groups)) {
1549
+ pm_regexp_defer(parser, PM_REGEXP_DEFERRED_NUMBER, start, parser->cursor, number);
1550
+ return;
1551
+ }
1552
+
1553
+ parser->cursor = start;
1554
+ if (*parser->cursor == '8' || *parser->cursor == '9') {
1555
+ parser->cursor++;
1556
+ return;
1557
+ }
1558
+
1559
+ for (int index = 0; index < 3 && parser->cursor < parser->end && *parser->cursor >= '0' && *parser->cursor <= '7'; index++) {
1560
+ parser->cursor++;
1561
+ }
1562
+ }
1563
+
1564
+ /**
1565
+ * Parse a backslash escape sequence in a regexp, handling \u (unicode),
1566
+ * \p/\P (property), \x (hex), and other single-character escapes. The lexer
1567
+ * writes each \M-, \C-, and \c escape in the content as the \x escape of its
1568
+ * byte, so those forms never reach here.
1569
+ */
1570
+ static void
1571
+ pm_regexp_parse_backslash_escape(pm_regexp_parser_t *parser) {
1572
+ if (pm_regexp_char_is_eof(parser)) return;
1573
+
1574
+ switch (*parser->cursor) {
1575
+ case 'u':
1576
+ parser->cursor++; // skip 'u'
1577
+ pm_regexp_parse_unicode_escape(parser);
1578
+ break;
1579
+ case 'p':
1580
+ case 'P':
1581
+ pm_regexp_parse_property_escape(parser);
1582
+ break;
1583
+ case 'x':
1584
+ parser->cursor++; // skip 'x'
1585
+ pm_regexp_parse_hex_escape(parser);
1586
+ break;
1587
+ case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
1588
+ pm_regexp_parse_numbered_backref(parser);
1589
+ break;
1590
+ case 'k': {
1591
+ /* A backreference by number or name, as in \k<n> or \k'n'. Without
1592
+ * a < or ' after it, the k is a character. */
1593
+ parser->cursor++;
1594
+ if (parser->cursor >= parser->end || (*parser->cursor != '<' && *parser->cursor != '\'')) break;
1595
+
1596
+ uint8_t close = (*parser->cursor++ == '<') ? '>' : '\'';
1597
+ pm_regexp_reference_t reference;
1598
+ if (pm_regexp_parse_reference_with_level(parser, close, &reference) && pm_regexp_check_reference(parser, &reference)) {
1599
+ pm_regexp_defer_reference(parser, &reference, PM_REGEXP_DEFERRED_NUMBER);
1600
+ }
1601
+ break;
1602
+ }
1603
+ case 'g': {
1604
+ /* A call of a group by number or name, as in \g<n> or \g'n'.
1605
+ * Without a < or ' after it, the g is a character. */
1606
+ parser->cursor++;
1607
+ if (parser->cursor >= parser->end || (*parser->cursor != '<' && *parser->cursor != '\'')) break;
1608
+
1609
+ uint8_t close = (*parser->cursor++ == '<') ? '>' : '\'';
1610
+
1611
+ /* \g<0> calls the whole pattern. A 0 or + before anything else is
1612
+ * dropped, so \g<01> calls group 1 and \g<+1> counts forward. */
1613
+ bool forward = false;
1614
+ if (parser->cursor < parser->end && *parser->cursor == '0') {
1615
+ parser->cursor++;
1616
+ if (parser->cursor < parser->end && *parser->cursor == close) {
1617
+ parser->cursor++;
1618
+ break;
1619
+ }
1620
+ } else if (parser->cursor < parser->end && *parser->cursor == '+') {
1621
+ parser->cursor++;
1622
+ forward = true;
1623
+ }
1624
+
1625
+ pm_regexp_reference_t reference;
1626
+ if (pm_regexp_parse_reference(parser, close, &reference) && pm_regexp_check_relative_call(parser, &reference, forward)) {
1627
+ if (reference.number == 0 && !forward) {
1628
+ pm_regexp_defer(parser, PM_REGEXP_DEFERRED_CALL_NAME, reference.start, reference.end, 0);
1629
+ } else {
1630
+ /* A call that counts is to the group that many after the
1631
+ * groups opened so far, or before them for a - . */
1632
+ int64_t number = reference.number;
1633
+ if (forward || number < 0) {
1634
+ if (number > 0) number--;
1635
+ number += (int64_t) parser->groups + 1;
1636
+ }
1637
+ pm_regexp_defer(parser, PM_REGEXP_DEFERRED_CALL_NUMBER, reference.start, reference.end, number);
1638
+ }
1639
+ }
1640
+ break;
1641
+ }
1642
+ default:
1643
+ parser->cursor++;
1644
+ break;
1645
+ }
1646
+ }
1647
+
1648
+ /**
1649
+ * Read the character at the cursor and return its value, which is its bytes
1650
+ * joined into one number. For every supported encoding, these numbers order
1651
+ * characters the same way as the code points that the regular expression
1652
+ * engine compares. An invalid byte, which the lexer has already reported, is
1653
+ * read as a character of its own.
1654
+ */
1655
+ static uint32_t
1656
+ pm_regexp_parse_char_value(pm_regexp_parser_t *parser) {
1657
+ const uint8_t *cursor = parser->cursor;
1658
+ size_t width = 1;
1659
+
1660
+ if (*cursor >= 0x80) {
1661
+ width = pm_encoding_char_width(parser->encoding, cursor, (ptrdiff_t) (parser->end - cursor));
1662
+ if (width == 0) width = 1;
1663
+ }
1664
+
1665
+ uint32_t value = 0;
1666
+ for (size_t index = 0; index < width; index++) value = (value << 8) | cursor[index];
1667
+
1668
+ parser->cursor += width;
1669
+ return value;
1670
+ }
1671
+
1672
+ /**
1673
+ * The kinds of tokens in a character class.
1674
+ */
1675
+ typedef enum {
1676
+ /** The end of the pattern, before the class is closed. */
1677
+ PM_REGEXP_CLASS_TOKEN_EOF,
1678
+
1679
+ /** A character, written as itself or as an escape. */
1680
+ PM_REGEXP_CLASS_TOKEN_CHAR,
1681
+
1682
+ /** A set of characters, like \d or \p{Alpha}. */
1683
+ PM_REGEXP_CLASS_TOKEN_SET,
1684
+
1685
+ /** The ] that closes the class. */
1686
+ PM_REGEXP_CLASS_TOKEN_CLOSE,
1687
+
1688
+ /** The - between the ends of a range. */
1689
+ PM_REGEXP_CLASS_TOKEN_RANGE,
1690
+
1691
+ /** The && between two classes that are intersected. */
1692
+ PM_REGEXP_CLASS_TOKEN_AND,
1693
+
1694
+ /** A [ that opens a class nested in this one. */
1695
+ PM_REGEXP_CLASS_TOKEN_OPEN,
1696
+
1697
+ /** A [: that is followed by :], so may open a bracket like [:alpha:]. */
1698
+ PM_REGEXP_CLASS_TOKEN_POSIX_OPEN
1699
+ } pm_regexp_class_token_type_t;
1700
+
1701
+ /**
1702
+ * A token in a character class.
1703
+ */
1704
+ typedef struct {
1705
+ /** The kind of token. */
1706
+ pm_regexp_class_token_type_t type;
1707
+
1708
+ /** Where the token starts in the pattern. */
1709
+ const uint8_t *start;
1710
+
1711
+ /** The value of a character, as pm_regexp_parse_char_value reads it. */
1712
+ uint32_t value;
1713
+
1714
+ /** Whether a character is written as an escape. */
1715
+ bool escaped;
1716
+ } pm_regexp_class_token_t;
1717
+
1718
+ /**
1719
+ * Whether a [: in a character class is followed by :] before the class could
1720
+ * be closed. The cursor is just past the colon. A ] that comes first closes
1721
+ * the class instead, unless it is escaped.
1722
+ */
1723
+ static bool
1724
+ pm_regexp_posix_bracket_close_p(const pm_regexp_parser_t *parser, const uint8_t *cursor) {
1725
+ bool escaped = false;
1726
+
1727
+ while (cursor < parser->end) {
1728
+ if (escaped) {
1729
+ escaped = false;
1730
+ } else if (*cursor == ':') {
1731
+ if (cursor + 1 < parser->end && cursor[1] == ']') return true;
1732
+ } else if (*cursor == ']') {
1733
+ return false;
1734
+ } else if (*cursor == '\\') {
1735
+ escaped = true;
1736
+ }
1737
+
1738
+ size_t width = 1;
1739
+ if (*cursor >= 0x80) {
1740
+ width = pm_encoding_char_width(parser->encoding, cursor, (ptrdiff_t) (parser->end - cursor));
1741
+ if (width == 0) width = 1;
1742
+ }
1743
+ cursor += width;
1744
+ }
1745
+
1746
+ return false;
1747
+ }
1748
+
1749
+ /**
1750
+ * Read an escape in a character class. The cursor is just past the backslash.
1751
+ *
1752
+ * The lexer writes each \M-, \C-, and \c escape as the \x escape of its byte,
1753
+ * and the preprocessor writes each \u escape as a \x escape or as its bytes, so
1754
+ * those forms never reach here.
1755
+ */
1756
+ static void
1757
+ pm_regexp_class_token_escape(pm_regexp_parser_t *parser, pm_regexp_class_token_t *token) {
1758
+ token->type = PM_REGEXP_CLASS_TOKEN_CHAR;
1759
+ token->escaped = true;
1760
+
1761
+ /* A backslash at the end of the pattern was already reported when the
1762
+ * escapes were read. */
1763
+ if (parser->cursor >= parser->end) {
1764
+ token->value = '\\';
1765
+ return;
1766
+ }
1767
+
1768
+ uint32_t length;
1769
+ switch (*parser->cursor) {
1770
+ case 'w': case 'W': case 'd': case 'D': case 's': case 'S': case 'h': case 'H':
1771
+ parser->cursor++;
1772
+ token->type = PM_REGEXP_CLASS_TOKEN_SET;
1773
+ return;
1774
+ case 'p': case 'P':
1775
+ if (pm_regexp_parse_property_escape(parser)) {
1776
+ token->type = PM_REGEXP_CLASS_TOKEN_SET;
1777
+ } else {
1778
+ token->value = parser->cursor[-1];
1779
+ }
1780
+ return;
1781
+ case 'x':
1782
+ parser->cursor++;
1783
+ token->value = pm_regexp_scan_digits(parser->cursor, parser->end, 2, 16, &length);
1784
+ parser->cursor += length;
1785
+ return;
1786
+ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7':
1787
+ token->value = pm_regexp_scan_digits(parser->cursor, parser->end, 3, 8, &length);
1788
+ parser->cursor += length;
1789
+ return;
1790
+ case 'n': parser->cursor++; token->value = '\n'; return;
1791
+ case 't': parser->cursor++; token->value = '\t'; return;
1792
+ case 'r': parser->cursor++; token->value = '\r'; return;
1793
+ case 'f': parser->cursor++; token->value = '\f'; return;
1794
+ case 'a': parser->cursor++; token->value = '\a'; return;
1795
+ case 'b': parser->cursor++; token->value = '\b'; return;
1796
+ case 'e': parser->cursor++; token->value = '\033'; return;
1797
+ case 'v': parser->cursor++; token->value = '\v'; return;
1798
+ default:
1799
+ token->value = pm_regexp_parse_char_value(parser);
1800
+ return;
1801
+ }
1802
+ }
1803
+
1804
+ /**
1805
+ * Read the next token in a character class.
1806
+ */
1807
+ static void
1808
+ pm_regexp_class_token_fetch(pm_regexp_parser_t *parser, pm_regexp_class_token_t *token) {
1809
+ token->start = parser->cursor;
1810
+ token->escaped = false;
1811
+
1812
+ if (parser->cursor >= parser->end) {
1813
+ token->type = PM_REGEXP_CLASS_TOKEN_EOF;
1814
+ return;
1815
+ }
1816
+
1817
+ switch (*parser->cursor) {
1818
+ case ']':
1819
+ parser->cursor++;
1820
+ token->type = PM_REGEXP_CLASS_TOKEN_CLOSE;
1821
+ return;
1822
+ case '-':
1823
+ parser->cursor++;
1824
+ token->type = PM_REGEXP_CLASS_TOKEN_RANGE;
1825
+ return;
1826
+ case '&':
1827
+ if (parser->cursor + 1 < parser->end && parser->cursor[1] == '&') {
1828
+ parser->cursor += 2;
1829
+ token->type = PM_REGEXP_CLASS_TOKEN_AND;
1830
+ return;
1831
+ }
1832
+ break;
1833
+ case '[':
1834
+ parser->cursor++;
1835
+ token->type = PM_REGEXP_CLASS_TOKEN_OPEN;
1836
+
1837
+ if (parser->cursor < parser->end && *parser->cursor == ':' && pm_regexp_posix_bracket_close_p(parser, parser->cursor + 1)) {
1838
+ parser->cursor++;
1839
+ token->type = PM_REGEXP_CLASS_TOKEN_POSIX_OPEN;
1840
+ }
1841
+ return;
1842
+ case '\\':
1843
+ parser->cursor++;
1844
+ pm_regexp_class_token_escape(parser, token);
1845
+ return;
1846
+ default:
1847
+ break;
1848
+ }
1849
+
1850
+ token->type = PM_REGEXP_CLASS_TOKEN_CHAR;
1851
+ token->value = pm_regexp_parse_char_value(parser);
1852
+ }
1853
+
1854
+ /**
1855
+ * The names of the POSIX brackets, like [:alpha:].
1856
+ */
1857
+ static const char *const pm_regexp_posix_bracket_names[] = {
1858
+ "alnum", "alpha", "blank", "cntrl", "digit", "graph", "lower",
1859
+ "print", "punct", "space", "upper", "xdigit", "ascii", "word"
1860
+ };
1861
+
1862
+ /**
1863
+ * The results of reading a POSIX bracket.
1864
+ */
1865
+ typedef enum {
1866
+ /** The bracket is invalid, which has been reported. */
1867
+ PM_REGEXP_POSIX_BRACKET_INVALID,
1868
+
1869
+ /** The [ is not a bracket, so it is a character of the class. */
1870
+ PM_REGEXP_POSIX_BRACKET_NONE,
1871
+
1872
+ /** The bracket is valid, and the cursor is past it. */
1873
+ PM_REGEXP_POSIX_BRACKET_VALID
1874
+ } pm_regexp_posix_bracket_t;
1875
+
1876
+ /**
1877
+ * Read a POSIX bracket, like [:alpha:] or [:^alpha:]. The cursor is just past
1878
+ * its [:, which starts at the given position.
1879
+ *
1880
+ * A known name that is not followed by :] is invalid. So is an unknown name
1881
+ * of up to 20 characters that is followed by :]. Anything else is not a
1882
+ * bracket at all.
1883
+ */
1884
+ static pm_regexp_posix_bracket_t
1885
+ pm_regexp_parse_posix_bracket(pm_regexp_parser_t *parser, const uint8_t *start) {
1886
+ const uint8_t *cursor = parser->cursor;
1887
+ const uint8_t *end = parser->end;
1888
+ if (cursor < end && *cursor == '^') cursor++;
1889
+
1890
+ /* The shortest bracket name has 4 characters, so along with its :] and the
1891
+ * ] that closes the class, a bracket needs 7 characters. */
1892
+ size_t characters = 0;
1893
+ for (const uint8_t *count = cursor; count < end && characters < 7; characters++) {
1894
+ size_t width = (*count >= 0x80) ? pm_encoding_char_width(parser->encoding, count, (ptrdiff_t) (end - count)) : 1;
1895
+ count += (width == 0) ? 1 : width;
1896
+ }
1897
+
1898
+ if (characters >= 7) {
1899
+ for (size_t index = 0; index < sizeof(pm_regexp_posix_bracket_names) / sizeof(pm_regexp_posix_bracket_names[0]); index++) {
1900
+ const char *name = pm_regexp_posix_bracket_names[index];
1901
+ size_t length = strlen(name);
1902
+ if ((size_t) (end - cursor) < length || memcmp(cursor, name, length) != 0) continue;
1903
+
1904
+ cursor += length;
1905
+ if (end - cursor < 2 || cursor[0] != ':' || cursor[1] != ']') {
1906
+ pm_regexp_parse_error(parser, start, cursor, "invalid POSIX bracket type");
1907
+ return PM_REGEXP_POSIX_BRACKET_INVALID;
1908
+ }
1909
+
1910
+ parser->cursor = cursor + 2;
1911
+ return PM_REGEXP_POSIX_BRACKET_VALID;
1912
+ }
1913
+ }
1914
+
1915
+ /* Look a little way ahead for the :] of an unknown name. */
1916
+ size_t count = 0;
1917
+ while (cursor < end && *cursor != ':' && *cursor != ']' && count++ < 20) {
1918
+ size_t width = (*cursor >= 0x80) ? pm_encoding_char_width(parser->encoding, cursor, (ptrdiff_t) (end - cursor)) : 1;
1919
+ cursor += (width == 0) ? 1 : width;
1920
+ }
1921
+
1922
+ if (end - cursor >= 2 && cursor[0] == ':' && cursor[1] == ']') {
1923
+ pm_regexp_parse_error(parser, start, cursor + 2, "invalid POSIX bracket type");
1924
+ return PM_REGEXP_POSIX_BRACKET_INVALID;
1925
+ }
1926
+
1927
+ return PM_REGEXP_POSIX_BRACKET_NONE;
1928
+ }
1929
+
1930
+ /**
1931
+ * Where a character class is in reading its values and ranges.
1932
+ */
1933
+ typedef enum {
1934
+ /** No value yet, or none since the last &&. */
1935
+ PM_REGEXP_CLASS_STATE_START,
1936
+
1937
+ /** A value, which a - may make the start of a range. */
1938
+ PM_REGEXP_CLASS_STATE_VALUE,
1939
+
1940
+ /** The start of a range and its -, so the end comes next. */
1941
+ PM_REGEXP_CLASS_STATE_RANGE,
1942
+
1943
+ /** A whole range. */
1944
+ PM_REGEXP_CLASS_STATE_COMPLETE
1945
+ } pm_regexp_class_state_t;
1946
+
1947
+ /**
1948
+ * The state of reading a character class.
1949
+ */
1950
+ typedef struct {
1951
+ /** Where the class is in reading its values and ranges. */
1952
+ pm_regexp_class_state_t state;
1953
+
1954
+ /** Whether the last value is a set of characters, like \d. */
1955
+ bool set;
1956
+
1957
+ /** The last value, if it is a character. */
1958
+ uint32_t value;
1959
+
1960
+ /** Where the last value starts in the pattern. */
1961
+ const uint8_t *start;
1962
+ } pm_regexp_class_t;
1963
+
1964
+ /**
1965
+ * Add a character to a character class. If it ends a range, the range must
1966
+ * not be empty. The character starts at the given position.
1967
+ */
1968
+ static bool
1969
+ pm_regexp_class_add_char(pm_regexp_parser_t *parser, pm_regexp_class_t *character_class, uint32_t value, const uint8_t *start) {
1970
+ switch (character_class->state) {
1971
+ case PM_REGEXP_CLASS_STATE_RANGE:
1972
+ if (character_class->value > value) {
1973
+ pm_regexp_parse_error(parser, character_class->start, parser->cursor, "empty range in char class");
1974
+ return false;
1975
+ }
1976
+ character_class->state = PM_REGEXP_CLASS_STATE_COMPLETE;
1977
+ break;
1978
+ case PM_REGEXP_CLASS_STATE_VALUE:
1979
+ break;
1980
+ case PM_REGEXP_CLASS_STATE_START:
1981
+ case PM_REGEXP_CLASS_STATE_COMPLETE:
1982
+ character_class->state = PM_REGEXP_CLASS_STATE_VALUE;
1983
+ break;
1984
+ }
1985
+
1986
+ character_class->set = false;
1987
+ character_class->value = value;
1988
+ character_class->start = start;
1989
+ return true;
1990
+ }
1991
+
1992
+ /**
1993
+ * Add a set of characters, like \d, to a character class. A set can't end a
1994
+ * range. The set starts at the given position.
1995
+ */
1996
+ static bool
1997
+ pm_regexp_class_add_set(pm_regexp_parser_t *parser, pm_regexp_class_t *character_class, const uint8_t *start) {
1998
+ if (character_class->state == PM_REGEXP_CLASS_STATE_RANGE) {
1999
+ pm_regexp_parse_error(parser, character_class->start, parser->cursor, "char-class value at end of range");
2000
+ return false;
2001
+ }
2002
+
2003
+ character_class->state = PM_REGEXP_CLASS_STATE_VALUE;
2004
+ character_class->set = true;
2005
+ character_class->start = start;
2006
+ return true;
2007
+ }
2008
+
2009
+ /**
2010
+ * Parse a character class, like [a-z] or [^\d&&[:alpha:]]. The cursor is just
2011
+ * past its [. Classes can nest, and the depth is how deeply this one is nested
2012
+ * in groups and other classes. Returns false at the first error.
2013
+ *
2014
+ * The named capture pass reads the content rather than the pattern. There an
2015
+ * escape like \u{61} or \xE3\x81\x82 is still its text, so the values and
2016
+ * ranges of the class aren't what the pattern holds. That pass only finds
2017
+ * where the class ends, and doesn't check its ranges.
2018
+ */
2019
+ static bool
2020
+ pm_regexp_parse_character_class(pm_regexp_parser_t *parser, uint16_t depth) {
2021
+ const uint8_t *open = parser->cursor - 1;
2022
+
2023
+ if (depth >= PM_REGEXP_PARSE_DEPTH_MAX) {
2024
+ pm_regexp_parse_error(parser, parser->start, parser->end, "parse depth limit over");
2025
+ return false;
2026
+ }
2027
+
2028
+ if (pm_parser_stack_exhausted(parser->parser)) {
2029
+ pm_regexp_parse_stack_exhausted(parser);
2030
+ return false;
2031
+ }
2032
+
2033
+ pm_regexp_class_token_t token;
2034
+ pm_regexp_class_token_fetch(parser, &token);
2035
+
2036
+ if (token.type == PM_REGEXP_CLASS_TOKEN_CHAR && token.value == '^' && !token.escaped) {
2037
+ pm_regexp_class_token_fetch(parser, &token);
2038
+ }
2039
+
2040
+ /* A ] right after the [ or [^ is a character of the class, as long as
2041
+ * another ] comes later in the pattern. Otherwise the class is empty. */
2042
+ if (token.type == PM_REGEXP_CLASS_TOKEN_CLOSE) {
2043
+ if (pm_memchr(parser->cursor, ']', (size_t) (parser->end - parser->cursor), parser->encoding_changed, parser->encoding) == NULL) {
2044
+ pm_regexp_parse_error(parser, token.start, parser->cursor, "empty char-class");
2045
+ return false;
2046
+ }
2047
+
2048
+ token.type = PM_REGEXP_CLASS_TOKEN_CHAR;
2049
+ token.value = ']';
2050
+ }
2051
+
2052
+ pm_regexp_class_t character_class = { .state = PM_REGEXP_CLASS_STATE_START, .set = false, .value = 0, .start = token.start };
2053
+
2054
+ while (token.type != PM_REGEXP_CLASS_TOKEN_CLOSE) {
2055
+ bool fetched = false;
2056
+
2057
+ switch (token.type) {
2058
+ case PM_REGEXP_CLASS_TOKEN_EOF:
2059
+ pm_regexp_parse_error(parser, open, parser->end, "premature end of char-class");
2060
+ return false;
2061
+ case PM_REGEXP_CLASS_TOKEN_CHAR:
2062
+ if (!pm_regexp_class_add_char(parser, &character_class, token.value, token.start)) return false;
2063
+ break;
2064
+ case PM_REGEXP_CLASS_TOKEN_SET:
2065
+ if (!pm_regexp_class_add_set(parser, &character_class, token.start)) return false;
2066
+ break;
2067
+ case PM_REGEXP_CLASS_TOKEN_POSIX_OPEN:
2068
+ switch (pm_regexp_parse_posix_bracket(parser, token.start)) {
2069
+ case PM_REGEXP_POSIX_BRACKET_INVALID:
2070
+ return false;
2071
+ case PM_REGEXP_POSIX_BRACKET_NONE:
2072
+ /* The [ is a character, and the class goes on from
2073
+ * the colon after it. */
2074
+ parser->cursor = token.start + 1;
2075
+ if (!pm_regexp_class_add_char(parser, &character_class, '[', token.start)) return false;
2076
+ break;
2077
+ case PM_REGEXP_POSIX_BRACKET_VALID:
2078
+ if (!pm_regexp_class_add_set(parser, &character_class, token.start)) return false;
2079
+ break;
2080
+ }
2081
+ break;
2082
+ case PM_REGEXP_CLASS_TOKEN_RANGE: {
2083
+ const uint8_t *range = token.start;
2084
+
2085
+ switch (character_class.state) {
2086
+ case PM_REGEXP_CLASS_STATE_VALUE:
2087
+ /* A - before the end of the class or a && is a
2088
+ * character, as in [a-]. Otherwise it makes the
2089
+ * value the start of a range, which a set can't be. */
2090
+ pm_regexp_class_token_fetch(parser, &token);
2091
+ fetched = true;
2092
+
2093
+ if (token.type == PM_REGEXP_CLASS_TOKEN_CLOSE || token.type == PM_REGEXP_CLASS_TOKEN_AND) {
2094
+ if (!pm_regexp_class_add_char(parser, &character_class, '-', range)) return false;
2095
+ } else if (character_class.set) {
2096
+ pm_regexp_parse_error(parser, character_class.start, parser->cursor, "unmatched range specifier in char-class");
2097
+ return false;
2098
+ } else {
2099
+ character_class.state = PM_REGEXP_CLASS_STATE_RANGE;
2100
+ }
2101
+ break;
2102
+ case PM_REGEXP_CLASS_STATE_RANGE:
2103
+ /* A - after a - ends the range, as in [!--]. */
2104
+ if (!pm_regexp_class_add_char(parser, &character_class, '-', range)) return false;
2105
+ break;
2106
+ case PM_REGEXP_CLASS_STATE_START:
2107
+ case PM_REGEXP_CLASS_STATE_COMPLETE:
2108
+ /* A - at the start of the class or after a range is a
2109
+ * character, as in [-a] or [a-b-c]. */
2110
+ pm_regexp_class_token_fetch(parser, &token);
2111
+ fetched = true;
2112
+ if (!pm_regexp_class_add_char(parser, &character_class, '-', range)) return false;
2113
+ break;
2114
+ }
2115
+ break;
2116
+ }
2117
+ case PM_REGEXP_CLASS_TOKEN_OPEN:
2118
+ if (!pm_regexp_parse_character_class(parser, (uint16_t) (depth + 1))) return false;
2119
+ break;
2120
+ case PM_REGEXP_CLASS_TOKEN_AND:
2121
+ character_class.state = PM_REGEXP_CLASS_STATE_START;
2122
+ break;
2123
+ case PM_REGEXP_CLASS_TOKEN_CLOSE:
2124
+ break;
2125
+ }
2126
+
2127
+ if (!fetched) pm_regexp_class_token_fetch(parser, &token);
2128
+ }
2129
+
2130
+ return true;
2131
+ }
2132
+
2133
+ // Forward declaration here since parsing groups needs to go back up the grammar
2134
+ // to parse expressions within them.
2135
+ static bool
2136
+ pm_regexp_parse_expression(pm_regexp_parser_t *parser, uint16_t depth);
2137
+
2138
+ /**
2139
+ * Parse the name of a named group, as in the n of (?<n>a) or (?'n'a), with the
2140
+ * cursor on its first character, the way Onigmo's fetch_name reads it, and
2141
+ * consume the > or ' that closes it. In Ruby any character can be part of a
2142
+ * name, but a name must not be empty, must not start with a digit or a -, and
2143
+ * must be closed before the next ). Returns false when the name is not closed,
2144
+ * which stops the walk. After any other error the walk goes on past the name,
2145
+ * to report the errors that follow it.
2146
+ */
2147
+ static bool
2148
+ pm_regexp_parse_group_name(pm_regexp_parser_t *parser, uint8_t close) {
2149
+ const uint8_t *start = parser->cursor;
2150
+
2151
+ if (parser->cursor >= parser->end) {
2152
+ pm_regexp_parse_error(parser, start, parser->cursor, "group name is empty");
2153
+ return false;
2154
+ }
2155
+
2156
+ if (*parser->cursor == close) {
2157
+ pm_regexp_parse_error(parser, start, parser->cursor, "group name is empty");
2158
+ parser->cursor++;
2159
+ return true;
2160
+ }
2161
+
2162
+ size_t width;
2163
+ uint32_t digit;
2164
+ bool invalid = *parser->cursor == '-' || pm_regexp_digit(parser, parser->cursor, &width, &digit);
2165
+
2166
+ /* The first character is never the end of the name, even when it is a ). */
2167
+ pm_regexp_skip_char(parser);
2168
+ while (parser->cursor < parser->end && *parser->cursor != close && *parser->cursor != ')') {
2169
+ pm_regexp_skip_char(parser);
2170
+ }
2171
+
2172
+ if (invalid) {
2173
+ /* The engine quotes the name up to the character that would end it. */
2174
+ pm_regexp_parse_name_error(parser, start, parser->cursor, "invalid group name");
2175
+ if (parser->cursor >= parser->end || *parser->cursor != close) return false;
2176
+
2177
+ parser->groups++;
2178
+ parser->cursor++;
2179
+ return true;
2180
+ }
2181
+
2182
+ if (parser->cursor >= parser->end || *parser->cursor != close) {
2183
+ /* A name that is not closed is quoted to the end of the pattern. */
2184
+ pm_regexp_parse_name_error(parser, start, parser->end, "invalid group name");
2185
+ return false;
2186
+ }
2187
+
2188
+ parser->groups++;
2189
+ pm_regexp_names_append(parser, (pm_regexp_name_t) { .start = start, .length = (size_t) (parser->cursor - start) });
2190
+
2191
+ parser->cursor++;
2192
+ return true;
2193
+ }
2194
+
2195
+ /**
2196
+ * Parse the condition of a conditional group, as in the 1 of (?(1)a|b), with
2197
+ * the cursor after its (. The condition is the number of a group, or the name
2198
+ * of one between < and > or between quotes. Returns false after an error.
2199
+ */
2200
+ static bool
2201
+ pm_regexp_parse_condition(pm_regexp_parser_t *parser, const uint8_t *group_start) {
2202
+ if (pm_regexp_char_is_eof(parser)) {
2203
+ pm_regexp_parse_error(parser, group_start, parser->cursor, "undefined group option");
2204
+ return false;
2205
+ }
2206
+
2207
+ pm_regexp_reference_t reference;
2208
+ size_t width;
2209
+ uint32_t digit;
2210
+ if (pm_regexp_digit(parser, parser->cursor, &width, &digit)) {
2211
+ if (!pm_regexp_parse_reference(parser, ')', &reference)) return false;
2212
+ pm_regexp_defer_reference(parser, &reference, PM_REGEXP_DEFERRED_CONDITION_NUMBER);
2213
+ return true;
2214
+ }
2215
+
2216
+ switch (*parser->cursor) {
2217
+ case '<':
2218
+ case '\'': {
2219
+ uint8_t close = (*parser->cursor++ == '<') ? '>' : '\'';
2220
+ if (!pm_regexp_parse_reference_with_level(parser, close, &reference)) return false;
2221
+ if (!pm_regexp_check_reference(parser, &reference)) return false;
2222
+ pm_regexp_defer_reference(parser, &reference, PM_REGEXP_DEFERRED_NAMED_NUMBER);
2223
+
2224
+ /* The name must be followed by the ) that ends the condition. */
2225
+ if (parser->cursor >= parser->end || *parser->cursor != ')') {
2226
+ pm_regexp_parse_error(parser, parser->cursor, parser->cursor, "undefined group option");
2227
+ return false;
2228
+ }
2229
+
2230
+ parser->cursor++;
2231
+ return true;
2232
+ }
2233
+ default:
2234
+ pm_regexp_parse_error(parser, parser->cursor, parser->cursor + 1, "invalid conditional pattern");
2235
+ return false;
2236
+ }
2237
+ }
2238
+
2239
+ /**
2240
+ * Groups can have quite a few different patterns for syntax. They basically
2241
+ * just wrap a set of expressions, but they can potentially have options after a
2242
+ * question mark. If there _isn't_ a question mark, then it's just a set of
2243
+ * expressions. If there _is_, then here are the options:
2244
+ *
2245
+ * * (?#...) - inline comments
2246
+ * * (?:subexp) - non-capturing group
2247
+ * * (?=subexp) - positive lookahead
2248
+ * * (?!subexp) - negative lookahead
2249
+ * * (?>subexp) - atomic group
2250
+ * * (?~subexp) - absence operator
2251
+ * * (?<=subexp) - positive lookbehind
2252
+ * * (?<!subexp) - negative lookbehind
2253
+ * * (?<name>subexp) - named capturing group
2254
+ * * (?'name'subexp) - named capturing group
2255
+ * * (?(cond)yes-subexp) - conditional expression
2256
+ * * (?(cond)yes-subexp|no-subexp) - conditional expression
2257
+ * * (?imxdau-imx) - turn on and off configuration
2258
+ * * (?imxdau-imx:subexp) - turn on and off configuration for an expression
2259
+ *
2260
+ * A group like (?i) only sets options, for the rest of the group around it.
2261
+ * There is nothing for a quantifier to repeat after it, as in (?i)*, so this
2262
+ * sets options_only to tell the caller not to read one.
2263
+ */
2264
+ static bool
2265
+ pm_regexp_parse_group(pm_regexp_parser_t *parser, uint16_t depth, bool *options_only) {
2266
+ /* Every level of nested groups passes through here, so this bounds the
2267
+ * group recursion by the stack budget. The check lives here rather than
2268
+ * beside the depth check in pm_regexp_parse_expression because there it
2269
+ * stops that function from being inlined, which adds a frame to every
2270
+ * level of nesting. */
2271
+ if (pm_parser_stack_exhausted(parser->parser)) {
2272
+ pm_regexp_parse_stack_exhausted(parser);
2273
+ return false;
2274
+ }
2275
+
2276
+ const uint8_t *group_start = parser->cursor;
2277
+
2278
+ /* Whether the options of the group turn extended mode on (1) or off (-1),
2279
+ * or leave it as it is (0). */
2280
+ int extended = 0;
2281
+
2282
+ /* Whether the group is conditional, as in (?(1)a|b), which can have at
2283
+ * most two alternatives: one for when its condition holds and one for when
2284
+ * it does not. */
2285
+ bool conditional = false;
2286
+
2287
+ // First, parse any options for the group. A group without them captures.
2288
+ if (!pm_regexp_char_accept(parser, '?')) {
2289
+ parser->groups++;
2290
+ } else {
2291
+ if (pm_regexp_char_is_eof(parser)) {
2292
+ pm_regexp_parse_error(parser, group_start, parser->cursor, "end pattern in group");
2293
+ return false;
2294
+ }
2295
+
2296
+ switch (*parser->cursor) {
2297
+ case '#': { // inline comments
2298
+ /* Find the ) that ends the comment the way Onigmo does. A
2299
+ * backslash escapes the character after it, so (?#a\)) ends
2300
+ * at its second ). */
2301
+ parser->cursor++;
2302
+
2303
+ while (parser->cursor < parser->end) {
2304
+ uint8_t byte = *parser->cursor;
2305
+ pm_regexp_skip_char(parser);
2306
+
2307
+ if (byte == ')') return true;
2308
+ if (byte == '\\' && parser->cursor < parser->end) pm_regexp_skip_char(parser);
2309
+ }
2310
+
2311
+ pm_regexp_parse_error(parser, group_start, parser->cursor, "end pattern in group");
2312
+ return false;
2313
+ }
2314
+ case ':': // non-capturing group
2315
+ case '=': // positive lookahead
2316
+ case '!': // negative lookahead
2317
+ case '>': // atomic group
2318
+ case '~': // absence operator
2319
+ parser->cursor++;
2320
+ break;
2321
+ case '<':
2322
+ parser->cursor++;
2323
+ if (pm_regexp_char_is_eof(parser)) {
2324
+ pm_regexp_parse_error(parser, group_start, parser->cursor, "end pattern with unmatched parenthesis");
2325
+ return false;
2326
+ }
2327
+
2328
+ switch (*parser->cursor) {
2329
+ case '=': // positive lookbehind
2330
+ case '!': // negative lookbehind
2331
+ parser->cursor++;
2332
+ break;
2333
+ default: // named capture group
2334
+ if (!pm_regexp_parse_group_name(parser, '>')) return false;
2335
+ break;
2336
+ }
2337
+ break;
2338
+ case '\'': // named capture group
2339
+ parser->cursor++;
2340
+ if (!pm_regexp_parse_group_name(parser, '\'')) return false;
2341
+ break;
2342
+ case '(': // conditional expression
2343
+ parser->cursor++;
2344
+ if (!pm_regexp_parse_condition(parser, group_start)) return false;
2345
+ conditional = true;
2346
+ break;
2347
+ case 'i': case 'm': case 'x': case 'a': case 'd': case 'u': case '-': {
2348
+ /* Read the options the way Onigmo does. Each of i, m, and x is
2349
+ * turned on, or off after a -, and a, d, and u can only be
2350
+ * turned on. The options end at a :, which starts the
2351
+ * subexpression that they apply to, or at a ), after which
2352
+ * they apply to the rest of the group around this one. */
2353
+ bool negated = false;
2354
+
2355
+ while (true) {
2356
+ if (pm_regexp_char_is_eof(parser)) {
2357
+ pm_regexp_parse_error(parser, group_start, parser->cursor, "end pattern in group");
2358
+ return false;
2359
+ }
2360
+
2361
+ uint8_t option = *parser->cursor;
2362
+ if (option == ':' || option == ')') break;
2363
+
2364
+ switch (option) {
2365
+ case '-':
2366
+ negated = true;
2367
+ break;
2368
+ case 'x':
2369
+ extended = negated ? -1 : 1;
2370
+ break;
2371
+ case 'i':
2372
+ case 'm':
2373
+ break;
2374
+ case 'a':
2375
+ case 'd':
2376
+ case 'u':
2377
+ if (!negated) break;
2378
+ PRISM_FALLTHROUGH
2379
+ default:
2380
+ pm_regexp_parse_error(parser, parser->cursor, parser->cursor + 1, "undefined group option");
2381
+ return false;
2382
+ }
2383
+
2384
+ parser->cursor++;
2385
+ }
2386
+
2387
+ if (*parser->cursor == ')') {
2388
+ if (extended != 0) parser->extended_mode = (extended > 0);
2389
+ parser->cursor++;
2390
+ *options_only = true;
2391
+ return true;
2392
+ }
2393
+
2394
+ /* The : that starts the subexpression. */
2395
+ parser->cursor++;
2396
+ break;
2397
+ }
2398
+ default:
2399
+ parser->cursor++;
2400
+ pm_regexp_parse_error(parser, parser->cursor - 1, parser->cursor, "undefined group option");
2401
+ break;
2402
+ }
2403
+ }
2404
+
2405
+ bool extended_mode = parser->extended_mode;
2406
+ if (extended != 0) parser->extended_mode = (extended > 0);
2407
+
2408
+ // Now, parse the expressions within this group.
2409
+ size_t alternatives = 1;
2410
+
2411
+ while (true) {
2412
+ pm_regexp_skip_extended_whitespace(parser);
2413
+ if (pm_regexp_char_is_eof(parser) || *parser->cursor == ')') break;
2414
+
2415
+ if (!pm_regexp_parse_expression(parser, (uint16_t) (depth + 1))) {
2416
+ parser->extended_mode = extended_mode;
2417
+ return false;
2418
+ }
2419
+
2420
+ if (pm_regexp_char_accept(parser, '|') && conditional && ++alternatives == 3) {
2421
+ pm_regexp_parse_error(parser, parser->cursor - 1, parser->cursor, "invalid conditional pattern");
2422
+ }
2423
+ }
2424
+
2425
+ // Finally, make sure we have a closing parenthesis.
2426
+ parser->extended_mode = extended_mode;
2427
+ if (pm_regexp_char_expect(parser, ')')) return true;
2428
+
2429
+ pm_regexp_parse_error(parser, group_start, parser->cursor, "end pattern with unmatched parenthesis");
2430
+ return false;
2431
+ }
2432
+
2433
+ /**
2434
+ * item : anchor
2435
+ * | match-posix-class
2436
+ * | match-char-set
2437
+ * | match-char-class
2438
+ * | match-char-prop
2439
+ * | match-char
2440
+ * | match-any
2441
+ * | group
2442
+ * | quantified
2443
+ * ;
2444
+ */
2445
+ static bool
2446
+ pm_regexp_parse_item(pm_regexp_parser_t *parser, uint16_t depth) {
2447
+ switch (*parser->cursor) {
2448
+ case '^':
2449
+ case '$':
2450
+ parser->cursor++;
2451
+ return pm_regexp_parse_quantifier(parser);
2452
+ case '\\':
2453
+ parser->cursor++;
2454
+ pm_regexp_parse_backslash_escape(parser);
2455
+ return pm_regexp_parse_quantifier(parser);
2456
+ case '(': {
2457
+ parser->cursor++;
2458
+
2459
+ bool options_only = false;
2460
+ if (!pm_regexp_parse_group(parser, depth, &options_only)) return false;
2461
+
2462
+ /* A quantifier after a group like (?i) is the next item, which
2463
+ * reports that it has nothing to repeat. */
2464
+ return options_only || pm_regexp_parse_quantifier(parser);
2465
+ }
2466
+ case '[':
2467
+ parser->cursor++;
2468
+ return pm_regexp_parse_character_class(parser, depth) && pm_regexp_parse_quantifier(parser);
2469
+ case '*':
2470
+ case '?':
2471
+ case '+':
2472
+ parser->cursor++;
2473
+ pm_regexp_parse_error(parser, parser->cursor - 1, parser->cursor, "target of repeat operator is not specified");
2474
+ return true;
2475
+ case '{': {
2476
+ const uint8_t *start = parser->cursor++;
2477
+
2478
+ switch (pm_regexp_parse_interval(parser)) {
2479
+ case PM_REGEXP_INTERVAL_INVALID:
2480
+ return false;
2481
+ case PM_REGEXP_INTERVAL_NONE:
2482
+ /* The { is a character. */
2483
+ return pm_regexp_parse_quantifier(parser);
2484
+ case PM_REGEXP_INTERVAL_VALID:
2485
+ pm_regexp_parse_error(parser, start, parser->cursor, "target of repeat operator is not specified");
2486
+ return true;
2487
+ }
2488
+
2489
+ return true;
2490
+ }
2491
+ case ')':
2492
+ parser->cursor++;
2493
+ pm_regexp_parse_error(parser, parser->cursor - 1, parser->cursor, "unmatched close parenthesis");
2494
+ return true;
2495
+ case '#':
2496
+ if (parser->extended_mode) {
2497
+ if (!pm_regexp_char_find(parser, '\n')) parser->cursor = parser->end;
2498
+ return true;
2499
+ }
2500
+ PRISM_FALLTHROUGH
2501
+ default: {
2502
+ size_t width;
2503
+ if (!parser->encoding_changed) {
2504
+ width = pm_encoding_utf_8_char_width(parser->cursor, (ptrdiff_t) (parser->end - parser->cursor));
2505
+ } else {
2506
+ width = pm_encoding_char_width(parser->encoding, parser->cursor, (ptrdiff_t) (parser->end - parser->cursor));
2507
+ }
2508
+
2509
+ if (width == 0) {
2510
+ /* An invalid character, which the lexer has already reported,
2511
+ * is skipped a byte at a time. */
2512
+ if (*parser->cursor >= 0x80 && parser->encoding_changed) {
2513
+ parser->cursor++;
2514
+ return pm_regexp_parse_quantifier(parser);
2515
+ }
2516
+ return false;
2517
+ }
2518
+
2519
+ parser->cursor += width;
2520
+ return pm_regexp_parse_quantifier(parser);
2521
+ }
2522
+ }
2523
+ }
2524
+
2525
+ /**
2526
+ * expression : item*
2527
+ * ;
2528
+ */
2529
+ static bool
2530
+ pm_regexp_parse_expression(pm_regexp_parser_t *parser, uint16_t depth) {
2531
+ if (depth >= PM_REGEXP_PARSE_DEPTH_MAX) {
2532
+ pm_regexp_parse_error(parser, parser->start, parser->end, "parse depth limit over");
2533
+ return false;
2534
+ }
2535
+
2536
+ /* An alternative can be empty, as in /a||b/, so a | here ends it. */
2537
+ if (*parser->cursor != '|' && !pm_regexp_parse_item(parser, depth)) {
2538
+ return false;
2539
+ }
2540
+
2541
+ while (true) {
2542
+ pm_regexp_skip_extended_whitespace(parser);
2543
+ if (pm_regexp_char_is_eof(parser) || *parser->cursor == '|') return true;
2544
+
2545
+ /* A ) ends the group that this expression is in. Outside of every
2546
+ * group it is unmatched, as in /a)/, and the item reports it. */
2547
+ if (*parser->cursor == ')' && depth > 0) return true;
2548
+
2549
+ if (!pm_regexp_parse_item(parser, depth)) return false;
2550
+ }
2551
+ }
2552
+
2553
+ /**
2554
+ * pattern : EOF
2555
+ * | expression EOF
2556
+ * | expression '|' pattern
2557
+ * ;
2558
+ */
2559
+ static bool
2560
+ pm_regexp_parse_pattern(pm_regexp_parser_t *parser) {
2561
+ do {
2562
+ pm_regexp_skip_extended_whitespace(parser);
2563
+ if (pm_regexp_char_is_eof(parser)) return true;
2564
+ if (!pm_regexp_parse_expression(parser, 0)) return false;
2565
+ } while (pm_regexp_char_accept(parser, '|'));
2566
+
2567
+ return pm_regexp_char_is_eof(parser);
2568
+ }
2569
+
2570
+ // ---------------------------------------------------------------------------
2571
+ // Encoding validation
2572
+ // ---------------------------------------------------------------------------
2573
+
2574
+ /**
2575
+ * Append an error to the regular expression as a whole, followed by its
2576
+ * content, which is how errors are reported once its pattern has been read but
2577
+ * before it is parsed. The message is written out with the content, since the
2578
+ * same error kind holds any of these messages.
2579
+ */
2580
+ static void
2581
+ pm_regexp_error_with_content(const pm_regexp_t *regexp, const char *message) {
2582
+ pm_parser_t *parser = regexp->parser;
2583
+
2584
+ char letters[4];
2585
+ pm_regexp_option_letters(regexp->flags, letters);
2586
+
2587
+ pm_buffer_t buffer = { 0 };
2588
+ pm_buffer_append_string(&buffer, message, strlen(message));
2589
+ pm_buffer_append_string(&buffer, ": /", 3);
2590
+ pm_regexp_format_for_error(&buffer, regexp->encoding, regexp->source, regexp->size);
2591
+ pm_buffer_append_byte(&buffer, '/');
2592
+ pm_buffer_append_string(&buffer, letters, strlen(letters));
2593
+ pm_buffer_append_byte(&buffer, '\0');
2594
+
2595
+ pm_diagnostic_list_append_format(&parser->metadata_arena, &parser->error_list, regexp->location.start, regexp->location.length, PM_ERR_REGEXP_PARSE_ERROR, pm_buffer_value(&buffer));
2596
+ pm_buffer_cleanup(&buffer);
2597
+ }
2598
+
2599
+ /**
2600
+ * Append an error of the given kind to the regular expression as a whole, where
2601
+ * the message of that kind ends with the content.
2602
+ */
2603
+ static void
2604
+ pm_regexp_error_kind_with_content(const pm_regexp_t *regexp, pm_diagnostic_id_t diag_id) {
2605
+ pm_parser_t *parser = regexp->parser;
2606
+
2607
+ char letters[4];
2608
+ pm_regexp_option_letters(regexp->flags, letters);
2609
+
2610
+ pm_buffer_t buffer = { 0 };
2611
+ pm_regexp_format_for_error(&buffer, regexp->encoding, regexp->source, regexp->size);
2612
+ pm_diagnostic_list_append_format(&parser->metadata_arena, &parser->error_list, regexp->location.start, regexp->location.length, diag_id, (int) buffer.length, pm_buffer_value(&buffer), letters);
2613
+ pm_buffer_cleanup(&buffer);
2614
+ }
2615
+
2616
+ /**
2617
+ * Whether the content holds a character that is not ASCII. An invalid
2618
+ * character does not count, since it is an error of its own, reported where it
2619
+ * is lexed.
2620
+ */
2621
+ static bool
2622
+ pm_regexp_non_ascii_p(const pm_encoding_t *encoding, const uint8_t *cursor, const uint8_t *end) {
2623
+ switch (encoding->kind) {
2624
+ case PM_ENCODING_KIND_ASCII:
2625
+ /* No byte that is not ASCII is a valid character. */
2626
+ return false;
2627
+ case PM_ENCODING_KIND_SINGLE_BYTE:
2628
+ /* Every byte that is not ASCII is a valid character. */
2629
+ for (; cursor < end; cursor++) {
2630
+ if (*cursor >= 0x80) return true;
2631
+ }
2632
+ return false;
2633
+ case PM_ENCODING_KIND_UTF_8:
2634
+ /* A byte that is not ASCII may begin an invalid character, which
2635
+ * is skipped a byte at a time as the lexer reports it. UTF-8 is
2636
+ * decoded directly, since it is by far the most common. */
2637
+ for (; cursor < end; cursor++) {
2638
+ if (*cursor >= 0x80 && pm_encoding_utf_8_char_width(cursor, end - cursor)) return true;
2639
+ }
2640
+ return false;
2641
+ default:
2642
+ /* The same as UTF-8, through the decoder of the encoding. */
2643
+ for (; cursor < end; cursor++) {
2644
+ if (*cursor >= 0x80 && pm_encoding_char_width(encoding, cursor, end - cursor)) return true;
2645
+ }
2646
+ return false;
2647
+ }
2648
+ }
2649
+
2650
+ /**
2651
+ * Find the encoding option of a regular expression: /n, /u, /e, or /s. Return
2652
+ * its letter and set the encoding to the one it names. If there is none,
2653
+ * return '\0' and set the encoding to NULL.
2654
+ */
2655
+ static char
2656
+ pm_regexp_encoding_option(pm_node_flags_t flags, const pm_encoding_t **encoding) {
2657
+ if (flags & PM_REGULAR_EXPRESSION_FLAGS_ASCII_8BIT) {
2658
+ *encoding = PM_ENCODING_ASCII_8BIT_ENTRY;
2659
+ return 'n';
2660
+ } else if (flags & PM_REGULAR_EXPRESSION_FLAGS_UTF_8) {
2661
+ *encoding = PM_ENCODING_UTF_8_ENTRY;
2662
+ return 'u';
2663
+ } else if (flags & PM_REGULAR_EXPRESSION_FLAGS_EUC_JP) {
2664
+ *encoding = PM_ENCODING_EUC_JP_ENTRY;
2665
+ return 'e';
2666
+ } else if (flags & PM_REGULAR_EXPRESSION_FLAGS_WINDOWS_31J) {
2667
+ *encoding = PM_ENCODING_WINDOWS_31J_ENTRY;
2668
+ return 's';
2669
+ }
2670
+
2671
+ *encoding = NULL;
2672
+ return '\0';
2673
+ }
2674
+
2675
+ /**
2676
+ * Pick the encoding to read the escapes of a regular expression in.
2677
+ *
2678
+ * If it has an encoding option like /u, use that encoding, as long as the
2679
+ * content has no non-ASCII characters in some other encoding. Otherwise, use
2680
+ * the encoding of the content. One exception: US-ASCII content with no option
2681
+ * is read as binary.
2682
+ *
2683
+ * The option encoding is NULL if the regular expression has no such option.
2684
+ */
2685
+ static const pm_encoding_t *
2686
+ pm_regexp_read_encoding(const pm_regexp_t *regexp, const pm_encoding_t *option_encoding) {
2687
+ const pm_encoding_t *content = regexp->encoding;
2688
+
2689
+ if (option_encoding == NULL) {
2690
+ return (content == PM_ENCODING_US_ASCII_ENTRY) ? PM_ENCODING_ASCII_8BIT_ENTRY : content;
2691
+ }
2692
+
2693
+ if (content == option_encoding || !pm_regexp_non_ascii_p(content, regexp->source, regexp->source + regexp->size)) return option_encoding;
2694
+ return content;
2695
+ }
2696
+
2697
+ /**
2698
+ * Check the encoding option of a regular expression (/n, /u, /e, or /s)
2699
+ * against the characters written in it, before any of its escapes are read.
2700
+ * Every character that is not ASCII must already be in the encoding that the
2701
+ * option names, so the content must be in that one, which is the source
2702
+ * encoding unless the content joins strings in another encoding. When it is
2703
+ * not, the regular expression is still validated, in the encoding of its
2704
+ * content, except with /n, where such a character is an error of its own and
2705
+ * nothing more is checked.
2706
+ *
2707
+ * Returns the encoding that the rest of the regular expression is read in, as
2708
+ * pm_regexp_read_encoding gives it, or NULL if nothing more is checked.
2709
+ */
2710
+ static const pm_encoding_t *
2711
+ pm_regexp_check_option(const pm_regexp_t *regexp) {
2712
+ pm_parser_t *parser = regexp->parser;
2713
+ const pm_encoding_t *encoding;
2714
+ char option = pm_regexp_encoding_option(regexp->flags, &encoding);
2715
+
2716
+ const pm_encoding_t *read_encoding = pm_regexp_read_encoding(regexp, encoding);
2717
+ if (option == '\0' || read_encoding == encoding) return read_encoding;
2718
+
2719
+ pm_diagnostic_list_append_format(&parser->metadata_arena, &parser->error_list, regexp->location.start, regexp->location.length, PM_ERR_REGEXP_ENCODING_OPTION_MISMATCH, option, regexp->encoding->name);
2720
+ if (option != 'n') return read_encoding;
2721
+
2722
+ pm_regexp_error_kind_with_content(regexp, PM_ERR_REGEXP_NON_ESCAPED_MBC);
2723
+ return NULL;
2724
+ }
2725
+
2726
+ /**
2727
+ * The state of reading the escapes of a regular expression, which finds the
2728
+ * encoding that its characters and escapes fix it to before its pattern is
2729
+ * parsed.
2730
+ */
2731
+ typedef struct {
2732
+ /** The regular expression, whose content is read. */
2733
+ const pm_regexp_t *regexp;
2734
+
2735
+ /** The end of the content. */
2736
+ const uint8_t *end;
2737
+
2738
+ /** The encoding that the content is read in. */
2739
+ const pm_encoding_t *encoding;
2740
+
2741
+ /**
2742
+ * The encoding that the characters and escapes read so far fix the
2743
+ * regular expression to, or NULL if none of them fixes it.
2744
+ */
2745
+ const pm_encoding_t *fixed_encoding;
2746
+
2747
+ /**
2748
+ * Whether a property escape came before anything fixed the encoding,
2749
+ * which fixes it to the encoding that the content is read in.
2750
+ */
2751
+ bool has_property;
2752
+
2753
+ /**
2754
+ * The pattern that the content preprocesses to. It is only written once
2755
+ * it first differs from the content, which it does for few regular
2756
+ * expressions. Until then, the content is the pattern.
2757
+ */
2758
+ pm_buffer_t pattern;
2759
+
2760
+ /** The end of the content that the pattern holds so far. */
2761
+ const uint8_t *written;
2762
+
2763
+ /** Whether the pattern differs from the content. */
2764
+ bool rewritten;
2765
+
2766
+ /**
2767
+ * Where the pattern stops lining up with the content. In each place, the
2768
+ * content offset is in the pattern and the source offset is in the content.
2769
+ */
2770
+ pm_regexp_offsets_t offsets;
2771
+ } pm_regexp_preprocessor_t;
2772
+
2773
+ /**
2774
+ * Start writing something into the pattern in place of the content at the
2775
+ * given position. The content before it is copied into the pattern first.
2776
+ */
2777
+ static void
2778
+ pm_regexp_preprocess_replace(pm_regexp_preprocessor_t *preprocessor, const uint8_t *from) {
2779
+ pm_buffer_append_bytes(&preprocessor->pattern, preprocessor->written, (size_t) (from - preprocessor->written));
2780
+ preprocessor->written = from;
2781
+ }
2782
+
2783
+ /**
2784
+ * Finish writing something into the pattern in place of the content up to the
2785
+ * given position, and record where the two stop lining up.
2786
+ */
2787
+ static void
2788
+ pm_regexp_preprocess_resume(pm_regexp_preprocessor_t *preprocessor, const uint8_t *to) {
2789
+ preprocessor->written = to;
2790
+ preprocessor->rewritten = true;
2791
+
2792
+ uint32_t pattern = (uint32_t) pm_buffer_length(&preprocessor->pattern);
2793
+ uint32_t content = (uint32_t) (to - preprocessor->regexp->source);
2794
+ pm_regexp_offsets_record(preprocessor->regexp->parser, &preprocessor->offsets, pattern, content, 0);
2795
+ }
2796
+
2797
+ /**
2798
+ * Fix the regular expression to the given encoding, which a character or an
2799
+ * escape that is not ASCII calls for. Returns false if it was fixed to another
2800
+ * encoding already, which is an error for the caller to report.
2801
+ */
2802
+ static bool
2803
+ pm_regexp_preprocess_fix_encoding(pm_regexp_preprocessor_t *preprocessor, const pm_encoding_t *encoding) {
2804
+ if (preprocessor->fixed_encoding == NULL) preprocessor->fixed_encoding = encoding;
2805
+ return preprocessor->fixed_encoding == encoding;
2806
+ }
2807
+
2808
+
2809
+ /**
2810
+ * Read the escape at the cursor as the byte that it stands for, which is how
2811
+ * an escape of a byte that is not ASCII is read, along with the escapes after
2812
+ * it that complete its character. The lexer writes each \M-, \C-, and \c
2813
+ * escape in the content as the \x escape of its byte, so those forms never
2814
+ * reach here. Returns the byte, or -1 after reporting an error.
2815
+ */
2816
+ static int
2817
+ pm_regexp_preprocess_escaped_byte(pm_regexp_preprocessor_t *preprocessor, const uint8_t **parent_cursor) {
2818
+ const uint8_t *end = preprocessor->end;
2819
+ const uint8_t *cursor = *parent_cursor;
2820
+ uint32_t code;
2821
+ uint32_t length;
2822
+
2823
+ if (cursor == end || *cursor++ != '\\') {
2824
+ pm_regexp_error_with_content(preprocessor->regexp, "too short escaped multibyte character");
2825
+ return -1;
2826
+ }
2827
+
2828
+ if (cursor == end) {
2829
+ pm_regexp_error_with_content(preprocessor->regexp, "too short escape sequence");
2830
+ return -1;
2831
+ }
2832
+
2833
+ switch (*cursor++) {
2834
+ case '\\': code = '\\'; break;
2835
+ case 'n': code = '\n'; break;
2836
+ case 't': code = '\t'; break;
2837
+ case 'r': code = '\r'; break;
2838
+ case 'f': code = '\f'; break;
2839
+ case 'v': code = '\v'; break;
2840
+ case 'a': code = '\a'; break;
2841
+ case 'e': code = '\033'; break;
2842
+ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7':
2843
+ code = pm_regexp_scan_digits(cursor - 1, end, 3, 8, &length);
2844
+ cursor += length - 1;
2845
+ break;
2846
+ case 'x':
2847
+ code = pm_regexp_scan_digits(cursor, end, 2, 16, &length);
2848
+ if (length == 0) {
2849
+ pm_regexp_error_with_content(preprocessor->regexp, "invalid hex escape");
2850
+ return -1;
2851
+ }
2852
+ cursor += length;
2853
+ break;
2854
+ default:
2855
+ pm_regexp_error_with_content(preprocessor->regexp, "unexpected escape sequence");
2856
+ return -1;
2857
+ }
2858
+
2859
+ if (code > 0xFF) {
2860
+ pm_regexp_error_with_content(preprocessor->regexp, "invalid escape code");
2861
+ return -1;
2862
+ }
2863
+
2864
+ *parent_cursor = cursor;
2865
+ return (int) code;
2866
+ }
2867
+
2868
+ /**
2869
+ * Read the escape of a byte at the cursor, along with the escapes after it
2870
+ * that complete the character it begins.
2871
+ *
2872
+ * A character that is not ASCII fixes the regular expression to the encoding
2873
+ * that the content is read in, and goes into the pattern as its bytes. An
2874
+ * ASCII character keeps its escape, which the pattern reads the same way.
2875
+ */
2876
+ static bool
2877
+ pm_regexp_preprocess_escaped_char(pm_regexp_preprocessor_t *preprocessor, const uint8_t **parent_cursor) {
2878
+ const pm_encoding_t *encoding = preprocessor->encoding;
2879
+ const uint8_t *start = *parent_cursor;
2880
+ uint8_t bytes[8];
2881
+ size_t length = 0;
2882
+
2883
+ do {
2884
+ int byte = pm_regexp_preprocess_escaped_byte(preprocessor, parent_cursor);
2885
+ if (byte < 0) return false;
2886
+ bytes[length++] = (uint8_t) byte;
2887
+ } while (length < sizeof(bytes) && pm_encoding_char_width(encoding, bytes, (ptrdiff_t) length) == 0 && pm_encoding_char_prefix_p(encoding, bytes, (ptrdiff_t) length));
2888
+
2889
+ if (pm_encoding_char_width(encoding, bytes, (ptrdiff_t) length) == 0 && !pm_encoding_char_prefix_p(encoding, bytes, (ptrdiff_t) length)) {
2890
+ pm_regexp_error_kind_with_content(preprocessor->regexp, PM_ERR_INVALID_MULTIBYTE_ESCAPE);
2891
+ return false;
2892
+ }
2893
+
2894
+ if (length > 1 || bytes[0] >= 0x80) {
2895
+ if (!pm_regexp_preprocess_fix_encoding(preprocessor, encoding)) {
2896
+ pm_regexp_error_kind_with_content(preprocessor->regexp, PM_ERR_REGEXP_ESCAPED_NON_ASCII_IN_UTF8);
2897
+ return false;
2898
+ }
2899
+
2900
+ pm_regexp_preprocess_replace(preprocessor, start);
2901
+ pm_buffer_append_bytes(&preprocessor->pattern, bytes, length);
2902
+ pm_regexp_preprocess_resume(preprocessor, *parent_cursor);
2903
+ }
2904
+
2905
+ return true;
2906
+ }
2907
+
2908
+ /**
2909
+ * Read a code point of a \u escape and write it into the pattern. One that is
2910
+ * not ASCII fixes the regular expression to UTF-8 and goes into the pattern as
2911
+ * its UTF-8 bytes. An ASCII one goes in as a \x escape.
2912
+ */
2913
+ static bool
2914
+ pm_regexp_preprocess_code_point(pm_regexp_preprocessor_t *preprocessor, uint32_t value) {
2915
+ if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) {
2916
+ pm_regexp_error_kind_with_content(preprocessor->regexp, PM_ERR_REGEXP_INVALID_UNICODE_RANGE);
2917
+ return false;
2918
+ }
2919
+
2920
+ if (value < 0x80) {
2921
+ pm_buffer_append_format(&preprocessor->pattern, "\\x%02X", (unsigned int) value);
2922
+ return true;
2923
+ }
2924
+
2925
+ if (!pm_regexp_preprocess_fix_encoding(preprocessor, PM_ENCODING_UTF_8_ENTRY)) {
2926
+ pm_regexp_error_kind_with_content(preprocessor->regexp, PM_ERR_REGEXP_UTF8_CHAR_NON_UTF8_REGEXP);
2927
+ return false;
2928
+ }
2929
+
2930
+ pm_buffer_append_unicode_codepoint(&preprocessor->pattern, value);
2931
+ return true;
2932
+ }
2933
+
2934
+ /**
2935
+ * Whether the byte is whitespace between the code points of a \u{...} escape.
2936
+ */
2937
+ static PRISM_INLINE bool
2938
+ pm_regexp_preprocess_space_p(uint8_t byte) {
2939
+ return byte == ' ' || (byte >= '\t' && byte <= '\r');
2940
+ }
2941
+
2942
+ /**
2943
+ * Read the code points of a \u{...} escape, from the cursor after its brace up
2944
+ * to its closing brace.
2945
+ */
2946
+ static bool
2947
+ pm_regexp_preprocess_code_point_list(pm_regexp_preprocessor_t *preprocessor, const uint8_t **parent_cursor) {
2948
+ const uint8_t *end = preprocessor->end;
2949
+ const uint8_t *cursor = *parent_cursor;
2950
+ bool has_code_point = false;
2951
+
2952
+ while (cursor < end && pm_regexp_preprocess_space_p(*cursor)) cursor++;
2953
+
2954
+ while (true) {
2955
+ uint32_t length;
2956
+ uint32_t value = pm_regexp_scan_digits(cursor, end, UINT32_MAX, 16, &length);
2957
+ if (length == 0) break;
2958
+
2959
+ /* The largest code point, 10FFFF, has six digits. */
2960
+ if (length > 6) {
2961
+ pm_regexp_error_kind_with_content(preprocessor->regexp, PM_ERR_REGEXP_INVALID_UNICODE_RANGE);
2962
+ return false;
2963
+ }
2964
+ cursor += length;
2965
+
2966
+ if (!pm_regexp_preprocess_code_point(preprocessor, value)) return false;
2967
+ has_code_point = true;
2968
+
2969
+ while (cursor < end && pm_regexp_preprocess_space_p(*cursor)) cursor++;
2970
+ }
2971
+
2972
+ if (!has_code_point || cursor == end || *cursor++ != '}') {
2973
+ pm_regexp_error_with_content(preprocessor->regexp, "invalid Unicode list");
2974
+ return false;
2975
+ }
2976
+
2977
+ *parent_cursor = cursor;
2978
+ return true;
2979
+ }
2980
+
2981
+ /**
2982
+ * Whether the content needs to be preprocessed at all. Most regular
2983
+ * expressions don't, so this quick check lets them skip it.
2984
+ *
2985
+ * Only a byte that is not ASCII, or an escape of a byte, a code point, or a
2986
+ * property, can fix the encoding or be an error. Only those and comments make
2987
+ * the pattern differ from the content. Any # might start a comment, since an
2988
+ * option like (?x) can turn on extended mode anywhere.
2989
+ */
2990
+ static bool
2991
+ pm_regexp_preprocess_needed_p(const uint8_t *cursor, const uint8_t *end) {
2992
+ while (cursor < end) {
2993
+ uint8_t byte = *cursor++;
2994
+
2995
+ switch (byte) {
2996
+ case '\\':
2997
+ /* A trailing backslash is an error. */
2998
+ if (cursor == end) return true;
2999
+
3000
+ byte = *cursor++;
3001
+ switch (byte) {
3002
+ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7':
3003
+ case 'x': case 'u': case 'p': case 'P':
3004
+ return true;
3005
+ default:
3006
+ break;
3007
+ }
3008
+ break;
3009
+ case '#':
3010
+ return true;
3011
+ default:
3012
+ break;
3013
+ }
3014
+
3015
+ /* The byte last read, whether on its own or after a backslash, fixes
3016
+ * the encoding if it is not ASCII. */
3017
+ if (byte >= 0x80) return true;
3018
+ }
3019
+
3020
+ return false;
3021
+ }
3022
+
3023
+ /**
3024
+ * The ASCII bytes that reading the escapes of the content stops at. Every other
3025
+ * ASCII byte is a character that neither fixes the encoding nor starts an
3026
+ * escape or a comment, so it is skipped.
3027
+ */
3028
+ static const bool pm_regexp_preprocess_stops[128] = {
3029
+ ['\\'] = true, ['#'] = true, ['['] = true, [']'] = true, ['('] = true, [')'] = true
3030
+ };
3031
+
3032
+ /**
3033
+ * Read the content from the cursor, checking its escapes and finding the
3034
+ * encoding that its characters fix it to. Comments are skipped, both (?#...)
3035
+ * and, in extended mode, those from # to the end of the line, except that a
3036
+ * character that is not ASCII in a comment fixes a regular expression read in
3037
+ * UTF-8 to UTF-8. An invalid character that was lexed is an error of its own,
3038
+ * reported where it was lexed, so it is skipped a byte at a time; one in
3039
+ * content that was not lexed is an error here.
3040
+ *
3041
+ * Within a group that turns extended mode on or off for its subexpression, as
3042
+ * in (?x:...), this is called again for the subexpression, which reads up to
3043
+ * the parenthesis that its own count of open parentheses closes. The depth is
3044
+ * how many such groups enclose the content being read.
3045
+ */
3046
+ static bool
3047
+ pm_regexp_preprocess_scan(pm_regexp_preprocessor_t *preprocessor, const uint8_t **parent_cursor, bool extended, bool nested, uint16_t depth) {
3048
+ /* Groups nested this deeply are an error of the pattern, which its walk
3049
+ * reports. Past that depth, this leaves the cursor where it is, so that
3050
+ * the caller reads the escapes of the subexpression as part of its own
3051
+ * rather than this recursing without bound. */
3052
+ if (depth >= PM_REGEXP_PARSE_DEPTH_MAX) {
3053
+ return true;
3054
+ }
3055
+
3056
+ const pm_regexp_t *regexp = preprocessor->regexp;
3057
+ if (pm_parser_stack_exhausted(regexp->parser)) {
3058
+ pm_parser_err_stack_exhausted(regexp->parser, regexp->location.start, regexp->location.length);
3059
+ return false;
3060
+ }
3061
+
3062
+ const pm_encoding_t *encoding = preprocessor->encoding;
3063
+ const uint8_t *end = preprocessor->end;
3064
+ const uint8_t *cursor = *parent_cursor;
3065
+
3066
+ uint32_t character_classes = 0;
3067
+ uint32_t parentheses = 1;
3068
+
3069
+ while (cursor < end) {
3070
+ /* Every supported encoding is ASCII-compatible, so a byte below 0x80
3071
+ * at the start of a character is a character by itself. */
3072
+ while (cursor < end && *cursor < 0x80 && !pm_regexp_preprocess_stops[*cursor]) cursor++;
3073
+ if (cursor == end) break;
3074
+
3075
+ switch (*cursor++) {
3076
+ case '\\': {
3077
+ if (cursor == end) {
3078
+ pm_regexp_error_with_content(preprocessor->regexp, "too short escape sequence");
3079
+ return false;
3080
+ }
3081
+
3082
+ if (*cursor >= 0x80) {
3083
+ size_t width = pm_encoding_char_width(encoding, cursor, end - cursor);
3084
+ if (width == 0) {
3085
+ if (preprocessor->regexp->unlexed) {
3086
+ pm_regexp_error_with_content(preprocessor->regexp, "invalid multibyte character");
3087
+ return false;
3088
+ }
3089
+
3090
+ cursor++;
3091
+ break;
3092
+ }
3093
+
3094
+ /* A backslash before a character of more than one byte
3095
+ * is read along with the character. */
3096
+ if (width > 1) {
3097
+ cursor += width;
3098
+ if (!pm_regexp_preprocess_fix_encoding(preprocessor, encoding)) {
3099
+ pm_regexp_error_with_content(preprocessor->regexp, "non ASCII character in UTF-8 regexp");
3100
+ return false;
3101
+ }
3102
+ break;
3103
+ }
3104
+ }
3105
+
3106
+ switch (*cursor++) {
3107
+ case '1': case '2': case '3': case '4': case '5': case '6': case '7': {
3108
+ /* A backreference, or the octal escape of an ASCII
3109
+ * character (up to 0x7F, the largest), is kept as it
3110
+ * is, since the two cannot be told apart here. A
3111
+ * larger value is the escape of a byte. */
3112
+ uint32_t length;
3113
+ if (pm_regexp_scan_digits(cursor - 1, end, 3, 8, &length) <= 0x7F) break;
3114
+ }
3115
+ PRISM_FALLTHROUGH
3116
+ case '0': case 'x':
3117
+ cursor -= 2;
3118
+ if (!pm_regexp_preprocess_escaped_char(preprocessor, &cursor)) return false;
3119
+ break;
3120
+ case 'u':
3121
+ if (cursor == end) {
3122
+ pm_regexp_error_with_content(preprocessor->regexp, "too short escape sequence");
3123
+ return false;
3124
+ }
3125
+
3126
+ /* The code points replace the escape in the pattern. */
3127
+ pm_regexp_preprocess_replace(preprocessor, cursor - 2);
3128
+
3129
+ if (*cursor == '{') {
3130
+ cursor++;
3131
+ if (!pm_regexp_preprocess_code_point_list(preprocessor, &cursor)) return false;
3132
+ } else {
3133
+ uint32_t length;
3134
+ uint32_t value = pm_regexp_scan_digits(cursor, end, 4, 16, &length);
3135
+ if (length != 4) {
3136
+ pm_regexp_error_with_content(preprocessor->regexp, "invalid Unicode escape");
3137
+ return false;
3138
+ }
3139
+
3140
+ cursor += 4;
3141
+ if (!pm_regexp_preprocess_code_point(preprocessor, value)) return false;
3142
+ }
3143
+
3144
+ pm_regexp_preprocess_resume(preprocessor, cursor);
3145
+ break;
3146
+ case 'p':
3147
+ case 'P':
3148
+ if (preprocessor->fixed_encoding == NULL) preprocessor->has_property = true;
3149
+ break;
3150
+ default:
3151
+ break;
3152
+ }
3153
+ break;
3154
+ }
3155
+ case '#':
3156
+ if (extended && !character_classes) {
3157
+ /* The comment and the newline that ends it are left out
3158
+ * of the pattern. */
3159
+ pm_regexp_preprocess_replace(preprocessor, cursor - 1);
3160
+
3161
+ while (cursor < end && *cursor != '\n') {
3162
+ if (*cursor >= 0x80 && preprocessor->fixed_encoding == NULL && encoding == PM_ENCODING_UTF_8_ENTRY) {
3163
+ preprocessor->fixed_encoding = encoding;
3164
+ }
3165
+ cursor++;
3166
+ }
3167
+ if (cursor < end) cursor++;
3168
+
3169
+ pm_regexp_preprocess_resume(preprocessor, cursor);
3170
+ }
3171
+ break;
3172
+ case '[':
3173
+ character_classes++;
3174
+ break;
3175
+ case ']':
3176
+ if (character_classes > 0) character_classes--;
3177
+ break;
3178
+ case ')':
3179
+ if (character_classes == 0 && nested && --parentheses == 0) {
3180
+ *parent_cursor = cursor;
3181
+ return true;
3182
+ }
3183
+ break;
3184
+ case '(':
3185
+ if (character_classes > 0) {
3186
+ break;
3187
+ } else if (cursor + 1 < end && *cursor == '?' && cursor[1] == '#') {
3188
+ const uint8_t *comment = cursor;
3189
+ bool closed = false;
3190
+
3191
+ while (!closed && cursor < end) {
3192
+ uint8_t byte = *cursor++;
3193
+
3194
+ if (byte == ')') {
3195
+ closed = true;
3196
+ } else if (byte == '\\' || byte >= 0x80) {
3197
+ if (byte >= 0x80) {
3198
+ if (preprocessor->fixed_encoding == NULL && encoding == PM_ENCODING_UTF_8_ENTRY) {
3199
+ preprocessor->fixed_encoding = encoding;
3200
+ }
3201
+ cursor--;
3202
+ }
3203
+
3204
+ /* A backslash skips the character after it, so
3205
+ * that it does not close the comment. */
3206
+ if (cursor < end) {
3207
+ size_t width = pm_encoding_char_width(encoding, cursor, end - cursor);
3208
+ if (width == 0 && preprocessor->regexp->unlexed) {
3209
+ pm_regexp_error_with_content(preprocessor->regexp, "invalid multibyte character");
3210
+ return false;
3211
+ }
3212
+
3213
+ cursor += (width == 0) ? 1 : width;
3214
+ }
3215
+ }
3216
+ }
3217
+
3218
+ /* A comment is left out of the pattern. An unterminated
3219
+ * one is read as the text that it holds, which is a
3220
+ * syntax error of the pattern. */
3221
+ if (closed) {
3222
+ pm_regexp_preprocess_replace(preprocessor, comment - 1);
3223
+ pm_regexp_preprocess_resume(preprocessor, cursor);
3224
+ } else {
3225
+ cursor = comment;
3226
+ }
3227
+ } else if (cursor + 1 < end && *cursor == '?') {
3228
+ /* Look through the options of the group for one that
3229
+ * turns extended mode on or off. */
3230
+ int extend = 0;
3231
+ bool invert = false;
3232
+ if (nested) parentheses++;
3233
+
3234
+ for (const uint8_t *option = cursor + 1; option < end; option++) {
3235
+ switch (*option) {
3236
+ case 'x':
3237
+ extend = invert ? -1 : 1;
3238
+ continue;
3239
+ case '-':
3240
+ invert = true;
3241
+ continue;
3242
+ case 'i': case 'm': case 'a': case 'd': case 'u':
3243
+ continue;
3244
+ case ':':
3245
+ case ')':
3246
+ if (extend == 0 || (extend == -1) != extended) break;
3247
+
3248
+ if (*option == ':') {
3249
+ if (!pm_regexp_preprocess_scan(preprocessor, &cursor, extend == 1, true, (uint16_t) (depth + 1))) return false;
3250
+ } else {
3251
+ extended = (extend == 1);
3252
+ }
3253
+ break;
3254
+ default:
3255
+ break;
3256
+ }
3257
+ break;
3258
+ }
3259
+ } else if (nested) {
3260
+ parentheses++;
3261
+ }
3262
+ break;
3263
+ default: {
3264
+ /* Every other ASCII byte was skipped above, so this is the
3265
+ * first byte of a character that is not ASCII. */
3266
+ size_t width = pm_encoding_char_width(encoding, cursor - 1, end - (cursor - 1));
3267
+ if (width == 0) {
3268
+ if (preprocessor->regexp->unlexed) {
3269
+ pm_regexp_error_with_content(preprocessor->regexp, "invalid multibyte character");
3270
+ return false;
3271
+ }
3272
+
3273
+ break;
3274
+ }
3275
+
3276
+ cursor += width - 1;
3277
+ if (!pm_regexp_preprocess_fix_encoding(preprocessor, encoding)) {
3278
+ pm_regexp_error_with_content(preprocessor->regexp, "non ASCII character in UTF-8 regexp");
3279
+ return false;
3280
+ }
3281
+ break;
3282
+ }
3283
+ }
3284
+ }
3285
+
3286
+ if (nested) *parent_cursor = cursor;
3287
+ return true;
3288
+ }
3289
+
3290
+ /**
3291
+ * The options of a regular expression that fix its encoding, which affect how
3292
+ * the encoding is resolved from what its content fixes it to.
3293
+ */
3294
+ typedef enum {
3295
+ /** No encoding option. */
3296
+ PM_REGEXP_ENCODING_OPTION_NONE,
3297
+
3298
+ /** The /n option, which reads the content as binary. */
3299
+ PM_REGEXP_ENCODING_OPTION_BINARY,
3300
+
3301
+ /** The /e, /s, or /u option, which fixes the encoding to its own. */
3302
+ PM_REGEXP_ENCODING_OPTION_FIXED
3303
+ } pm_regexp_encoding_option_t;
3304
+
3305
+ /**
3306
+ * Resolve the encoding of the regular expression from the encoding that its
3307
+ * content is read in and the one that its content fixes it to. Returns NULL
3308
+ * after reporting an error if the two are incompatible with its options.
3309
+ */
3310
+ static const pm_encoding_t *
3311
+ pm_regexp_resolve_encoding(const pm_regexp_t *regexp, pm_regexp_encoding_option_t option, const pm_encoding_t *encoding, const pm_encoding_t *fixed_encoding) {
3312
+ if (fixed_encoding != NULL) {
3313
+ if ((option == PM_REGEXP_ENCODING_OPTION_FIXED && fixed_encoding != encoding) || (option == PM_REGEXP_ENCODING_OPTION_BINARY && fixed_encoding != PM_ENCODING_ASCII_8BIT_ENTRY)) {
3314
+ pm_regexp_error_kind_with_content(regexp, PM_ERR_REGEXP_INCOMPAT_CHAR_ENCODING);
3315
+ return NULL;
3316
+ }
3317
+
3318
+ return fixed_encoding;
3319
+ }
3320
+
3321
+ /* Without an encoding option, a regular expression that nothing fixes is
3322
+ * in US-ASCII, as is one with /n, whose content must then all be ASCII. */
3323
+ return (option == PM_REGEXP_ENCODING_OPTION_FIXED) ? encoding : PM_ENCODING_US_ASCII_ENTRY;
3324
+ }
3325
+
3326
+ /**
3327
+ * Return the flag that marks the regular expression as being in the given
3328
+ * encoding, which it needs only when its options and the source encoding do not
3329
+ * already give it that one.
3330
+ */
3331
+ static pm_node_flags_t
3332
+ pm_regexp_encoding_flags(const pm_parser_t *parser, pm_node_flags_t flags, const pm_encoding_t *encoding) {
3333
+ const pm_encoding_t *implied;
3334
+ if (pm_regexp_encoding_option(flags, &implied) == '\0') implied = parser->encoding;
3335
+
3336
+ if (encoding == implied) return 0;
3337
+ if (encoding == PM_ENCODING_UTF_8_ENTRY) return PM_REGULAR_EXPRESSION_FLAGS_FORCED_UTF8_ENCODING;
3338
+ if (encoding == PM_ENCODING_ASCII_8BIT_ENTRY) return PM_REGULAR_EXPRESSION_FLAGS_FORCED_BINARY_ENCODING;
3339
+ if (encoding == PM_ENCODING_US_ASCII_ENTRY) return PM_REGULAR_EXPRESSION_FLAGS_FORCED_US_ASCII_ENCODING;
3340
+ return 0;
3341
+ }
3342
+
3343
+ /**
3344
+ * Check the property escapes that the pattern holds against the encoding that
3345
+ * the pattern is parsed in, which its encoding option or the source decides.
3346
+ * In an encoding whose characters are Unicode code points, any property name
3347
+ * is accepted. EUC-JP and Shift_JIS know the POSIX properties and the script
3348
+ * properties, and every other encoding knows only the POSIX properties.
3349
+ */
3350
+ static void
3351
+ pm_regexp_check_properties(const pm_regexp_t *regexp, const pm_regexp_parser_t *regexp_parser) {
3352
+ pm_parser_t *parser = regexp->parser;
3353
+ const uint8_t *name;
3354
+ size_t length;
3355
+
3356
+ switch (regexp_parser->encoding->kind) {
3357
+ case PM_ENCODING_KIND_UTF_8:
3358
+ case PM_ENCODING_KIND_CESU_8:
3359
+ return;
3360
+ case PM_ENCODING_KIND_EUC_JP:
3361
+ case PM_ENCODING_KIND_SHIFT_JIS:
3362
+ name = regexp_parser->unicode_property_name;
3363
+ length = regexp_parser->unicode_property_name_length;
3364
+ break;
3365
+ default:
3366
+ name = regexp_parser->property_name;
3367
+ length = regexp_parser->property_name_length;
3368
+ break;
3369
+ }
3370
+
3371
+ if (name == NULL) return;
3372
+
3373
+ char letters[4];
3374
+ pm_regexp_option_letters(regexp->flags, letters);
3375
+
3376
+ pm_buffer_t formatted = { 0 };
3377
+ pm_regexp_format_for_error(&formatted, regexp->encoding, regexp->source, regexp->size);
3378
+ pm_diagnostic_list_append_format(&parser->metadata_arena, &parser->error_list, regexp->location.start, regexp->location.length, PM_ERR_REGEXP_INVALID_CHAR_PROPERTY, (int) length, (const char *) name, (int) formatted.length, (const char *) formatted.value, letters);
3379
+ pm_buffer_cleanup(&formatted);
3380
+ }
3381
+
3382
+ /**
3383
+ * Validate a regular expression, in the order that Ruby reads it, which stops
3384
+ * at the first of these steps that finds an error:
3385
+ *
3386
+ * 1. Check its encoding option against the characters written in it.
3387
+ * 2. Read its escapes, to find the encoding that they and its characters fix
3388
+ * it to, and the pattern that they preprocess to.
3389
+ * 3. Resolve its encoding from that and its options.
3390
+ * 4. Parse the pattern in that encoding.
3391
+ *
3392
+ * The first three read the content, where the lexer keeps the escapes that the
3393
+ * regular expression engine reads as their text, so that escaped bytes can be
3394
+ * told from literal ones. The offsets map places in the content to places in
3395
+ * the source, starting at the given offset, for errors in the pattern. Without
3396
+ * them, those errors are reported at the whole regular expression. Returns the
3397
+ * flags of the encoding of the regular expression. If the next token is =~,
3398
+ * save the capture names until the Ruby parser has read the right operand.
3399
+ */
3400
+ static pm_node_flags_t
3401
+ pm_regexp_validate(const pm_regexp_t *regexp, const pm_regexp_offsets_t *offsets, uint32_t source_start, const pm_node_t *match_receiver) {
3402
+ pm_parser_t *parser = regexp->parser;
3403
+ const uint8_t *source = regexp->source;
3404
+ size_t size = regexp->size;
3405
+ pm_node_flags_t flags = regexp->flags;
3406
+ bool extended_mode = (flags & PM_REGULAR_EXPRESSION_FLAGS_EXTENDED) != 0;
3407
+
3408
+ const pm_encoding_t *read_encoding = pm_regexp_check_option(regexp);
3409
+ if (read_encoding == NULL) return 0;
3410
+
3411
+ pm_regexp_preprocessor_t preprocessor = {
3412
+ .regexp = regexp,
3413
+ .end = source + size,
3414
+ .encoding = read_encoding,
3415
+ .fixed_encoding = NULL,
3416
+ .has_property = false,
3417
+ .pattern = { 0 },
3418
+ .written = source,
3419
+ .rewritten = false,
3420
+ .offsets = { 0 }
3421
+ };
3422
+
3423
+ const uint8_t *cursor = source;
3424
+ if (pm_regexp_preprocess_needed_p(source, source + size) && !pm_regexp_preprocess_scan(&preprocessor, &cursor, extended_mode, false, 0)) {
3425
+ pm_buffer_cleanup(&preprocessor.pattern);
3426
+ return 0;
3427
+ }
3428
+
3429
+ /* A property escape before anything else fixes the encoding fixes it to
3430
+ * the one that the content is read in. */
3431
+ if (preprocessor.has_property && preprocessor.fixed_encoding == NULL) {
3432
+ preprocessor.fixed_encoding = read_encoding;
3433
+ }
3434
+
3435
+ const pm_encoding_t *option_encoding;
3436
+ char letter = pm_regexp_encoding_option(flags, &option_encoding);
3437
+
3438
+ pm_regexp_encoding_option_t option = PM_REGEXP_ENCODING_OPTION_NONE;
3439
+ if (letter == 'n') {
3440
+ option = PM_REGEXP_ENCODING_OPTION_BINARY;
3441
+ } else if (letter != '\0') {
3442
+ option = PM_REGEXP_ENCODING_OPTION_FIXED;
3443
+ }
3444
+
3445
+ const pm_encoding_t *encoding = pm_regexp_resolve_encoding(regexp, option, read_encoding, preprocessor.fixed_encoding);
3446
+ if (encoding == NULL) {
3447
+ pm_buffer_cleanup(&preprocessor.pattern);
3448
+ return 0;
3449
+ }
3450
+
3451
+ const uint8_t *pattern = source;
3452
+ size_t pattern_size = size;
3453
+
3454
+ if (preprocessor.rewritten) {
3455
+ pm_regexp_preprocess_replace(&preprocessor, source + size);
3456
+ pattern = (const uint8_t *) pm_buffer_value(&preprocessor.pattern);
3457
+ pattern_size = pm_buffer_length(&preprocessor.pattern);
3458
+ }
3459
+
3460
+ pm_regexp_parser_t regexp_parser = {
3461
+ .parser = parser,
3462
+ .regexp = regexp,
3463
+ .start = pattern,
3464
+ .cursor = pattern,
3465
+ .end = pattern + pattern_size,
3466
+ .pattern_offsets = preprocessor.rewritten ? &preprocessor.offsets : NULL,
3467
+ .offsets = offsets,
3468
+ .source_start = source_start,
3469
+ .location = regexp->location,
3470
+ .extended_mode = extended_mode,
3471
+ .encoding_changed = encoding != PM_ENCODING_UTF_8_ENTRY,
3472
+ .encoding = encoding,
3473
+ .property_name = NULL,
3474
+ .property_name_length = 0,
3475
+ .unicode_property_name = NULL,
3476
+ .unicode_property_name_length = 0
3477
+ };
3478
+
3479
+ pm_regexp_parse_pattern(&regexp_parser);
3480
+ pm_regexp_check_deferreds(&regexp_parser);
3481
+ pm_regexp_check_properties(regexp, &regexp_parser);
3482
+
3483
+ if (match_receiver != NULL && regexp_parser.names.size > 0) {
3484
+ pm_regexp_match_t *match = PM_ARENA_ALLOC(&parser->scratch_arena, pm_regexp_match_t);
3485
+ match->receiver = match_receiver;
3486
+ match->size = regexp_parser.names.size;
3487
+ match->captures = PM_ARENA_ALLOC_ARRAY(&parser->scratch_arena, pm_regexp_capture_t, match->size);
3488
+
3489
+ for (size_t index = 0; index < match->size; index++) {
3490
+ const pm_regexp_name_t *name = &regexp_parser.names.values[index];
3491
+ uint32_t start = pm_regexp_source_offset(&regexp_parser, name->start, true);
3492
+ uint32_t end = pm_regexp_source_offset(&regexp_parser, name->start + name->length, false);
3493
+ const uint8_t *bytes = name->start;
3494
+
3495
+ /* The rewritten pattern and joined content use temporary buffers. */
3496
+ if (preprocessor.rewritten || offsets == NULL) {
3497
+ uint8_t *copy = PM_ARENA_ALLOC_ARRAY(&parser->scratch_arena, uint8_t, name->length);
3498
+ memcpy(copy, bytes, name->length);
3499
+ bytes = copy;
3500
+ }
3501
+
3502
+ match->captures[index] = (pm_regexp_capture_t) { .name = bytes, .length = name->length, .location = { .start = start, .length = end - start } };
3503
+ }
3504
+
3505
+ parser->regexp_match = match;
3506
+ }
3507
+
3508
+ pm_buffer_cleanup(&preprocessor.pattern);
3509
+
3510
+ return pm_regexp_encoding_flags(parser, flags, encoding);
3511
+ }
3512
+
3513
+ /**
3514
+ * Parse a regular expression and validate its encoding, returning the flags of
3515
+ * its encoding. The offsets are where its content stops lining up with the
3516
+ * source.
3517
+ */
3518
+ pm_node_flags_t
3519
+ pm_regexp_parse(pm_parser_t *parser, pm_regular_expression_node_t *node, const pm_regexp_offsets_t *offsets) {
3520
+ const pm_regexp_t regexp = {
3521
+ .parser = parser,
3522
+ .source = pm_string_source(&node->unescaped),
3523
+ .size = pm_string_length(&node->unescaped),
3524
+ .encoding = parser->encoding,
3525
+ .flags = PM_NODE_FLAGS(node),
3526
+ .location = node->base.location,
3527
+ .unlexed = false
3528
+ };
3529
+
3530
+ const pm_node_t *match_receiver = parser->current.type == PM_TOKEN_EQUAL_TILDE ? (const pm_node_t *) node : NULL;
3531
+ return pm_regexp_validate(&regexp, offsets, node->content_loc.start, match_receiver);
3532
+ }
3533
+
3534
+ /**
3535
+ * Strings joined into one piece of content, along with its encoding.
3536
+ *
3537
+ * The strings are the literal parts of a regular expression, or the parts of
3538
+ * a string that it interpolates. The content takes the encoding of the first
3539
+ * string with a non-ASCII character. Every later string with a non-ASCII
3540
+ * character must be in that same encoding.
3541
+ */
3542
+ typedef struct {
3543
+ /** The parser that the regular expression is in. */
3544
+ const pm_parser_t *parser;
3545
+
3546
+ /** The bytes of the content. */
3547
+ pm_buffer_t buffer;
3548
+
3549
+ /** The encoding of the content so far, or NULL before its first string. */
3550
+ const pm_encoding_t *encoding;
3551
+
3552
+ /** Whether the content so far is all ASCII. */
3553
+ bool ascii_only;
3554
+
3555
+ /**
3556
+ * The encoding of the first string that is not ASCII and is in another
3557
+ * encoding than the content before it, so that the two cannot be joined.
3558
+ * NULL if every string can be.
3559
+ */
3560
+ const pm_encoding_t *incompatible;
3561
+ } pm_regexp_joined_t;
3562
+
3563
+ /**
3564
+ * Return the encoding of a string node. That is UTF-8 or binary if the string
3565
+ * forces one, and the source encoding otherwise.
3566
+ */
3567
+ static const pm_encoding_t *
3568
+ pm_regexp_string_encoding(const pm_parser_t *parser, const pm_string_node_t *node) {
3569
+ if (PM_NODE_FLAG_P(node, PM_STRING_FLAGS_FORCED_UTF8_ENCODING)) return PM_ENCODING_UTF_8_ENTRY;
3570
+ if (PM_NODE_FLAG_P(node, PM_STRING_FLAGS_FORCED_BINARY_ENCODING)) return PM_ENCODING_ASCII_8BIT_ENTRY;
3571
+ return parser->encoding;
3572
+ }
3573
+
3574
+ /**
3575
+ * Join the given content, in the given encoding, to the content so far.
3576
+ */
3577
+ static void
3578
+ pm_regexp_join(pm_regexp_joined_t *joined, const uint8_t *source, size_t size, const pm_encoding_t *encoding) {
3579
+ pm_string_t content;
3580
+ pm_string_shared_init(&content, source, source + size);
3581
+ bool ascii_only = pm_string_ascii_only_p(&content);
3582
+
3583
+ if (joined->encoding == NULL) {
3584
+ joined->encoding = encoding;
3585
+ joined->ascii_only = ascii_only;
3586
+ } else if (!ascii_only) {
3587
+ if (joined->ascii_only) {
3588
+ joined->encoding = encoding;
3589
+ joined->ascii_only = false;
3590
+ } else if (encoding != joined->encoding && joined->incompatible == NULL) {
3591
+ joined->incompatible = encoding;
3592
+ }
3593
+ }
3594
+
3595
+ pm_buffer_append_string(&joined->buffer, (const char *) source, size);
3596
+ }
3597
+
3598
+ /**
3599
+ * Join the given parts to the content. An interpolated string is joined part
3600
+ * by part. Every part must have a value known while parsing.
3601
+ */
3602
+ static void
3603
+ pm_regexp_join_string_parts(pm_regexp_joined_t *joined, const pm_node_list_t *parts) {
3604
+ for (size_t index = 0; index < parts->size; index++) {
3605
+ const pm_node_t *part = parts->nodes[index];
3606
+
3607
+ switch (PM_NODE_TYPE(part)) {
3608
+ case PM_STRING_NODE: {
3609
+ const pm_string_node_t *string = (const pm_string_node_t *) part;
3610
+ pm_regexp_join(joined, pm_string_source(&string->unescaped), pm_string_length(&string->unescaped), pm_regexp_string_encoding(joined->parser, string));
3611
+ break;
3612
+ }
3613
+ case PM_INTERPOLATED_STRING_NODE:
3614
+ pm_regexp_join_string_parts(joined, &((const pm_interpolated_string_node_t *) part)->parts);
3615
+ break;
3616
+ case PM_EMBEDDED_STATEMENTS_NODE:
3617
+ pm_regexp_join_string_parts(joined, &((const pm_embedded_statements_node_t *) part)->statements->body);
3618
+ break;
3619
+ default:
3620
+ PRISM_ASSERT(false && "unexpected part of a string whose value is known");
3621
+ break;
3622
+ }
3623
+ }
3624
+ }
3625
+
3626
+ /**
3627
+ * Report that two strings cannot be joined, because their encodings differ.
3628
+ */
3629
+ static void
3630
+ pm_regexp_error_incompatible(pm_parser_t *parser, pm_location_t location, const pm_encoding_t *left, const pm_encoding_t *right) {
3631
+ pm_diagnostic_list_append_format(&parser->metadata_arena, &parser->error_list, location.start, location.length, PM_ERR_REGEXP_INTERPOLATION_ENCODING, left->name, right->name);
3632
+ }
3633
+
3634
+ /**
3635
+ * A literal part of a regular expression with interpolation. That is either
3636
+ * the regular expression's own text, or an interpolated string whose value is
3637
+ * known while parsing. Each part is checked as a regular expression of its own.
3638
+ */
3639
+ typedef struct {
3640
+ /** The part as a regular expression of its own. */
3641
+ pm_regexp_t regexp;
3642
+
3643
+ /**
3644
+ * If the part interpolates an interpolated string, its parts are joined
3645
+ * here, and the buffer holds the content of the part.
3646
+ */
3647
+ pm_regexp_joined_t joined;
3648
+ } pm_regexp_part_t;
3649
+
3650
+ /**
3651
+ * Read one part of a regular expression with interpolation into a literal
3652
+ * part. Return false if the part is not literal, like #{x}.
3653
+ *
3654
+ * The flags are the flags of the regular expression.
3655
+ */
3656
+ static bool
3657
+ pm_regexp_part_init(pm_regexp_part_t *part, pm_parser_t *parser, pm_node_flags_t flags, const pm_node_t *node) {
3658
+ part->joined = (pm_regexp_joined_t) { .parser = parser, .buffer = { 0 }, .encoding = NULL, .ascii_only = true, .incompatible = NULL };
3659
+
3660
+ /* The lexer already reported invalid characters in the regular
3661
+ * expression's own text. Nothing has checked the value of a string that
3662
+ * it interpolates yet. */
3663
+ bool unlexed = false;
3664
+ if (PM_NODE_TYPE_P(node, PM_EMBEDDED_STATEMENTS_NODE)) {
3665
+ const pm_statements_node_t *statements = ((const pm_embedded_statements_node_t *) node)->statements;
3666
+ if (statements == NULL || statements->body.size != 1) return false;
3667
+
3668
+ node = statements->body.nodes[0];
3669
+ unlexed = true;
3670
+ }
3671
+
3672
+ const uint8_t *source;
3673
+ size_t size;
3674
+ const pm_encoding_t *encoding;
3675
+
3676
+ switch (PM_NODE_TYPE(node)) {
3677
+ case PM_STRING_NODE: {
3678
+ const pm_string_node_t *string = (const pm_string_node_t *) node;
3679
+ source = pm_string_source(&string->unescaped);
3680
+ size = pm_string_length(&string->unescaped);
3681
+ encoding = pm_regexp_string_encoding(parser, string);
3682
+ break;
3683
+ }
3684
+ case PM_INTERPOLATED_STRING_NODE: {
3685
+ if (!PM_NODE_FLAG_P(node, PM_INTERPOLATED_STRING_NODE_FLAGS_STATIC_VALUE)) return false;
3686
+ pm_regexp_join_string_parts(&part->joined, &((const pm_interpolated_string_node_t *) node)->parts);
3687
+
3688
+ source = (const uint8_t *) pm_buffer_value(&part->joined.buffer);
3689
+ size = pm_buffer_length(&part->joined.buffer);
3690
+ encoding = (part->joined.encoding == NULL) ? parser->encoding : part->joined.encoding;
3691
+ break;
3692
+ }
3693
+ default:
3694
+ return false;
3695
+ }
3696
+
3697
+ /* In a US-ASCII source, a part of a regular expression without an
3698
+ * encoding option is binary, even the value of a UTF-8 string like
3699
+ * "あ". So the parts never conflict, and they join as binary. */
3700
+ const pm_encoding_t *option_encoding;
3701
+ if (parser->encoding == PM_ENCODING_US_ASCII_ENTRY && pm_regexp_encoding_option(flags, &option_encoding) == '\0') {
3702
+ encoding = PM_ENCODING_ASCII_8BIT_ENTRY;
3703
+ }
3704
+
3705
+ /* Ruby reads each part without the options m, i, and x, so a part's
3706
+ * errors do not show them. */
3707
+ part->regexp = (pm_regexp_t) {
3708
+ .parser = parser,
3709
+ .source = source,
3710
+ .size = size,
3711
+ .encoding = encoding,
3712
+ .flags = flags & (pm_node_flags_t) ~(PM_REGULAR_EXPRESSION_FLAGS_MULTI_LINE | PM_REGULAR_EXPRESSION_FLAGS_IGNORE_CASE | PM_REGULAR_EXPRESSION_FLAGS_EXTENDED),
3713
+ .location = node->location,
3714
+ .unlexed = unlexed
3715
+ };
3716
+
3717
+ return true;
3718
+ }
3719
+
3720
+ /**
3721
+ * Release what a literal part holds.
3722
+ */
3723
+ static void
3724
+ pm_regexp_part_cleanup(pm_regexp_part_t *part) {
3725
+ pm_buffer_cleanup(&part->joined.buffer);
3726
+ }
3727
+
3728
+ /**
3729
+ * Check the escapes of one literal part on its own, without the options of the
3730
+ * regular expression. That way a comment under /x does not hide an escape.
3731
+ * Return whether the escapes are valid. If not, the error has been reported.
3732
+ */
3733
+ static bool
3734
+ pm_regexp_part_escapes_valid_p(const pm_regexp_t *regexp) {
3735
+ const uint8_t *source = regexp->source;
3736
+ if (!pm_regexp_preprocess_needed_p(source, source + regexp->size)) return true;
3737
+
3738
+ const pm_encoding_t *option_encoding;
3739
+ pm_regexp_encoding_option(regexp->flags, &option_encoding);
3740
+
3741
+ pm_regexp_preprocessor_t preprocessor = {
3742
+ .regexp = regexp,
3743
+ .end = source + regexp->size,
3744
+ .encoding = pm_regexp_read_encoding(regexp, option_encoding),
3745
+ .fixed_encoding = NULL,
3746
+ .has_property = false,
3747
+ .pattern = { 0 },
3748
+ .written = source,
3749
+ .rewritten = false,
3750
+ .offsets = { 0 }
3751
+ };
3752
+
3753
+ const uint8_t *cursor = source;
3754
+ bool valid = pm_regexp_preprocess_scan(&preprocessor, &cursor, false, false, 0);
3755
+
3756
+ pm_buffer_cleanup(&preprocessor.pattern);
3757
+ return valid;
3758
+ }
3759
+
3760
+ /**
3761
+ * Validate a regular expression with interpolation, one literal part at a
3762
+ * time.
3763
+ *
3764
+ * For each part, check the encoding option against it, unless the regular
3765
+ * expression is a static literal. Then check the escapes of the part. Only the
3766
+ * first error in the escapes is reported.
3767
+ *
3768
+ * If it is a static literal, join its parts and validate the result as one
3769
+ * regular expression.
3770
+ */
3771
+ void
3772
+ pm_regexp_parse_interpolated(pm_parser_t *parser, const pm_interpolated_regular_expression_node_t *node) {
3773
+ pm_node_flags_t flags = PM_NODE_FLAGS(node);
3774
+ bool is_static = PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL);
3775
+ const pm_node_list_t *parts = &node->parts;
3776
+ /* A heredoc can split a regexp into several literal tokens. Those can
3777
+ * still introduce locals, unlike a regexp with actual interpolation. */
3778
+ bool match_receiver = parser->current.type == PM_TOKEN_EQUAL_TILDE;
3779
+
3780
+ /* Each part that does not match the option is its own error, so the
3781
+ * option is checked against every part, even after an error. */
3782
+ const pm_encoding_t *option_encoding;
3783
+ bool check_option = !is_static && pm_regexp_encoding_option(flags, &option_encoding) != '\0';
3784
+
3785
+ pm_regexp_joined_t joined = { .parser = parser, .buffer = { 0 }, .encoding = NULL, .ascii_only = true, .incompatible = NULL };
3786
+ bool valid = true;
3787
+
3788
+ for (size_t index = 0; index < parts->size && (valid || check_option); index++) {
3789
+ match_receiver = match_receiver && PM_NODE_TYPE_P(parts->nodes[index], PM_STRING_NODE);
3790
+ pm_regexp_part_t part;
3791
+ if (!pm_regexp_part_init(&part, parser, flags, parts->nodes[index])) continue;
3792
+
3793
+ if (check_option && part.joined.incompatible == NULL) pm_regexp_check_option(&part.regexp);
3794
+
3795
+ /* After the first error, only the option is checked. */
3796
+ if (valid) {
3797
+ if (part.joined.incompatible != NULL) {
3798
+ pm_regexp_error_incompatible(parser, part.regexp.location, part.joined.encoding, part.joined.incompatible);
3799
+ valid = false;
3800
+ } else if (!pm_regexp_part_escapes_valid_p(&part.regexp)) {
3801
+ valid = false;
3802
+ } else if (is_static) {
3803
+ pm_regexp_join(&joined, part.regexp.source, part.regexp.size, part.regexp.encoding);
3804
+ }
3805
+ }
3806
+
3807
+ pm_regexp_part_cleanup(&part);
3808
+ }
3809
+
3810
+ if (valid && is_static) {
3811
+ if (joined.incompatible != NULL) {
3812
+ pm_regexp_error_incompatible(parser, node->base.location, joined.encoding, joined.incompatible);
3813
+ } else {
3814
+ /* Every part has been checked on its own. Any invalid character
3815
+ * left is in the regular expression's own text, and the lexer
3816
+ * reported it. The joined content does not line up with the
3817
+ * source, so errors are reported at the whole regular expression. */
3818
+ const pm_regexp_t regexp = {
3819
+ .parser = parser,
3820
+ .source = (const uint8_t *) pm_buffer_value(&joined.buffer),
3821
+ .size = pm_buffer_length(&joined.buffer),
3822
+ .encoding = (joined.encoding == NULL) ? parser->encoding : joined.encoding,
3823
+ .flags = flags,
3824
+ .location = node->base.location,
3825
+ .unlexed = false
3826
+ };
3827
+
3828
+ pm_regexp_validate(&regexp, NULL, 0, match_receiver ? (const pm_node_t *) node : NULL);
3829
+ }
3830
+ }
3831
+
3832
+ pm_buffer_cleanup(&joined.buffer);
3833
+ }