prism 2.0.0-aarch64-mingw-ucrt

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 (232) hide show
  1. checksums.yaml +7 -0
  2. data/BSDmakefile +58 -0
  3. data/CHANGELOG.md +881 -0
  4. data/CODE_OF_CONDUCT.md +76 -0
  5. data/CONTRIBUTING.md +58 -0
  6. data/LICENSE.md +7 -0
  7. data/Makefile +145 -0
  8. data/README.md +81 -0
  9. data/config.yml +4752 -0
  10. data/docs/build_system.md +119 -0
  11. data/docs/configuration.md +69 -0
  12. data/docs/cruby_compilation.md +27 -0
  13. data/docs/design.md +53 -0
  14. data/docs/encoding.md +121 -0
  15. data/docs/fuzzing.md +81 -0
  16. data/docs/heredocs.md +36 -0
  17. data/docs/javascript.md +133 -0
  18. data/docs/local_variable_depth.md +229 -0
  19. data/docs/mapping.md +117 -0
  20. data/docs/parser_translation.md +24 -0
  21. data/docs/parsing_rules.md +22 -0
  22. data/docs/releasing.md +147 -0
  23. data/docs/relocation.md +32 -0
  24. data/docs/ripper_translation.md +63 -0
  25. data/docs/ruby_api.md +45 -0
  26. data/docs/ruby_parser_translation.md +19 -0
  27. data/docs/serialization.md +244 -0
  28. data/docs/testing.md +72 -0
  29. data/ext/prism/api_node.c +7005 -0
  30. data/ext/prism/extconf.rb +126 -0
  31. data/ext/prism/extension.c +1768 -0
  32. data/ext/prism/extension.h +19 -0
  33. data/include/prism/arena.h +45 -0
  34. data/include/prism/arena.hpp +42 -0
  35. data/include/prism/ast.h +10381 -0
  36. data/include/prism/ast.hpp +641 -0
  37. data/include/prism/buffer.h +60 -0
  38. data/include/prism/buffer.hpp +55 -0
  39. data/include/prism/comments.h +72 -0
  40. data/include/prism/compiler/accel.h +26 -0
  41. data/include/prism/compiler/align.h +36 -0
  42. data/include/prism/compiler/assume.h +25 -0
  43. data/include/prism/compiler/branch.h +26 -0
  44. data/include/prism/compiler/bswap.h +46 -0
  45. data/include/prism/compiler/cplusplus.hpp +16 -0
  46. data/include/prism/compiler/endianness.h +34 -0
  47. data/include/prism/compiler/exceptions.hpp +17 -0
  48. data/include/prism/compiler/exported.h +24 -0
  49. data/include/prism/compiler/fallthrough.h +22 -0
  50. data/include/prism/compiler/filesystem.h +32 -0
  51. data/include/prism/compiler/flex_array.h +19 -0
  52. data/include/prism/compiler/force_inline.h +21 -0
  53. data/include/prism/compiler/format.h +27 -0
  54. data/include/prism/compiler/inline.h +17 -0
  55. data/include/prism/compiler/lifetimebound.hpp +25 -0
  56. data/include/prism/compiler/nodiscard.h +22 -0
  57. data/include/prism/compiler/nonnull.h +18 -0
  58. data/include/prism/compiler/unused.h +18 -0
  59. data/include/prism/constant_pool.h +106 -0
  60. data/include/prism/diagnostic.h +111 -0
  61. data/include/prism/errors_format.h +61 -0
  62. data/include/prism/excludes.h +29 -0
  63. data/include/prism/integer.h +41 -0
  64. data/include/prism/internal/allocator.h +68 -0
  65. data/include/prism/internal/allocator_debug.h +88 -0
  66. data/include/prism/internal/arena.h +108 -0
  67. data/include/prism/internal/bit.h +42 -0
  68. data/include/prism/internal/buffer.h +94 -0
  69. data/include/prism/internal/char.h +145 -0
  70. data/include/prism/internal/comments.h +53 -0
  71. data/include/prism/internal/constant_pool.h +152 -0
  72. data/include/prism/internal/diagnostic.h +389 -0
  73. data/include/prism/internal/encoding.h +242 -0
  74. data/include/prism/internal/integer.h +68 -0
  75. data/include/prism/internal/isinf.h +16 -0
  76. data/include/prism/internal/line_offset_list.h +34 -0
  77. data/include/prism/internal/list.h +62 -0
  78. data/include/prism/internal/magic_comments.h +23 -0
  79. data/include/prism/internal/memchr.h +15 -0
  80. data/include/prism/internal/node.h +42 -0
  81. data/include/prism/internal/options.h +232 -0
  82. data/include/prism/internal/parser.h +1004 -0
  83. data/include/prism/internal/regexp.h +26 -0
  84. data/include/prism/internal/serialize.h +39 -0
  85. data/include/prism/internal/source.h +72 -0
  86. data/include/prism/internal/static_literals.h +100 -0
  87. data/include/prism/internal/stringy.h +30 -0
  88. data/include/prism/internal/strncasecmp.h +18 -0
  89. data/include/prism/internal/strpbrk.h +33 -0
  90. data/include/prism/internal/tokens.h +11 -0
  91. data/include/prism/internal/xxh3.h +16 -0
  92. data/include/prism/json.h +40 -0
  93. data/include/prism/line_offset_list.h +69 -0
  94. data/include/prism/magic_comments.h +53 -0
  95. data/include/prism/node.h +139 -0
  96. data/include/prism/node.hpp +272 -0
  97. data/include/prism/node_type.hpp +38 -0
  98. data/include/prism/options.h +363 -0
  99. data/include/prism/options.hpp +43 -0
  100. data/include/prism/parser.h +433 -0
  101. data/include/prism/parser.hpp +274 -0
  102. data/include/prism/prettyprint.h +39 -0
  103. data/include/prism/serialize.h +123 -0
  104. data/include/prism/source.h +163 -0
  105. data/include/prism/stream.h +36 -0
  106. data/include/prism/string_query.h +82 -0
  107. data/include/prism/stringy.h +61 -0
  108. data/include/prism/stringy.hpp +31 -0
  109. data/include/prism/version.h +46 -0
  110. data/include/prism.h +123 -0
  111. data/include/prism.hpp +24 -0
  112. data/lib/prism/3.4/prism.so +0 -0
  113. data/lib/prism/4.0/prism.so +0 -0
  114. data/lib/prism/compiler.rb +815 -0
  115. data/lib/prism/desugar_compiler.rb +463 -0
  116. data/lib/prism/dispatcher.rb +2383 -0
  117. data/lib/prism/dot_visitor.rb +4848 -0
  118. data/lib/prism/dsl.rb +1369 -0
  119. data/lib/prism/ffi.rb +746 -0
  120. data/lib/prism/inspect_visitor.rb +2425 -0
  121. data/lib/prism/lex_compat.rb +953 -0
  122. data/lib/prism/mutation_compiler.rb +780 -0
  123. data/lib/prism/node.rb +33940 -0
  124. data/lib/prism/node_ext.rb +504 -0
  125. data/lib/prism/node_find.rb +215 -0
  126. data/lib/prism/parse_result/errors.rb +72 -0
  127. data/lib/prism/parse_result/newlines.rb +423 -0
  128. data/lib/prism/parse_result.rb +1236 -0
  129. data/lib/prism/pattern.rb +314 -0
  130. data/lib/prism/polyfill/append_as_bytes.rb +15 -0
  131. data/lib/prism/polyfill/byteindex.rb +13 -0
  132. data/lib/prism/polyfill/scan_byte.rb +14 -0
  133. data/lib/prism/polyfill/unpack1.rb +14 -0
  134. data/lib/prism/polyfill/warn.rb +36 -0
  135. data/lib/prism/reflection.rb +427 -0
  136. data/lib/prism/relocation.rb +567 -0
  137. data/lib/prism/serialize.rb +4589 -0
  138. data/lib/prism/string_query.rb +54 -0
  139. data/lib/prism/translation/parser/builder.rb +70 -0
  140. data/lib/prism/translation/parser/compiler.rb +2226 -0
  141. data/lib/prism/translation/parser/lexer.rb +769 -0
  142. data/lib/prism/translation/parser.rb +376 -0
  143. data/lib/prism/translation/parser_current.rb +26 -0
  144. data/lib/prism/translation/parser_versions.rb +36 -0
  145. data/lib/prism/translation/ripper/filter.rb +53 -0
  146. data/lib/prism/translation/ripper/lexer.rb +133 -0
  147. data/lib/prism/translation/ripper/sexp.rb +118 -0
  148. data/lib/prism/translation/ripper/shim.rb +7 -0
  149. data/lib/prism/translation/ripper.rb +4278 -0
  150. data/lib/prism/translation/ruby_parser.rb +1721 -0
  151. data/lib/prism/translation.rb +20 -0
  152. data/lib/prism/visitor.rb +1440 -0
  153. data/lib/prism.rb +168 -0
  154. data/prism.gemspec +251 -0
  155. data/rbi/generated/prism/compiler.rbi +489 -0
  156. data/rbi/generated/prism/desugar_compiler.rbi +306 -0
  157. data/rbi/generated/prism/dispatcher.rbi +1138 -0
  158. data/rbi/generated/prism/dot_visitor.rbi +618 -0
  159. data/rbi/generated/prism/dsl.rbi +751 -0
  160. data/rbi/generated/prism/inspect_visitor.rbi +503 -0
  161. data/rbi/generated/prism/lex_compat.rbi +162 -0
  162. data/rbi/generated/prism/mutation_compiler.rbi +464 -0
  163. data/rbi/generated/prism/node.rbi +15143 -0
  164. data/rbi/generated/prism/node_ext.rbi +259 -0
  165. data/rbi/generated/prism/node_find.rbi +79 -0
  166. data/rbi/generated/prism/parse_result/errors.rbi +21 -0
  167. data/rbi/generated/prism/parse_result/newlines.rbi +208 -0
  168. data/rbi/generated/prism/parse_result.rbi +776 -0
  169. data/rbi/generated/prism/pattern.rbi +134 -0
  170. data/rbi/generated/prism/reflection.rbi +89 -0
  171. data/rbi/generated/prism/relocation.rbi +329 -0
  172. data/rbi/generated/prism/serialize.rbi +185 -0
  173. data/rbi/generated/prism/string_query.rbi +43 -0
  174. data/rbi/generated/prism/translation.rbi +7 -0
  175. data/rbi/generated/prism/visitor.rbi +650 -0
  176. data/rbi/generated/prism.rbi +86 -0
  177. data/rbi/prism/translation/parser.rbi +11 -0
  178. data/rbi/prism/translation/parser_versions.rbi +28 -0
  179. data/rbi/prism/translation/ripper.rbi +15 -0
  180. data/rbi/rubyvm/node_find.rbi +14 -0
  181. data/sig/generated/prism/compiler.rbs +492 -0
  182. data/sig/generated/prism/desugar_compiler.rbs +305 -0
  183. data/sig/generated/prism/dispatcher.rbs +1292 -0
  184. data/sig/generated/prism/dot_visitor.rbs +635 -0
  185. data/sig/generated/prism/dsl.rbs +928 -0
  186. data/sig/generated/prism/inspect_visitor.rbs +509 -0
  187. data/sig/generated/prism/lex_compat.rbs +166 -0
  188. data/sig/generated/prism/mutation_compiler.rbs +464 -0
  189. data/sig/generated/prism/node.rbs +21632 -0
  190. data/sig/generated/prism/node_ext.rbs +290 -0
  191. data/sig/generated/prism/node_find.rbs +90 -0
  192. data/sig/generated/prism/parse_result/errors.rbs +22 -0
  193. data/sig/generated/prism/parse_result/newlines.rbs +223 -0
  194. data/sig/generated/prism/parse_result.rbs +871 -0
  195. data/sig/generated/prism/pattern.rbs +156 -0
  196. data/sig/generated/prism/reflection.rbs +101 -0
  197. data/sig/generated/prism/relocation.rbs +428 -0
  198. data/sig/generated/prism/serialize.rbs +200 -0
  199. data/sig/generated/prism/string_query.rbs +43 -0
  200. data/sig/generated/prism/translation.rbs +8 -0
  201. data/sig/generated/prism/visitor.rbs +1111 -0
  202. data/sig/generated/prism.rbs +84 -0
  203. data/sig/manifest.yaml +2 -0
  204. data/src/arena.c +117 -0
  205. data/src/buffer.c +389 -0
  206. data/src/char.c +289 -0
  207. data/src/comments.c +454 -0
  208. data/src/constant_pool.c +406 -0
  209. data/src/diagnostic.c +894 -0
  210. data/src/encoding.c +5345 -0
  211. data/src/errors_format.c +519 -0
  212. data/src/integer.c +681 -0
  213. data/src/json.c +5733 -0
  214. data/src/line_offset_list.c +100 -0
  215. data/src/list.c +24 -0
  216. data/src/memchr.c +37 -0
  217. data/src/node.c +4363 -0
  218. data/src/options.c +445 -0
  219. data/src/parser.c +371 -0
  220. data/src/prettyprint.c +9024 -0
  221. data/src/prism.c +23901 -0
  222. data/src/regexp.c +1705 -0
  223. data/src/serialize.c +2660 -0
  224. data/src/source.c +524 -0
  225. data/src/static_literals.c +685 -0
  226. data/src/string_query.c +180 -0
  227. data/src/stringy.c +61 -0
  228. data/src/strncasecmp.c +37 -0
  229. data/src/strpbrk.c +447 -0
  230. data/src/tokens.c +724 -0
  231. data/src/xxh3.c +292 -0
  232. metadata +275 -0
data/src/regexp.c ADDED
@@ -0,0 +1,1705 @@
1
+ #include "prism/internal/regexp.h"
2
+
3
+ #include "prism/compiler/inline.h"
4
+ #include "prism/compiler/fallthrough.h"
5
+ #include "prism/internal/buffer.h"
6
+ #include "prism/internal/char.h"
7
+ #include "prism/internal/diagnostic.h"
8
+ #include "prism/internal/encoding.h"
9
+ #include "prism/internal/memchr.h"
10
+ #include "prism/internal/parser.h"
11
+ #include "prism/internal/stringy.h"
12
+ #include "prism/internal/strncasecmp.h"
13
+
14
+ #include <assert.h>
15
+ #include <string.h>
16
+
17
+ /** The maximum depth of nested groups allowed in a regular expression. */
18
+ #define PM_REGEXP_PARSE_DEPTH_MAX 4096
19
+
20
+ /**
21
+ * This is the parser that is going to handle parsing regular expressions.
22
+ */
23
+ typedef struct {
24
+ /** The parser that is currently being used. */
25
+ pm_parser_t *parser;
26
+
27
+ /** A pointer to the start of the source that we are parsing. */
28
+ const uint8_t *start;
29
+
30
+ /** A pointer to the current position in the source. */
31
+ const uint8_t *cursor;
32
+
33
+ /** A pointer to the end of the source that we are parsing. */
34
+ const uint8_t *end;
35
+
36
+ /** The encoding of the source. */
37
+ const pm_encoding_t *encoding;
38
+
39
+ /** The callback to call when a named capture group is found. */
40
+ pm_regexp_name_callback_t name_callback;
41
+
42
+ /** The data to pass to the name callback. */
43
+ void *name_data;
44
+
45
+ /** The start of the regexp node (for error locations). */
46
+ const uint8_t *node_start;
47
+
48
+ /** The end of the regexp node (for error locations). */
49
+ const uint8_t *node_end;
50
+
51
+ /**
52
+ * The explicit encoding determined by escape sequences. NULL if no
53
+ * encoding-setting escape has been seen, UTF-8 for `\u` escapes, or the
54
+ * source encoding for `\x` escapes.
55
+ */
56
+ const pm_encoding_t *explicit_encoding;
57
+
58
+ /**
59
+ * Pointer to the first non-POSIX property name (for /n error messages).
60
+ * POSIX properties (Alnum, Alpha, etc.) work in all encodings.
61
+ * Script properties (Hiragana, Katakana, etc.) work in /e, /s, /u.
62
+ * Unicode-only properties (L, Ll, etc.) work only in /u.
63
+ */
64
+ const uint8_t *property_name;
65
+
66
+ /** Length of the first non-POSIX property name found. */
67
+ size_t property_name_length;
68
+
69
+ /**
70
+ * Pointer to the first Unicode-only property name (for /e, /s error
71
+ * messages). NULL if only POSIX or script properties have been seen.
72
+ */
73
+ const uint8_t *unicode_property_name;
74
+
75
+ /** Length of the first Unicode-only property name found. */
76
+ size_t unicode_property_name_length;
77
+
78
+ /** Buffer of hex escape byte values >= 0x80, separated by 0x00 sentinels. */
79
+ pm_buffer_t hex_escape_buffer;
80
+
81
+ /** Count of non-ASCII literal bytes (not from escapes). */
82
+ uint32_t non_ascii_literal_count;
83
+
84
+ /**
85
+ * Whether or not the regular expression currently being parsed is in
86
+ * extended mode, wherein whitespace is ignored and comments are allowed.
87
+ */
88
+ bool extended_mode;
89
+
90
+ /** Whether the encoding has changed from the default. */
91
+ bool encoding_changed;
92
+
93
+ /**
94
+ * Whether syntax errors are reported. The named capture pass walks content
95
+ * that may be an owned copy of the source (so pointers into it have no
96
+ * offset in the source), and whose errors the validation pass has already
97
+ * reported, so it reports nothing.
98
+ */
99
+ bool report_errors;
100
+
101
+ /** Whether a `\u{...}` escape with value >= 0x80 was seen. */
102
+ bool has_unicode_escape;
103
+
104
+ /** Whether a `\xNN` escape (or `\M-x`, etc.) with value >= 0x80 was seen. */
105
+ bool has_hex_escape;
106
+
107
+ /**
108
+ * Tracks whether the last encoding-setting escape was `\u` (true) or `\x`
109
+ * (false). This matters for error messages when both types are mixed.
110
+ */
111
+ bool last_escape_was_unicode;
112
+
113
+ /** Whether any `\p{...}` or `\P{...}` property escape was found. */
114
+ bool has_property_escape;
115
+
116
+ /** Whether a Unicode-only property escape was found (not POSIX or script). */
117
+ bool has_unicode_property_escape;
118
+
119
+ /** Whether a `\u` escape with invalid range (surrogate or > 0x10FFFF) was seen. */
120
+ bool invalid_unicode_range;
121
+
122
+ /** Whether we are accumulating consecutive hex escape bytes. */
123
+ bool hex_group_active;
124
+
125
+ /** Whether an invalid multibyte character was found during parsing. */
126
+ bool has_invalid_multibyte;
127
+ } pm_regexp_parser_t;
128
+
129
+ /**
130
+ * Append a syntax error to the parser's error list. Errors are only reported
131
+ * when report_errors is set, which is the case for the validation pass that
132
+ * walks the raw source, so start and end always point into the original source.
133
+ */
134
+ static PRISM_INLINE void
135
+ pm_regexp_parse_error(pm_regexp_parser_t *regexp_parser, const uint8_t *start, const uint8_t *end, const char *message) {
136
+ if (regexp_parser->report_errors) {
137
+ pm_parser_t *parser = regexp_parser->parser;
138
+ pm_diagnostic_list_append_format(&parser->metadata_arena, &parser->error_list, (uint32_t) (start - parser->start), (uint32_t) (end - start), PM_ERR_REGEXP_PARSE_ERROR, message);
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Append a formatted syntax error to the parser's error list, following the
144
+ * same rules as pm_regexp_parse_error. This is a macro because we need
145
+ * variadic args for the format string.
146
+ */
147
+ #define pm_regexp_parse_error_format(regexp_parser_, err_start_, err_end_, diag_id, ...) \
148
+ do { \
149
+ if ((regexp_parser_)->report_errors) { \
150
+ pm_parser_t *parser_ = (regexp_parser_)->parser; \
151
+ pm_diagnostic_list_append_format(&parser_->metadata_arena, &parser_->error_list, (uint32_t) ((err_start_) - parser_->start), (uint32_t) ((err_end_) - (err_start_)), diag_id, __VA_ARGS__); \
152
+ } \
153
+ } while (0)
154
+
155
+ /**
156
+ * This appends a new string to the list of named captures. This function
157
+ * assumes the caller has already checked the validity of the name callback.
158
+ */
159
+ static void
160
+ pm_regexp_parser_named_capture(pm_regexp_parser_t *parser, const uint8_t *start, const uint8_t *end) {
161
+ pm_string_t string;
162
+ pm_string_shared_init(&string, start, end);
163
+ parser->name_callback(parser->parser, &string, parser->name_data);
164
+ }
165
+
166
+ /**
167
+ * Returns true if the next character is the end of the source.
168
+ */
169
+ static PRISM_INLINE bool
170
+ pm_regexp_char_is_eof(pm_regexp_parser_t *parser) {
171
+ return parser->cursor >= parser->end;
172
+ }
173
+
174
+ /**
175
+ * Optionally accept a char and consume it if it exists.
176
+ */
177
+ static PRISM_INLINE bool
178
+ pm_regexp_char_accept(pm_regexp_parser_t *parser, uint8_t value) {
179
+ if (!pm_regexp_char_is_eof(parser) && *parser->cursor == value) {
180
+ parser->cursor++;
181
+ return true;
182
+ }
183
+ return false;
184
+ }
185
+
186
+ /**
187
+ * Expect a character to be present and consume it.
188
+ */
189
+ static PRISM_INLINE bool
190
+ pm_regexp_char_expect(pm_regexp_parser_t *parser, uint8_t value) {
191
+ if (!pm_regexp_char_is_eof(parser) && *parser->cursor == value) {
192
+ parser->cursor++;
193
+ return true;
194
+ }
195
+ return false;
196
+ }
197
+
198
+ /**
199
+ * This advances the current token to the next instance of the given character.
200
+ */
201
+ static bool
202
+ pm_regexp_char_find(pm_regexp_parser_t *parser, uint8_t value) {
203
+ if (pm_regexp_char_is_eof(parser)) {
204
+ return false;
205
+ }
206
+
207
+ const uint8_t *end = (const uint8_t *) pm_memchr(parser->cursor, value, (size_t) (parser->end - parser->cursor), parser->encoding_changed, parser->encoding);
208
+ if (end == NULL) {
209
+ return false;
210
+ }
211
+
212
+ parser->cursor = end + 1;
213
+ return true;
214
+ }
215
+
216
+ /**
217
+ * Mark a group boundary in the hex escape byte buffer. When consecutive hex
218
+ * escape bytes >= 0x80 are followed by a non-hex-escape, this appends a 0x00
219
+ * sentinel to separate the groups for later multibyte validation.
220
+ */
221
+ static PRISM_INLINE void
222
+ pm_regexp_hex_group_boundary(pm_regexp_parser_t *parser) {
223
+ if (parser->hex_group_active) {
224
+ pm_buffer_append_byte(&parser->hex_escape_buffer, 0x00);
225
+ parser->hex_group_active = false;
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Track a hex escape byte value >= 0x80 for multibyte validation.
231
+ */
232
+ static PRISM_INLINE void
233
+ pm_regexp_track_hex_escape(pm_regexp_parser_t *parser, uint8_t byte) {
234
+ if (byte >= 0x80) {
235
+ pm_buffer_append_byte(&parser->hex_escape_buffer, byte);
236
+ parser->hex_group_active = true;
237
+ parser->has_hex_escape = true;
238
+
239
+ parser->explicit_encoding = parser->encoding;
240
+ parser->last_escape_was_unicode = false;
241
+ } else {
242
+ pm_regexp_hex_group_boundary(parser);
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Parse a hex digit character and return its value, or -1 if not a hex digit.
248
+ */
249
+ static PRISM_INLINE int
250
+ pm_regexp_hex_digit_value(uint8_t byte) {
251
+ if (byte >= '0' && byte <= '9') return byte - '0';
252
+ if (byte >= 'a' && byte <= 'f') return byte - 'a' + 10;
253
+ if (byte >= 'A' && byte <= 'F') return byte - 'A' + 10;
254
+ return -1;
255
+ }
256
+
257
+ /**
258
+ * Range quantifiers are a special class of quantifiers that look like
259
+ *
260
+ * * {digit}
261
+ * * {digit,}
262
+ * * {digit,digit}
263
+ * * {,digit}
264
+ *
265
+ * If there are any spaces in between, then this just becomes a regular
266
+ * character match expression and we have to backtrack. So when this function
267
+ * first starts running, we'll create a "save" point and then attempt to parse
268
+ * the quantifier. If it fails, we'll restore the save point and return.
269
+ *
270
+ * To properly track everything, we're going to build a little state machine.
271
+ * It looks something like the following:
272
+ *
273
+ * +-------+ +---------+ ------------+
274
+ * ---- lbrace ---> | start | ---- digit ---> | minimum | |
275
+ * +-------+ +---------+ <--- digit -+
276
+ * | | |
277
+ * +-------+ | | rbrace
278
+ * | comma | <----- comma +---- comma -------+ |
279
+ * +-------+ V V
280
+ * | +---------+ +---------+
281
+ * +-- digit --> | maximum | -- rbrace --> || final ||
282
+ * +---------+ +---------+
283
+ * | ^
284
+ * +- digit -+
285
+ *
286
+ * Note that by the time we've hit this function, the lbrace has already been
287
+ * consumed so we're in the start state.
288
+ */
289
+ static bool
290
+ pm_regexp_parse_range_quantifier(pm_regexp_parser_t *parser) {
291
+ const uint8_t *savepoint = parser->cursor;
292
+
293
+ enum {
294
+ PM_REGEXP_RANGE_QUANTIFIER_STATE_START,
295
+ PM_REGEXP_RANGE_QUANTIFIER_STATE_MINIMUM,
296
+ PM_REGEXP_RANGE_QUANTIFIER_STATE_MAXIMUM,
297
+ PM_REGEXP_RANGE_QUANTIFIER_STATE_COMMA
298
+ } state = PM_REGEXP_RANGE_QUANTIFIER_STATE_START;
299
+
300
+ while (1) {
301
+ if (parser->cursor >= parser->end) {
302
+ parser->cursor = savepoint;
303
+ return true;
304
+ }
305
+
306
+ switch (state) {
307
+ case PM_REGEXP_RANGE_QUANTIFIER_STATE_START:
308
+ switch (*parser->cursor) {
309
+ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
310
+ parser->cursor++;
311
+ state = PM_REGEXP_RANGE_QUANTIFIER_STATE_MINIMUM;
312
+ break;
313
+ case ',':
314
+ parser->cursor++;
315
+ state = PM_REGEXP_RANGE_QUANTIFIER_STATE_COMMA;
316
+ break;
317
+ default:
318
+ parser->cursor = savepoint;
319
+ return true;
320
+ }
321
+ break;
322
+ case PM_REGEXP_RANGE_QUANTIFIER_STATE_MINIMUM:
323
+ switch (*parser->cursor) {
324
+ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
325
+ parser->cursor++;
326
+ break;
327
+ case ',':
328
+ parser->cursor++;
329
+ state = PM_REGEXP_RANGE_QUANTIFIER_STATE_MAXIMUM;
330
+ break;
331
+ case '}':
332
+ parser->cursor++;
333
+ return true;
334
+ default:
335
+ parser->cursor = savepoint;
336
+ return true;
337
+ }
338
+ break;
339
+ case PM_REGEXP_RANGE_QUANTIFIER_STATE_COMMA:
340
+ switch (*parser->cursor) {
341
+ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
342
+ parser->cursor++;
343
+ state = PM_REGEXP_RANGE_QUANTIFIER_STATE_MAXIMUM;
344
+ break;
345
+ default:
346
+ parser->cursor = savepoint;
347
+ return true;
348
+ }
349
+ break;
350
+ case PM_REGEXP_RANGE_QUANTIFIER_STATE_MAXIMUM:
351
+ switch (*parser->cursor) {
352
+ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
353
+ parser->cursor++;
354
+ break;
355
+ case '}':
356
+ parser->cursor++;
357
+ return true;
358
+ default:
359
+ parser->cursor = savepoint;
360
+ return true;
361
+ }
362
+ break;
363
+ }
364
+ }
365
+
366
+ return true;
367
+ }
368
+
369
+ /**
370
+ * quantifier : star-quantifier
371
+ * | plus-quantifier
372
+ * | optional-quantifier
373
+ * | range-quantifier
374
+ * | <empty>
375
+ * ;
376
+ */
377
+ static bool
378
+ pm_regexp_parse_quantifier(pm_regexp_parser_t *parser) {
379
+ while (!pm_regexp_char_is_eof(parser)) {
380
+ switch (*parser->cursor) {
381
+ case '*':
382
+ case '+':
383
+ case '?':
384
+ parser->cursor++;
385
+ break;
386
+ case '{':
387
+ parser->cursor++;
388
+ if (!pm_regexp_parse_range_quantifier(parser)) return false;
389
+ break;
390
+ default:
391
+ // In this case there is no quantifier.
392
+ return true;
393
+ }
394
+ }
395
+
396
+ return true;
397
+ }
398
+
399
+ /**
400
+ * match-posix-class : '[' '[' ':' '^'? CHAR+ ':' ']' ']'
401
+ * ;
402
+ */
403
+ static bool
404
+ pm_regexp_parse_posix_class(pm_regexp_parser_t *parser) {
405
+ if (!pm_regexp_char_expect(parser, ':')) {
406
+ return false;
407
+ }
408
+
409
+ pm_regexp_char_accept(parser, '^');
410
+
411
+ return (
412
+ pm_regexp_char_find(parser, ':') &&
413
+ pm_regexp_char_expect(parser, ']') &&
414
+ pm_regexp_char_expect(parser, ']')
415
+ );
416
+ }
417
+
418
+ /**
419
+ * Property escape classification. Onigmo supports three tiers of property
420
+ * names depending on the encoding:
421
+ *
422
+ * - POSIX properties (Alnum, Alpha, ASCII, Blank, Cntrl, Digit, Graph, Lower,
423
+ * Print, Punct, Space, Upper, XDigit, Word): valid in all encodings.
424
+ * - Script properties (Hiragana, Katakana, Han, Latin, Greek, Cyrillic): valid
425
+ * in EUC-JP (/e), Windows-31J (/s), and UTF-8 (/u), but not ASCII-8BIT (/n).
426
+ * - Unicode-only properties (general categories like L, Ll, Lu, etc., plus
427
+ * Any, Assigned): valid only in UTF-8 (/u).
428
+ */
429
+ typedef enum {
430
+ PM_REGEXP_PROPERTY_POSIX,
431
+ PM_REGEXP_PROPERTY_SCRIPT,
432
+ PM_REGEXP_PROPERTY_UNICODE
433
+ } pm_regexp_property_type_t;
434
+
435
+ /**
436
+ * Classify a property name. The name may start with '^' for negation, which
437
+ * is skipped before matching.
438
+ */
439
+ static pm_regexp_property_type_t
440
+ pm_regexp_classify_property(const uint8_t *name, size_t length) {
441
+ // Skip leading '^' for negated properties like \p{^Hiragana}.
442
+ if (length > 0 && name[0] == '^') {
443
+ name++;
444
+ length--;
445
+ }
446
+
447
+ #define PM_REGEXP_CASECMP(str_) (pm_strncasecmp(name, (const uint8_t *) (str_), length) == 0)
448
+
449
+ switch (length) {
450
+ case 3:
451
+ if (PM_REGEXP_CASECMP("Han")) return PM_REGEXP_PROPERTY_SCRIPT;
452
+ break;
453
+ case 4:
454
+ if (PM_REGEXP_CASECMP("Word")) return PM_REGEXP_PROPERTY_POSIX;
455
+ break;
456
+ case 5:
457
+ /* Most properties are length 5, so dispatch on first character. */
458
+ switch (name[0] | 0x20) {
459
+ case 'a':
460
+ if (PM_REGEXP_CASECMP("Alnum")) return PM_REGEXP_PROPERTY_POSIX;
461
+ if (PM_REGEXP_CASECMP("Alpha")) return PM_REGEXP_PROPERTY_POSIX;
462
+ if (PM_REGEXP_CASECMP("ASCII")) return PM_REGEXP_PROPERTY_POSIX;
463
+ break;
464
+ case 'b':
465
+ if (PM_REGEXP_CASECMP("Blank")) return PM_REGEXP_PROPERTY_POSIX;
466
+ break;
467
+ case 'c':
468
+ if (PM_REGEXP_CASECMP("Cntrl")) return PM_REGEXP_PROPERTY_POSIX;
469
+ break;
470
+ case 'd':
471
+ if (PM_REGEXP_CASECMP("Digit")) return PM_REGEXP_PROPERTY_POSIX;
472
+ break;
473
+ case 'g':
474
+ if (PM_REGEXP_CASECMP("Graph")) return PM_REGEXP_PROPERTY_POSIX;
475
+ if (PM_REGEXP_CASECMP("Greek")) return PM_REGEXP_PROPERTY_SCRIPT;
476
+ break;
477
+ case 'l':
478
+ if (PM_REGEXP_CASECMP("Lower")) return PM_REGEXP_PROPERTY_POSIX;
479
+ if (PM_REGEXP_CASECMP("Latin")) return PM_REGEXP_PROPERTY_SCRIPT;
480
+ break;
481
+ case 'p':
482
+ if (PM_REGEXP_CASECMP("Print")) return PM_REGEXP_PROPERTY_POSIX;
483
+ if (PM_REGEXP_CASECMP("Punct")) return PM_REGEXP_PROPERTY_POSIX;
484
+ break;
485
+ case 's':
486
+ if (PM_REGEXP_CASECMP("Space")) return PM_REGEXP_PROPERTY_POSIX;
487
+ break;
488
+ case 'u':
489
+ if (PM_REGEXP_CASECMP("Upper")) return PM_REGEXP_PROPERTY_POSIX;
490
+ break;
491
+ }
492
+ break;
493
+ case 6:
494
+ if (PM_REGEXP_CASECMP("XDigit")) return PM_REGEXP_PROPERTY_POSIX;
495
+ break;
496
+ case 8:
497
+ if (PM_REGEXP_CASECMP("Hiragana")) return PM_REGEXP_PROPERTY_SCRIPT;
498
+ if (PM_REGEXP_CASECMP("Katakana")) return PM_REGEXP_PROPERTY_SCRIPT;
499
+ if (PM_REGEXP_CASECMP("Cyrillic")) return PM_REGEXP_PROPERTY_SCRIPT;
500
+ break;
501
+ }
502
+
503
+ #undef PM_REGEXP_CASECMP
504
+
505
+ // Everything else is Unicode-only (general categories, other scripts, etc.).
506
+ return PM_REGEXP_PROPERTY_UNICODE;
507
+ }
508
+
509
+ /**
510
+ * Check for and skip a `\p{...}` or `\P{...}` Unicode property escape. The
511
+ * cursor should be pointing at 'p' or 'P' when this is called. If a property
512
+ * escape is found, record it on the regexp parser and advance past the closing
513
+ * '}'.
514
+ *
515
+ * Properties are classified into three tiers (POSIX, script, Unicode-only) to
516
+ * determine which encoding modifiers they are valid with.
517
+ */
518
+ static bool
519
+ pm_regexp_parse_property_escape(pm_regexp_parser_t *parser) {
520
+ assert(*parser->cursor == 'p' || *parser->cursor == 'P');
521
+
522
+ if (parser->cursor + 1 < parser->end && parser->cursor[1] == '{') {
523
+ const uint8_t *name_start = parser->cursor + 2;
524
+ const uint8_t *search = name_start;
525
+
526
+ while (search < parser->end && *search != '}') search++;
527
+
528
+ if (search < parser->end) {
529
+ size_t name_length = (size_t) (search - name_start);
530
+ parser->has_property_escape = true;
531
+
532
+ pm_regexp_property_type_t type = pm_regexp_classify_property(name_start, name_length);
533
+
534
+ // Track the first non-POSIX property name (for /n error messages).
535
+ if (type >= PM_REGEXP_PROPERTY_SCRIPT && parser->property_name == NULL) {
536
+ parser->property_name = name_start;
537
+ parser->property_name_length = name_length;
538
+ }
539
+
540
+ // Track the first Unicode-only property name (for /e, /s error messages).
541
+ if (type == PM_REGEXP_PROPERTY_UNICODE) {
542
+ parser->has_unicode_property_escape = true;
543
+ if (parser->unicode_property_name == NULL) {
544
+ parser->unicode_property_name = name_start;
545
+ parser->unicode_property_name_length = name_length;
546
+ }
547
+ }
548
+
549
+ parser->cursor = search + 1; // skip past '}'
550
+ return true;
551
+ }
552
+ }
553
+
554
+ // Not a property escape, just skip the single character after '\'.
555
+ parser->cursor++;
556
+ return false;
557
+ }
558
+
559
+ /**
560
+ * Validate and skip a \u escape sequence in a regular expression. The cursor
561
+ * should be pointing at the character after 'u' when this is called. This
562
+ * handles both the \u{NNNN MMMM} and \uNNNN forms. Also tracks encoding
563
+ * state for validation.
564
+ */
565
+ static void
566
+ pm_regexp_parse_unicode_escape(pm_regexp_parser_t *parser) {
567
+ const uint8_t *escape_start = parser->cursor - 2; // points to '\'
568
+
569
+ if (pm_regexp_char_is_eof(parser)) {
570
+ pm_regexp_parse_error(parser, escape_start, parser->cursor, "invalid Unicode escape");
571
+ return;
572
+ }
573
+
574
+ if (*parser->cursor == '{') {
575
+ parser->cursor++; // skip '{'
576
+
577
+ // Skip leading whitespace.
578
+ while (!pm_regexp_char_is_eof(parser) && pm_char_is_whitespace(*parser->cursor)) {
579
+ parser->cursor++;
580
+ }
581
+
582
+ bool has_codepoint = false;
583
+
584
+ while (!pm_regexp_char_is_eof(parser) && *parser->cursor != '}') {
585
+ // Parse the hex digits to compute the codepoint value.
586
+ uint32_t value = 0;
587
+ size_t hex_count = 0;
588
+
589
+ int digit;
590
+ while (!pm_regexp_char_is_eof(parser) && (digit = pm_regexp_hex_digit_value(*parser->cursor)) >= 0) {
591
+ value = (value << 4) | (uint32_t) digit;
592
+ hex_count++;
593
+ parser->cursor++;
594
+ }
595
+
596
+ if (hex_count == 0) {
597
+ // Skip to '}' or end of regexp to find the full extent.
598
+ while (!pm_regexp_char_is_eof(parser) && *parser->cursor != '}') {
599
+ parser->cursor++;
600
+ }
601
+
602
+ const uint8_t *escape_end = parser->cursor;
603
+ if (!pm_regexp_char_is_eof(parser)) {
604
+ escape_end++;
605
+ parser->cursor++; // skip '}'
606
+ }
607
+
608
+ pm_regexp_parse_error_format(parser, escape_start, escape_end, PM_ERR_ESCAPE_INVALID_UNICODE_LIST, (int) (escape_end - escape_start), (const char *) escape_start);
609
+ return;
610
+ }
611
+
612
+ if (hex_count > 6) {
613
+ pm_regexp_parse_error(parser, escape_start, parser->cursor, "invalid Unicode range");
614
+ }
615
+
616
+ // Track encoding state for this codepoint.
617
+ if (value >= 0x80) {
618
+ parser->has_unicode_escape = true;
619
+ parser->explicit_encoding = PM_ENCODING_UTF_8_ENTRY;
620
+ parser->last_escape_was_unicode = true;
621
+ pm_regexp_hex_group_boundary(parser);
622
+ }
623
+
624
+ // Check for invalid Unicode range (surrogates or > 0x10FFFF).
625
+ if (value > 0x10FFFF || (value >= 0xD800 && value <= 0xDFFF)) {
626
+ parser->invalid_unicode_range = true;
627
+ }
628
+
629
+ has_codepoint = true;
630
+
631
+ // Skip whitespace between codepoints.
632
+ while (!pm_regexp_char_is_eof(parser) && pm_char_is_whitespace(*parser->cursor)) {
633
+ parser->cursor++;
634
+ }
635
+ }
636
+
637
+ if (pm_regexp_char_is_eof(parser)) {
638
+ pm_regexp_parse_error(parser, escape_start, parser->cursor, "unterminated Unicode escape");
639
+ } else {
640
+ if (!has_codepoint) {
641
+ pm_regexp_parse_error_format(parser, escape_start, parser->cursor + 1, PM_ERR_ESCAPE_INVALID_UNICODE_LIST, (int) (parser->cursor + 1 - escape_start), (const char *) escape_start);
642
+ }
643
+ parser->cursor++; // skip '}'
644
+ }
645
+ } else {
646
+ // \uNNNN form — need exactly 4 hex digits.
647
+ uint32_t value = 0;
648
+ size_t hex_count = 0;
649
+
650
+ int digit;
651
+ while (hex_count < 4 && !pm_regexp_char_is_eof(parser) && (digit = pm_regexp_hex_digit_value(*parser->cursor)) >= 0) {
652
+ value = (value << 4) | (uint32_t) digit;
653
+ hex_count++;
654
+ parser->cursor++;
655
+ }
656
+
657
+ if (hex_count < 4) {
658
+ pm_regexp_parse_error(parser, escape_start, parser->cursor, "invalid Unicode escape");
659
+ } else if (value >= 0x80) {
660
+ parser->has_unicode_escape = true;
661
+ parser->explicit_encoding = PM_ENCODING_UTF_8_ENTRY;
662
+ parser->last_escape_was_unicode = true;
663
+ pm_regexp_hex_group_boundary(parser);
664
+ }
665
+
666
+ // Check for invalid Unicode range.
667
+ if (hex_count == 4 && (value > 0x10FFFF || (value >= 0xD800 && value <= 0xDFFF))) {
668
+ parser->invalid_unicode_range = true;
669
+ }
670
+ }
671
+ }
672
+
673
+ // Forward declaration because character sets can be nested.
674
+ static bool
675
+ pm_regexp_parse_lbracket(pm_regexp_parser_t *parser, uint16_t depth);
676
+
677
+ /**
678
+ * Parse a \x escape and return the byte value. The cursor should be pointing
679
+ * at the character after 'x'. Returns -1 if no hex digits follow.
680
+ */
681
+ static int
682
+ pm_regexp_parse_hex_escape(pm_regexp_parser_t *parser) {
683
+ int value = -1;
684
+
685
+ if (!pm_regexp_char_is_eof(parser)) {
686
+ int digit = pm_regexp_hex_digit_value(*parser->cursor);
687
+ if (digit >= 0) {
688
+ value = digit;
689
+ parser->cursor++;
690
+
691
+ if (!pm_regexp_char_is_eof(parser)) {
692
+ digit = pm_regexp_hex_digit_value(*parser->cursor);
693
+ if (digit >= 0) {
694
+ value = (value << 4) | digit;
695
+ parser->cursor++;
696
+ }
697
+ }
698
+ }
699
+ }
700
+
701
+ if (value >= 0) {
702
+ pm_regexp_track_hex_escape(parser, (uint8_t) value);
703
+ }
704
+
705
+ return value;
706
+ }
707
+
708
+ /**
709
+ * Parse a backslash escape sequence in a regexp, handling \u (unicode),
710
+ * \p/\P (property), \x (hex), and other single-character escapes. Also
711
+ * tracks encoding state for \M-x and \C-\M-x escapes.
712
+ */
713
+ static void
714
+ pm_regexp_parse_backslash_escape(pm_regexp_parser_t *parser) {
715
+ if (pm_regexp_char_is_eof(parser)) return;
716
+
717
+ switch (*parser->cursor) {
718
+ case 'u':
719
+ parser->cursor++; // skip 'u'
720
+ pm_regexp_parse_unicode_escape(parser);
721
+ break;
722
+ case 'p':
723
+ case 'P':
724
+ pm_regexp_parse_property_escape(parser);
725
+ break;
726
+ case 'x':
727
+ parser->cursor++; // skip 'x'
728
+ pm_regexp_parse_hex_escape(parser);
729
+ break;
730
+ case 'M':
731
+ // \M-x produces (x | 0x80), always >= 0x80
732
+ if (parser->cursor + 2 < parser->end && parser->cursor[1] == '-') {
733
+ parser->cursor += 2; // skip 'M-'
734
+ if (!pm_regexp_char_is_eof(parser)) {
735
+ if (*parser->cursor == '\\') {
736
+ parser->cursor++;
737
+ // \M-\C-x or \M-\cx — the resulting byte is always >= 0x80
738
+ // We just need to track it as a hex escape >= 0x80.
739
+ pm_regexp_parse_backslash_escape(parser);
740
+ } else {
741
+ parser->cursor++;
742
+ }
743
+ // \M-x always produces a byte >= 0x80
744
+ pm_regexp_track_hex_escape(parser, 0x80);
745
+ }
746
+ } else {
747
+ parser->cursor++;
748
+ }
749
+ break;
750
+ case 'C':
751
+ // \C-x produces (x & 0x1F)
752
+ if (parser->cursor + 2 < parser->end && parser->cursor[1] == '-') {
753
+ parser->cursor += 2; // skip 'C-'
754
+ if (!pm_regexp_char_is_eof(parser)) {
755
+ if (*parser->cursor == '\\') {
756
+ parser->cursor++;
757
+ pm_regexp_parse_backslash_escape(parser);
758
+ } else {
759
+ parser->cursor++;
760
+ }
761
+ }
762
+ } else {
763
+ parser->cursor++;
764
+ }
765
+ break;
766
+ case 'c':
767
+ // \cx produces (x & 0x1F)
768
+ parser->cursor++; // skip 'c'
769
+ if (!pm_regexp_char_is_eof(parser)) {
770
+ if (*parser->cursor == '\\') {
771
+ parser->cursor++;
772
+ pm_regexp_parse_backslash_escape(parser);
773
+ } else {
774
+ parser->cursor++;
775
+ }
776
+ }
777
+ break;
778
+ default:
779
+ pm_regexp_hex_group_boundary(parser);
780
+ parser->cursor++;
781
+ break;
782
+ }
783
+ }
784
+
785
+ /**
786
+ * Check if a byte at the current position is a non-ASCII byte in a multibyte
787
+ * encoding that produces an invalid character. If so, emit an error at the
788
+ * byte location immediately.
789
+ */
790
+ static void
791
+ pm_regexp_parse_invalid_multibyte(pm_regexp_parser_t *parser, const uint8_t *cursor) {
792
+ uint8_t byte = *cursor;
793
+ if (byte >= 0x80 && parser->encoding_changed && parser->encoding->multibyte) {
794
+ size_t width = parser->encoding->char_width(cursor, (ptrdiff_t) (parser->end - cursor));
795
+ if (width > 1) {
796
+ parser->cursor += width - 1;
797
+ } else if (width == 0) {
798
+ parser->has_invalid_multibyte = true;
799
+ pm_regexp_parse_error_format(parser, cursor, cursor + 1, PM_ERR_INVALID_MULTIBYTE_CHAR, parser->encoding->name);
800
+ }
801
+ }
802
+ }
803
+
804
+ /**
805
+ * match-char-set : '[' '^'? (match-range | match-char)* ']'
806
+ * ;
807
+ */
808
+ static bool
809
+ pm_regexp_parse_character_set(pm_regexp_parser_t *parser, uint16_t depth) {
810
+ pm_regexp_char_accept(parser, '^');
811
+
812
+ while (!pm_regexp_char_is_eof(parser) && *parser->cursor != ']') {
813
+ switch (*parser->cursor++) {
814
+ case '[':
815
+ pm_regexp_parse_lbracket(parser, (uint16_t) (depth + 1));
816
+ break;
817
+ case '\\':
818
+ pm_regexp_parse_backslash_escape(parser);
819
+ break;
820
+ default:
821
+ // We've already advanced the cursor by one byte. If the byte
822
+ // was >= 0x80 in a multibyte encoding, we may need to consume
823
+ // additional continuation bytes and validate the character.
824
+ if (*(parser->cursor - 1) >= 0x80) {
825
+ parser->non_ascii_literal_count++;
826
+ }
827
+ pm_regexp_parse_invalid_multibyte(parser, parser->cursor - 1);
828
+ break;
829
+ }
830
+ }
831
+
832
+ return pm_regexp_char_expect(parser, ']');
833
+ }
834
+
835
+ /**
836
+ * A left bracket can either mean a POSIX class or a character set.
837
+ */
838
+ static bool
839
+ pm_regexp_parse_lbracket(pm_regexp_parser_t *parser, uint16_t depth) {
840
+ if (depth >= PM_REGEXP_PARSE_DEPTH_MAX) {
841
+ pm_regexp_parse_error(parser, parser->start, parser->end, "parse depth limit over");
842
+ return false;
843
+ }
844
+
845
+ if ((parser->cursor < parser->end) && parser->cursor[0] == ']') {
846
+ parser->cursor++;
847
+ pm_regexp_parse_error(parser, parser->cursor - 1, parser->cursor, "empty char-class");
848
+ return true;
849
+ }
850
+
851
+ const uint8_t *reset = parser->cursor;
852
+
853
+ if ((parser->cursor + 2 < parser->end) && parser->cursor[0] == '[' && parser->cursor[1] == ':') {
854
+ parser->cursor++;
855
+ if (pm_regexp_parse_posix_class(parser)) return true;
856
+
857
+ parser->cursor = reset;
858
+ }
859
+
860
+ return pm_regexp_parse_character_set(parser, depth);
861
+ }
862
+
863
+ // Forward declaration here since parsing groups needs to go back up the grammar
864
+ // to parse expressions within them.
865
+ static bool
866
+ pm_regexp_parse_expression(pm_regexp_parser_t *parser, uint16_t depth);
867
+
868
+ /**
869
+ * These are the states of the options that are configurable on the regular
870
+ * expression (or from within a group).
871
+ */
872
+ typedef enum {
873
+ PM_REGEXP_OPTION_STATE_INVALID,
874
+ PM_REGEXP_OPTION_STATE_TOGGLEABLE,
875
+ PM_REGEXP_OPTION_STATE_ADDABLE,
876
+ PM_REGEXP_OPTION_STATE_ADDED,
877
+ PM_REGEXP_OPTION_STATE_REMOVED
878
+ } pm_regexp_option_state_t;
879
+
880
+ // These are the options that are configurable on the regular expression (or
881
+ // from within a group).
882
+
883
+ /** The minimum character value for a regexp option slot. */
884
+ #define PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM 'a'
885
+
886
+ /** The maximum character value for a regexp option slot. */
887
+ #define PRISM_REGEXP_OPTION_STATE_SLOT_MAXIMUM 'x'
888
+
889
+ /** The number of regexp option slots. */
890
+ #define PRISM_REGEXP_OPTION_STATE_SLOTS (PRISM_REGEXP_OPTION_STATE_SLOT_MAXIMUM - PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM + 1)
891
+
892
+ /**
893
+ * This is the set of options that are configurable on the regular expression.
894
+ */
895
+ typedef struct {
896
+ /** The current state of each option. */
897
+ uint8_t values[PRISM_REGEXP_OPTION_STATE_SLOTS];
898
+ } pm_regexp_options_t;
899
+
900
+ /**
901
+ * Initialize a new set of options to their default values.
902
+ */
903
+ static void
904
+ pm_regexp_options_init(pm_regexp_options_t *options) {
905
+ memset(options, PM_REGEXP_OPTION_STATE_INVALID, sizeof(uint8_t) * PRISM_REGEXP_OPTION_STATE_SLOTS);
906
+ options->values['i' - PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM] = PM_REGEXP_OPTION_STATE_TOGGLEABLE;
907
+ options->values['m' - PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM] = PM_REGEXP_OPTION_STATE_TOGGLEABLE;
908
+ options->values['x' - PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM] = PM_REGEXP_OPTION_STATE_TOGGLEABLE;
909
+ options->values['d' - PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM] = PM_REGEXP_OPTION_STATE_ADDABLE;
910
+ options->values['a' - PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM] = PM_REGEXP_OPTION_STATE_ADDABLE;
911
+ options->values['u' - PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM] = PM_REGEXP_OPTION_STATE_ADDABLE;
912
+ }
913
+
914
+ /**
915
+ * Attempt to add the given option to the set of options. Returns true if it was
916
+ * added, false if it was already present.
917
+ */
918
+ static bool
919
+ pm_regexp_options_add(pm_regexp_options_t *options, uint8_t key) {
920
+ if (key >= PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM && key <= PRISM_REGEXP_OPTION_STATE_SLOT_MAXIMUM) {
921
+ key = (uint8_t) (key - PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM);
922
+
923
+ switch (options->values[key]) {
924
+ case PM_REGEXP_OPTION_STATE_INVALID:
925
+ case PM_REGEXP_OPTION_STATE_REMOVED:
926
+ return false;
927
+ case PM_REGEXP_OPTION_STATE_TOGGLEABLE:
928
+ case PM_REGEXP_OPTION_STATE_ADDABLE:
929
+ options->values[key] = PM_REGEXP_OPTION_STATE_ADDED;
930
+ return true;
931
+ case PM_REGEXP_OPTION_STATE_ADDED:
932
+ return true;
933
+ }
934
+ }
935
+
936
+ return false;
937
+ }
938
+
939
+ /**
940
+ * Attempt to remove the given option from the set of options. Returns true if
941
+ * it was removed, false if it was already absent.
942
+ */
943
+ static bool
944
+ pm_regexp_options_remove(pm_regexp_options_t *options, uint8_t key) {
945
+ if (key >= PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM && key <= PRISM_REGEXP_OPTION_STATE_SLOT_MAXIMUM) {
946
+ key = (uint8_t) (key - PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM);
947
+
948
+ switch (options->values[key]) {
949
+ case PM_REGEXP_OPTION_STATE_INVALID:
950
+ case PM_REGEXP_OPTION_STATE_ADDABLE:
951
+ return false;
952
+ case PM_REGEXP_OPTION_STATE_TOGGLEABLE:
953
+ case PM_REGEXP_OPTION_STATE_ADDED:
954
+ case PM_REGEXP_OPTION_STATE_REMOVED:
955
+ options->values[key] = PM_REGEXP_OPTION_STATE_REMOVED;
956
+ return true;
957
+ }
958
+ }
959
+
960
+ return false;
961
+ }
962
+
963
+ /**
964
+ * True if the given key is set in the options.
965
+ */
966
+ static uint8_t
967
+ pm_regexp_options_state(pm_regexp_options_t *options, uint8_t key) {
968
+ if (key >= PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM && key <= PRISM_REGEXP_OPTION_STATE_SLOT_MAXIMUM) {
969
+ key = (uint8_t) (key - PRISM_REGEXP_OPTION_STATE_SLOT_MINIMUM);
970
+ return options->values[key];
971
+ }
972
+
973
+ return false;
974
+ }
975
+
976
+ /**
977
+ * Groups can have quite a few different patterns for syntax. They basically
978
+ * just wrap a set of expressions, but they can potentially have options after a
979
+ * question mark. If there _isn't_ a question mark, then it's just a set of
980
+ * expressions. If there _is_, then here are the options:
981
+ *
982
+ * * (?#...) - inline comments
983
+ * * (?:subexp) - non-capturing group
984
+ * * (?=subexp) - positive lookahead
985
+ * * (?!subexp) - negative lookahead
986
+ * * (?>subexp) - atomic group
987
+ * * (?~subexp) - absence operator
988
+ * * (?<=subexp) - positive lookbehind
989
+ * * (?<!subexp) - negative lookbehind
990
+ * * (?<name>subexp) - named capturing group
991
+ * * (?'name'subexp) - named capturing group
992
+ * * (?(cond)yes-subexp) - conditional expression
993
+ * * (?(cond)yes-subexp|no-subexp) - conditional expression
994
+ * * (?imxdau-imx) - turn on and off configuration
995
+ * * (?imxdau-imx:subexp) - turn on and off configuration for an expression
996
+ */
997
+ static bool
998
+ pm_regexp_parse_group(pm_regexp_parser_t *parser, uint16_t depth) {
999
+ const uint8_t *group_start = parser->cursor;
1000
+
1001
+ pm_regexp_options_t options;
1002
+ pm_regexp_options_init(&options);
1003
+
1004
+ // First, parse any options for the group.
1005
+ if (pm_regexp_char_accept(parser, '?')) {
1006
+ if (pm_regexp_char_is_eof(parser)) {
1007
+ pm_regexp_parse_error(parser, group_start, parser->cursor, "end pattern in group");
1008
+ return false;
1009
+ }
1010
+
1011
+ switch (*parser->cursor) {
1012
+ case '#': { // inline comments
1013
+ parser->cursor++;
1014
+ if (pm_regexp_char_is_eof(parser)) {
1015
+ pm_regexp_parse_error(parser, group_start, parser->cursor, "end pattern in group");
1016
+ return false;
1017
+ }
1018
+
1019
+ if (parser->encoding_changed && parser->encoding->multibyte) {
1020
+ bool escaped = false;
1021
+
1022
+ // Here we're going to take a slow path and iterate through
1023
+ // each multibyte character to find the close paren. We do
1024
+ // this because \ can be a trailing byte in some encodings.
1025
+ while (parser->cursor < parser->end) {
1026
+ if (!escaped && *parser->cursor == ')') {
1027
+ parser->cursor++;
1028
+ return true;
1029
+ }
1030
+
1031
+ size_t width = parser->encoding->char_width(parser->cursor, (ptrdiff_t) (parser->end - parser->cursor));
1032
+ if (width == 0) {
1033
+ if (*parser->cursor >= 0x80) {
1034
+ parser->has_invalid_multibyte = true;
1035
+ pm_regexp_parse_error_format(parser, parser->cursor, parser->cursor + 1, PM_ERR_INVALID_MULTIBYTE_CHAR, parser->encoding->name);
1036
+ parser->cursor++;
1037
+ continue;
1038
+ }
1039
+ return false;
1040
+ }
1041
+
1042
+ escaped = (width == 1) && (*parser->cursor == '\\');
1043
+ parser->cursor += width;
1044
+ }
1045
+
1046
+ return false;
1047
+ } else {
1048
+ // Here we can take the fast path and use memchr to find the
1049
+ // next ) because we are safe checking backward for \ since
1050
+ // it cannot be a trailing character.
1051
+ bool found = pm_regexp_char_find(parser, ')');
1052
+
1053
+ while (found && (parser->start <= parser->cursor - 2) && (*(parser->cursor - 2) == '\\')) {
1054
+ found = pm_regexp_char_find(parser, ')');
1055
+ }
1056
+
1057
+ return found;
1058
+ }
1059
+ }
1060
+ case ':': // non-capturing group
1061
+ case '=': // positive lookahead
1062
+ case '!': // negative lookahead
1063
+ case '>': // atomic group
1064
+ case '~': // absence operator
1065
+ parser->cursor++;
1066
+ break;
1067
+ case '<':
1068
+ parser->cursor++;
1069
+ if (pm_regexp_char_is_eof(parser)) {
1070
+ pm_regexp_parse_error(parser, group_start, parser->cursor, "end pattern with unmatched parenthesis");
1071
+ return false;
1072
+ }
1073
+
1074
+ switch (*parser->cursor) {
1075
+ case '=': // positive lookbehind
1076
+ case '!': // negative lookbehind
1077
+ parser->cursor++;
1078
+ break;
1079
+ default: { // named capture group
1080
+ const uint8_t *start = parser->cursor;
1081
+ if (!pm_regexp_char_find(parser, '>')) {
1082
+ return false;
1083
+ }
1084
+
1085
+ if (parser->cursor - start == 1) {
1086
+ pm_regexp_parse_error(parser, start, parser->cursor, "group name is empty");
1087
+ }
1088
+
1089
+ if (parser->name_callback != NULL) {
1090
+ pm_regexp_parser_named_capture(parser, start, parser->cursor - 1);
1091
+ }
1092
+
1093
+ break;
1094
+ }
1095
+ }
1096
+ break;
1097
+ case '\'': { // named capture group
1098
+ const uint8_t *start = ++parser->cursor;
1099
+ if (!pm_regexp_char_find(parser, '\'')) {
1100
+ return false;
1101
+ }
1102
+
1103
+ if (parser->name_callback != NULL) {
1104
+ pm_regexp_parser_named_capture(parser, start, parser->cursor - 1);
1105
+ }
1106
+
1107
+ break;
1108
+ }
1109
+ case '(': // conditional expression
1110
+ if (!pm_regexp_char_find(parser, ')')) {
1111
+ return false;
1112
+ }
1113
+ break;
1114
+ case 'i': case 'm': case 'x': case 'd': case 'a': case 'u': // options
1115
+ while (!pm_regexp_char_is_eof(parser) && *parser->cursor != '-' && *parser->cursor != ':' && *parser->cursor != ')') {
1116
+ if (!pm_regexp_options_add(&options, *parser->cursor)) {
1117
+ return false;
1118
+ }
1119
+ parser->cursor++;
1120
+ }
1121
+
1122
+ if (pm_regexp_char_is_eof(parser)) {
1123
+ return false;
1124
+ }
1125
+
1126
+ // If we are at the end of the group of options and there is no
1127
+ // subexpression, then we are going to be setting the options
1128
+ // for the parent group. In this case we are safe to return now.
1129
+ if (*parser->cursor == ')') {
1130
+ if (pm_regexp_options_state(&options, 'x') == PM_REGEXP_OPTION_STATE_ADDED) {
1131
+ parser->extended_mode = true;
1132
+ }
1133
+
1134
+ parser->cursor++;
1135
+ return true;
1136
+ }
1137
+
1138
+ // If we hit a -, then we're done parsing options.
1139
+ if (*parser->cursor != '-') break;
1140
+
1141
+ PRISM_FALLTHROUGH
1142
+ case '-':
1143
+ parser->cursor++;
1144
+ while (!pm_regexp_char_is_eof(parser) && *parser->cursor != ':' && *parser->cursor != ')') {
1145
+ if (!pm_regexp_options_remove(&options, *parser->cursor)) {
1146
+ return false;
1147
+ }
1148
+ parser->cursor++;
1149
+ }
1150
+
1151
+ if (pm_regexp_char_is_eof(parser)) {
1152
+ return false;
1153
+ }
1154
+
1155
+ // If we are at the end of the group of options and there is no
1156
+ // subexpression, then we are going to be setting the options
1157
+ // for the parent group. In this case we are safe to return now.
1158
+ if (*parser->cursor == ')') {
1159
+ switch (pm_regexp_options_state(&options, 'x')) {
1160
+ case PM_REGEXP_OPTION_STATE_ADDED:
1161
+ parser->extended_mode = true;
1162
+ break;
1163
+ case PM_REGEXP_OPTION_STATE_REMOVED:
1164
+ parser->extended_mode = false;
1165
+ break;
1166
+ }
1167
+
1168
+ parser->cursor++;
1169
+ return true;
1170
+ }
1171
+
1172
+ break;
1173
+ default:
1174
+ parser->cursor++;
1175
+ pm_regexp_parse_error(parser, parser->cursor - 1, parser->cursor, "undefined group option");
1176
+ break;
1177
+ }
1178
+ }
1179
+
1180
+ bool extended_mode = parser->extended_mode;
1181
+ switch (pm_regexp_options_state(&options, 'x')) {
1182
+ case PM_REGEXP_OPTION_STATE_ADDED:
1183
+ parser->extended_mode = true;
1184
+ break;
1185
+ case PM_REGEXP_OPTION_STATE_REMOVED:
1186
+ parser->extended_mode = false;
1187
+ break;
1188
+ }
1189
+
1190
+ // Now, parse the expressions within this group.
1191
+ while (!pm_regexp_char_is_eof(parser) && *parser->cursor != ')') {
1192
+ if (!pm_regexp_parse_expression(parser, (uint16_t) (depth + 1))) {
1193
+ parser->extended_mode = extended_mode;
1194
+ return false;
1195
+ }
1196
+ pm_regexp_char_accept(parser, '|');
1197
+ }
1198
+
1199
+ // Finally, make sure we have a closing parenthesis.
1200
+ parser->extended_mode = extended_mode;
1201
+ if (pm_regexp_char_expect(parser, ')')) return true;
1202
+
1203
+ pm_regexp_parse_error(parser, group_start, parser->cursor, "end pattern with unmatched parenthesis");
1204
+ return false;
1205
+ }
1206
+
1207
+ /**
1208
+ * item : anchor
1209
+ * | match-posix-class
1210
+ * | match-char-set
1211
+ * | match-char-class
1212
+ * | match-char-prop
1213
+ * | match-char
1214
+ * | match-any
1215
+ * | group
1216
+ * | quantified
1217
+ * ;
1218
+ */
1219
+ static bool
1220
+ pm_regexp_parse_item(pm_regexp_parser_t *parser, uint16_t depth) {
1221
+ switch (*parser->cursor) {
1222
+ case '^':
1223
+ case '$':
1224
+ parser->cursor++;
1225
+ return pm_regexp_parse_quantifier(parser);
1226
+ case '\\':
1227
+ parser->cursor++;
1228
+ pm_regexp_parse_backslash_escape(parser);
1229
+ return pm_regexp_parse_quantifier(parser);
1230
+ case '(':
1231
+ parser->cursor++;
1232
+ return pm_regexp_parse_group(parser, depth) && pm_regexp_parse_quantifier(parser);
1233
+ case '[':
1234
+ parser->cursor++;
1235
+ return pm_regexp_parse_lbracket(parser, depth) && pm_regexp_parse_quantifier(parser);
1236
+ case '*':
1237
+ case '?':
1238
+ case '+':
1239
+ parser->cursor++;
1240
+ pm_regexp_parse_error(parser, parser->cursor - 1, parser->cursor, "target of repeat operator is not specified");
1241
+ return true;
1242
+ case ')':
1243
+ parser->cursor++;
1244
+ pm_regexp_parse_error(parser, parser->cursor - 1, parser->cursor, "unmatched close parenthesis");
1245
+ return true;
1246
+ case '#':
1247
+ if (parser->extended_mode) {
1248
+ if (!pm_regexp_char_find(parser, '\n')) parser->cursor = parser->end;
1249
+ return true;
1250
+ }
1251
+ PRISM_FALLTHROUGH
1252
+ default: {
1253
+ size_t width;
1254
+ if (!parser->encoding_changed) {
1255
+ width = pm_encoding_utf_8_char_width(parser->cursor, (ptrdiff_t) (parser->end - parser->cursor));
1256
+ } else {
1257
+ width = parser->encoding->char_width(parser->cursor, (ptrdiff_t) (parser->end - parser->cursor));
1258
+ }
1259
+
1260
+ if (width == 0) {
1261
+ if (*parser->cursor >= 0x80 && parser->encoding_changed) {
1262
+ if (parser->encoding->multibyte) {
1263
+ // Invalid multibyte character in a multibyte encoding.
1264
+ // Emit the error at the byte location immediately.
1265
+ parser->has_invalid_multibyte = true;
1266
+ pm_regexp_parse_error_format(parser, parser->cursor, parser->cursor + 1, PM_ERR_INVALID_MULTIBYTE_CHAR, parser->encoding->name);
1267
+ } else {
1268
+ // Non-ASCII byte in a single-byte encoding (e.g.,
1269
+ // US-ASCII). Count it for later error reporting.
1270
+ parser->non_ascii_literal_count++;
1271
+ }
1272
+ parser->cursor++;
1273
+ return pm_regexp_parse_quantifier(parser);
1274
+ }
1275
+ return false;
1276
+ }
1277
+
1278
+ // Count non-ASCII literal bytes.
1279
+ for (size_t i = 0; i < width; i++) {
1280
+ if (parser->cursor[i] >= 0x80) parser->non_ascii_literal_count++;
1281
+ }
1282
+
1283
+ parser->cursor += width;
1284
+ return pm_regexp_parse_quantifier(parser);
1285
+ }
1286
+ }
1287
+ }
1288
+
1289
+ /**
1290
+ * expression : item+
1291
+ * ;
1292
+ */
1293
+ static bool
1294
+ pm_regexp_parse_expression(pm_regexp_parser_t *parser, uint16_t depth) {
1295
+ if (depth >= PM_REGEXP_PARSE_DEPTH_MAX) {
1296
+ pm_regexp_parse_error(parser, parser->start, parser->end, "parse depth limit over");
1297
+ return false;
1298
+ }
1299
+
1300
+ if (!pm_regexp_parse_item(parser, depth)) {
1301
+ return false;
1302
+ }
1303
+
1304
+ while (!pm_regexp_char_is_eof(parser) && *parser->cursor != ')' && *parser->cursor != '|') {
1305
+ if (!pm_regexp_parse_item(parser, depth)) {
1306
+ return false;
1307
+ }
1308
+ }
1309
+
1310
+ return true;
1311
+ }
1312
+
1313
+ /**
1314
+ * pattern : EOF
1315
+ * | expression EOF
1316
+ * | expression '|' pattern
1317
+ * ;
1318
+ */
1319
+ static bool
1320
+ pm_regexp_parse_pattern(pm_regexp_parser_t *parser) {
1321
+ do {
1322
+ if (pm_regexp_char_is_eof(parser)) return true;
1323
+ if (!pm_regexp_parse_expression(parser, 0)) return false;
1324
+ } while (pm_regexp_char_accept(parser, '|'));
1325
+
1326
+ return pm_regexp_char_is_eof(parser);
1327
+ }
1328
+
1329
+ // ---------------------------------------------------------------------------
1330
+ // Encoding validation
1331
+ // ---------------------------------------------------------------------------
1332
+
1333
+ /**
1334
+ * Validate that groups of hex escape bytes in the buffer form valid multibyte
1335
+ * characters in the given encoding. Groups are separated by 0x00 sentinels.
1336
+ */
1337
+ static bool
1338
+ pm_regexp_validate_hex_escapes(const pm_encoding_t *encoding, const pm_buffer_t *buffer) {
1339
+ const uint8_t *data = (const uint8_t *) pm_buffer_value(buffer);
1340
+ size_t len = pm_buffer_length(buffer);
1341
+ size_t i = 0;
1342
+
1343
+ while (i < len) {
1344
+ size_t group_start = i;
1345
+ while (i < len && data[i] != 0x00) i++;
1346
+
1347
+ for (size_t j = group_start; j < i; ) {
1348
+ size_t width = encoding->char_width(data + j, (ptrdiff_t) (i - j));
1349
+ if (width == 0) return false;
1350
+ j += width;
1351
+ }
1352
+
1353
+ if (i < len) i++; // skip sentinel
1354
+ }
1355
+
1356
+ return true;
1357
+ }
1358
+
1359
+ /**
1360
+ * Format regexp source content for use in error messages, hex-escaping
1361
+ * non-ASCII bytes.
1362
+ */
1363
+ static void
1364
+ pm_regexp_format_for_error(pm_buffer_t *buffer, const pm_encoding_t *encoding, const uint8_t *source, size_t length) {
1365
+ size_t index = 0;
1366
+
1367
+ if (encoding == PM_ENCODING_UTF_8_ENTRY) {
1368
+ pm_buffer_append_string(buffer, (const char *) source, length);
1369
+ return;
1370
+ }
1371
+
1372
+ while (index < length) {
1373
+ if (source[index] < 0x80) {
1374
+ pm_buffer_append_byte(buffer, source[index]);
1375
+ index++;
1376
+ } else if (encoding->multibyte) {
1377
+ size_t width = encoding->char_width(source + index, (ptrdiff_t) (length - index));
1378
+
1379
+ if (width > 1) {
1380
+ pm_buffer_append_string(buffer, "\\x{", 3);
1381
+ for (size_t i = 0; i < width; i++) {
1382
+ pm_buffer_append_format(buffer, "%02X", source[index + i]);
1383
+ }
1384
+ pm_buffer_append_byte(buffer, '}');
1385
+ index += width;
1386
+ } else {
1387
+ pm_buffer_append_format(buffer, "\\x%02X", source[index]);
1388
+ index++;
1389
+ }
1390
+ } else {
1391
+ pm_buffer_append_format(buffer, "\\x%02X", source[index]);
1392
+ index++;
1393
+ }
1394
+ }
1395
+ }
1396
+
1397
+ /**
1398
+ * Emit an encoding validation error on the regexp node.
1399
+ */
1400
+ #define PM_REGEXP_ENCODING_ERROR(parser, diag_id, ...) \
1401
+ pm_diagnostic_list_append_format( \
1402
+ &(parser)->parser->metadata_arena, \
1403
+ &(parser)->parser->error_list, \
1404
+ (uint32_t) ((parser)->node_start - (parser)->parser->start), \
1405
+ (uint32_t) ((parser)->node_end - (parser)->node_start), \
1406
+ diag_id, __VA_ARGS__)
1407
+
1408
+ /**
1409
+ * Validate encoding for a regexp with an encoding modifier (/e, /s, /u, /n).
1410
+ *
1411
+ * The decision tree is:
1412
+ *
1413
+ * 1. No escape-set encoding (explicit_encoding == NULL):
1414
+ * a. ASCII-only content: validate property escapes, return forced US-ASCII
1415
+ * for /n or the modifier flags for others.
1416
+ * b. US-ASCII source with non-ASCII literals: emit per-byte errors.
1417
+ * c. Source encoding differs from modifier encoding: emit mismatch error.
1418
+ *
1419
+ * 2. Mixed \u and \x escapes: emit the appropriate conflict error depending
1420
+ * on the modifier and which escape type was last.
1421
+ *
1422
+ * 3. \u escape with non-/u modifier: incompatible encoding error.
1423
+ *
1424
+ * 4. Validate that hex escape byte sequences form valid multibyte characters
1425
+ * in the modifier's encoding.
1426
+ */
1427
+ static pm_node_flags_t
1428
+ pm_regexp_validate_encoding_modifier(pm_regexp_parser_t *parser, bool ascii_only, pm_node_flags_t flags, char modifier, const pm_encoding_t *modifier_encoding, const char *source_start, int source_length) {
1429
+
1430
+ if (parser->explicit_encoding == NULL) {
1431
+ if (ascii_only) {
1432
+ // Check property escapes against the modifier's encoding tier.
1433
+ // /n (ASCII-8BIT): only POSIX properties are valid.
1434
+ // /e, /s: POSIX and script properties are valid.
1435
+ // /u: all properties are valid.
1436
+ if (modifier == 'n' && parser->property_name != NULL) {
1437
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_INVALID_CHAR_PROPERTY,
1438
+ (int) parser->property_name_length, (const char *) parser->property_name,
1439
+ source_length, source_start);
1440
+ } else if (modifier != 'u' && parser->has_unicode_property_escape) {
1441
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_INVALID_CHAR_PROPERTY,
1442
+ (int) parser->unicode_property_name_length, (const char *) parser->unicode_property_name,
1443
+ source_length, source_start);
1444
+ }
1445
+ return modifier == 'n' ? PM_REGULAR_EXPRESSION_FLAGS_FORCED_US_ASCII_ENCODING : flags;
1446
+ }
1447
+
1448
+ if (parser->encoding == PM_ENCODING_US_ASCII_ENTRY) {
1449
+ for (uint32_t i = 0; i < parser->non_ascii_literal_count; i++) {
1450
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_INVALID_MULTIBYTE_CHAR, parser->encoding->name);
1451
+ }
1452
+ } else if (parser->encoding != modifier_encoding) {
1453
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_ENCODING_OPTION_MISMATCH, modifier, parser->encoding->name);
1454
+
1455
+ if (modifier == 'n' && !ascii_only) {
1456
+ pm_buffer_t formatted = { 0 };
1457
+ pm_regexp_format_for_error(&formatted, parser->encoding, (const uint8_t *) source_start, (size_t) source_length);
1458
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_NON_ESCAPED_MBC, (int) formatted.length, (const char *) formatted.value);
1459
+ pm_buffer_cleanup(&formatted);
1460
+ }
1461
+ }
1462
+
1463
+ return flags;
1464
+ }
1465
+
1466
+ // Mixed unicode + hex escapes.
1467
+ if (parser->has_unicode_escape && parser->has_hex_escape) {
1468
+ if (modifier == 'n') {
1469
+ if (parser->last_escape_was_unicode) {
1470
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_UTF8_CHAR_NON_UTF8_REGEXP, source_length, source_start);
1471
+ } else {
1472
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_ESCAPED_NON_ASCII_IN_UTF8, source_length, source_start);
1473
+ }
1474
+ } else {
1475
+ if (!pm_regexp_validate_hex_escapes(modifier_encoding, &parser->hex_escape_buffer)) {
1476
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_INVALID_MULTIBYTE_ESCAPE, source_length, source_start);
1477
+ }
1478
+ }
1479
+
1480
+ return flags;
1481
+ }
1482
+
1483
+ if (modifier != 'u' && parser->explicit_encoding == PM_ENCODING_UTF_8_ENTRY) {
1484
+ if (parser->last_escape_was_unicode) {
1485
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_INCOMPAT_CHAR_ENCODING, source_length, source_start);
1486
+ } else if (parser->encoding != PM_ENCODING_UTF_8_ENTRY) {
1487
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_INCOMPAT_CHAR_ENCODING, source_length, source_start);
1488
+ }
1489
+ }
1490
+
1491
+ if (modifier != 'n' && !pm_regexp_validate_hex_escapes(modifier_encoding, &parser->hex_escape_buffer)) {
1492
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_INVALID_MULTIBYTE_ESCAPE, source_length, source_start);
1493
+ }
1494
+
1495
+ return flags;
1496
+ }
1497
+
1498
+ /**
1499
+ * Validate encoding for a regexp without a modifier and compute the encoding
1500
+ * flags to set on the node.
1501
+ *
1502
+ * The decision tree is:
1503
+ *
1504
+ * 1. If a modifier (/n, /u, /e, /s) is present, delegate to
1505
+ * pm_regexp_validate_encoding_modifier.
1506
+ * 2. Invalid multibyte chars or unicode ranges: suppress further checks (errors
1507
+ * were already emitted during parsing).
1508
+ * 3. US-ASCII source with non-ASCII literals: emit per-byte errors.
1509
+ * 4. ASCII-only content: return forced US-ASCII (or forced UTF-8 if \p{...}).
1510
+ * 5. Escape-set encoding present: validate hex escapes against the target
1511
+ * encoding, handle mixed \u + \x conflicts, and return the appropriate
1512
+ * forced encoding flag.
1513
+ */
1514
+ static pm_node_flags_t
1515
+ pm_regexp_validate_encoding(pm_regexp_parser_t *parser, bool ascii_only, pm_node_flags_t flags, const char *source_start, int source_length) {
1516
+
1517
+ // Invalid multibyte characters suppress further validation.
1518
+ // Errors were already emitted at the byte locations during parsing.
1519
+ if (parser->has_invalid_multibyte) {
1520
+ return flags;
1521
+ }
1522
+
1523
+ if (parser->invalid_unicode_range) {
1524
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_INVALID_UNICODE_RANGE, source_length, source_start);
1525
+ return flags;
1526
+ }
1527
+
1528
+ // Check modifier flags first.
1529
+ if (flags & PM_REGULAR_EXPRESSION_FLAGS_ASCII_8BIT) {
1530
+ return pm_regexp_validate_encoding_modifier(parser, ascii_only, flags, 'n', PM_ENCODING_ASCII_8BIT_ENTRY, source_start, source_length);
1531
+ }
1532
+ if (flags & PM_REGULAR_EXPRESSION_FLAGS_UTF_8) {
1533
+ return pm_regexp_validate_encoding_modifier(parser, ascii_only, flags, 'u', PM_ENCODING_UTF_8_ENTRY, source_start, source_length);
1534
+ }
1535
+ if (flags & PM_REGULAR_EXPRESSION_FLAGS_EUC_JP) {
1536
+ return pm_regexp_validate_encoding_modifier(parser, ascii_only, flags, 'e', PM_ENCODING_EUC_JP_ENTRY, source_start, source_length);
1537
+ }
1538
+ if (flags & PM_REGULAR_EXPRESSION_FLAGS_WINDOWS_31J) {
1539
+ return pm_regexp_validate_encoding_modifier(parser, ascii_only, flags, 's', PM_ENCODING_WINDOWS_31J_ENTRY, source_start, source_length);
1540
+ }
1541
+
1542
+ // No modifier — check for non-ASCII literals in US-ASCII encoding.
1543
+ if (parser->encoding == PM_ENCODING_US_ASCII_ENTRY && parser->explicit_encoding == NULL && !ascii_only) {
1544
+ for (uint32_t i = 0; i < parser->non_ascii_literal_count; i++) {
1545
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_INVALID_MULTIBYTE_CHAR, parser->encoding->name);
1546
+ }
1547
+ }
1548
+
1549
+ // ASCII-only regexps get downgraded to US-ASCII, unless property escapes
1550
+ // force UTF-8.
1551
+ if (ascii_only) {
1552
+ if (parser->has_property_escape) {
1553
+ return PM_REGULAR_EXPRESSION_FLAGS_FORCED_UTF8_ENCODING;
1554
+ }
1555
+ return PM_REGULAR_EXPRESSION_FLAGS_FORCED_US_ASCII_ENCODING;
1556
+ }
1557
+
1558
+ // Check explicit encoding from escape sequences.
1559
+ if (parser->explicit_encoding != NULL) {
1560
+ // Mixed unicode + hex escapes without modifier.
1561
+ if (parser->has_unicode_escape && parser->has_hex_escape && parser->encoding != PM_ENCODING_UTF_8_ENTRY) {
1562
+ if (parser->encoding != PM_ENCODING_US_ASCII_ENTRY &&
1563
+ parser->encoding != PM_ENCODING_ASCII_8BIT_ENTRY &&
1564
+ !pm_regexp_validate_hex_escapes(parser->encoding, &parser->hex_escape_buffer)) {
1565
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_INVALID_MULTIBYTE_ESCAPE, source_length, source_start);
1566
+ } else if (parser->last_escape_was_unicode) {
1567
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_UTF8_CHAR_NON_UTF8_REGEXP, source_length, source_start);
1568
+ } else {
1569
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_REGEXP_ESCAPED_NON_ASCII_IN_UTF8, source_length, source_start);
1570
+ }
1571
+
1572
+ return 0;
1573
+ }
1574
+
1575
+ if (parser->explicit_encoding == PM_ENCODING_UTF_8_ENTRY) {
1576
+ if (!pm_regexp_validate_hex_escapes(parser->explicit_encoding, &parser->hex_escape_buffer)) {
1577
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_INVALID_MULTIBYTE_ESCAPE, source_length, source_start);
1578
+ }
1579
+
1580
+ return PM_REGULAR_EXPRESSION_FLAGS_FORCED_UTF8_ENCODING;
1581
+ } else if (parser->encoding == PM_ENCODING_US_ASCII_ENTRY) {
1582
+ return PM_REGULAR_EXPRESSION_FLAGS_FORCED_BINARY_ENCODING;
1583
+ } else {
1584
+ if (!pm_regexp_validate_hex_escapes(parser->explicit_encoding, &parser->hex_escape_buffer)) {
1585
+ PM_REGEXP_ENCODING_ERROR(parser, PM_ERR_INVALID_MULTIBYTE_ESCAPE, source_length, source_start);
1586
+ }
1587
+ }
1588
+ }
1589
+
1590
+ return 0;
1591
+ }
1592
+
1593
+ /**
1594
+ * Parse a regular expression, validate its encoding, and optionally extract
1595
+ * named capture groups. Encoding validation walks the raw source (content_loc)
1596
+ * to distinguish escape-produced bytes from literal bytes. Named capture
1597
+ * extraction walks the unescaped content since escape sequences in group names
1598
+ * (e.g., line continuations) have already been processed by the lexer.
1599
+ */
1600
+ pm_node_flags_t
1601
+ pm_regexp_parse(pm_parser_t *parser, pm_regular_expression_node_t *node, pm_regexp_name_callback_t name_callback, void *name_data) {
1602
+ const uint8_t *source = parser->start + node->content_loc.start;
1603
+ size_t size = node->content_loc.length;
1604
+ bool extended_mode = PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_EXTENDED);
1605
+ pm_node_flags_t flags = PM_NODE_FLAGS(node);
1606
+
1607
+ const uint8_t *node_start = parser->start + node->base.location.start;
1608
+ const uint8_t *node_end = parser->start + node->base.location.start + node->base.location.length;
1609
+
1610
+ // First pass: walk raw source for encoding validation (no name extraction).
1611
+ pm_regexp_parser_t regexp_parser = {
1612
+ .parser = parser,
1613
+ .start = source,
1614
+ .cursor = source,
1615
+ .end = source + size,
1616
+ .extended_mode = extended_mode,
1617
+ .encoding_changed = parser->encoding_changed,
1618
+ .encoding = parser->encoding,
1619
+ .name_callback = NULL,
1620
+ .name_data = NULL,
1621
+ .report_errors = true,
1622
+ .node_start = node_start,
1623
+ .node_end = node_end,
1624
+ .has_unicode_escape = false,
1625
+ .has_hex_escape = false,
1626
+ .last_escape_was_unicode = false,
1627
+ .explicit_encoding = NULL,
1628
+ .has_property_escape = false,
1629
+ .has_unicode_property_escape = false,
1630
+ .property_name = NULL,
1631
+ .property_name_length = 0,
1632
+ .unicode_property_name = NULL,
1633
+ .unicode_property_name_length = 0,
1634
+ .non_ascii_literal_count = 0,
1635
+ .invalid_unicode_range = false,
1636
+ .hex_escape_buffer = { 0 },
1637
+ .hex_group_active = false,
1638
+ .has_invalid_multibyte = false,
1639
+ };
1640
+
1641
+ pm_regexp_parse_pattern(&regexp_parser);
1642
+
1643
+ // Compute ascii_only from the regexp parser's tracked state. We cannot
1644
+ // use node->unescaped for this because regexp unescaped content preserves
1645
+ // escape text (e.g., \x80 is 4 ASCII chars), not the binary values.
1646
+ bool ascii_only = !regexp_parser.has_hex_escape && !regexp_parser.has_unicode_escape && regexp_parser.non_ascii_literal_count == 0;
1647
+ // Use the unescaped content for error messages to match CRuby's format,
1648
+ // where Ruby escapes like \M-\C-? are resolved to bytes but regexp escapes
1649
+ // like \u{80} are preserved as text.
1650
+ const char *error_source = (const char *) pm_string_source(&node->unescaped);
1651
+ int error_source_length = (int) pm_string_length(&node->unescaped);
1652
+ pm_node_flags_t encoding_flags = pm_regexp_validate_encoding(&regexp_parser, ascii_only, flags, error_source, error_source_length);
1653
+ pm_buffer_cleanup(&regexp_parser.hex_escape_buffer);
1654
+
1655
+ // Second pass: walk unescaped content for named capture extraction.
1656
+ if (name_callback != NULL) {
1657
+ pm_regexp_parse_named_captures(parser, pm_string_source(&node->unescaped), pm_string_length(&node->unescaped), extended_mode, name_callback, name_data);
1658
+ }
1659
+
1660
+ return encoding_flags;
1661
+ }
1662
+
1663
+ /**
1664
+ * Parse an interpolated regular expression for named capture groups only.
1665
+ * This is used for the =~ operator with interpolated regexps where we don't
1666
+ * have a pm_regular_expression_node_t. No encoding validation is performed.
1667
+ *
1668
+ * Note: The encoding-tracking fields (has_unicode_escape, has_hex_escape, etc.)
1669
+ * are initialized but not used for the result. They exist because the parsing
1670
+ * functions (pm_regexp_parse_backslash_escape, etc.) unconditionally update
1671
+ * them as they walk through the content.
1672
+ */
1673
+ void
1674
+ pm_regexp_parse_named_captures(pm_parser_t *parser, const uint8_t *source, size_t size, bool extended_mode, pm_regexp_name_callback_t name_callback, void *name_data) {
1675
+ pm_regexp_parser_t regexp_parser = {
1676
+ .parser = parser,
1677
+ .start = source,
1678
+ .cursor = source,
1679
+ .end = source + size,
1680
+ .extended_mode = extended_mode,
1681
+ .encoding_changed = parser->encoding_changed,
1682
+ .encoding = parser->encoding,
1683
+ .name_callback = name_callback,
1684
+ .name_data = name_data,
1685
+ .report_errors = false,
1686
+ .has_unicode_escape = false,
1687
+ .has_hex_escape = false,
1688
+ .last_escape_was_unicode = false,
1689
+ .explicit_encoding = NULL,
1690
+ .has_property_escape = false,
1691
+ .has_unicode_property_escape = false,
1692
+ .property_name = NULL,
1693
+ .property_name_length = 0,
1694
+ .unicode_property_name = NULL,
1695
+ .unicode_property_name_length = 0,
1696
+ .non_ascii_literal_count = 0,
1697
+ .invalid_unicode_range = false,
1698
+ .hex_escape_buffer = { 0 },
1699
+ .hex_group_active = false,
1700
+ .has_invalid_multibyte = false,
1701
+ };
1702
+
1703
+ pm_regexp_parse_pattern(&regexp_parser);
1704
+ pm_buffer_cleanup(&regexp_parser.hex_escape_buffer);
1705
+ }