Debian Codegraph @

src/prism.c

raw symbols SCIP
1 #include "prism.h"
2
3 /**
4 * The prism version and the serialization format.
5 */
6 const char *
7 pm_version(void) {
8 return PRISM_VERSION;
9 }
10
11 /**
12 * In heredocs, tabs automatically complete up to the next 8 spaces. This is
13 * defined in CRuby as TAB_WIDTH.
14 */
15 #define PM_TAB_WHITESPACE_SIZE 8
16
17 // Macros for min/max.
18 #define MIN(a,b) (((a)<(b))?(a):(b))
19 #define MAX(a,b) (((a)>(b))?(a):(b))
20
21 /******************************************************************************/
22 /* Helpful AST-related macros */
23 /******************************************************************************/
24
25 #define FL PM_NODE_FLAGS
26 #define UP PM_NODE_UPCAST
27
28 #define PM_TOKEN_START(token_) ((token_)->start)
29 #define PM_TOKEN_END(token_) ((token_)->end)
30
31 #define PM_NODE_START(node_) (UP(node_)->location.start)
32 #define PM_NODE_END(node_) (UP(node_)->location.end)
33
34 #define PM_LOCATION_NULL_VALUE(parser_) ((pm_location_t) { .start = (parser_)->start, .end = (parser_)->start })
35 #define PM_LOCATION_TOKEN_VALUE(token_) ((pm_location_t) { .start = PM_TOKEN_START(token_), .end = PM_TOKEN_END(token_) })
36 #define PM_LOCATION_NODE_VALUE(node_) ((pm_location_t) { .start = PM_NODE_START(node_), .end = PM_NODE_END(node_) })
37 #define PM_OPTIONAL_LOCATION_TOKEN_VALUE(token) ((token)->type == PM_TOKEN_NOT_PROVIDED ? ((pm_location_t) { 0 }) : PM_LOCATION_TOKEN_VALUE(token))
38
39 /******************************************************************************/
40 /* Lex mode manipulations */
41 /******************************************************************************/
42
43 /**
44 * Returns the incrementor character that should be used to increment the
45 * nesting count if one is possible.
46 */
47 static inline uint8_t
48 lex_mode_incrementor(const uint8_t start) {
49 switch (start) {
50 case '(':
51 case '[':
52 case '{':
53 case '<':
54 return start;
55 default:
56 return '\0';
57 }
58 }
59
60 /**
61 * Returns the matching character that should be used to terminate a list
62 * beginning with the given character.
63 */
64 static inline uint8_t
65 lex_mode_terminator(const uint8_t start) {
66 switch (start) {
67 case '(':
68 return ')';
69 case '[':
70 return ']';
71 case '{':
72 return '}';
73 case '<':
74 return '>';
75 default:
76 return start;
77 }
78 }
79
80 /**
81 * Push a new lex state onto the stack. If we're still within the pre-allocated
82 * space of the lex state stack, then we'll just use a new slot. Otherwise we'll
83 * allocate a new pointer and use that.
84 */
85 static bool
86 lex_mode_push(pm_parser_t *parser, pm_lex_mode_t lex_mode) {
87 lex_mode.prev = parser->lex_modes.current;
88 parser->lex_modes.index++;
89
90 if (parser->lex_modes.index > PM_LEX_STACK_SIZE - 1) {
91 parser->lex_modes.current = (pm_lex_mode_t *) xmalloc(sizeof(pm_lex_mode_t));
92 if (parser->lex_modes.current == NULL) return false;
93
94 *parser->lex_modes.current = lex_mode;
95 } else {
96 parser->lex_modes.stack[parser->lex_modes.index] = lex_mode;
97 parser->lex_modes.current = &parser->lex_modes.stack[parser->lex_modes.index];
98 }
99
100 return true;
101 }
102
103 /**
104 * Push on a new list lex mode.
105 */
106 static inline bool
107 lex_mode_push_list(pm_parser_t *parser, bool interpolation, uint8_t delimiter) {
108 uint8_t incrementor = lex_mode_incrementor(delimiter);
109 uint8_t terminator = lex_mode_terminator(delimiter);
110
111 pm_lex_mode_t lex_mode = {
112 .mode = PM_LEX_LIST,
113 .as.list = {
114 .nesting = 0,
115 .interpolation = interpolation,
116 .incrementor = incrementor,
117 .terminator = terminator
118 }
119 };
120
121 // These are the places where we need to split up the content of the list.
122 // We'll use strpbrk to find the first of these characters.
123 uint8_t *breakpoints = lex_mode.as.list.breakpoints;
124 memcpy(breakpoints, "\\ \t\f\r\v\n\0\0\0", sizeof(lex_mode.as.list.breakpoints));
125 size_t index = 7;
126
127 // Now we'll add the terminator to the list of breakpoints. If the
128 // terminator is not already a NULL byte, add it to the list.
129 if (terminator != '\0') {
130 breakpoints[index++] = terminator;
131 }
132
133 // If interpolation is allowed, then we're going to check for the #
134 // character. Otherwise we'll only look for escapes and the terminator.
135 if (interpolation) {
136 breakpoints[index++] = '#';
137 }
138
139 // If there is an incrementor, then we'll check for that as well.
140 if (incrementor != '\0') {
141 breakpoints[index++] = incrementor;
142 }
143
144 parser->explicit_encoding = NULL;
145 return lex_mode_push(parser, lex_mode);
146 }
147
148 /**
149 * Push on a new list lex mode that is only used for compatibility. This is
150 * called when we're at the end of the file. We want the parser to be able to
151 * perform its normal error tolerance.
152 */
153 static inline bool
154 lex_mode_push_list_eof(pm_parser_t *parser) {
155 return lex_mode_push_list(parser, false, '\0');
156 }
157
158 /**
159 * Push on a new regexp lex mode.
160 */
161 static inline bool
162 lex_mode_push_regexp(pm_parser_t *parser, uint8_t incrementor, uint8_t terminator) {
163 pm_lex_mode_t lex_mode = {
164 .mode = PM_LEX_REGEXP,
165 .as.regexp = {
166 .nesting = 0,
167 .incrementor = incrementor,
168 .terminator = terminator
169 }
170 };
171
172 // These are the places where we need to split up the content of the
173 // regular expression. We'll use strpbrk to find the first of these
174 // characters.
175 uint8_t *breakpoints = lex_mode.as.regexp.breakpoints;
176 memcpy(breakpoints, "\r\n\\#\0\0", sizeof(lex_mode.as.regexp.breakpoints));
177 size_t index = 4;
178
179 // First we'll add the terminator.
180 if (terminator != '\0') {
181 breakpoints[index++] = terminator;
182 }
183
184 // Next, if there is an incrementor, then we'll check for that as well.
185 if (incrementor != '\0') {
186 breakpoints[index++] = incrementor;
187 }
188
189 parser->explicit_encoding = NULL;
190 return lex_mode_push(parser, lex_mode);
191 }
192
193 /**
194 * Push on a new string lex mode.
195 */
196 static inline bool
197 lex_mode_push_string(pm_parser_t *parser, bool interpolation, bool label_allowed, uint8_t incrementor, uint8_t terminator) {
198 pm_lex_mode_t lex_mode = {
199 .mode = PM_LEX_STRING,
200 .as.string = {
201 .nesting = 0,
202 .interpolation = interpolation,
203 .label_allowed = label_allowed,
204 .incrementor = incrementor,
205 .terminator = terminator
206 }
207 };
208
209 // These are the places where we need to split up the content of the
210 // string. We'll use strpbrk to find the first of these characters.
211 uint8_t *breakpoints = lex_mode.as.string.breakpoints;
212 memcpy(breakpoints, "\r\n\\\0\0\0", sizeof(lex_mode.as.string.breakpoints));
213 size_t index = 3;
214
215 // Now add in the terminator. If the terminator is not already a NULL byte,
216 // then we'll add it.
217 if (terminator != '\0') {
218 breakpoints[index++] = terminator;
219 }
220
221 // If interpolation is allowed, then we're going to check for the #
222 // character. Otherwise we'll only look for escapes and the terminator.
223 if (interpolation) {
224 breakpoints[index++] = '#';
225 }
226
227 // If we have an incrementor, then we'll add that in as a breakpoint as
228 // well.
229 if (incrementor != '\0') {
230 breakpoints[index++] = incrementor;
231 }
232
233 parser->explicit_encoding = NULL;
234 return lex_mode_push(parser, lex_mode);
235 }
236
237 /**
238 * Push on a new string lex mode that is only used for compatibility. This is
239 * called when we're at the end of the file. We want the parser to be able to
240 * perform its normal error tolerance.
241 */
242 static inline bool
243 lex_mode_push_string_eof(pm_parser_t *parser) {
244 return lex_mode_push_string(parser, false, false, '\0', '\0');
245 }
246
247 /**
248 * Pop the current lex state off the stack. If we're within the pre-allocated
249 * space of the lex state stack, then we'll just decrement the index. Otherwise
250 * we'll free the current pointer and use the previous pointer.
251 */
252 static void
253 lex_mode_pop(pm_parser_t *parser) {
254 if (parser->lex_modes.index == 0) {
255 parser->lex_modes.current->mode = PM_LEX_DEFAULT;
256 } else if (parser->lex_modes.index < PM_LEX_STACK_SIZE) {
257 parser->lex_modes.index--;
258 parser->lex_modes.current = &parser->lex_modes.stack[parser->lex_modes.index];
259 } else {
260 parser->lex_modes.index--;
261 pm_lex_mode_t *prev = parser->lex_modes.current->prev;
262 xfree(parser->lex_modes.current);
263 parser->lex_modes.current = prev;
264 }
265 }
266
267 /**
268 * This is the equivalent of IS_lex_state is CRuby.
269 */
270 static inline bool
271 lex_state_p(const pm_parser_t *parser, pm_lex_state_t state) {
272 return parser->lex_state & state;
273 }
274
275 typedef enum {
276 PM_IGNORED_NEWLINE_NONE = 0,
277 PM_IGNORED_NEWLINE_ALL,
278 PM_IGNORED_NEWLINE_PATTERN
279 } pm_ignored_newline_type_t;
280
281 static inline pm_ignored_newline_type_t
282 lex_state_ignored_p(pm_parser_t *parser) {
283 bool ignored = lex_state_p(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_CLASS | PM_LEX_STATE_FNAME | PM_LEX_STATE_DOT) && !lex_state_p(parser, PM_LEX_STATE_LABELED);
284
285 if (ignored) {
286 return PM_IGNORED_NEWLINE_ALL;
287 } else if ((parser->lex_state & ~((unsigned int) PM_LEX_STATE_LABEL)) == (PM_LEX_STATE_ARG | PM_LEX_STATE_LABELED)) {
288 return PM_IGNORED_NEWLINE_PATTERN;
289 } else {
290 return PM_IGNORED_NEWLINE_NONE;
291 }
292 }
293
294 static inline bool
295 lex_state_beg_p(pm_parser_t *parser) {
296 return lex_state_p(parser, PM_LEX_STATE_BEG_ANY) || ((parser->lex_state & (PM_LEX_STATE_ARG | PM_LEX_STATE_LABELED)) == (PM_LEX_STATE_ARG | PM_LEX_STATE_LABELED));
297 }
298
299 static inline bool
300 lex_state_arg_p(pm_parser_t *parser) {
301 return lex_state_p(parser, PM_LEX_STATE_ARG_ANY);
302 }
303
304 static inline bool
305 lex_state_spcarg_p(pm_parser_t *parser, bool space_seen) {
306 if (parser->current.end >= parser->end) {
307 return false;
308 }
309 return lex_state_arg_p(parser) && space_seen && !pm_char_is_whitespace(*parser->current.end);
310 }
311
312 static inline bool
313 lex_state_end_p(pm_parser_t *parser) {
314 return lex_state_p(parser, PM_LEX_STATE_END_ANY);
315 }
316
317 /**
318 * This is the equivalent of IS_AFTER_OPERATOR in CRuby.
319 */
320 static inline bool
321 lex_state_operator_p(pm_parser_t *parser) {
322 return lex_state_p(parser, PM_LEX_STATE_FNAME | PM_LEX_STATE_DOT);
323 }
324
325 /**
326 * Set the state of the lexer. This is defined as a function to be able to put a
327 * breakpoint in it.
328 */
329 static inline void
330 lex_state_set(pm_parser_t *parser, pm_lex_state_t state) {
331 parser->lex_state = state;
332 }
333
334 #ifndef PM_DEBUG_LOGGING
335 /**
336 * Debugging logging will print additional information to stdout whenever the
337 * lexer state changes.
338 */
339 #define PM_DEBUG_LOGGING 0
340 #endif
341
342 #if PM_DEBUG_LOGGING
343 PRISM_ATTRIBUTE_UNUSED static void
344 debug_state(pm_parser_t *parser) {
345 fprintf(stderr, "STATE: ");
346 bool first = true;
347
348 if (parser->lex_state == PM_LEX_STATE_NONE) {
349 fprintf(stderr, "NONE\n");
350 return;
351 }
352
353 #define CHECK_STATE(state) \
354 if (parser->lex_state & state) { \
355 if (!first) fprintf(stderr, "|"); \
356 fprintf(stderr, "%s", #state); \
357 first = false; \
358 }
359
360 CHECK_STATE(PM_LEX_STATE_BEG)
361 CHECK_STATE(PM_LEX_STATE_END)
362 CHECK_STATE(PM_LEX_STATE_ENDARG)
363 CHECK_STATE(PM_LEX_STATE_ENDFN)
364 CHECK_STATE(PM_LEX_STATE_ARG)
365 CHECK_STATE(PM_LEX_STATE_CMDARG)
366 CHECK_STATE(PM_LEX_STATE_MID)
367 CHECK_STATE(PM_LEX_STATE_FNAME)
368 CHECK_STATE(PM_LEX_STATE_DOT)
369 CHECK_STATE(PM_LEX_STATE_CLASS)
370 CHECK_STATE(PM_LEX_STATE_LABEL)
371 CHECK_STATE(PM_LEX_STATE_LABELED)
372 CHECK_STATE(PM_LEX_STATE_FITEM)
373
374 #undef CHECK_STATE
375
376 fprintf(stderr, "\n");
377 }
378
379 static void
380 debug_lex_state_set(pm_parser_t *parser, pm_lex_state_t state, char const * caller_name, int line_number) {
381 fprintf(stderr, "Caller: %s:%d\nPrevious: ", caller_name, line_number);
382 debug_state(parser);
383 lex_state_set(parser, state);
384 fprintf(stderr, "Now: ");
385 debug_state(parser);
386 fprintf(stderr, "\n");
387 }
388
389 #define lex_state_set(parser, state) debug_lex_state_set(parser, state, __func__, __LINE__)
390 #endif
391
392 /******************************************************************************/
393 /* Command-line macro helpers */
394 /******************************************************************************/
395
396 /** True if the parser has the given command-line option. */
397 #define PM_PARSER_COMMAND_LINE_OPTION(parser, option) ((parser)->command_line & (option))
398
399 /** True if the -a command line option was given. */
400 #define PM_PARSER_COMMAND_LINE_OPTION_A(parser) PM_PARSER_COMMAND_LINE_OPTION(parser, PM_OPTIONS_COMMAND_LINE_A)
401
402 /** True if the -e command line option was given. */
403 #define PM_PARSER_COMMAND_LINE_OPTION_E(parser) PM_PARSER_COMMAND_LINE_OPTION(parser, PM_OPTIONS_COMMAND_LINE_E)
404
405 /** True if the -l command line option was given. */
406 #define PM_PARSER_COMMAND_LINE_OPTION_L(parser) PM_PARSER_COMMAND_LINE_OPTION(parser, PM_OPTIONS_COMMAND_LINE_L)
407
408 /** True if the -n command line option was given. */
409 #define PM_PARSER_COMMAND_LINE_OPTION_N(parser) PM_PARSER_COMMAND_LINE_OPTION(parser, PM_OPTIONS_COMMAND_LINE_N)
410
411 /** True if the -p command line option was given. */
412 #define PM_PARSER_COMMAND_LINE_OPTION_P(parser) PM_PARSER_COMMAND_LINE_OPTION(parser, PM_OPTIONS_COMMAND_LINE_P)
413
414 /** True if the -x command line option was given. */
415 #define PM_PARSER_COMMAND_LINE_OPTION_X(parser) PM_PARSER_COMMAND_LINE_OPTION(parser, PM_OPTIONS_COMMAND_LINE_X)
416
417 /******************************************************************************/
418 /* Diagnostic-related functions */
419 /******************************************************************************/
420
421 /**
422 * Append an error to the list of errors on the parser.
423 */
424 static inline void
425 pm_parser_err(pm_parser_t *parser, const uint8_t *start, const uint8_t *end, pm_diagnostic_id_t diag_id) {
426 pm_diagnostic_list_append(&parser->error_list, start, end, diag_id);
427 }
428
429 /**
430 * Append an error to the list of errors on the parser using a format string.
431 */
432 #define PM_PARSER_ERR_FORMAT(parser, start, end, diag_id, ...) \
433 pm_diagnostic_list_append_format(&parser->error_list, start, end, diag_id, __VA_ARGS__)
434
435 /**
436 * Append an error to the list of errors on the parser using the location of the
437 * current token.
438 */
439 static inline void
440 pm_parser_err_current(pm_parser_t *parser, pm_diagnostic_id_t diag_id) {
441 pm_parser_err(parser, parser->current.start, parser->current.end, diag_id);
442 }
443
444 /**
445 * Append an error to the list of errors on the parser using the given location
446 * using a format string.
447 */
448 #define PM_PARSER_ERR_LOCATION_FORMAT(parser, location, diag_id, ...) \
449 PM_PARSER_ERR_FORMAT(parser, (location)->start, (location)->end, diag_id, __VA_ARGS__)
450
451 /**
452 * Append an error to the list of errors on the parser using the location of the
453 * given node.
454 */
455 static inline void
456 pm_parser_err_node(pm_parser_t *parser, const pm_node_t *node, pm_diagnostic_id_t diag_id) {
457 pm_parser_err(parser, node->location.start, node->location.end, diag_id);
458 }
459
460 /**
461 * Append an error to the list of errors on the parser using the location of the
462 * given node and a format string.
463 */
464 #define PM_PARSER_ERR_NODE_FORMAT(parser, node, diag_id, ...) \
465 PM_PARSER_ERR_FORMAT(parser, (node)->location.start, (node)->location.end, diag_id, __VA_ARGS__)
466
467 /**
468 * Append an error to the list of errors on the parser using the location of the
469 * given node and a format string, and add on the content of the node.
470 */
471 #define PM_PARSER_ERR_NODE_FORMAT_CONTENT(parser, node, diag_id) \
472 PM_PARSER_ERR_NODE_FORMAT(parser, node, diag_id, (int) ((node)->location.end - (node)->location.start), (const char *) (node)->location.start)
473
474 /**
475 * Append an error to the list of errors on the parser using the location of the
476 * previous token.
477 */
478 static inline void
479 pm_parser_err_previous(pm_parser_t *parser, pm_diagnostic_id_t diag_id) {
480 pm_parser_err(parser, parser->previous.start, parser->previous.end, diag_id);
481 }
482
483 /**
484 * Append an error to the list of errors on the parser using the location of the
485 * given token.
486 */
487 static inline void
488 pm_parser_err_token(pm_parser_t *parser, const pm_token_t *token, pm_diagnostic_id_t diag_id) {
489 pm_parser_err(parser, token->start, token->end, diag_id);
490 }
491
492 /**
493 * Append an error to the list of errors on the parser using the location of the
494 * given token and a format string.
495 */
496 #define PM_PARSER_ERR_TOKEN_FORMAT(parser, token, diag_id, ...) \
497 PM_PARSER_ERR_FORMAT(parser, (token).start, (token).end, diag_id, __VA_ARGS__)
498
499 /**
500 * Append an error to the list of errors on the parser using the location of the
501 * given token and a format string, and add on the content of the token.
502 */
503 #define PM_PARSER_ERR_TOKEN_FORMAT_CONTENT(parser, token, diag_id) \
504 PM_PARSER_ERR_TOKEN_FORMAT(parser, token, diag_id, (int) ((token).end - (token).start), (const char *) (token).start)
505
506 /**
507 * Append a warning to the list of warnings on the parser.
508 */
509 static inline void
510 pm_parser_warn(pm_parser_t *parser, const uint8_t *start, const uint8_t *end, pm_diagnostic_id_t diag_id) {
511 pm_diagnostic_list_append(&parser->warning_list, start, end, diag_id);
512 }
513
514 /**
515 * Append a warning to the list of warnings on the parser using the location of
516 * the given token.
517 */
518 static inline void
519 pm_parser_warn_token(pm_parser_t *parser, const pm_token_t *token, pm_diagnostic_id_t diag_id) {
520 pm_parser_warn(parser, token->start, token->end, diag_id);
521 }
522
523 /**
524 * Append a warning to the list of warnings on the parser using the location of
525 * the given node.
526 */
527 static inline void
528 pm_parser_warn_node(pm_parser_t *parser, const pm_node_t *node, pm_diagnostic_id_t diag_id) {
529 pm_parser_warn(parser, node->location.start, node->location.end, diag_id);
530 }
531
532 /**
533 * Append a warning to the list of warnings on the parser using a format string.
534 */
535 #define PM_PARSER_WARN_FORMAT(parser, start, end, diag_id, ...) \
536 pm_diagnostic_list_append_format(&parser->warning_list, start, end, diag_id, __VA_ARGS__)
537
538 /**
539 * Append a warning to the list of warnings on the parser using the location of
540 * the given token and a format string.
541 */
542 #define PM_PARSER_WARN_TOKEN_FORMAT(parser, token, diag_id, ...) \
543 PM_PARSER_WARN_FORMAT(parser, (token).start, (token).end, diag_id, __VA_ARGS__)
544
545 /**
546 * Append a warning to the list of warnings on the parser using the location of
547 * the given token and a format string, and add on the content of the token.
548 */
549 #define PM_PARSER_WARN_TOKEN_FORMAT_CONTENT(parser, token, diag_id) \
550 PM_PARSER_WARN_TOKEN_FORMAT(parser, token, diag_id, (int) ((token).end - (token).start), (const char *) (token).start)
551
552 /**
553 * Append a warning to the list of warnings on the parser using the location of
554 * the given node and a format string.
555 */
556 #define PM_PARSER_WARN_NODE_FORMAT(parser, node, diag_id, ...) \
557 PM_PARSER_WARN_FORMAT(parser, (node)->location.start, (node)->location.end, diag_id, __VA_ARGS__)
558
559 /**
560 * Add an error for an expected heredoc terminator. This is a special function
561 * only because it grabs its location off of a lex mode instead of a node or a
562 * token.
563 */
564 static void
565 pm_parser_err_heredoc_term(pm_parser_t *parser, const uint8_t *ident_start, size_t ident_length) {
566 PM_PARSER_ERR_FORMAT(
567 parser,
568 ident_start,
569 ident_start + ident_length,
570 PM_ERR_HEREDOC_TERM,
571 (int) ident_length,
572 (const char *) ident_start
573 );
574 }
575
576 /******************************************************************************/
577 /* Scope-related functions */
578 /******************************************************************************/
579
580 /**
581 * Allocate and initialize a new scope. Push it onto the scope stack.
582 */
583 static bool
584 pm_parser_scope_push(pm_parser_t *parser, bool closed) {
585 pm_scope_t *scope = (pm_scope_t *) xmalloc(sizeof(pm_scope_t));
586 if (scope == NULL) return false;
587
588 *scope = (pm_scope_t) {
589 .previous = parser->current_scope,
590 .locals = { 0 },
591 .parameters = PM_SCOPE_PARAMETERS_NONE,
592 .implicit_parameters = { 0 },
593 .shareable_constant = parser->current_scope == NULL ? PM_SCOPE_SHAREABLE_CONSTANT_NONE : parser->current_scope->shareable_constant,
594 .closed = closed
595 };
596
597 parser->current_scope = scope;
598 return true;
599 }
600
601 /**
602 * Determine if the current scope is at the top level. This means it is either
603 * the top-level scope or it is open to the top-level.
604 */
605 static bool
606 pm_parser_scope_toplevel_p(pm_parser_t *parser) {
607 pm_scope_t *scope = parser->current_scope;
608
609 do {
610 if (scope->previous == NULL) return true;
611 if (scope->closed) return false;
612 } while ((scope = scope->previous) != NULL);
613
614 assert(false && "unreachable");
615 return true;
616 }
617
618 /**
619 * Retrieve the scope at the given depth.
620 */
621 static pm_scope_t *
622 pm_parser_scope_find(pm_parser_t *parser, uint32_t depth) {
623 pm_scope_t *scope = parser->current_scope;
624
625 while (depth-- > 0) {
626 assert(scope != NULL);
627 scope = scope->previous;
628 }
629
630 return scope;
631 }
632
633 typedef enum {
634 PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_PASS,
635 PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_CONFLICT,
636 PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_FAIL
637 } pm_scope_forwarding_param_check_result_t;
638
639 static pm_scope_forwarding_param_check_result_t
640 pm_parser_scope_forwarding_param_check(pm_parser_t *parser, const uint8_t mask) {
641 pm_scope_t *scope = parser->current_scope;
642 bool conflict = false;
643
644 while (scope != NULL) {
645 if (scope->parameters & mask) {
646 if (scope->closed) {
647 if (conflict) {
648 return PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_CONFLICT;
649 } else {
650 return PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_PASS;
651 }
652 }
653
654 conflict = true;
655 }
656
657 if (scope->closed) break;
658 scope = scope->previous;
659 }
660
661 return PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_FAIL;
662 }
663
664 static void
665 pm_parser_scope_forwarding_block_check(pm_parser_t *parser, const pm_token_t * token) {
666 switch (pm_parser_scope_forwarding_param_check(parser, PM_SCOPE_PARAMETERS_FORWARDING_BLOCK)) {
667 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_PASS:
668 // Pass.
669 break;
670 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_CONFLICT:
671 pm_parser_err_token(parser, token, PM_ERR_ARGUMENT_CONFLICT_AMPERSAND);
672 break;
673 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_FAIL:
674 pm_parser_err_token(parser, token, PM_ERR_ARGUMENT_NO_FORWARDING_AMPERSAND);
675 break;
676 }
677 }
678
679 static void
680 pm_parser_scope_forwarding_positionals_check(pm_parser_t *parser, const pm_token_t * token) {
681 switch (pm_parser_scope_forwarding_param_check(parser, PM_SCOPE_PARAMETERS_FORWARDING_POSITIONALS)) {
682 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_PASS:
683 // Pass.
684 break;
685 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_CONFLICT:
686 pm_parser_err_token(parser, token, PM_ERR_ARGUMENT_CONFLICT_STAR);
687 break;
688 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_FAIL:
689 pm_parser_err_token(parser, token, PM_ERR_ARGUMENT_NO_FORWARDING_STAR);
690 break;
691 }
692 }
693
694 static void
695 pm_parser_scope_forwarding_all_check(pm_parser_t *parser, const pm_token_t *token) {
696 switch (pm_parser_scope_forwarding_param_check(parser, PM_SCOPE_PARAMETERS_FORWARDING_ALL)) {
697 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_PASS:
698 // Pass.
699 break;
700 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_CONFLICT:
701 // This shouldn't happen, because ... is not allowed in the
702 // declaration of blocks. If we get here, we assume we already have
703 // an error for this.
704 break;
705 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_FAIL:
706 pm_parser_err_token(parser, token, PM_ERR_ARGUMENT_NO_FORWARDING_ELLIPSES);
707 break;
708 }
709 }
710
711 static void
712 pm_parser_scope_forwarding_keywords_check(pm_parser_t *parser, const pm_token_t * token) {
713 switch (pm_parser_scope_forwarding_param_check(parser, PM_SCOPE_PARAMETERS_FORWARDING_KEYWORDS)) {
714 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_PASS:
715 // Pass.
716 break;
717 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_CONFLICT:
718 pm_parser_err_token(parser, token, PM_ERR_ARGUMENT_CONFLICT_STAR_STAR);
719 break;
720 case PM_SCOPE_FORWARDING_PARAM_CHECK_RESULT_FAIL:
721 pm_parser_err_token(parser, token, PM_ERR_ARGUMENT_NO_FORWARDING_STAR_STAR);
722 break;
723 }
724 }
725
726 /**
727 * Get the current state of constant shareability.
728 */
729 static inline pm_shareable_constant_value_t
730 pm_parser_scope_shareable_constant_get(pm_parser_t *parser) {
731 return parser->current_scope->shareable_constant;
732 }
733
734 /**
735 * Set the current state of constant shareability. We'll set it on all of the
736 * open scopes so that reads are quick.
737 */
738 static void
739 pm_parser_scope_shareable_constant_set(pm_parser_t *parser, pm_shareable_constant_value_t shareable_constant) {
740 pm_scope_t *scope = parser->current_scope;
741
742 do {
743 scope->shareable_constant = shareable_constant;
744 } while (!scope->closed && (scope = scope->previous) != NULL);
745 }
746
747 /******************************************************************************/
748 /* Local variable-related functions */
749 /******************************************************************************/
750
751 /**
752 * The point at which the set of locals switches from being a list to a hash.
753 */
754 #define PM_LOCALS_HASH_THRESHOLD 9
755
756 static void
757 pm_locals_free(pm_locals_t *locals) {
758 if (locals->capacity > 0) {
759 xfree(locals->locals);
760 }
761 }
762
763 /**
764 * Use as simple and fast a hash function as we can that still properly mixes
765 * the bits.
766 */
767 static uint32_t
768 pm_locals_hash(pm_constant_id_t name) {
769 name = ((name >> 16) ^ name) * 0x45d9f3b;
770 name = ((name >> 16) ^ name) * 0x45d9f3b;
771 name = (name >> 16) ^ name;
772 return name;
773 }
774
775 /**
776 * Resize the locals list to be twice its current size. If the next capacity is
777 * above the threshold for switching to a hash, then we'll switch to a hash.
778 */
779 static void
780 pm_locals_resize(pm_locals_t *locals) {
781 uint32_t next_capacity = locals->capacity == 0 ? 4 : (locals->capacity * 2);
782 assert(next_capacity > locals->capacity);
783
784 pm_local_t *next_locals = xcalloc(next_capacity, sizeof(pm_local_t));
785 if (next_locals == NULL) abort();
786
787 if (next_capacity < PM_LOCALS_HASH_THRESHOLD) {
788 if (locals->size > 0) {
789 memcpy(next_locals, locals->locals, locals->size * sizeof(pm_local_t));
790 }
791 } else {
792 // If we just switched from a list to a hash, then we need to fill in
793 // the hash values of all of the locals.
794 bool hash_needed = (locals->capacity <= PM_LOCALS_HASH_THRESHOLD);
795 uint32_t mask = next_capacity - 1;
796
797 for (uint32_t index = 0; index < locals->capacity; index++) {
798 pm_local_t *local = &locals->locals[index];
799
800 if (local->name != PM_CONSTANT_ID_UNSET) {
801 if (hash_needed) local->hash = pm_locals_hash(local->name);
802
803 uint32_t hash = local->hash;
804 while (next_locals[hash & mask].name != PM_CONSTANT_ID_UNSET) hash++;
805 next_locals[hash & mask] = *local;
806 }
807 }
808 }
809
810 pm_locals_free(locals);
811 locals->locals = next_locals;
812 locals->capacity = next_capacity;
813 }
814
815 /**
816 * Add a new local to the set of locals. This will automatically rehash the
817 * locals if the size is greater than 3/4 of the capacity.
818 *
819 * @param locals The set of locals to add to.
820 * @param name The name of the local.
821 * @param start The source location that represents the start of the local. This
822 * is used for the location of the warning in case this local is not read.
823 * @param end The source location that represents the end of the local. This is
824 * used for the location of the warning in case this local is not read.
825 * @param reads The initial number of reads for this local. Usually this is set
826 * to 0, but for some locals (like parameters) we want to initialize it with
827 * 1 so that we never warn on unused parameters.
828 * @return True if the local was added, and false if the local already exists.
829 */
830 static bool
831 pm_locals_write(pm_locals_t *locals, pm_constant_id_t name, const uint8_t *start, const uint8_t *end, uint32_t reads) {
832 if (locals->size >= (locals->capacity / 4 * 3)) {
833 pm_locals_resize(locals);
834 }
835
836 if (locals->capacity < PM_LOCALS_HASH_THRESHOLD) {
837 for (uint32_t index = 0; index < locals->capacity; index++) {
838 pm_local_t *local = &locals->locals[index];
839
840 if (local->name == PM_CONSTANT_ID_UNSET) {
841 *local = (pm_local_t) {
842 .name = name,
843 .location = { .start = start, .end = end },
844 .index = locals->size++,
845 .reads = reads,
846 .hash = 0
847 };
848 return true;
849 } else if (local->name == name) {
850 return false;
851 }
852 }
853 } else {
854 uint32_t mask = locals->capacity - 1;
855 uint32_t hash = pm_locals_hash(name);
856 uint32_t initial_hash = hash;
857
858 do {
859 pm_local_t *local = &locals->locals[hash & mask];
860
861 if (local->name == PM_CONSTANT_ID_UNSET) {
862 *local = (pm_local_t) {
863 .name = name,
864 .location = { .start = start, .end = end },
865 .index = locals->size++,
866 .reads = reads,
867 .hash = initial_hash
868 };
869 return true;
870 } else if (local->name == name) {
871 return false;
872 } else {
873 hash++;
874 }
875 } while ((hash & mask) != initial_hash);
876 }
877
878 assert(false && "unreachable");
879 return true;
880 }
881
882 /**
883 * Finds the index of a local variable in the locals set. If it is not found,
884 * this returns UINT32_MAX.
885 */
886 static uint32_t
887 pm_locals_find(pm_locals_t *locals, pm_constant_id_t name) {
888 if (locals->capacity < PM_LOCALS_HASH_THRESHOLD) {
889 for (uint32_t index = 0; index < locals->size; index++) {
890 pm_local_t *local = &locals->locals[index];
891 if (local->name == name) return index;
892 }
893 } else {
894 uint32_t mask = locals->capacity - 1;
895 uint32_t hash = pm_locals_hash(name);
896 uint32_t initial_hash = hash & mask;
897
898 do {
899 pm_local_t *local = &locals->locals[hash & mask];
900
901 if (local->name == PM_CONSTANT_ID_UNSET) {
902 return UINT32_MAX;
903 } else if (local->name == name) {
904 return hash & mask;
905 } else {
906 hash++;
907 }
908 } while ((hash & mask) != initial_hash);
909 }
910
911 return UINT32_MAX;
912 }
913
914 /**
915 * Called when a variable is read in a certain lexical context. Tracks the read
916 * by adding to the reads count.
917 */
918 static void
919 pm_locals_read(pm_locals_t *locals, pm_constant_id_t name) {
920 uint32_t index = pm_locals_find(locals, name);
921 assert(index != UINT32_MAX);
922
923 pm_local_t *local = &locals->locals[index];
924 assert(local->reads < UINT32_MAX);
925
926 local->reads++;
927 }
928
929 /**
930 * Called when a variable read is transformed into a variable write, because a
931 * write operator is found after the variable name.
932 */
933 static void
934 pm_locals_unread(pm_locals_t *locals, pm_constant_id_t name) {
935 uint32_t index = pm_locals_find(locals, name);
936 assert(index != UINT32_MAX);
937
938 pm_local_t *local = &locals->locals[index];
939 assert(local->reads > 0);
940
941 local->reads--;
942 }
943
944 /**
945 * Returns the current number of reads for a local variable.
946 */
947 static uint32_t
948 pm_locals_reads(pm_locals_t *locals, pm_constant_id_t name) {
949 uint32_t index = pm_locals_find(locals, name);
950 assert(index != UINT32_MAX);
951
952 return locals->locals[index].reads;
953 }
954
955 /**
956 * Write out the locals into the given list of constant ids in the correct
957 * order. This is used to set the list of locals on the nodes in the tree once
958 * we're sure no additional locals will be added to the set.
959 *
960 * This function is also responsible for warning when a local variable has been
961 * written but not read in certain contexts.
962 */
963 static void
964 pm_locals_order(PRISM_ATTRIBUTE_UNUSED pm_parser_t *parser, pm_locals_t *locals, pm_constant_id_list_t *list, bool toplevel) {
965 pm_constant_id_list_init_capacity(list, locals->size);
966
967 // If we're still below the threshold for switching to a hash, then we only
968 // need to loop over the locals until we hit the size because the locals are
969 // stored in a list.
970 uint32_t capacity = locals->capacity < PM_LOCALS_HASH_THRESHOLD ? locals->size : locals->capacity;
971
972 // We will only warn for unused variables if we're not at the top level, or
973 // if we're parsing a file outside of eval or -e.
974 bool warn_unused = !toplevel || (!parser->parsing_eval && !PM_PARSER_COMMAND_LINE_OPTION_E(parser));
975
976 for (uint32_t index = 0; index < capacity; index++) {
977 pm_local_t *local = &locals->locals[index];
978
979 if (local->name != PM_CONSTANT_ID_UNSET) {
980 pm_constant_id_list_insert(list, (size_t) local->index, local->name);
981
982 if (warn_unused && local->reads == 0 && ((parser->start_line >= 0) || (pm_newline_list_line(&parser->newline_list, local->location.start, parser->start_line) >= 0))) {
983 pm_constant_t *constant = pm_constant_pool_id_to_constant(&parser->constant_pool, local->name);
984
985 if (constant->length >= 1 && *constant->start != '_') {
986 PM_PARSER_WARN_FORMAT(
987 parser,
988 local->location.start,
989 local->location.end,
990 PM_WARN_UNUSED_LOCAL_VARIABLE,
991 (int) constant->length,
992 (const char *) constant->start
993 );
994 }
995 }
996 }
997 }
998 }
999
1000 /******************************************************************************/
1001 /* Node-related functions */
1002 /******************************************************************************/
1003
1004 /**
1005 * Retrieve the constant pool id for the given location.
1006 */
1007 static inline pm_constant_id_t
1008 pm_parser_constant_id_location(pm_parser_t *parser, const uint8_t *start, const uint8_t *end) {
1009 return pm_constant_pool_insert_shared(&parser->constant_pool, start, (size_t) (end - start));
1010 }
1011
1012 /**
1013 * Retrieve the constant pool id for the given string.
1014 */
1015 static inline pm_constant_id_t
1016 pm_parser_constant_id_owned(pm_parser_t *parser, uint8_t *start, size_t length) {
1017 return pm_constant_pool_insert_owned(&parser->constant_pool, start, length);
1018 }
1019
1020 /**
1021 * Retrieve the constant pool id for the given static literal C string.
1022 */
1023 static inline pm_constant_id_t
1024 pm_parser_constant_id_constant(pm_parser_t *parser, const char *start, size_t length) {
1025 return pm_constant_pool_insert_constant(&parser->constant_pool, (const uint8_t *) start, length);
1026 }
1027
1028 /**
1029 * Retrieve the constant pool id for the given token.
1030 */
1031 static inline pm_constant_id_t
1032 pm_parser_constant_id_token(pm_parser_t *parser, const pm_token_t *token) {
1033 return pm_parser_constant_id_location(parser, token->start, token->end);
1034 }
1035
1036 /**
1037 * Retrieve the constant pool id for the given token. If the token is not
1038 * provided, then return 0.
1039 */
1040 static inline pm_constant_id_t
1041 pm_parser_optional_constant_id_token(pm_parser_t *parser, const pm_token_t *token) {
1042 return token->type == PM_TOKEN_NOT_PROVIDED ? 0 : pm_parser_constant_id_token(parser, token);
1043 }
1044
1045 /**
1046 * Check whether or not the given node is value expression.
1047 * If the node is value node, it returns NULL.
1048 * If not, it returns the pointer to the node to be inspected as "void expression".
1049 */
1050 static pm_node_t *
1051 pm_check_value_expression(pm_parser_t *parser, pm_node_t *node) {
1052 pm_node_t *void_node = NULL;
1053
1054 while (node != NULL) {
1055 switch (PM_NODE_TYPE(node)) {
1056 case PM_RETURN_NODE:
1057 case PM_BREAK_NODE:
1058 case PM_NEXT_NODE:
1059 case PM_REDO_NODE:
1060 case PM_RETRY_NODE:
1061 case PM_MATCH_REQUIRED_NODE:
1062 return void_node != NULL ? void_node : node;
1063 case PM_MATCH_PREDICATE_NODE:
1064 return NULL;
1065 case PM_BEGIN_NODE: {
1066 pm_begin_node_t *cast = (pm_begin_node_t *) node;
1067
1068 if (cast->ensure_clause != NULL) {
1069 if (cast->rescue_clause != NULL) {
1070 pm_node_t *vn = pm_check_value_expression(parser, UP(cast->rescue_clause));
1071 if (vn != NULL) return vn;
1072 }
1073
1074 if (cast->statements != NULL) {
1075 pm_node_t *vn = pm_check_value_expression(parser, UP(cast->statements));
1076 if (vn != NULL) return vn;
1077 }
1078
1079 node = UP(cast->ensure_clause);
1080 } else if (cast->rescue_clause != NULL) {
1081 if (cast->statements == NULL) return NULL;
1082
1083 pm_node_t *vn = pm_check_value_expression(parser, UP(cast->statements));
1084 if (vn == NULL) return NULL;
1085 if (void_node == NULL) void_node = vn;
1086
1087 for (pm_rescue_node_t *rescue_clause = cast->rescue_clause; rescue_clause != NULL; rescue_clause = rescue_clause->subsequent) {
1088 pm_node_t *vn = pm_check_value_expression(parser, UP(rescue_clause->statements));
1089 if (vn == NULL) {
1090 void_node = NULL;
1091 break;
1092 }
1093 if (void_node == NULL) {
1094 void_node = vn;
1095 }
1096 }
1097
1098 if (cast->else_clause != NULL) {
1099 node = UP(cast->else_clause);
1100 } else {
1101 return void_node;
1102 }
1103 } else {
1104 node = UP(cast->statements);
1105 }
1106
1107 break;
1108 }
1109 case PM_ENSURE_NODE: {
1110 pm_ensure_node_t *cast = (pm_ensure_node_t *) node;
1111 node = UP(cast->statements);
1112 break;
1113 }
1114 case PM_PARENTHESES_NODE: {
1115 pm_parentheses_node_t *cast = (pm_parentheses_node_t *) node;
1116 node = UP(cast->body);
1117 break;
1118 }
1119 case PM_STATEMENTS_NODE: {
1120 pm_statements_node_t *cast = (pm_statements_node_t *) node;
1121 node = cast->body.nodes[cast->body.size - 1];
1122 break;
1123 }
1124 case PM_IF_NODE: {
1125 pm_if_node_t *cast = (pm_if_node_t *) node;
1126 if (cast->statements == NULL || cast->subsequent == NULL) {
1127 return NULL;
1128 }
1129 pm_node_t *vn = pm_check_value_expression(parser, UP(cast->statements));
1130 if (vn == NULL) {
1131 return NULL;
1132 }
1133 if (void_node == NULL) {
1134 void_node = vn;
1135 }
1136 node = cast->subsequent;
1137 break;
1138 }
1139 case PM_UNLESS_NODE: {
1140 pm_unless_node_t *cast = (pm_unless_node_t *) node;
1141 if (cast->statements == NULL || cast->else_clause == NULL) {
1142 return NULL;
1143 }
1144 pm_node_t *vn = pm_check_value_expression(parser, UP(cast->statements));
1145 if (vn == NULL) {
1146 return NULL;
1147 }
1148 if (void_node == NULL) {
1149 void_node = vn;
1150 }
1151 node = UP(cast->else_clause);
1152 break;
1153 }
1154 case PM_ELSE_NODE: {
1155 pm_else_node_t *cast = (pm_else_node_t *) node;
1156 node = UP(cast->statements);
1157 break;
1158 }
1159 case PM_AND_NODE: {
1160 pm_and_node_t *cast = (pm_and_node_t *) node;
1161 node = cast->left;
1162 break;
1163 }
1164 case PM_OR_NODE: {
1165 pm_or_node_t *cast = (pm_or_node_t *) node;
1166 node = cast->left;
1167 break;
1168 }
1169 case PM_LOCAL_VARIABLE_WRITE_NODE: {
1170 pm_local_variable_write_node_t *cast = (pm_local_variable_write_node_t *) node;
1171
1172 pm_scope_t *scope = parser->current_scope;
1173 for (uint32_t depth = 0; depth < cast->depth; depth++) scope = scope->previous;
1174
1175 pm_locals_read(&scope->locals, cast->name);
1176 return NULL;
1177 }
1178 default:
1179 return NULL;
1180 }
1181 }
1182
1183 return NULL;
1184 }
1185
1186 static inline void
1187 pm_assert_value_expression(pm_parser_t *parser, pm_node_t *node) {
1188 pm_node_t *void_node = pm_check_value_expression(parser, node);
1189 if (void_node != NULL) {
1190 pm_parser_err_node(parser, void_node, PM_ERR_VOID_EXPRESSION);
1191 }
1192 }
1193
1194 /**
1195 * Warn if the given node is a "void" statement.
1196 */
1197 static void
1198 pm_void_statement_check(pm_parser_t *parser, const pm_node_t *node) {
1199 const char *type = NULL;
1200 int length = 0;
1201
1202 switch (PM_NODE_TYPE(node)) {
1203 case PM_BACK_REFERENCE_READ_NODE:
1204 case PM_CLASS_VARIABLE_READ_NODE:
1205 case PM_GLOBAL_VARIABLE_READ_NODE:
1206 case PM_INSTANCE_VARIABLE_READ_NODE:
1207 case PM_LOCAL_VARIABLE_READ_NODE:
1208 case PM_NUMBERED_REFERENCE_READ_NODE:
1209 type = "a variable";
1210 length = 10;
1211 break;
1212 case PM_CALL_NODE: {
1213 const pm_call_node_t *cast = (const pm_call_node_t *) node;
1214 if (cast->call_operator_loc.start != NULL || cast->message_loc.start == NULL) break;
1215
1216 const pm_constant_t *message = pm_constant_pool_id_to_constant(&parser->constant_pool, cast->name);
1217 switch (message->length) {
1218 case 1:
1219 switch (message->start[0]) {
1220 case '+':
1221 case '-':
1222 case '*':
1223 case '/':
1224 case '%':
1225 case '|':
1226 case '^':
1227 case '&':
1228 case '>':
1229 case '<':
1230 type = (const char *) message->start;
1231 length = 1;
1232 break;
1233 }
1234 break;
1235 case 2:
1236 switch (message->start[1]) {
1237 case '=':
1238 if (message->start[0] == '<' || message->start[0] == '>' || message->start[0] == '!' || message->start[0] == '=') {
1239 type = (const char *) message->start;
1240 length = 2;
1241 }
1242 break;
1243 case '@':
1244 if (message->start[0] == '+' || message->start[0] == '-') {
1245 type = (const char *) message->start;
1246 length = 2;
1247 }
1248 break;
1249 case '*':
1250 if (message->start[0] == '*') {
1251 type = (const char *) message->start;
1252 length = 2;
1253 }
1254 break;
1255 }
1256 break;
1257 case 3:
1258 if (memcmp(message->start, "<=>", 3) == 0) {
1259 type = "<=>";
1260 length = 3;
1261 }
1262 break;
1263 }
1264
1265 break;
1266 }
1267 case PM_CONSTANT_PATH_NODE:
1268 type = "::";
1269 length = 2;
1270 break;
1271 case PM_CONSTANT_READ_NODE:
1272 type = "a constant";
1273 length = 10;
1274 break;
1275 case PM_DEFINED_NODE:
1276 type = "defined?";
1277 length = 8;
1278 break;
1279 case PM_FALSE_NODE:
1280 type = "false";
1281 length = 5;
1282 break;
1283 case PM_FLOAT_NODE:
1284 case PM_IMAGINARY_NODE:
1285 case PM_INTEGER_NODE:
1286 case PM_INTERPOLATED_REGULAR_EXPRESSION_NODE:
1287 case PM_INTERPOLATED_STRING_NODE:
1288 case PM_RATIONAL_NODE:
1289 case PM_REGULAR_EXPRESSION_NODE:
1290 case PM_SOURCE_ENCODING_NODE:
1291 case PM_SOURCE_FILE_NODE:
1292 case PM_SOURCE_LINE_NODE:
1293 case PM_STRING_NODE:
1294 case PM_SYMBOL_NODE:
1295 type = "a literal";
1296 length = 9;
1297 break;
1298 case PM_NIL_NODE:
1299 type = "nil";
1300 length = 3;
1301 break;
1302 case PM_RANGE_NODE: {
1303 const pm_range_node_t *cast = (const pm_range_node_t *) node;
1304
1305 if (PM_NODE_FLAG_P(cast, PM_RANGE_FLAGS_EXCLUDE_END)) {
1306 type = "...";
1307 length = 3;
1308 } else {
1309 type = "..";
1310 length = 2;
1311 }
1312
1313 break;
1314 }
1315 case PM_SELF_NODE:
1316 type = "self";
1317 length = 4;
1318 break;
1319 case PM_TRUE_NODE:
1320 type = "true";
1321 length = 4;
1322 break;
1323 default:
1324 break;
1325 }
1326
1327 if (type != NULL) {
1328 PM_PARSER_WARN_NODE_FORMAT(parser, node, PM_WARN_VOID_STATEMENT, length, type);
1329 }
1330 }
1331
1332 /**
1333 * Warn if any of the statements that are not the last statement in the list are
1334 * a "void" statement.
1335 */
1336 static void
1337 pm_void_statements_check(pm_parser_t *parser, const pm_statements_node_t *node, bool last_value) {
1338 assert(node->body.size > 0);
1339 const size_t size = node->body.size - (last_value ? 1 : 0);
1340 for (size_t index = 0; index < size; index++) {
1341 pm_void_statement_check(parser, node->body.nodes[index]);
1342 }
1343 }
1344
1345 /**
1346 * When we're handling the predicate of a conditional, we need to know our
1347 * context in order to determine the kind of warning we should deliver to the
1348 * user.
1349 */
1350 typedef enum {
1351 PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL,
1352 PM_CONDITIONAL_PREDICATE_TYPE_FLIP_FLOP,
1353 PM_CONDITIONAL_PREDICATE_TYPE_NOT
1354 } pm_conditional_predicate_type_t;
1355
1356 /**
1357 * Add a warning to the parser if the predicate of a conditional is a literal.
1358 */
1359 static void
1360 pm_parser_warn_conditional_predicate_literal(pm_parser_t *parser, pm_node_t *node, pm_conditional_predicate_type_t type, pm_diagnostic_id_t diag_id, const char *prefix) {
1361 switch (type) {
1362 case PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL:
1363 PM_PARSER_WARN_NODE_FORMAT(parser, node, diag_id, prefix, "condition");
1364 break;
1365 case PM_CONDITIONAL_PREDICATE_TYPE_FLIP_FLOP:
1366 PM_PARSER_WARN_NODE_FORMAT(parser, node, diag_id, prefix, "flip-flop");
1367 break;
1368 case PM_CONDITIONAL_PREDICATE_TYPE_NOT:
1369 break;
1370 }
1371 }
1372
1373 /**
1374 * Return true if the value being written within the predicate of a conditional
1375 * is a literal value.
1376 */
1377 static bool
1378 pm_conditional_predicate_warn_write_literal_p(const pm_node_t *node) {
1379 switch (PM_NODE_TYPE(node)) {
1380 case PM_ARRAY_NODE: {
1381 if (PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL)) return true;
1382
1383 const pm_array_node_t *cast = (const pm_array_node_t *) node;
1384 for (size_t index = 0; index < cast->elements.size; index++) {
1385 if (!pm_conditional_predicate_warn_write_literal_p(cast->elements.nodes[index])) return false;
1386 }
1387
1388 return true;
1389 }
1390 case PM_HASH_NODE: {
1391 if (PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL)) return true;
1392
1393 const pm_hash_node_t *cast = (const pm_hash_node_t *) node;
1394 for (size_t index = 0; index < cast->elements.size; index++) {
1395 const pm_node_t *element = cast->elements.nodes[index];
1396 if (!PM_NODE_TYPE_P(element, PM_ASSOC_NODE)) return false;
1397
1398 const pm_assoc_node_t *assoc = (const pm_assoc_node_t *) element;
1399 if (!pm_conditional_predicate_warn_write_literal_p(assoc->key) || !pm_conditional_predicate_warn_write_literal_p(assoc->value)) return false;
1400 }
1401
1402 return true;
1403 }
1404 case PM_FALSE_NODE:
1405 case PM_FLOAT_NODE:
1406 case PM_IMAGINARY_NODE:
1407 case PM_INTEGER_NODE:
1408 case PM_NIL_NODE:
1409 case PM_RATIONAL_NODE:
1410 case PM_REGULAR_EXPRESSION_NODE:
1411 case PM_SOURCE_ENCODING_NODE:
1412 case PM_SOURCE_FILE_NODE:
1413 case PM_SOURCE_LINE_NODE:
1414 case PM_STRING_NODE:
1415 case PM_SYMBOL_NODE:
1416 case PM_TRUE_NODE:
1417 return true;
1418 default:
1419 return false;
1420 }
1421 }
1422
1423 /**
1424 * Add a warning to the parser if the value that is being written inside of a
1425 * predicate to a conditional is a literal.
1426 */
1427 static inline void
1428 pm_conditional_predicate_warn_write_literal(pm_parser_t *parser, const pm_node_t *node) {
1429 if (pm_conditional_predicate_warn_write_literal_p(node)) {
1430 pm_parser_warn_node(parser, node, parser->version <= PM_OPTIONS_VERSION_CRUBY_3_3 ? PM_WARN_EQUAL_IN_CONDITIONAL_3_3 : PM_WARN_EQUAL_IN_CONDITIONAL);
1431 }
1432 }
1433
1434 /**
1435 * The predicate of conditional nodes can change what would otherwise be regular
1436 * nodes into specialized nodes. For example:
1437 *
1438 * if foo .. bar => RangeNode becomes FlipFlopNode
1439 * if foo and bar .. baz => RangeNode becomes FlipFlopNode
1440 * if /foo/ => RegularExpressionNode becomes MatchLastLineNode
1441 * if /foo #{bar}/ => InterpolatedRegularExpressionNode becomes InterpolatedMatchLastLineNode
1442 *
1443 * We also want to warn the user if they're using a static literal as a
1444 * predicate or writing a static literal as the predicate.
1445 */
1446 static void
1447 pm_conditional_predicate(pm_parser_t *parser, pm_node_t *node, pm_conditional_predicate_type_t type) {
1448 switch (PM_NODE_TYPE(node)) {
1449 case PM_AND_NODE: {
1450 pm_and_node_t *cast = (pm_and_node_t *) node;
1451 pm_conditional_predicate(parser, cast->left, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
1452 pm_conditional_predicate(parser, cast->right, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
1453 break;
1454 }
1455 case PM_OR_NODE: {
1456 pm_or_node_t *cast = (pm_or_node_t *) node;
1457 pm_conditional_predicate(parser, cast->left, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
1458 pm_conditional_predicate(parser, cast->right, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
1459 break;
1460 }
1461 case PM_PARENTHESES_NODE: {
1462 pm_parentheses_node_t *cast = (pm_parentheses_node_t *) node;
1463
1464 if ((cast->body != NULL) && PM_NODE_TYPE_P(cast->body, PM_STATEMENTS_NODE)) {
1465 pm_statements_node_t *statements = (pm_statements_node_t *) cast->body;
1466 if (statements->body.size == 1) pm_conditional_predicate(parser, statements->body.nodes[0], type);
1467 }
1468
1469 break;
1470 }
1471 case PM_BEGIN_NODE: {
1472 pm_begin_node_t *cast = (pm_begin_node_t *) node;
1473 if (cast->statements != NULL) {
1474 pm_statements_node_t *statements = cast->statements;
1475 if (statements->body.size == 1) pm_conditional_predicate(parser, statements->body.nodes[0], type);
1476 }
1477 break;
1478 }
1479 case PM_RANGE_NODE: {
1480 pm_range_node_t *cast = (pm_range_node_t *) node;
1481
1482 if (cast->left != NULL) pm_conditional_predicate(parser, cast->left, PM_CONDITIONAL_PREDICATE_TYPE_FLIP_FLOP);
1483 if (cast->right != NULL) pm_conditional_predicate(parser, cast->right, PM_CONDITIONAL_PREDICATE_TYPE_FLIP_FLOP);
1484
1485 // Here we change the range node into a flip flop node. We can do
1486 // this since the nodes are exactly the same except for the type.
1487 // We're only asserting against the size when we should probably
1488 // assert against the entire layout, but we'll assume tests will
1489 // catch this.
1490 assert(sizeof(pm_range_node_t) == sizeof(pm_flip_flop_node_t));
1491 node->type = PM_FLIP_FLOP_NODE;
1492
1493 break;
1494 }
1495 case PM_REGULAR_EXPRESSION_NODE:
1496 // Here we change the regular expression node into a match last line
1497 // node. We can do this since the nodes are exactly the same except
1498 // for the type.
1499 assert(sizeof(pm_regular_expression_node_t) == sizeof(pm_match_last_line_node_t));
1500 node->type = PM_MATCH_LAST_LINE_NODE;
1501
1502 if (!PM_PARSER_COMMAND_LINE_OPTION_E(parser)) {
1503 pm_parser_warn_conditional_predicate_literal(parser, node, type, PM_WARN_LITERAL_IN_CONDITION_DEFAULT, "regex ");
1504 }
1505
1506 break;
1507 case PM_INTERPOLATED_REGULAR_EXPRESSION_NODE:
1508 // Here we change the interpolated regular expression node into an
1509 // interpolated match last line node. We can do this since the nodes
1510 // are exactly the same except for the type.
1511 assert(sizeof(pm_interpolated_regular_expression_node_t) == sizeof(pm_interpolated_match_last_line_node_t));
1512 node->type = PM_INTERPOLATED_MATCH_LAST_LINE_NODE;
1513
1514 if (!PM_PARSER_COMMAND_LINE_OPTION_E(parser)) {
1515 pm_parser_warn_conditional_predicate_literal(parser, node, type, PM_WARN_LITERAL_IN_CONDITION_VERBOSE, "regex ");
1516 }
1517
1518 break;
1519 case PM_INTEGER_NODE:
1520 if (type == PM_CONDITIONAL_PREDICATE_TYPE_FLIP_FLOP) {
1521 if (!PM_PARSER_COMMAND_LINE_OPTION_E(parser)) {
1522 pm_parser_warn_node(parser, node, PM_WARN_INTEGER_IN_FLIP_FLOP);
1523 }
1524 } else {
1525 pm_parser_warn_conditional_predicate_literal(parser, node, type, PM_WARN_LITERAL_IN_CONDITION_VERBOSE, "");
1526 }
1527 break;
1528 case PM_STRING_NODE:
1529 case PM_SOURCE_FILE_NODE:
1530 case PM_INTERPOLATED_STRING_NODE:
1531 pm_parser_warn_conditional_predicate_literal(parser, node, type, PM_WARN_LITERAL_IN_CONDITION_DEFAULT, "string ");
1532 break;
1533 case PM_SYMBOL_NODE:
1534 case PM_INTERPOLATED_SYMBOL_NODE:
1535 pm_parser_warn_conditional_predicate_literal(parser, node, type, PM_WARN_LITERAL_IN_CONDITION_VERBOSE, "symbol ");
1536 break;
1537 case PM_SOURCE_LINE_NODE:
1538 case PM_SOURCE_ENCODING_NODE:
1539 case PM_FLOAT_NODE:
1540 case PM_RATIONAL_NODE:
1541 case PM_IMAGINARY_NODE:
1542 pm_parser_warn_conditional_predicate_literal(parser, node, type, PM_WARN_LITERAL_IN_CONDITION_VERBOSE, "");
1543 break;
1544 case PM_CLASS_VARIABLE_WRITE_NODE:
1545 pm_conditional_predicate_warn_write_literal(parser, ((pm_class_variable_write_node_t *) node)->value);
1546 break;
1547 case PM_CONSTANT_WRITE_NODE:
1548 pm_conditional_predicate_warn_write_literal(parser, ((pm_constant_write_node_t *) node)->value);
1549 break;
1550 case PM_GLOBAL_VARIABLE_WRITE_NODE:
1551 pm_conditional_predicate_warn_write_literal(parser, ((pm_global_variable_write_node_t *) node)->value);
1552 break;
1553 case PM_INSTANCE_VARIABLE_WRITE_NODE:
1554 pm_conditional_predicate_warn_write_literal(parser, ((pm_instance_variable_write_node_t *) node)->value);
1555 break;
1556 case PM_LOCAL_VARIABLE_WRITE_NODE:
1557 pm_conditional_predicate_warn_write_literal(parser, ((pm_local_variable_write_node_t *) node)->value);
1558 break;
1559 case PM_MULTI_WRITE_NODE:
1560 pm_conditional_predicate_warn_write_literal(parser, ((pm_multi_write_node_t *) node)->value);
1561 break;
1562 default:
1563 break;
1564 }
1565 }
1566
1567 /**
1568 * In a lot of places in the tree you can have tokens that are not provided but
1569 * that do not cause an error. For example, this happens in a method call
1570 * without parentheses. In these cases we set the token to the "not provided" type.
1571 * For example:
1572 *
1573 * pm_token_t token = not_provided(parser);
1574 */
1575 static inline pm_token_t
1576 not_provided(pm_parser_t *parser) {
1577 return (pm_token_t) { .type = PM_TOKEN_NOT_PROVIDED, .start = parser->start, .end = parser->start };
1578 }
1579
1580 /**
1581 * This is a special out parameter to the parse_arguments_list function that
1582 * includes opening and closing parentheses in addition to the arguments since
1583 * it's so common. It is handy to use when passing argument information to one
1584 * of the call node creation functions.
1585 */
1586 typedef struct {
1587 /** The optional location of the opening parenthesis or bracket. */
1588 pm_location_t opening_loc;
1589
1590 /** The lazily-allocated optional arguments node. */
1591 pm_arguments_node_t *arguments;
1592
1593 /** The optional location of the closing parenthesis or bracket. */
1594 pm_location_t closing_loc;
1595
1596 /** The optional block attached to the call. */
1597 pm_node_t *block;
1598
1599 /** The flag indicating whether this arguments list has forwarding argument. */
1600 bool has_forwarding;
1601 } pm_arguments_t;
1602
1603 /**
1604 * Retrieve the end location of a `pm_arguments_t` object.
1605 */
1606 static inline const uint8_t *
1607 pm_arguments_end(pm_arguments_t *arguments) {
1608 if (arguments->block != NULL) {
1609 const uint8_t *end = arguments->block->location.end;
1610 if (arguments->closing_loc.start != NULL && arguments->closing_loc.end > end) {
1611 end = arguments->closing_loc.end;
1612 }
1613 return end;
1614 }
1615 if (arguments->closing_loc.start != NULL) {
1616 return arguments->closing_loc.end;
1617 }
1618 if (arguments->arguments != NULL) {
1619 return arguments->arguments->base.location.end;
1620 }
1621 return arguments->closing_loc.end;
1622 }
1623
1624 /**
1625 * Check that we're not about to attempt to attach a brace block to a call that
1626 * has arguments without parentheses.
1627 */
1628 static void
1629 pm_arguments_validate_block(pm_parser_t *parser, pm_arguments_t *arguments, pm_block_node_t *block) {
1630 // First, check that we have arguments and that we don't have a closing
1631 // location for them.
1632 if (arguments->arguments == NULL || arguments->closing_loc.start != NULL) {
1633 return;
1634 }
1635
1636 // Next, check that we don't have a single parentheses argument. This would
1637 // look like:
1638 //
1639 // foo (1) {}
1640 //
1641 // In this case, it's actually okay for the block to be attached to the
1642 // call, even though it looks like it's attached to the argument.
1643 if (arguments->arguments->arguments.size == 1 && PM_NODE_TYPE_P(arguments->arguments->arguments.nodes[0], PM_PARENTHESES_NODE)) {
1644 return;
1645 }
1646
1647 // If we didn't hit a case before this check, then at this point we need to
1648 // add a syntax error.
1649 pm_parser_err_node(parser, UP(block), PM_ERR_ARGUMENT_UNEXPECTED_BLOCK);
1650 }
1651
1652 /******************************************************************************/
1653 /* Basic character checks */
1654 /******************************************************************************/
1655
1656 /**
1657 * This function is used extremely frequently to lex all of the identifiers in a
1658 * source file, so it's important that it be as fast as possible. For this
1659 * reason we have the encoding_changed boolean to check if we need to go through
1660 * the function pointer or can just directly use the UTF-8 functions.
1661 */
1662 static inline size_t
1663 char_is_identifier_start(const pm_parser_t *parser, const uint8_t *b, ptrdiff_t n) {
1664 if (n <= 0) return 0;
1665
1666 if (parser->encoding_changed) {
1667 size_t width;
1668
1669 if ((width = parser->encoding->alpha_char(b, n)) != 0) {
1670 return width;
1671 } else if (*b == '_') {
1672 return 1;
1673 } else if (*b >= 0x80) {
1674 return parser->encoding->char_width(b, n);
1675 } else {
1676 return 0;
1677 }
1678 } else if (*b < 0x80) {
1679 return (pm_encoding_unicode_table[*b] & PRISM_ENCODING_ALPHABETIC_BIT ? 1 : 0) || (*b == '_');
1680 } else {
1681 return pm_encoding_utf_8_char_width(b, n);
1682 }
1683 }
1684
1685 /**
1686 * Similar to char_is_identifier but this function assumes that the encoding
1687 * has not been changed.
1688 */
1689 static inline size_t
1690 char_is_identifier_utf8(const uint8_t *b, ptrdiff_t n) {
1691 if (n <= 0) {
1692 return 0;
1693 } else if (*b < 0x80) {
1694 return (*b == '_') || (pm_encoding_unicode_table[*b] & PRISM_ENCODING_ALPHANUMERIC_BIT ? 1 : 0);
1695 } else {
1696 return pm_encoding_utf_8_char_width(b, n);
1697 }
1698 }
1699
1700 /**
1701 * Like the above, this function is also used extremely frequently to lex all of
1702 * the identifiers in a source file once the first character has been found. So
1703 * it's important that it be as fast as possible.
1704 */
1705 static inline size_t
1706 char_is_identifier(const pm_parser_t *parser, const uint8_t *b, ptrdiff_t n) {
1707 if (n <= 0) {
1708 return 0;
1709 } else if (parser->encoding_changed) {
1710 size_t width;
1711
1712 if ((width = parser->encoding->alnum_char(b, n)) != 0) {
1713 return width;
1714 } else if (*b == '_') {
1715 return 1;
1716 } else if (*b >= 0x80) {
1717 return parser->encoding->char_width(b, n);
1718 } else {
1719 return 0;
1720 }
1721 } else {
1722 return char_is_identifier_utf8(b, n);
1723 }
1724 }
1725
1726 // Here we're defining a perfect hash for the characters that are allowed in
1727 // global names. This is used to quickly check the next character after a $ to
1728 // see if it's a valid character for a global name.
1729 #define BIT(c, idx) (((c) / 32 - 1 == idx) ? (1U << ((c) % 32)) : 0)
1730 #define PUNCT(idx) ( \
1731 BIT('~', idx) | BIT('*', idx) | BIT('$', idx) | BIT('?', idx) | \
1732 BIT('!', idx) | BIT('@', idx) | BIT('/', idx) | BIT('\\', idx) | \
1733 BIT(';', idx) | BIT(',', idx) | BIT('.', idx) | BIT('=', idx) | \
1734 BIT(':', idx) | BIT('<', idx) | BIT('>', idx) | BIT('\"', idx) | \
1735 BIT('&', idx) | BIT('`', idx) | BIT('\'', idx) | BIT('+', idx) | \
1736 BIT('0', idx))
1737
1738 const unsigned int pm_global_name_punctuation_hash[(0x7e - 0x20 + 31) / 32] = { PUNCT(0), PUNCT(1), PUNCT(2) };
1739
1740 #undef BIT
1741 #undef PUNCT
1742
1743 static inline bool
1744 char_is_global_name_punctuation(const uint8_t b) {
1745 const unsigned int i = (const unsigned int) b;
1746 if (i <= 0x20 || 0x7e < i) return false;
1747
1748 return (pm_global_name_punctuation_hash[(i - 0x20) / 32] >> (i % 32)) & 1;
1749 }
1750
1751 static inline bool
1752 token_is_setter_name(pm_token_t *token) {
1753 return (
1754 (token->type == PM_TOKEN_BRACKET_LEFT_RIGHT_EQUAL) ||
1755 ((token->type == PM_TOKEN_IDENTIFIER) &&
1756 (token->end - token->start >= 2) &&
1757 (token->end[-1] == '='))
1758 );
1759 }
1760
1761 /**
1762 * Returns true if the given local variable is a keyword.
1763 */
1764 static bool
1765 pm_local_is_keyword(const char *source, size_t length) {
1766 #define KEYWORD(name) if (memcmp(source, name, length) == 0) return true
1767
1768 switch (length) {
1769 case 2:
1770 switch (source[0]) {
1771 case 'd': KEYWORD("do"); return false;
1772 case 'i': KEYWORD("if"); KEYWORD("in"); return false;
1773 case 'o': KEYWORD("or"); return false;
1774 default: return false;
1775 }
1776 case 3:
1777 switch (source[0]) {
1778 case 'a': KEYWORD("and"); return false;
1779 case 'd': KEYWORD("def"); return false;
1780 case 'e': KEYWORD("end"); return false;
1781 case 'f': KEYWORD("for"); return false;
1782 case 'n': KEYWORD("nil"); KEYWORD("not"); return false;
1783 default: return false;
1784 }
1785 case 4:
1786 switch (source[0]) {
1787 case 'c': KEYWORD("case"); return false;
1788 case 'e': KEYWORD("else"); return false;
1789 case 'n': KEYWORD("next"); return false;
1790 case 'r': KEYWORD("redo"); return false;
1791 case 's': KEYWORD("self"); return false;
1792 case 't': KEYWORD("then"); KEYWORD("true"); return false;
1793 case 'w': KEYWORD("when"); return false;
1794 default: return false;
1795 }
1796 case 5:
1797 switch (source[0]) {
1798 case 'a': KEYWORD("alias"); return false;
1799 case 'b': KEYWORD("begin"); KEYWORD("break"); return false;
1800 case 'c': KEYWORD("class"); return false;
1801 case 'e': KEYWORD("elsif"); return false;
1802 case 'f': KEYWORD("false"); return false;
1803 case 'r': KEYWORD("retry"); return false;
1804 case 's': KEYWORD("super"); return false;
1805 case 'u': KEYWORD("undef"); KEYWORD("until"); return false;
1806 case 'w': KEYWORD("while"); return false;
1807 case 'y': KEYWORD("yield"); return false;
1808 default: return false;
1809 }
1810 case 6:
1811 switch (source[0]) {
1812 case 'e': KEYWORD("ensure"); return false;
1813 case 'm': KEYWORD("module"); return false;
1814 case 'r': KEYWORD("rescue"); KEYWORD("return"); return false;
1815 case 'u': KEYWORD("unless"); return false;
1816 default: return false;
1817 }
1818 case 8:
1819 KEYWORD("__LINE__");
1820 KEYWORD("__FILE__");
1821 return false;
1822 case 12:
1823 KEYWORD("__ENCODING__");
1824 return false;
1825 default:
1826 return false;
1827 }
1828
1829 #undef KEYWORD
1830 }
1831
1832 /******************************************************************************/
1833 /* Node flag handling functions */
1834 /******************************************************************************/
1835
1836 /**
1837 * Set the given flag on the given node.
1838 */
1839 static inline void
1840 pm_node_flag_set(pm_node_t *node, pm_node_flags_t flag) {
1841 node->flags |= flag;
1842 }
1843
1844 /**
1845 * Remove the given flag from the given node.
1846 */
1847 static inline void
1848 pm_node_flag_unset(pm_node_t *node, pm_node_flags_t flag) {
1849 node->flags &= (pm_node_flags_t) ~flag;
1850 }
1851
1852 /**
1853 * Set the repeated parameter flag on the given node.
1854 */
1855 static inline void
1856 pm_node_flag_set_repeated_parameter(pm_node_t *node) {
1857 assert(PM_NODE_TYPE(node) == PM_BLOCK_LOCAL_VARIABLE_NODE ||
1858 PM_NODE_TYPE(node) == PM_BLOCK_PARAMETER_NODE ||
1859 PM_NODE_TYPE(node) == PM_KEYWORD_REST_PARAMETER_NODE ||
1860 PM_NODE_TYPE(node) == PM_OPTIONAL_KEYWORD_PARAMETER_NODE ||
1861 PM_NODE_TYPE(node) == PM_OPTIONAL_PARAMETER_NODE ||
1862 PM_NODE_TYPE(node) == PM_REQUIRED_KEYWORD_PARAMETER_NODE ||
1863 PM_NODE_TYPE(node) == PM_REQUIRED_PARAMETER_NODE ||
1864 PM_NODE_TYPE(node) == PM_REST_PARAMETER_NODE);
1865
1866 pm_node_flag_set(node, PM_PARAMETER_FLAGS_REPEATED_PARAMETER);
1867 }
1868
1869 /******************************************************************************/
1870 /* Node creation functions */
1871 /******************************************************************************/
1872
1873 /**
1874 * When you have an encoding flag on a regular expression, it takes precedence
1875 * over all of the previously set encoding flags. So we need to mask off any
1876 * previously set encoding flags before setting the new one.
1877 */
1878 #define PM_REGULAR_EXPRESSION_ENCODING_MASK ~(PM_REGULAR_EXPRESSION_FLAGS_EUC_JP | PM_REGULAR_EXPRESSION_FLAGS_ASCII_8BIT | PM_REGULAR_EXPRESSION_FLAGS_WINDOWS_31J | PM_REGULAR_EXPRESSION_FLAGS_UTF_8)
1879
1880 /**
1881 * Parse out the options for a regular expression.
1882 */
1883 static inline pm_node_flags_t
1884 pm_regular_expression_flags_create(pm_parser_t *parser, const pm_token_t *closing) {
1885 pm_node_flags_t flags = 0;
1886
1887 if (closing->type == PM_TOKEN_REGEXP_END) {
1888 pm_buffer_t unknown_flags = { 0 };
1889
1890 for (const uint8_t *flag = closing->start + 1; flag < closing->end; flag++) {
1891 switch (*flag) {
1892 case 'i': flags |= PM_REGULAR_EXPRESSION_FLAGS_IGNORE_CASE; break;
1893 case 'm': flags |= PM_REGULAR_EXPRESSION_FLAGS_MULTI_LINE; break;
1894 case 'x': flags |= PM_REGULAR_EXPRESSION_FLAGS_EXTENDED; break;
1895 case 'o': flags |= PM_REGULAR_EXPRESSION_FLAGS_ONCE; break;
1896
1897 case 'e': flags = (pm_node_flags_t) (((pm_node_flags_t) (flags & PM_REGULAR_EXPRESSION_ENCODING_MASK)) | PM_REGULAR_EXPRESSION_FLAGS_EUC_JP); break;
1898 case 'n': flags = (pm_node_flags_t) (((pm_node_flags_t) (flags & PM_REGULAR_EXPRESSION_ENCODING_MASK)) | PM_REGULAR_EXPRESSION_FLAGS_ASCII_8BIT); break;
1899 case 's': flags = (pm_node_flags_t) (((pm_node_flags_t) (flags & PM_REGULAR_EXPRESSION_ENCODING_MASK)) | PM_REGULAR_EXPRESSION_FLAGS_WINDOWS_31J); break;
1900 case 'u': flags = (pm_node_flags_t) (((pm_node_flags_t) (flags & PM_REGULAR_EXPRESSION_ENCODING_MASK)) | PM_REGULAR_EXPRESSION_FLAGS_UTF_8); break;
1901
1902 default: pm_buffer_append_byte(&unknown_flags, *flag);
1903 }
1904 }
1905
1906 size_t unknown_flags_length = pm_buffer_length(&unknown_flags);
1907 if (unknown_flags_length != 0) {
1908 const char *word = unknown_flags_length >= 2 ? "options" : "option";
1909 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->previous, PM_ERR_REGEXP_UNKNOWN_OPTIONS, word, unknown_flags_length, pm_buffer_value(&unknown_flags));
1910 }
1911 pm_buffer_free(&unknown_flags);
1912 }
1913
1914 return flags;
1915 }
1916
1917 #undef PM_REGULAR_EXPRESSION_ENCODING_MASK
1918
1919 static pm_statements_node_t *
1920 pm_statements_node_create(pm_parser_t *parser);
1921
1922 static void
1923 pm_statements_node_body_append(pm_parser_t *parser, pm_statements_node_t *node, pm_node_t *statement, bool newline);
1924
1925 static size_t
1926 pm_statements_node_body_length(pm_statements_node_t *node);
1927
1928 /**
1929 * This function is here to allow us a place to extend in the future when we
1930 * implement our own arena allocation.
1931 */
1932 static inline void *
1933 pm_node_alloc(PRISM_ATTRIBUTE_UNUSED pm_parser_t *parser, size_t size) {
1934 void *memory = xcalloc(1, size);
1935 if (memory == NULL) {
1936 fprintf(stderr, "Failed to allocate %d bytes\n", (int) size);
1937 abort();
1938 }
1939 return memory;
1940 }
1941
1942 #define PM_NODE_ALLOC(parser_, type_) (type_ *) pm_node_alloc(parser_, sizeof(type_))
1943 #define PM_NODE_INIT(parser_, type_, flags_, start_, end_) (pm_node_t) { \
1944 .type = (type_), \
1945 .flags = (flags_), \
1946 .node_id = ++(parser_)->node_id, \
1947 .location = { .start = (start_), .end = (end_) } \
1948 }
1949
1950 #define PM_NODE_INIT_UNSET(parser_, type_, flags_) PM_NODE_INIT(parser_, type_, flags_, NULL, NULL)
1951 #define PM_NODE_INIT_BASE(parser_, type_, flags_) PM_NODE_INIT(parser_, type_, flags_, (parser_)->start, (parser_)->start)
1952 #define PM_NODE_INIT_TOKEN(parser_, type_, flags_, token_) PM_NODE_INIT(parser_, type_, flags_, PM_TOKEN_START(token_), PM_TOKEN_END(token_))
1953 #define PM_NODE_INIT_NODE(parser_, type_, flags_, node_) PM_NODE_INIT(parser_, type_, flags_, PM_NODE_START(node_), PM_NODE_END(node_))
1954
1955 #define PM_NODE_INIT_TOKENS(parser_, type_, flags_, left_, right_) PM_NODE_INIT(parser_, type_, flags_, PM_TOKEN_START(left_), PM_TOKEN_END(right_))
1956 #define PM_NODE_INIT_NODES(parser_, type_, flags_, left_, right_) PM_NODE_INIT(parser_, type_, flags_, PM_NODE_START(left_), PM_NODE_END(right_))
1957 #define PM_NODE_INIT_TOKEN_NODE(parser_, type_, flags_, token_, node_) PM_NODE_INIT(parser_, type_, flags_, PM_TOKEN_START(token_), PM_NODE_END(node_))
1958 #define PM_NODE_INIT_NODE_TOKEN(parser_, type_, flags_, node_, token_) PM_NODE_INIT(parser_, type_, flags_, PM_NODE_START(node_), PM_TOKEN_END(token_))
1959
1960 /**
1961 * Allocate a new MissingNode node.
1962 */
1963 static pm_missing_node_t *
1964 pm_missing_node_create(pm_parser_t *parser, const uint8_t *start, const uint8_t *end) {
1965 pm_missing_node_t *node = PM_NODE_ALLOC(parser, pm_missing_node_t);
1966
1967 *node = (pm_missing_node_t) {
1968 .base = PM_NODE_INIT(parser, PM_MISSING_NODE, 0, start, end)
1969 };
1970
1971 return node;
1972 }
1973
1974 /**
1975 * Allocate and initialize a new AliasGlobalVariableNode node.
1976 */
1977 static pm_alias_global_variable_node_t *
1978 pm_alias_global_variable_node_create(pm_parser_t *parser, const pm_token_t *keyword, pm_node_t *new_name, pm_node_t *old_name) {
1979 assert(keyword->type == PM_TOKEN_KEYWORD_ALIAS);
1980 pm_alias_global_variable_node_t *node = PM_NODE_ALLOC(parser, pm_alias_global_variable_node_t);
1981
1982 *node = (pm_alias_global_variable_node_t) {
1983 .base = PM_NODE_INIT_TOKEN_NODE(parser, PM_ALIAS_GLOBAL_VARIABLE_NODE, 0, keyword, old_name),
1984 .new_name = new_name,
1985 .old_name = old_name,
1986 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword)
1987 };
1988
1989 return node;
1990 }
1991
1992 /**
1993 * Allocate and initialize a new AliasMethodNode node.
1994 */
1995 static pm_alias_method_node_t *
1996 pm_alias_method_node_create(pm_parser_t *parser, const pm_token_t *keyword, pm_node_t *new_name, pm_node_t *old_name) {
1997 assert(keyword->type == PM_TOKEN_KEYWORD_ALIAS);
1998 pm_alias_method_node_t *node = PM_NODE_ALLOC(parser, pm_alias_method_node_t);
1999
2000 *node = (pm_alias_method_node_t) {
2001 .base = PM_NODE_INIT_TOKEN_NODE(parser, PM_ALIAS_METHOD_NODE, 0, keyword, old_name),
2002 .new_name = new_name,
2003 .old_name = old_name,
2004 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword)
2005 };
2006
2007 return node;
2008 }
2009
2010 /**
2011 * Allocate a new AlternationPatternNode node.
2012 */
2013 static pm_alternation_pattern_node_t *
2014 pm_alternation_pattern_node_create(pm_parser_t *parser, pm_node_t *left, pm_node_t *right, const pm_token_t *operator) {
2015 pm_alternation_pattern_node_t *node = PM_NODE_ALLOC(parser, pm_alternation_pattern_node_t);
2016
2017 *node = (pm_alternation_pattern_node_t) {
2018 .base = PM_NODE_INIT_NODES(parser, PM_ALTERNATION_PATTERN_NODE, 0, left, right),
2019 .left = left,
2020 .right = right,
2021 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
2022 };
2023
2024 return node;
2025 }
2026
2027 /**
2028 * Allocate and initialize a new and node.
2029 */
2030 static pm_and_node_t *
2031 pm_and_node_create(pm_parser_t *parser, pm_node_t *left, const pm_token_t *operator, pm_node_t *right) {
2032 pm_assert_value_expression(parser, left);
2033
2034 pm_and_node_t *node = PM_NODE_ALLOC(parser, pm_and_node_t);
2035
2036 *node = (pm_and_node_t) {
2037 .base = PM_NODE_INIT_NODES(parser, PM_AND_NODE, 0, left, right),
2038 .left = left,
2039 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
2040 .right = right
2041 };
2042
2043 return node;
2044 }
2045
2046 /**
2047 * Allocate an initialize a new arguments node.
2048 */
2049 static pm_arguments_node_t *
2050 pm_arguments_node_create(pm_parser_t *parser) {
2051 pm_arguments_node_t *node = PM_NODE_ALLOC(parser, pm_arguments_node_t);
2052
2053 *node = (pm_arguments_node_t) {
2054 .base = PM_NODE_INIT_BASE(parser, PM_ARGUMENTS_NODE, 0),
2055 .arguments = { 0 }
2056 };
2057
2058 return node;
2059 }
2060
2061 /**
2062 * Return the size of the given arguments node.
2063 */
2064 static size_t
2065 pm_arguments_node_size(pm_arguments_node_t *node) {
2066 return node->arguments.size;
2067 }
2068
2069 /**
2070 * Append an argument to an arguments node.
2071 */
2072 static void
2073 pm_arguments_node_arguments_append(pm_arguments_node_t *node, pm_node_t *argument) {
2074 if (pm_arguments_node_size(node) == 0) {
2075 node->base.location.start = argument->location.start;
2076 }
2077
2078 if (node->base.location.end < argument->location.end) {
2079 node->base.location.end = argument->location.end;
2080 }
2081
2082 pm_node_list_append(&node->arguments, argument);
2083
2084 if (PM_NODE_TYPE_P(argument, PM_SPLAT_NODE)) {
2085 if (PM_NODE_FLAG_P(node, PM_ARGUMENTS_NODE_FLAGS_CONTAINS_SPLAT)) {
2086 pm_node_flag_set(UP(node), PM_ARGUMENTS_NODE_FLAGS_CONTAINS_MULTIPLE_SPLATS);
2087 } else {
2088 pm_node_flag_set(UP(node), PM_ARGUMENTS_NODE_FLAGS_CONTAINS_SPLAT);
2089 }
2090 }
2091 }
2092
2093 /**
2094 * Allocate and initialize a new ArrayNode node.
2095 */
2096 static pm_array_node_t *
2097 pm_array_node_create(pm_parser_t *parser, const pm_token_t *opening) {
2098 pm_array_node_t *node = PM_NODE_ALLOC(parser, pm_array_node_t);
2099
2100 *node = (pm_array_node_t) {
2101 .base = PM_NODE_INIT_TOKEN(parser, PM_ARRAY_NODE, PM_NODE_FLAG_STATIC_LITERAL, opening),
2102 .opening_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(opening),
2103 .closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(opening),
2104 .elements = { 0 }
2105 };
2106
2107 return node;
2108 }
2109
2110 /**
2111 * Append an argument to an array node.
2112 */
2113 static inline void
2114 pm_array_node_elements_append(pm_array_node_t *node, pm_node_t *element) {
2115 if (!node->elements.size && !node->opening_loc.start) {
2116 node->base.location.start = element->location.start;
2117 }
2118
2119 pm_node_list_append(&node->elements, element);
2120 node->base.location.end = element->location.end;
2121
2122 // If the element is not a static literal, then the array is not a static
2123 // literal. Turn that flag off.
2124 if (PM_NODE_TYPE_P(element, PM_ARRAY_NODE) || PM_NODE_TYPE_P(element, PM_HASH_NODE) || PM_NODE_TYPE_P(element, PM_RANGE_NODE) || !PM_NODE_FLAG_P(element, PM_NODE_FLAG_STATIC_LITERAL)) {
2125 pm_node_flag_unset(UP(node), PM_NODE_FLAG_STATIC_LITERAL);
2126 }
2127
2128 if (PM_NODE_TYPE_P(element, PM_SPLAT_NODE)) {
2129 pm_node_flag_set(UP(node), PM_ARRAY_NODE_FLAGS_CONTAINS_SPLAT);
2130 }
2131 }
2132
2133 /**
2134 * Set the closing token and end location of an array node.
2135 */
2136 static void
2137 pm_array_node_close_set(pm_array_node_t *node, const pm_token_t *closing) {
2138 assert(closing->type == PM_TOKEN_BRACKET_RIGHT || closing->type == PM_TOKEN_STRING_END || closing->type == PM_TOKEN_MISSING || closing->type == PM_TOKEN_NOT_PROVIDED);
2139 node->base.location.end = closing->end;
2140 node->closing_loc = PM_LOCATION_TOKEN_VALUE(closing);
2141 }
2142
2143 /**
2144 * Allocate and initialize a new array pattern node. The node list given in the
2145 * nodes parameter is guaranteed to have at least two nodes.
2146 */
2147 static pm_array_pattern_node_t *
2148 pm_array_pattern_node_node_list_create(pm_parser_t *parser, pm_node_list_t *nodes) {
2149 pm_array_pattern_node_t *node = PM_NODE_ALLOC(parser, pm_array_pattern_node_t);
2150
2151 *node = (pm_array_pattern_node_t) {
2152 .base = PM_NODE_INIT_NODES(parser, PM_ARRAY_PATTERN_NODE, 0, nodes->nodes[0], nodes->nodes[nodes->size - 1]),
2153 .constant = NULL,
2154 .rest = NULL,
2155 .requireds = { 0 },
2156 .posts = { 0 },
2157 .opening_loc = { 0 },
2158 .closing_loc = { 0 }
2159 };
2160
2161 // For now we're going to just copy over each pointer manually. This could be
2162 // much more efficient, as we could instead resize the node list.
2163 bool found_rest = false;
2164 pm_node_t *child;
2165
2166 PM_NODE_LIST_FOREACH(nodes, index, child) {
2167 if (!found_rest && (PM_NODE_TYPE_P(child, PM_SPLAT_NODE) || PM_NODE_TYPE_P(child, PM_IMPLICIT_REST_NODE))) {
2168 node->rest = child;
2169 found_rest = true;
2170 } else if (found_rest) {
2171 pm_node_list_append(&node->posts, child);
2172 } else {
2173 pm_node_list_append(&node->requireds, child);
2174 }
2175 }
2176
2177 return node;
2178 }
2179
2180 /**
2181 * Allocate and initialize a new array pattern node from a single rest node.
2182 */
2183 static pm_array_pattern_node_t *
2184 pm_array_pattern_node_rest_create(pm_parser_t *parser, pm_node_t *rest) {
2185 pm_array_pattern_node_t *node = PM_NODE_ALLOC(parser, pm_array_pattern_node_t);
2186
2187 *node = (pm_array_pattern_node_t) {
2188 .base = PM_NODE_INIT_NODE(parser, PM_ARRAY_PATTERN_NODE, 0, rest),
2189 .constant = NULL,
2190 .rest = rest,
2191 .requireds = { 0 },
2192 .posts = { 0 },
2193 .opening_loc = { 0 },
2194 .closing_loc = { 0 }
2195 };
2196
2197 return node;
2198 }
2199
2200 /**
2201 * Allocate and initialize a new array pattern node from a constant and opening
2202 * and closing tokens.
2203 */
2204 static pm_array_pattern_node_t *
2205 pm_array_pattern_node_constant_create(pm_parser_t *parser, pm_node_t *constant, const pm_token_t *opening, const pm_token_t *closing) {
2206 pm_array_pattern_node_t *node = PM_NODE_ALLOC(parser, pm_array_pattern_node_t);
2207
2208 *node = (pm_array_pattern_node_t) {
2209 .base = PM_NODE_INIT_NODE_TOKEN(parser, PM_ARRAY_PATTERN_NODE, 0, constant, closing),
2210 .constant = constant,
2211 .rest = NULL,
2212 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
2213 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing),
2214 .requireds = { 0 },
2215 .posts = { 0 }
2216 };
2217
2218 return node;
2219 }
2220
2221 /**
2222 * Allocate and initialize a new array pattern node from an opening and closing
2223 * token.
2224 */
2225 static pm_array_pattern_node_t *
2226 pm_array_pattern_node_empty_create(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *closing) {
2227 pm_array_pattern_node_t *node = PM_NODE_ALLOC(parser, pm_array_pattern_node_t);
2228
2229 *node = (pm_array_pattern_node_t) {
2230 .base = PM_NODE_INIT_TOKENS(parser, PM_ARRAY_PATTERN_NODE, 0, opening, closing),
2231 .constant = NULL,
2232 .rest = NULL,
2233 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
2234 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing),
2235 .requireds = { 0 },
2236 .posts = { 0 }
2237 };
2238
2239 return node;
2240 }
2241
2242 static inline void
2243 pm_array_pattern_node_requireds_append(pm_array_pattern_node_t *node, pm_node_t *inner) {
2244 pm_node_list_append(&node->requireds, inner);
2245 }
2246
2247 /**
2248 * Allocate and initialize a new assoc node.
2249 */
2250 static pm_assoc_node_t *
2251 pm_assoc_node_create(pm_parser_t *parser, pm_node_t *key, const pm_token_t *operator, pm_node_t *value) {
2252 pm_assoc_node_t *node = PM_NODE_ALLOC(parser, pm_assoc_node_t);
2253 const uint8_t *end;
2254
2255 if (value != NULL && value->location.end > key->location.end) {
2256 end = value->location.end;
2257 } else if (operator->type != PM_TOKEN_NOT_PROVIDED) {
2258 end = operator->end;
2259 } else {
2260 end = key->location.end;
2261 }
2262
2263 // Hash string keys will be frozen, so we can mark them as frozen here so
2264 // that the compiler picks them up and also when we check for static literal
2265 // on the keys it gets factored in.
2266 if (PM_NODE_TYPE_P(key, PM_STRING_NODE)) {
2267 key->flags |= PM_STRING_FLAGS_FROZEN | PM_NODE_FLAG_STATIC_LITERAL;
2268 }
2269
2270 // If the key and value of this assoc node are both static literals, then
2271 // we can mark this node as a static literal.
2272 pm_node_flags_t flags = 0;
2273 if (
2274 !PM_NODE_TYPE_P(key, PM_ARRAY_NODE) && !PM_NODE_TYPE_P(key, PM_HASH_NODE) && !PM_NODE_TYPE_P(key, PM_RANGE_NODE) &&
2275 value && !PM_NODE_TYPE_P(value, PM_ARRAY_NODE) && !PM_NODE_TYPE_P(value, PM_HASH_NODE) && !PM_NODE_TYPE_P(value, PM_RANGE_NODE)
2276 ) {
2277 flags = key->flags & value->flags & PM_NODE_FLAG_STATIC_LITERAL;
2278 }
2279
2280 *node = (pm_assoc_node_t) {
2281 .base = PM_NODE_INIT(parser, PM_ASSOC_NODE, flags, key->location.start, end),
2282 .key = key,
2283 .operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator),
2284 .value = value
2285 };
2286
2287 return node;
2288 }
2289
2290 /**
2291 * Allocate and initialize a new assoc splat node.
2292 */
2293 static pm_assoc_splat_node_t *
2294 pm_assoc_splat_node_create(pm_parser_t *parser, pm_node_t *value, const pm_token_t *operator) {
2295 assert(operator->type == PM_TOKEN_USTAR_STAR);
2296 pm_assoc_splat_node_t *node = PM_NODE_ALLOC(parser, pm_assoc_splat_node_t);
2297
2298 *node = (pm_assoc_splat_node_t) {
2299 .base = (
2300 (value == NULL)
2301 ? PM_NODE_INIT_TOKEN(parser, PM_ASSOC_SPLAT_NODE, 0, operator)
2302 : PM_NODE_INIT_TOKEN_NODE(parser, PM_ASSOC_SPLAT_NODE, 0, operator, value)
2303 ),
2304 .value = value,
2305 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
2306 };
2307
2308 return node;
2309 }
2310
2311 /**
2312 * Allocate a new BackReferenceReadNode node.
2313 */
2314 static pm_back_reference_read_node_t *
2315 pm_back_reference_read_node_create(pm_parser_t *parser, const pm_token_t *name) {
2316 assert(name->type == PM_TOKEN_BACK_REFERENCE);
2317 pm_back_reference_read_node_t *node = PM_NODE_ALLOC(parser, pm_back_reference_read_node_t);
2318
2319 *node = (pm_back_reference_read_node_t) {
2320 .base = PM_NODE_INIT_TOKEN(parser, PM_BACK_REFERENCE_READ_NODE, 0, name),
2321 .name = pm_parser_constant_id_token(parser, name)
2322 };
2323
2324 return node;
2325 }
2326
2327 /**
2328 * Allocate and initialize new a begin node.
2329 */
2330 static pm_begin_node_t *
2331 pm_begin_node_create(pm_parser_t *parser, const pm_token_t *begin_keyword, pm_statements_node_t *statements) {
2332 pm_begin_node_t *node = PM_NODE_ALLOC(parser, pm_begin_node_t);
2333
2334 *node = (pm_begin_node_t) {
2335 .base = (
2336 (statements == NULL)
2337 ? PM_NODE_INIT_TOKEN(parser, PM_BEGIN_NODE, 0, begin_keyword)
2338 : PM_NODE_INIT_TOKEN_NODE(parser, PM_BEGIN_NODE, 0, begin_keyword, statements)
2339 ),
2340 .begin_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(begin_keyword),
2341 .statements = statements,
2342 .end_keyword_loc = { 0 }
2343 };
2344
2345 return node;
2346 }
2347
2348 /**
2349 * Set the rescue clause, optionally start, and end location of a begin node.
2350 */
2351 static void
2352 pm_begin_node_rescue_clause_set(pm_begin_node_t *node, pm_rescue_node_t *rescue_clause) {
2353 // If the begin keyword doesn't exist, we set the start on the begin_node
2354 if (!node->begin_keyword_loc.start) {
2355 node->base.location.start = rescue_clause->base.location.start;
2356 }
2357 node->base.location.end = rescue_clause->base.location.end;
2358 node->rescue_clause = rescue_clause;
2359 }
2360
2361 /**
2362 * Set the else clause and end location of a begin node.
2363 */
2364 static void
2365 pm_begin_node_else_clause_set(pm_begin_node_t *node, pm_else_node_t *else_clause) {
2366 node->base.location.end = else_clause->base.location.end;
2367 node->else_clause = else_clause;
2368 }
2369
2370 /**
2371 * Set the ensure clause and end location of a begin node.
2372 */
2373 static void
2374 pm_begin_node_ensure_clause_set(pm_begin_node_t *node, pm_ensure_node_t *ensure_clause) {
2375 node->base.location.end = ensure_clause->base.location.end;
2376 node->ensure_clause = ensure_clause;
2377 }
2378
2379 /**
2380 * Set the end keyword and end location of a begin node.
2381 */
2382 static void
2383 pm_begin_node_end_keyword_set(pm_begin_node_t *node, const pm_token_t *end_keyword) {
2384 assert(end_keyword->type == PM_TOKEN_KEYWORD_END || end_keyword->type == PM_TOKEN_MISSING);
2385
2386 node->base.location.end = end_keyword->end;
2387 node->end_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(end_keyword);
2388 }
2389
2390 /**
2391 * Allocate and initialize a new BlockArgumentNode node.
2392 */
2393 static pm_block_argument_node_t *
2394 pm_block_argument_node_create(pm_parser_t *parser, const pm_token_t *operator, pm_node_t *expression) {
2395 pm_block_argument_node_t *node = PM_NODE_ALLOC(parser, pm_block_argument_node_t);
2396
2397 *node = (pm_block_argument_node_t) {
2398 .base = (
2399 (expression == NULL)
2400 ? PM_NODE_INIT_TOKEN(parser, PM_BLOCK_ARGUMENT_NODE, 0, operator)
2401 : PM_NODE_INIT_TOKEN_NODE(parser, PM_BLOCK_ARGUMENT_NODE, 0, operator, expression)
2402 ),
2403 .expression = expression,
2404 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
2405 };
2406
2407 return node;
2408 }
2409
2410 /**
2411 * Allocate and initialize a new BlockNode node.
2412 */
2413 static pm_block_node_t *
2414 pm_block_node_create(pm_parser_t *parser, pm_constant_id_list_t *locals, const pm_token_t *opening, pm_node_t *parameters, pm_node_t *body, const pm_token_t *closing) {
2415 pm_block_node_t *node = PM_NODE_ALLOC(parser, pm_block_node_t);
2416
2417 *node = (pm_block_node_t) {
2418 .base = PM_NODE_INIT_TOKENS(parser, PM_BLOCK_NODE, 0, opening, closing),
2419 .locals = *locals,
2420 .parameters = parameters,
2421 .body = body,
2422 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
2423 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing)
2424 };
2425
2426 return node;
2427 }
2428
2429 /**
2430 * Allocate and initialize a new BlockParameterNode node.
2431 */
2432 static pm_block_parameter_node_t *
2433 pm_block_parameter_node_create(pm_parser_t *parser, const pm_token_t *name, const pm_token_t *operator) {
2434 assert(operator->type == PM_TOKEN_NOT_PROVIDED || operator->type == PM_TOKEN_UAMPERSAND || operator->type == PM_TOKEN_AMPERSAND);
2435 pm_block_parameter_node_t *node = PM_NODE_ALLOC(parser, pm_block_parameter_node_t);
2436
2437 *node = (pm_block_parameter_node_t) {
2438 .base = (
2439 (name->type == PM_TOKEN_NOT_PROVIDED)
2440 ? PM_NODE_INIT_TOKEN(parser, PM_BLOCK_PARAMETER_NODE, 0, operator)
2441 : PM_NODE_INIT_TOKENS(parser, PM_BLOCK_PARAMETER_NODE, 0, operator, name)
2442 ),
2443 .name = pm_parser_optional_constant_id_token(parser, name),
2444 .name_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(name),
2445 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
2446 };
2447
2448 return node;
2449 }
2450
2451 /**
2452 * Allocate and initialize a new BlockParametersNode node.
2453 */
2454 static pm_block_parameters_node_t *
2455 pm_block_parameters_node_create(pm_parser_t *parser, pm_parameters_node_t *parameters, const pm_token_t *opening) {
2456 pm_block_parameters_node_t *node = PM_NODE_ALLOC(parser, pm_block_parameters_node_t);
2457
2458 const uint8_t *start;
2459 if (opening->type != PM_TOKEN_NOT_PROVIDED) {
2460 start = opening->start;
2461 } else if (parameters != NULL) {
2462 start = parameters->base.location.start;
2463 } else {
2464 start = NULL;
2465 }
2466
2467 const uint8_t *end;
2468 if (parameters != NULL) {
2469 end = parameters->base.location.end;
2470 } else if (opening->type != PM_TOKEN_NOT_PROVIDED) {
2471 end = opening->end;
2472 } else {
2473 end = NULL;
2474 }
2475
2476 *node = (pm_block_parameters_node_t) {
2477 .base = PM_NODE_INIT(parser, PM_BLOCK_PARAMETERS_NODE, 0, start, end),
2478 .parameters = parameters,
2479 .opening_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(opening),
2480 .closing_loc = { 0 },
2481 .locals = { 0 }
2482 };
2483
2484 return node;
2485 }
2486
2487 /**
2488 * Set the closing location of a BlockParametersNode node.
2489 */
2490 static void
2491 pm_block_parameters_node_closing_set(pm_block_parameters_node_t *node, const pm_token_t *closing) {
2492 assert(closing->type == PM_TOKEN_PIPE || closing->type == PM_TOKEN_PARENTHESIS_RIGHT || closing->type == PM_TOKEN_MISSING);
2493
2494 node->base.location.end = closing->end;
2495 node->closing_loc = PM_LOCATION_TOKEN_VALUE(closing);
2496 }
2497
2498 /**
2499 * Allocate and initialize a new BlockLocalVariableNode node.
2500 */
2501 static pm_block_local_variable_node_t *
2502 pm_block_local_variable_node_create(pm_parser_t *parser, const pm_token_t *name) {
2503 pm_block_local_variable_node_t *node = PM_NODE_ALLOC(parser, pm_block_local_variable_node_t);
2504
2505 *node = (pm_block_local_variable_node_t) {
2506 .base = PM_NODE_INIT_TOKEN(parser, PM_BLOCK_LOCAL_VARIABLE_NODE, 0, name),
2507 .name = pm_parser_constant_id_token(parser, name)
2508 };
2509
2510 return node;
2511 }
2512
2513 /**
2514 * Append a new block-local variable to a BlockParametersNode node.
2515 */
2516 static void
2517 pm_block_parameters_node_append_local(pm_block_parameters_node_t *node, const pm_block_local_variable_node_t *local) {
2518 pm_node_list_append(&node->locals, UP(local));
2519
2520 if (node->base.location.start == NULL) node->base.location.start = local->base.location.start;
2521 node->base.location.end = local->base.location.end;
2522 }
2523
2524 /**
2525 * Allocate and initialize a new BreakNode node.
2526 */
2527 static pm_break_node_t *
2528 pm_break_node_create(pm_parser_t *parser, const pm_token_t *keyword, pm_arguments_node_t *arguments) {
2529 assert(keyword->type == PM_TOKEN_KEYWORD_BREAK);
2530 pm_break_node_t *node = PM_NODE_ALLOC(parser, pm_break_node_t);
2531
2532 *node = (pm_break_node_t) {
2533 .base = (
2534 (arguments == NULL)
2535 ? PM_NODE_INIT_TOKEN(parser, PM_BREAK_NODE, 0, keyword)
2536 : PM_NODE_INIT_TOKEN_NODE(parser, PM_BREAK_NODE, 0, keyword, arguments)
2537 ),
2538 .arguments = arguments,
2539 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword)
2540 };
2541
2542 return node;
2543 }
2544
2545 // There are certain flags that we want to use internally but don't want to
2546 // expose because they are not relevant beyond parsing. Therefore we'll define
2547 // them here and not define them in config.yml/a header file.
2548 static const pm_node_flags_t PM_WRITE_NODE_FLAGS_IMPLICIT_ARRAY = (1 << 2);
2549
2550 static const pm_node_flags_t PM_CALL_NODE_FLAGS_IMPLICIT_ARRAY = ((PM_CALL_NODE_FLAGS_LAST - 1) << 1);
2551 static const pm_node_flags_t PM_CALL_NODE_FLAGS_COMPARISON = ((PM_CALL_NODE_FLAGS_LAST - 1) << 2);
2552 static const pm_node_flags_t PM_CALL_NODE_FLAGS_INDEX = ((PM_CALL_NODE_FLAGS_LAST - 1) << 3);
2553
2554 /**
2555 * Allocate and initialize a new CallNode node. This sets everything to NULL or
2556 * PM_TOKEN_NOT_PROVIDED as appropriate such that its values can be overridden
2557 * in the various specializations of this function.
2558 */
2559 static pm_call_node_t *
2560 pm_call_node_create(pm_parser_t *parser, pm_node_flags_t flags) {
2561 pm_call_node_t *node = PM_NODE_ALLOC(parser, pm_call_node_t);
2562
2563 *node = (pm_call_node_t) {
2564 .base = PM_NODE_INIT_BASE(parser, PM_CALL_NODE, flags),
2565 .receiver = NULL,
2566 .call_operator_loc = { 0 },
2567 .message_loc = { 0 },
2568 .opening_loc = { 0 },
2569 .arguments = NULL,
2570 .closing_loc = { 0 },
2571 .equal_loc = { 0 },
2572 .block = NULL,
2573 .name = 0
2574 };
2575
2576 return node;
2577 }
2578
2579 /**
2580 * Returns the value that the ignore visibility flag should be set to for the
2581 * given receiver.
2582 */
2583 static inline pm_node_flags_t
2584 pm_call_node_ignore_visibility_flag(const pm_node_t *receiver) {
2585 return PM_NODE_TYPE_P(receiver, PM_SELF_NODE) ? PM_CALL_NODE_FLAGS_IGNORE_VISIBILITY : 0;
2586 }
2587
2588 /**
2589 * Allocate and initialize a new CallNode node from an aref or an aset
2590 * expression.
2591 */
2592 static pm_call_node_t *
2593 pm_call_node_aref_create(pm_parser_t *parser, pm_node_t *receiver, pm_arguments_t *arguments) {
2594 pm_assert_value_expression(parser, receiver);
2595
2596 pm_node_flags_t flags = pm_call_node_ignore_visibility_flag(receiver);
2597 if (arguments->block == NULL || PM_NODE_TYPE_P(arguments->block, PM_BLOCK_ARGUMENT_NODE)) {
2598 flags |= PM_CALL_NODE_FLAGS_INDEX;
2599 }
2600
2601 pm_call_node_t *node = pm_call_node_create(parser, flags);
2602
2603 node->base.location.start = receiver->location.start;
2604 node->base.location.end = pm_arguments_end(arguments);
2605
2606 node->receiver = receiver;
2607 node->message_loc.start = arguments->opening_loc.start;
2608 node->message_loc.end = arguments->closing_loc.end;
2609
2610 node->opening_loc = arguments->opening_loc;
2611 node->arguments = arguments->arguments;
2612 node->closing_loc = arguments->closing_loc;
2613 node->block = arguments->block;
2614
2615 node->name = pm_parser_constant_id_constant(parser, "[]", 2);
2616 return node;
2617 }
2618
2619 /**
2620 * Allocate and initialize a new CallNode node from a binary expression.
2621 */
2622 static pm_call_node_t *
2623 pm_call_node_binary_create(pm_parser_t *parser, pm_node_t *receiver, pm_token_t *operator, pm_node_t *argument, pm_node_flags_t flags) {
2624 pm_assert_value_expression(parser, receiver);
2625 pm_assert_value_expression(parser, argument);
2626
2627 pm_call_node_t *node = pm_call_node_create(parser, pm_call_node_ignore_visibility_flag(receiver) | flags);
2628
2629 node->base.location.start = MIN(receiver->location.start, argument->location.start);
2630 node->base.location.end = MAX(receiver->location.end, argument->location.end);
2631
2632 node->receiver = receiver;
2633 node->message_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator);
2634
2635 pm_arguments_node_t *arguments = pm_arguments_node_create(parser);
2636 pm_arguments_node_arguments_append(arguments, argument);
2637 node->arguments = arguments;
2638
2639 node->name = pm_parser_constant_id_token(parser, operator);
2640 return node;
2641 }
2642
2643 static const uint8_t * parse_operator_symbol_name(const pm_token_t *);
2644
2645 /**
2646 * Allocate and initialize a new CallNode node from a call expression.
2647 */
2648 static pm_call_node_t *
2649 pm_call_node_call_create(pm_parser_t *parser, pm_node_t *receiver, pm_token_t *operator, pm_token_t *message, pm_arguments_t *arguments) {
2650 pm_assert_value_expression(parser, receiver);
2651
2652 pm_call_node_t *node = pm_call_node_create(parser, pm_call_node_ignore_visibility_flag(receiver));
2653
2654 node->base.location.start = receiver->location.start;
2655 const uint8_t *end = pm_arguments_end(arguments);
2656 if (end == NULL) {
2657 end = message->end;
2658 }
2659 node->base.location.end = end;
2660
2661 node->receiver = receiver;
2662 node->call_operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator);
2663 node->message_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(message);
2664 node->opening_loc = arguments->opening_loc;
2665 node->arguments = arguments->arguments;
2666 node->closing_loc = arguments->closing_loc;
2667 node->block = arguments->block;
2668
2669 if (operator->type == PM_TOKEN_AMPERSAND_DOT) {
2670 pm_node_flag_set(UP(node), PM_CALL_NODE_FLAGS_SAFE_NAVIGATION);
2671 }
2672
2673 /**
2674 * If the final character is `@` as is the case for `foo.~@`,
2675 * we should ignore the @ in the same way we do for symbols.
2676 */
2677 node->name = pm_parser_constant_id_location(parser, message->start, parse_operator_symbol_name(message));
2678 return node;
2679 }
2680
2681 /**
2682 * Allocate and initialize a new synthesized CallNode node from a call expression.
2683 */
2684 static pm_call_node_t *
2685 pm_call_node_call_synthesized_create(pm_parser_t *parser, pm_node_t *receiver, const char *message, pm_arguments_node_t *arguments) {
2686 pm_call_node_t *node = pm_call_node_create(parser, 0);
2687 node->base.location.start = parser->start;
2688 node->base.location.end = parser->end;
2689
2690 node->receiver = receiver;
2691 node->call_operator_loc = (pm_location_t) { .start = NULL, .end = NULL };
2692 node->message_loc = (pm_location_t) { .start = NULL, .end = NULL };
2693 node->arguments = arguments;
2694
2695 node->name = pm_parser_constant_id_constant(parser, message, strlen(message));
2696 return node;
2697 }
2698
2699 /**
2700 * Allocate and initialize a new CallNode node from a call to a method name
2701 * without a receiver that could not have been a local variable read.
2702 */
2703 static pm_call_node_t *
2704 pm_call_node_fcall_create(pm_parser_t *parser, pm_token_t *message, pm_arguments_t *arguments) {
2705 pm_call_node_t *node = pm_call_node_create(parser, PM_CALL_NODE_FLAGS_IGNORE_VISIBILITY);
2706
2707 node->base.location.start = message->start;
2708 node->base.location.end = pm_arguments_end(arguments);
2709
2710 node->message_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(message);
2711 node->opening_loc = arguments->opening_loc;
2712 node->arguments = arguments->arguments;
2713 node->closing_loc = arguments->closing_loc;
2714 node->block = arguments->block;
2715
2716 node->name = pm_parser_constant_id_token(parser, message);
2717 return node;
2718 }
2719
2720 /**
2721 * Allocate and initialize a new CallNode node from a synthesized call to a
2722 * method name with the given arguments.
2723 */
2724 static pm_call_node_t *
2725 pm_call_node_fcall_synthesized_create(pm_parser_t *parser, pm_arguments_node_t *arguments, pm_constant_id_t name) {
2726 pm_call_node_t *node = pm_call_node_create(parser, PM_CALL_NODE_FLAGS_IGNORE_VISIBILITY);
2727
2728 node->base.location = PM_LOCATION_NULL_VALUE(parser);
2729 node->arguments = arguments;
2730
2731 node->name = name;
2732 return node;
2733 }
2734
2735 /**
2736 * Allocate and initialize a new CallNode node from a not expression.
2737 */
2738 static pm_call_node_t *
2739 pm_call_node_not_create(pm_parser_t *parser, pm_node_t *receiver, pm_token_t *message, pm_arguments_t *arguments) {
2740 pm_assert_value_expression(parser, receiver);
2741 if (receiver != NULL) pm_conditional_predicate(parser, receiver, PM_CONDITIONAL_PREDICATE_TYPE_NOT);
2742
2743 pm_call_node_t *node = pm_call_node_create(parser, receiver == NULL ? 0 : pm_call_node_ignore_visibility_flag(receiver));
2744
2745 node->base.location.start = message->start;
2746 if (arguments->closing_loc.start != NULL) {
2747 node->base.location.end = arguments->closing_loc.end;
2748 } else {
2749 assert(receiver != NULL);
2750 node->base.location.end = receiver->location.end;
2751 }
2752
2753 node->receiver = receiver;
2754 node->message_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(message);
2755 node->opening_loc = arguments->opening_loc;
2756 node->arguments = arguments->arguments;
2757 node->closing_loc = arguments->closing_loc;
2758
2759 node->name = pm_parser_constant_id_constant(parser, "!", 1);
2760 return node;
2761 }
2762
2763 /**
2764 * Allocate and initialize a new CallNode node from a call shorthand expression.
2765 */
2766 static pm_call_node_t *
2767 pm_call_node_shorthand_create(pm_parser_t *parser, pm_node_t *receiver, pm_token_t *operator, pm_arguments_t *arguments) {
2768 pm_assert_value_expression(parser, receiver);
2769
2770 pm_call_node_t *node = pm_call_node_create(parser, pm_call_node_ignore_visibility_flag(receiver));
2771
2772 node->base.location.start = receiver->location.start;
2773 node->base.location.end = pm_arguments_end(arguments);
2774
2775 node->receiver = receiver;
2776 node->call_operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator);
2777 node->opening_loc = arguments->opening_loc;
2778 node->arguments = arguments->arguments;
2779 node->closing_loc = arguments->closing_loc;
2780 node->block = arguments->block;
2781
2782 if (operator->type == PM_TOKEN_AMPERSAND_DOT) {
2783 pm_node_flag_set(UP(node), PM_CALL_NODE_FLAGS_SAFE_NAVIGATION);
2784 }
2785
2786 node->name = pm_parser_constant_id_constant(parser, "call", 4);
2787 return node;
2788 }
2789
2790 /**
2791 * Allocate and initialize a new CallNode node from a unary operator expression.
2792 */
2793 static pm_call_node_t *
2794 pm_call_node_unary_create(pm_parser_t *parser, pm_token_t *operator, pm_node_t *receiver, const char *name) {
2795 pm_assert_value_expression(parser, receiver);
2796
2797 pm_call_node_t *node = pm_call_node_create(parser, pm_call_node_ignore_visibility_flag(receiver));
2798
2799 node->base.location.start = operator->start;
2800 node->base.location.end = receiver->location.end;
2801
2802 node->receiver = receiver;
2803 node->message_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator);
2804
2805 node->name = pm_parser_constant_id_constant(parser, name, strlen(name));
2806 return node;
2807 }
2808
2809 /**
2810 * Allocate and initialize a new CallNode node from a call to a method name
2811 * without a receiver that could also have been a local variable read.
2812 */
2813 static pm_call_node_t *
2814 pm_call_node_variable_call_create(pm_parser_t *parser, pm_token_t *message) {
2815 pm_call_node_t *node = pm_call_node_create(parser, PM_CALL_NODE_FLAGS_IGNORE_VISIBILITY);
2816
2817 node->base.location = PM_LOCATION_TOKEN_VALUE(message);
2818 node->message_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(message);
2819
2820 node->name = pm_parser_constant_id_token(parser, message);
2821 return node;
2822 }
2823
2824 /**
2825 * Returns whether or not this call can be used on the left-hand side of an
2826 * operator assignment.
2827 */
2828 static inline bool
2829 pm_call_node_writable_p(const pm_parser_t *parser, const pm_call_node_t *node) {
2830 return (
2831 (node->message_loc.start != NULL) &&
2832 (node->message_loc.end[-1] != '!') &&
2833 (node->message_loc.end[-1] != '?') &&
2834 char_is_identifier_start(parser, node->message_loc.start, parser->end - node->message_loc.start) &&
2835 (node->opening_loc.start == NULL) &&
2836 (node->arguments == NULL) &&
2837 (node->block == NULL)
2838 );
2839 }
2840
2841 /**
2842 * Initialize the read name by reading the write name and chopping off the '='.
2843 */
2844 static void
2845 pm_call_write_read_name_init(pm_parser_t *parser, pm_constant_id_t *read_name, pm_constant_id_t *write_name) {
2846 pm_constant_t *write_constant = pm_constant_pool_id_to_constant(&parser->constant_pool, *write_name);
2847
2848 if (write_constant->length > 0) {
2849 size_t length = write_constant->length - 1;
2850
2851 void *memory = xmalloc(length);
2852 memcpy(memory, write_constant->start, length);
2853
2854 *read_name = pm_constant_pool_insert_owned(&parser->constant_pool, (uint8_t *) memory, length);
2855 } else {
2856 // We can get here if the message was missing because of a syntax error.
2857 *read_name = pm_parser_constant_id_constant(parser, "", 0);
2858 }
2859 }
2860
2861 /**
2862 * Allocate and initialize a new CallAndWriteNode node.
2863 */
2864 static pm_call_and_write_node_t *
2865 pm_call_and_write_node_create(pm_parser_t *parser, pm_call_node_t *target, const pm_token_t *operator, pm_node_t *value) {
2866 assert(target->block == NULL);
2867 assert(operator->type == PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL);
2868 pm_call_and_write_node_t *node = PM_NODE_ALLOC(parser, pm_call_and_write_node_t);
2869
2870 *node = (pm_call_and_write_node_t) {
2871 .base = PM_NODE_INIT_NODES(parser, PM_CALL_AND_WRITE_NODE, FL(target), target, value),
2872 .receiver = target->receiver,
2873 .call_operator_loc = target->call_operator_loc,
2874 .message_loc = target->message_loc,
2875 .read_name = 0,
2876 .write_name = target->name,
2877 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
2878 .value = value
2879 };
2880
2881 pm_call_write_read_name_init(parser, &node->read_name, &node->write_name);
2882
2883 // Here we're going to free the target, since it is no longer necessary.
2884 // However, we don't want to call `pm_node_destroy` because we want to keep
2885 // around all of its children since we just reused them.
2886 xfree(target);
2887
2888 return node;
2889 }
2890
2891 /**
2892 * Validate that index expressions do not have keywords or blocks if we are
2893 * parsing as Ruby 3.4+.
2894 */
2895 static void
2896 pm_index_arguments_check(pm_parser_t *parser, const pm_arguments_node_t *arguments, const pm_node_t *block) {
2897 if (parser->version >= PM_OPTIONS_VERSION_CRUBY_3_4) {
2898 if (arguments != NULL && PM_NODE_FLAG_P(arguments, PM_ARGUMENTS_NODE_FLAGS_CONTAINS_KEYWORDS)) {
2899 pm_node_t *node;
2900 PM_NODE_LIST_FOREACH(&arguments->arguments, index, node) {
2901 if (PM_NODE_TYPE_P(node, PM_KEYWORD_HASH_NODE)) {
2902 pm_parser_err_node(parser, node, PM_ERR_UNEXPECTED_INDEX_KEYWORDS);
2903 break;
2904 }
2905 }
2906 }
2907
2908 if (block != NULL) {
2909 pm_parser_err_node(parser, block, PM_ERR_UNEXPECTED_INDEX_BLOCK);
2910 }
2911 }
2912 }
2913
2914 /**
2915 * Allocate and initialize a new IndexAndWriteNode node.
2916 */
2917 static pm_index_and_write_node_t *
2918 pm_index_and_write_node_create(pm_parser_t *parser, pm_call_node_t *target, const pm_token_t *operator, pm_node_t *value) {
2919 assert(operator->type == PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL);
2920 pm_index_and_write_node_t *node = PM_NODE_ALLOC(parser, pm_index_and_write_node_t);
2921
2922 pm_index_arguments_check(parser, target->arguments, target->block);
2923
2924 assert(!target->block || PM_NODE_TYPE_P(target->block, PM_BLOCK_ARGUMENT_NODE));
2925 *node = (pm_index_and_write_node_t) {
2926 .base = PM_NODE_INIT_NODES(parser, PM_INDEX_AND_WRITE_NODE, FL(target), target, value),
2927 .receiver = target->receiver,
2928 .call_operator_loc = target->call_operator_loc,
2929 .opening_loc = target->opening_loc,
2930 .arguments = target->arguments,
2931 .closing_loc = target->closing_loc,
2932 .block = (pm_block_argument_node_t *) target->block,
2933 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
2934 .value = value
2935 };
2936
2937 // Here we're going to free the target, since it is no longer necessary.
2938 // However, we don't want to call `pm_node_destroy` because we want to keep
2939 // around all of its children since we just reused them.
2940 xfree(target);
2941
2942 return node;
2943 }
2944
2945 /**
2946 * Allocate a new CallOperatorWriteNode node.
2947 */
2948 static pm_call_operator_write_node_t *
2949 pm_call_operator_write_node_create(pm_parser_t *parser, pm_call_node_t *target, const pm_token_t *operator, pm_node_t *value) {
2950 assert(target->block == NULL);
2951 pm_call_operator_write_node_t *node = PM_NODE_ALLOC(parser, pm_call_operator_write_node_t);
2952
2953 *node = (pm_call_operator_write_node_t) {
2954 .base = PM_NODE_INIT_NODES(parser, PM_CALL_OPERATOR_WRITE_NODE, FL(target), target, value),
2955 .receiver = target->receiver,
2956 .call_operator_loc = target->call_operator_loc,
2957 .message_loc = target->message_loc,
2958 .read_name = 0,
2959 .write_name = target->name,
2960 .binary_operator = pm_parser_constant_id_location(parser, operator->start, operator->end - 1),
2961 .binary_operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
2962 .value = value
2963 };
2964
2965 pm_call_write_read_name_init(parser, &node->read_name, &node->write_name);
2966
2967 // Here we're going to free the target, since it is no longer necessary.
2968 // However, we don't want to call `pm_node_destroy` because we want to keep
2969 // around all of its children since we just reused them.
2970 xfree(target);
2971
2972 return node;
2973 }
2974
2975 /**
2976 * Allocate a new IndexOperatorWriteNode node.
2977 */
2978 static pm_index_operator_write_node_t *
2979 pm_index_operator_write_node_create(pm_parser_t *parser, pm_call_node_t *target, const pm_token_t *operator, pm_node_t *value) {
2980 pm_index_operator_write_node_t *node = PM_NODE_ALLOC(parser, pm_index_operator_write_node_t);
2981
2982 pm_index_arguments_check(parser, target->arguments, target->block);
2983
2984 assert(!target->block || PM_NODE_TYPE_P(target->block, PM_BLOCK_ARGUMENT_NODE));
2985 *node = (pm_index_operator_write_node_t) {
2986 .base = PM_NODE_INIT_NODES(parser, PM_INDEX_OPERATOR_WRITE_NODE, FL(target), target, value),
2987 .receiver = target->receiver,
2988 .call_operator_loc = target->call_operator_loc,
2989 .opening_loc = target->opening_loc,
2990 .arguments = target->arguments,
2991 .closing_loc = target->closing_loc,
2992 .block = (pm_block_argument_node_t *) target->block,
2993 .binary_operator = pm_parser_constant_id_location(parser, operator->start, operator->end - 1),
2994 .binary_operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
2995 .value = value
2996 };
2997
2998 // Here we're going to free the target, since it is no longer necessary.
2999 // However, we don't want to call `pm_node_destroy` because we want to keep
3000 // around all of its children since we just reused them.
3001 xfree(target);
3002
3003 return node;
3004 }
3005
3006 /**
3007 * Allocate and initialize a new CallOrWriteNode node.
3008 */
3009 static pm_call_or_write_node_t *
3010 pm_call_or_write_node_create(pm_parser_t *parser, pm_call_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3011 assert(target->block == NULL);
3012 assert(operator->type == PM_TOKEN_PIPE_PIPE_EQUAL);
3013 pm_call_or_write_node_t *node = PM_NODE_ALLOC(parser, pm_call_or_write_node_t);
3014
3015 *node = (pm_call_or_write_node_t) {
3016 .base = PM_NODE_INIT_NODES(parser, PM_CALL_OR_WRITE_NODE, FL(target), target, value),
3017 .receiver = target->receiver,
3018 .call_operator_loc = target->call_operator_loc,
3019 .message_loc = target->message_loc,
3020 .read_name = 0,
3021 .write_name = target->name,
3022 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3023 .value = value
3024 };
3025
3026 pm_call_write_read_name_init(parser, &node->read_name, &node->write_name);
3027
3028 // Here we're going to free the target, since it is no longer necessary.
3029 // However, we don't want to call `pm_node_destroy` because we want to keep
3030 // around all of its children since we just reused them.
3031 xfree(target);
3032
3033 return node;
3034 }
3035
3036 /**
3037 * Allocate and initialize a new IndexOrWriteNode node.
3038 */
3039 static pm_index_or_write_node_t *
3040 pm_index_or_write_node_create(pm_parser_t *parser, pm_call_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3041 assert(operator->type == PM_TOKEN_PIPE_PIPE_EQUAL);
3042 pm_index_or_write_node_t *node = PM_NODE_ALLOC(parser, pm_index_or_write_node_t);
3043
3044 pm_index_arguments_check(parser, target->arguments, target->block);
3045
3046 assert(!target->block || PM_NODE_TYPE_P(target->block, PM_BLOCK_ARGUMENT_NODE));
3047 *node = (pm_index_or_write_node_t) {
3048 .base = PM_NODE_INIT_NODES(parser, PM_INDEX_OR_WRITE_NODE, FL(target), target, value),
3049 .receiver = target->receiver,
3050 .call_operator_loc = target->call_operator_loc,
3051 .opening_loc = target->opening_loc,
3052 .arguments = target->arguments,
3053 .closing_loc = target->closing_loc,
3054 .block = (pm_block_argument_node_t *) target->block,
3055 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3056 .value = value
3057 };
3058
3059 // Here we're going to free the target, since it is no longer necessary.
3060 // However, we don't want to call `pm_node_destroy` because we want to keep
3061 // around all of its children since we just reused them.
3062 xfree(target);
3063
3064 return node;
3065 }
3066
3067 /**
3068 * Allocate and initialize a new CallTargetNode node from an existing call
3069 * node.
3070 */
3071 static pm_call_target_node_t *
3072 pm_call_target_node_create(pm_parser_t *parser, pm_call_node_t *target) {
3073 pm_call_target_node_t *node = PM_NODE_ALLOC(parser, pm_call_target_node_t);
3074
3075 *node = (pm_call_target_node_t) {
3076 .base = PM_NODE_INIT_NODE(parser, PM_CALL_TARGET_NODE, FL(target), target),
3077 .receiver = target->receiver,
3078 .call_operator_loc = target->call_operator_loc,
3079 .name = target->name,
3080 .message_loc = target->message_loc
3081 };
3082
3083 /* It is possible to get here where we have parsed an invalid syntax tree
3084 * where the call operator was not present. In that case we will have a
3085 * problem because it is a required location. In this case we need to fill
3086 * it in with a fake location so that the syntax tree remains valid. */
3087 if (node->call_operator_loc.start == NULL) {
3088 node->call_operator_loc = (pm_location_t) {
3089 .start = target->base.location.start,
3090 .end = target->base.location.start
3091 };
3092 }
3093
3094 // Here we're going to free the target, since it is no longer necessary.
3095 // However, we don't want to call `pm_node_destroy` because we want to keep
3096 // around all of its children since we just reused them.
3097 xfree(target);
3098
3099 return node;
3100 }
3101
3102 /**
3103 * Allocate and initialize a new IndexTargetNode node from an existing call
3104 * node.
3105 */
3106 static pm_index_target_node_t *
3107 pm_index_target_node_create(pm_parser_t *parser, pm_call_node_t *target) {
3108 pm_index_target_node_t *node = PM_NODE_ALLOC(parser, pm_index_target_node_t);
3109
3110 pm_index_arguments_check(parser, target->arguments, target->block);
3111 assert(!target->block || PM_NODE_TYPE_P(target->block, PM_BLOCK_ARGUMENT_NODE));
3112
3113 *node = (pm_index_target_node_t) {
3114 .base = PM_NODE_INIT_NODE(parser, PM_INDEX_TARGET_NODE, FL(target) | PM_CALL_NODE_FLAGS_ATTRIBUTE_WRITE, target),
3115 .receiver = target->receiver,
3116 .opening_loc = target->opening_loc,
3117 .arguments = target->arguments,
3118 .closing_loc = target->closing_loc,
3119 .block = (pm_block_argument_node_t *) target->block,
3120 };
3121
3122 // Here we're going to free the target, since it is no longer necessary.
3123 // However, we don't want to call `pm_node_destroy` because we want to keep
3124 // around all of its children since we just reused them.
3125 xfree(target);
3126
3127 return node;
3128 }
3129
3130 /**
3131 * Allocate and initialize a new CapturePatternNode node.
3132 */
3133 static pm_capture_pattern_node_t *
3134 pm_capture_pattern_node_create(pm_parser_t *parser, pm_node_t *value, pm_local_variable_target_node_t *target, const pm_token_t *operator) {
3135 pm_capture_pattern_node_t *node = PM_NODE_ALLOC(parser, pm_capture_pattern_node_t);
3136
3137 *node = (pm_capture_pattern_node_t) {
3138 .base = PM_NODE_INIT_NODES(parser, PM_CAPTURE_PATTERN_NODE, 0, value, target),
3139 .value = value,
3140 .target = target,
3141 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
3142 };
3143
3144 return node;
3145 }
3146
3147 /**
3148 * Allocate and initialize a new CaseNode node.
3149 */
3150 static pm_case_node_t *
3151 pm_case_node_create(pm_parser_t *parser, const pm_token_t *case_keyword, pm_node_t *predicate, const pm_token_t *end_keyword) {
3152 pm_case_node_t *node = PM_NODE_ALLOC(parser, pm_case_node_t);
3153
3154 *node = (pm_case_node_t) {
3155 .base = PM_NODE_INIT_TOKENS(parser, PM_CASE_NODE, 0, case_keyword, end_keyword),
3156 .predicate = predicate,
3157 .else_clause = NULL,
3158 .case_keyword_loc = PM_LOCATION_TOKEN_VALUE(case_keyword),
3159 .end_keyword_loc = PM_LOCATION_TOKEN_VALUE(end_keyword),
3160 .conditions = { 0 }
3161 };
3162
3163 return node;
3164 }
3165
3166 /**
3167 * Append a new condition to a CaseNode node.
3168 */
3169 static void
3170 pm_case_node_condition_append(pm_case_node_t *node, pm_node_t *condition) {
3171 assert(PM_NODE_TYPE_P(condition, PM_WHEN_NODE));
3172
3173 pm_node_list_append(&node->conditions, condition);
3174 node->base.location.end = condition->location.end;
3175 }
3176
3177 /**
3178 * Set the else clause of a CaseNode node.
3179 */
3180 static void
3181 pm_case_node_else_clause_set(pm_case_node_t *node, pm_else_node_t *else_clause) {
3182 node->else_clause = else_clause;
3183 node->base.location.end = else_clause->base.location.end;
3184 }
3185
3186 /**
3187 * Set the end location for a CaseNode node.
3188 */
3189 static void
3190 pm_case_node_end_keyword_loc_set(pm_case_node_t *node, const pm_token_t *end_keyword) {
3191 node->base.location.end = end_keyword->end;
3192 node->end_keyword_loc = PM_LOCATION_TOKEN_VALUE(end_keyword);
3193 }
3194
3195 /**
3196 * Allocate and initialize a new CaseMatchNode node.
3197 */
3198 static pm_case_match_node_t *
3199 pm_case_match_node_create(pm_parser_t *parser, const pm_token_t *case_keyword, pm_node_t *predicate, const pm_token_t *end_keyword) {
3200 pm_case_match_node_t *node = PM_NODE_ALLOC(parser, pm_case_match_node_t);
3201
3202 *node = (pm_case_match_node_t) {
3203 .base = PM_NODE_INIT_TOKENS(parser, PM_CASE_MATCH_NODE, 0, case_keyword, end_keyword),
3204 .predicate = predicate,
3205 .else_clause = NULL,
3206 .case_keyword_loc = PM_LOCATION_TOKEN_VALUE(case_keyword),
3207 .end_keyword_loc = PM_LOCATION_TOKEN_VALUE(end_keyword),
3208 .conditions = { 0 }
3209 };
3210
3211 return node;
3212 }
3213
3214 /**
3215 * Append a new condition to a CaseMatchNode node.
3216 */
3217 static void
3218 pm_case_match_node_condition_append(pm_case_match_node_t *node, pm_node_t *condition) {
3219 assert(PM_NODE_TYPE_P(condition, PM_IN_NODE));
3220
3221 pm_node_list_append(&node->conditions, condition);
3222 node->base.location.end = condition->location.end;
3223 }
3224
3225 /**
3226 * Set the else clause of a CaseMatchNode node.
3227 */
3228 static void
3229 pm_case_match_node_else_clause_set(pm_case_match_node_t *node, pm_else_node_t *else_clause) {
3230 node->else_clause = else_clause;
3231 node->base.location.end = else_clause->base.location.end;
3232 }
3233
3234 /**
3235 * Set the end location for a CaseMatchNode node.
3236 */
3237 static void
3238 pm_case_match_node_end_keyword_loc_set(pm_case_match_node_t *node, const pm_token_t *end_keyword) {
3239 node->base.location.end = end_keyword->end;
3240 node->end_keyword_loc = PM_LOCATION_TOKEN_VALUE(end_keyword);
3241 }
3242
3243 /**
3244 * Allocate a new ClassNode node.
3245 */
3246 static pm_class_node_t *
3247 pm_class_node_create(pm_parser_t *parser, pm_constant_id_list_t *locals, const pm_token_t *class_keyword, pm_node_t *constant_path, const pm_token_t *name, const pm_token_t *inheritance_operator, pm_node_t *superclass, pm_node_t *body, const pm_token_t *end_keyword) {
3248 pm_class_node_t *node = PM_NODE_ALLOC(parser, pm_class_node_t);
3249
3250 *node = (pm_class_node_t) {
3251 .base = PM_NODE_INIT_TOKENS(parser, PM_CLASS_NODE, 0, class_keyword, end_keyword),
3252 .locals = *locals,
3253 .class_keyword_loc = PM_LOCATION_TOKEN_VALUE(class_keyword),
3254 .constant_path = constant_path,
3255 .inheritance_operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(inheritance_operator),
3256 .superclass = superclass,
3257 .body = body,
3258 .end_keyword_loc = PM_LOCATION_TOKEN_VALUE(end_keyword),
3259 .name = pm_parser_constant_id_token(parser, name)
3260 };
3261
3262 return node;
3263 }
3264
3265 /**
3266 * Allocate and initialize a new ClassVariableAndWriteNode node.
3267 */
3268 static pm_class_variable_and_write_node_t *
3269 pm_class_variable_and_write_node_create(pm_parser_t *parser, pm_class_variable_read_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3270 assert(operator->type == PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL);
3271 pm_class_variable_and_write_node_t *node = PM_NODE_ALLOC(parser, pm_class_variable_and_write_node_t);
3272
3273 *node = (pm_class_variable_and_write_node_t) {
3274 .base = PM_NODE_INIT_NODES(parser, PM_CLASS_VARIABLE_AND_WRITE_NODE, 0, target, value),
3275 .name = target->name,
3276 .name_loc = target->base.location,
3277 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3278 .value = value
3279 };
3280
3281 return node;
3282 }
3283
3284 /**
3285 * Allocate and initialize a new ClassVariableOperatorWriteNode node.
3286 */
3287 static pm_class_variable_operator_write_node_t *
3288 pm_class_variable_operator_write_node_create(pm_parser_t *parser, pm_class_variable_read_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3289 pm_class_variable_operator_write_node_t *node = PM_NODE_ALLOC(parser, pm_class_variable_operator_write_node_t);
3290
3291 *node = (pm_class_variable_operator_write_node_t) {
3292 .base = PM_NODE_INIT_NODES(parser, PM_CLASS_VARIABLE_OPERATOR_WRITE_NODE, 0, target, value),
3293 .name = target->name,
3294 .name_loc = target->base.location,
3295 .binary_operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3296 .value = value,
3297 .binary_operator = pm_parser_constant_id_location(parser, operator->start, operator->end - 1)
3298 };
3299
3300 return node;
3301 }
3302
3303 /**
3304 * Allocate and initialize a new ClassVariableOrWriteNode node.
3305 */
3306 static pm_class_variable_or_write_node_t *
3307 pm_class_variable_or_write_node_create(pm_parser_t *parser, pm_class_variable_read_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3308 assert(operator->type == PM_TOKEN_PIPE_PIPE_EQUAL);
3309 pm_class_variable_or_write_node_t *node = PM_NODE_ALLOC(parser, pm_class_variable_or_write_node_t);
3310
3311 *node = (pm_class_variable_or_write_node_t) {
3312 .base = PM_NODE_INIT_NODES(parser, PM_CLASS_VARIABLE_OR_WRITE_NODE, 0, target, value),
3313 .name = target->name,
3314 .name_loc = target->base.location,
3315 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3316 .value = value
3317 };
3318
3319 return node;
3320 }
3321
3322 /**
3323 * Allocate and initialize a new ClassVariableReadNode node.
3324 */
3325 static pm_class_variable_read_node_t *
3326 pm_class_variable_read_node_create(pm_parser_t *parser, const pm_token_t *token) {
3327 assert(token->type == PM_TOKEN_CLASS_VARIABLE);
3328 pm_class_variable_read_node_t *node = PM_NODE_ALLOC(parser, pm_class_variable_read_node_t);
3329
3330 *node = (pm_class_variable_read_node_t) {
3331 .base = PM_NODE_INIT_TOKEN(parser, PM_CLASS_VARIABLE_READ_NODE, 0, token),
3332 .name = pm_parser_constant_id_token(parser, token)
3333 };
3334
3335 return node;
3336 }
3337
3338 /**
3339 * True if the given node is an implicit array node on a write, as in:
3340 *
3341 * a = *b
3342 * a = 1, 2, 3
3343 */
3344 static inline pm_node_flags_t
3345 pm_implicit_array_write_flags(const pm_node_t *node, pm_node_flags_t flags) {
3346 if (PM_NODE_TYPE_P(node, PM_ARRAY_NODE) && ((const pm_array_node_t *) node)->opening_loc.start == NULL) {
3347 return flags;
3348 }
3349 return 0;
3350 }
3351
3352 /**
3353 * Initialize a new ClassVariableWriteNode node from a ClassVariableRead node.
3354 */
3355 static pm_class_variable_write_node_t *
3356 pm_class_variable_write_node_create(pm_parser_t *parser, pm_class_variable_read_node_t *read_node, pm_token_t *operator, pm_node_t *value) {
3357 pm_class_variable_write_node_t *node = PM_NODE_ALLOC(parser, pm_class_variable_write_node_t);
3358 pm_node_flags_t flags = pm_implicit_array_write_flags(value, PM_WRITE_NODE_FLAGS_IMPLICIT_ARRAY);
3359
3360 *node = (pm_class_variable_write_node_t) {
3361 .base = PM_NODE_INIT_NODES(parser, PM_CLASS_VARIABLE_WRITE_NODE, flags, read_node, value),
3362 .name = read_node->name,
3363 .name_loc = PM_LOCATION_NODE_VALUE(UP(read_node)),
3364 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3365 .value = value
3366 };
3367
3368 return node;
3369 }
3370
3371 /**
3372 * Allocate and initialize a new ConstantPathAndWriteNode node.
3373 */
3374 static pm_constant_path_and_write_node_t *
3375 pm_constant_path_and_write_node_create(pm_parser_t *parser, pm_constant_path_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3376 assert(operator->type == PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL);
3377 pm_constant_path_and_write_node_t *node = PM_NODE_ALLOC(parser, pm_constant_path_and_write_node_t);
3378
3379 *node = (pm_constant_path_and_write_node_t) {
3380 .base = PM_NODE_INIT_NODES(parser, PM_CONSTANT_PATH_AND_WRITE_NODE, 0, target, value),
3381 .target = target,
3382 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3383 .value = value
3384 };
3385
3386 return node;
3387 }
3388
3389 /**
3390 * Allocate and initialize a new ConstantPathOperatorWriteNode node.
3391 */
3392 static pm_constant_path_operator_write_node_t *
3393 pm_constant_path_operator_write_node_create(pm_parser_t *parser, pm_constant_path_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3394 pm_constant_path_operator_write_node_t *node = PM_NODE_ALLOC(parser, pm_constant_path_operator_write_node_t);
3395
3396 *node = (pm_constant_path_operator_write_node_t) {
3397 .base = PM_NODE_INIT_NODES(parser, PM_CONSTANT_PATH_OPERATOR_WRITE_NODE, 0, target, value),
3398 .target = target,
3399 .binary_operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3400 .value = value,
3401 .binary_operator = pm_parser_constant_id_location(parser, operator->start, operator->end - 1)
3402 };
3403
3404 return node;
3405 }
3406
3407 /**
3408 * Allocate and initialize a new ConstantPathOrWriteNode node.
3409 */
3410 static pm_constant_path_or_write_node_t *
3411 pm_constant_path_or_write_node_create(pm_parser_t *parser, pm_constant_path_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3412 assert(operator->type == PM_TOKEN_PIPE_PIPE_EQUAL);
3413 pm_constant_path_or_write_node_t *node = PM_NODE_ALLOC(parser, pm_constant_path_or_write_node_t);
3414
3415 *node = (pm_constant_path_or_write_node_t) {
3416 .base = PM_NODE_INIT_NODES(parser, PM_CONSTANT_PATH_OR_WRITE_NODE, 0, target, value),
3417 .target = target,
3418 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3419 .value = value
3420 };
3421
3422 return node;
3423 }
3424
3425 /**
3426 * Allocate and initialize a new ConstantPathNode node.
3427 */
3428 static pm_constant_path_node_t *
3429 pm_constant_path_node_create(pm_parser_t *parser, pm_node_t *parent, const pm_token_t *delimiter, const pm_token_t *name_token) {
3430 pm_assert_value_expression(parser, parent);
3431 pm_constant_path_node_t *node = PM_NODE_ALLOC(parser, pm_constant_path_node_t);
3432
3433 pm_constant_id_t name = PM_CONSTANT_ID_UNSET;
3434 if (name_token->type == PM_TOKEN_CONSTANT) {
3435 name = pm_parser_constant_id_token(parser, name_token);
3436 }
3437
3438 if (parent == NULL) {
3439 *node = (pm_constant_path_node_t) {
3440 .base = PM_NODE_INIT_TOKENS(parser, PM_CONSTANT_PATH_NODE, 0, delimiter, name_token),
3441 .parent = parent,
3442 .name = name,
3443 .delimiter_loc = PM_LOCATION_TOKEN_VALUE(delimiter),
3444 .name_loc = PM_LOCATION_TOKEN_VALUE(name_token)
3445 };
3446 } else {
3447 *node = (pm_constant_path_node_t) {
3448 .base = PM_NODE_INIT_NODE_TOKEN(parser, PM_CONSTANT_PATH_NODE, 0, parent, name_token),
3449 .parent = parent,
3450 .name = name,
3451 .delimiter_loc = PM_LOCATION_TOKEN_VALUE(delimiter),
3452 .name_loc = PM_LOCATION_TOKEN_VALUE(name_token)
3453 };
3454 }
3455
3456 return node;
3457 }
3458
3459 /**
3460 * Allocate a new ConstantPathWriteNode node.
3461 */
3462 static pm_constant_path_write_node_t *
3463 pm_constant_path_write_node_create(pm_parser_t *parser, pm_constant_path_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3464 pm_constant_path_write_node_t *node = PM_NODE_ALLOC(parser, pm_constant_path_write_node_t);
3465 pm_node_flags_t flags = pm_implicit_array_write_flags(value, PM_WRITE_NODE_FLAGS_IMPLICIT_ARRAY);
3466
3467 *node = (pm_constant_path_write_node_t) {
3468 .base = PM_NODE_INIT_NODES(parser, PM_CONSTANT_PATH_WRITE_NODE, flags, target, value),
3469 .target = target,
3470 .operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator),
3471 .value = value
3472 };
3473
3474 return node;
3475 }
3476
3477 /**
3478 * Allocate and initialize a new ConstantAndWriteNode node.
3479 */
3480 static pm_constant_and_write_node_t *
3481 pm_constant_and_write_node_create(pm_parser_t *parser, pm_constant_read_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3482 assert(operator->type == PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL);
3483 pm_constant_and_write_node_t *node = PM_NODE_ALLOC(parser, pm_constant_and_write_node_t);
3484
3485 *node = (pm_constant_and_write_node_t) {
3486 .base = PM_NODE_INIT_NODES(parser, PM_CONSTANT_AND_WRITE_NODE, 0, target, value),
3487 .name = target->name,
3488 .name_loc = target->base.location,
3489 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3490 .value = value
3491 };
3492
3493 return node;
3494 }
3495
3496 /**
3497 * Allocate and initialize a new ConstantOperatorWriteNode node.
3498 */
3499 static pm_constant_operator_write_node_t *
3500 pm_constant_operator_write_node_create(pm_parser_t *parser, pm_constant_read_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3501 pm_constant_operator_write_node_t *node = PM_NODE_ALLOC(parser, pm_constant_operator_write_node_t);
3502
3503 *node = (pm_constant_operator_write_node_t) {
3504 .base = PM_NODE_INIT_NODES(parser, PM_CONSTANT_OPERATOR_WRITE_NODE, 0, target, value),
3505 .name = target->name,
3506 .name_loc = target->base.location,
3507 .binary_operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3508 .value = value,
3509 .binary_operator = pm_parser_constant_id_location(parser, operator->start, operator->end - 1)
3510 };
3511
3512 return node;
3513 }
3514
3515 /**
3516 * Allocate and initialize a new ConstantOrWriteNode node.
3517 */
3518 static pm_constant_or_write_node_t *
3519 pm_constant_or_write_node_create(pm_parser_t *parser, pm_constant_read_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3520 assert(operator->type == PM_TOKEN_PIPE_PIPE_EQUAL);
3521 pm_constant_or_write_node_t *node = PM_NODE_ALLOC(parser, pm_constant_or_write_node_t);
3522
3523 *node = (pm_constant_or_write_node_t) {
3524 .base = PM_NODE_INIT_NODES(parser, PM_CONSTANT_OR_WRITE_NODE, 0, target, value),
3525 .name = target->name,
3526 .name_loc = target->base.location,
3527 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3528 .value = value
3529 };
3530
3531 return node;
3532 }
3533
3534 /**
3535 * Allocate and initialize a new ConstantReadNode node.
3536 */
3537 static pm_constant_read_node_t *
3538 pm_constant_read_node_create(pm_parser_t *parser, const pm_token_t *name) {
3539 assert(name->type == PM_TOKEN_CONSTANT || name->type == PM_TOKEN_MISSING);
3540 pm_constant_read_node_t *node = PM_NODE_ALLOC(parser, pm_constant_read_node_t);
3541
3542 *node = (pm_constant_read_node_t) {
3543 .base = PM_NODE_INIT_TOKEN(parser, PM_CONSTANT_READ_NODE, 0, name),
3544 .name = pm_parser_constant_id_token(parser, name)
3545 };
3546
3547 return node;
3548 }
3549
3550 /**
3551 * Allocate a new ConstantWriteNode node.
3552 */
3553 static pm_constant_write_node_t *
3554 pm_constant_write_node_create(pm_parser_t *parser, pm_constant_read_node_t *target, const pm_token_t *operator, pm_node_t *value) {
3555 pm_constant_write_node_t *node = PM_NODE_ALLOC(parser, pm_constant_write_node_t);
3556 pm_node_flags_t flags = pm_implicit_array_write_flags(value, PM_WRITE_NODE_FLAGS_IMPLICIT_ARRAY);
3557
3558 *node = (pm_constant_write_node_t) {
3559 .base = PM_NODE_INIT_NODES(parser, PM_CONSTANT_WRITE_NODE, flags, target, value),
3560 .name = target->name,
3561 .name_loc = target->base.location,
3562 .operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator),
3563 .value = value
3564 };
3565
3566 return node;
3567 }
3568
3569 /**
3570 * Check if the receiver of a `def` node is allowed.
3571 */
3572 static void
3573 pm_def_node_receiver_check(pm_parser_t *parser, const pm_node_t *node) {
3574 switch (PM_NODE_TYPE(node)) {
3575 case PM_BEGIN_NODE: {
3576 const pm_begin_node_t *cast = (pm_begin_node_t *) node;
3577 if (cast->statements != NULL) pm_def_node_receiver_check(parser, UP(cast->statements));
3578 break;
3579 }
3580 case PM_PARENTHESES_NODE: {
3581 const pm_parentheses_node_t *cast = (const pm_parentheses_node_t *) node;
3582 if (cast->body != NULL) pm_def_node_receiver_check(parser, cast->body);
3583 break;
3584 }
3585 case PM_STATEMENTS_NODE: {
3586 const pm_statements_node_t *cast = (const pm_statements_node_t *) node;
3587 pm_def_node_receiver_check(parser, cast->body.nodes[cast->body.size - 1]);
3588 break;
3589 }
3590 case PM_ARRAY_NODE:
3591 case PM_FLOAT_NODE:
3592 case PM_IMAGINARY_NODE:
3593 case PM_INTEGER_NODE:
3594 case PM_INTERPOLATED_REGULAR_EXPRESSION_NODE:
3595 case PM_INTERPOLATED_STRING_NODE:
3596 case PM_INTERPOLATED_SYMBOL_NODE:
3597 case PM_INTERPOLATED_X_STRING_NODE:
3598 case PM_RATIONAL_NODE:
3599 case PM_REGULAR_EXPRESSION_NODE:
3600 case PM_SOURCE_ENCODING_NODE:
3601 case PM_SOURCE_FILE_NODE:
3602 case PM_SOURCE_LINE_NODE:
3603 case PM_STRING_NODE:
3604 case PM_SYMBOL_NODE:
3605 case PM_X_STRING_NODE:
3606 pm_parser_err_node(parser, node, PM_ERR_SINGLETON_FOR_LITERALS);
3607 break;
3608 default:
3609 break;
3610 }
3611 }
3612
3613 /**
3614 * Allocate and initialize a new DefNode node.
3615 */
3616 static pm_def_node_t *
3617 pm_def_node_create(
3618 pm_parser_t *parser,
3619 pm_constant_id_t name,
3620 const pm_token_t *name_loc,
3621 pm_node_t *receiver,
3622 pm_parameters_node_t *parameters,
3623 pm_node_t *body,
3624 pm_constant_id_list_t *locals,
3625 const pm_token_t *def_keyword,
3626 const pm_token_t *operator,
3627 const pm_token_t *lparen,
3628 const pm_token_t *rparen,
3629 const pm_token_t *equal,
3630 const pm_token_t *end_keyword
3631 ) {
3632 pm_def_node_t *node = PM_NODE_ALLOC(parser, pm_def_node_t);
3633
3634 if (receiver != NULL) {
3635 pm_def_node_receiver_check(parser, receiver);
3636 }
3637
3638 *node = (pm_def_node_t) {
3639 .base = (
3640 (end_keyword->type == PM_TOKEN_NOT_PROVIDED)
3641 ? PM_NODE_INIT_TOKEN_NODE(parser, PM_DEF_NODE, 0, def_keyword, body)
3642 : PM_NODE_INIT_TOKENS(parser, PM_DEF_NODE, 0, def_keyword, end_keyword)
3643 ),
3644 .name = name,
3645 .name_loc = PM_LOCATION_TOKEN_VALUE(name_loc),
3646 .receiver = receiver,
3647 .parameters = parameters,
3648 .body = body,
3649 .locals = *locals,
3650 .def_keyword_loc = PM_LOCATION_TOKEN_VALUE(def_keyword),
3651 .operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator),
3652 .lparen_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(lparen),
3653 .rparen_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(rparen),
3654 .equal_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(equal),
3655 .end_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(end_keyword)
3656 };
3657
3658 return node;
3659 }
3660
3661 /**
3662 * Allocate a new DefinedNode node.
3663 */
3664 static pm_defined_node_t *
3665 pm_defined_node_create(pm_parser_t *parser, const pm_token_t *lparen, pm_node_t *value, const pm_token_t *rparen, const pm_token_t *keyword) {
3666 pm_defined_node_t *node = PM_NODE_ALLOC(parser, pm_defined_node_t);
3667
3668 *node = (pm_defined_node_t) {
3669 .base = (
3670 (rparen->type == PM_TOKEN_NOT_PROVIDED)
3671 ? PM_NODE_INIT_TOKEN_NODE(parser, PM_DEFINED_NODE, 0, keyword, value)
3672 : PM_NODE_INIT_TOKENS(parser, PM_DEFINED_NODE, 0, keyword, rparen)
3673 ),
3674 .lparen_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(lparen),
3675 .value = value,
3676 .rparen_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(rparen),
3677 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword)
3678 };
3679
3680 return node;
3681 }
3682
3683 /**
3684 * Allocate and initialize a new ElseNode node.
3685 */
3686 static pm_else_node_t *
3687 pm_else_node_create(pm_parser_t *parser, const pm_token_t *else_keyword, pm_statements_node_t *statements, const pm_token_t *end_keyword) {
3688 pm_else_node_t *node = PM_NODE_ALLOC(parser, pm_else_node_t);
3689
3690 *node = (pm_else_node_t) {
3691 .base = (
3692 ((end_keyword->type == PM_TOKEN_NOT_PROVIDED) && (statements != NULL))
3693 ? PM_NODE_INIT_TOKEN_NODE(parser, PM_ELSE_NODE, 0, else_keyword, statements)
3694 : PM_NODE_INIT_TOKENS(parser, PM_ELSE_NODE, 0, else_keyword, end_keyword)
3695 ),
3696 .else_keyword_loc = PM_LOCATION_TOKEN_VALUE(else_keyword),
3697 .statements = statements,
3698 .end_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(end_keyword)
3699 };
3700
3701 return node;
3702 }
3703
3704 /**
3705 * Allocate and initialize a new EmbeddedStatementsNode node.
3706 */
3707 static pm_embedded_statements_node_t *
3708 pm_embedded_statements_node_create(pm_parser_t *parser, const pm_token_t *opening, pm_statements_node_t *statements, const pm_token_t *closing) {
3709 pm_embedded_statements_node_t *node = PM_NODE_ALLOC(parser, pm_embedded_statements_node_t);
3710
3711 *node = (pm_embedded_statements_node_t) {
3712 .base = PM_NODE_INIT_TOKENS(parser, PM_EMBEDDED_STATEMENTS_NODE, 0, opening, closing),
3713 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
3714 .statements = statements,
3715 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing)
3716 };
3717
3718 return node;
3719 }
3720
3721 /**
3722 * Allocate and initialize a new EmbeddedVariableNode node.
3723 */
3724 static pm_embedded_variable_node_t *
3725 pm_embedded_variable_node_create(pm_parser_t *parser, const pm_token_t *operator, pm_node_t *variable) {
3726 pm_embedded_variable_node_t *node = PM_NODE_ALLOC(parser, pm_embedded_variable_node_t);
3727
3728 *node = (pm_embedded_variable_node_t) {
3729 .base = PM_NODE_INIT_TOKEN_NODE(parser, PM_EMBEDDED_VARIABLE_NODE, 0, operator, variable),
3730 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
3731 .variable = variable
3732 };
3733
3734 return node;
3735 }
3736
3737 /**
3738 * Allocate a new EnsureNode node.
3739 */
3740 static pm_ensure_node_t *
3741 pm_ensure_node_create(pm_parser_t *parser, const pm_token_t *ensure_keyword, pm_statements_node_t *statements, const pm_token_t *end_keyword) {
3742 pm_ensure_node_t *node = PM_NODE_ALLOC(parser, pm_ensure_node_t);
3743
3744 *node = (pm_ensure_node_t) {
3745 .base = PM_NODE_INIT_TOKENS(parser, PM_ENSURE_NODE, 0, ensure_keyword, end_keyword),
3746 .ensure_keyword_loc = PM_LOCATION_TOKEN_VALUE(ensure_keyword),
3747 .statements = statements,
3748 .end_keyword_loc = PM_LOCATION_TOKEN_VALUE(end_keyword)
3749 };
3750
3751 return node;
3752 }
3753
3754 /**
3755 * Allocate and initialize a new FalseNode node.
3756 */
3757 static pm_false_node_t *
3758 pm_false_node_create(pm_parser_t *parser, const pm_token_t *token) {
3759 assert(token->type == PM_TOKEN_KEYWORD_FALSE);
3760 pm_false_node_t *node = PM_NODE_ALLOC(parser, pm_false_node_t);
3761
3762 *node = (pm_false_node_t) {
3763 .base = PM_NODE_INIT_TOKEN(parser, PM_FALSE_NODE, PM_NODE_FLAG_STATIC_LITERAL, token)
3764 };
3765
3766 return node;
3767 }
3768
3769 /**
3770 * Allocate and initialize a new find pattern node. The node list given in the
3771 * nodes parameter is guaranteed to have at least two nodes.
3772 */
3773 static pm_find_pattern_node_t *
3774 pm_find_pattern_node_create(pm_parser_t *parser, pm_node_list_t *nodes) {
3775 pm_find_pattern_node_t *node = PM_NODE_ALLOC(parser, pm_find_pattern_node_t);
3776
3777 pm_node_t *left = nodes->nodes[0];
3778 assert(PM_NODE_TYPE_P(left, PM_SPLAT_NODE));
3779 pm_splat_node_t *left_splat_node = (pm_splat_node_t *) left;
3780
3781 pm_node_t *right;
3782
3783 if (nodes->size == 1) {
3784 right = UP(pm_missing_node_create(parser, left->location.end, left->location.end));
3785 } else {
3786 right = nodes->nodes[nodes->size - 1];
3787 assert(PM_NODE_TYPE_P(right, PM_SPLAT_NODE));
3788 }
3789
3790 #if PRISM_SERIALIZE_ONLY_SEMANTICS_FIELDS
3791 // FindPatternNode#right is typed as SplatNode in this case, so replace the potential MissingNode with a SplatNode.
3792 // The resulting AST will anyway be ignored, but this file still needs to compile.
3793 pm_splat_node_t *right_splat_node = PM_NODE_TYPE_P(right, PM_SPLAT_NODE) ? (pm_splat_node_t *) right : left_splat_node;
3794 #else
3795 pm_node_t *right_splat_node = right;
3796 #endif
3797 *node = (pm_find_pattern_node_t) {
3798 .base = PM_NODE_INIT_NODES(parser, PM_FIND_PATTERN_NODE, 0, left, right),
3799 .constant = NULL,
3800 .left = left_splat_node,
3801 .right = right_splat_node,
3802 .requireds = { 0 },
3803 .opening_loc = { 0 },
3804 .closing_loc = { 0 }
3805 };
3806
3807 // For now we're going to just copy over each pointer manually. This could be
3808 // much more efficient, as we could instead resize the node list to only point
3809 // to 1...-1.
3810 for (size_t index = 1; index < nodes->size - 1; index++) {
3811 pm_node_list_append(&node->requireds, nodes->nodes[index]);
3812 }
3813
3814 return node;
3815 }
3816
3817 /**
3818 * Parse the value of a double, add appropriate errors if there is an issue, and
3819 * return the value that should be saved on the PM_FLOAT_NODE node.
3820 */
3821 static double
3822 pm_double_parse(pm_parser_t *parser, const pm_token_t *token) {
3823 ptrdiff_t diff = token->end - token->start;
3824 if (diff <= 0) return 0.0;
3825
3826 // First, get a buffer of the content.
3827 size_t length = (size_t) diff;
3828 char *buffer = xmalloc(sizeof(char) * (length + 1));
3829 memcpy((void *) buffer, token->start, length);
3830
3831 // Next, determine if we need to replace the decimal point because of
3832 // locale-specific options, and then normalize them if we have to.
3833 char decimal_point = *localeconv()->decimal_point;
3834 if (decimal_point != '.') {
3835 for (size_t index = 0; index < length; index++) {
3836 if (buffer[index] == '.') buffer[index] = decimal_point;
3837 }
3838 }
3839
3840 // Next, handle underscores by removing them from the buffer.
3841 for (size_t index = 0; index < length; index++) {
3842 if (buffer[index] == '_') {
3843 memmove((void *) (buffer + index), (void *) (buffer + index + 1), length - index);
3844 length--;
3845 }
3846 }
3847
3848 // Null-terminate the buffer so that strtod cannot read off the end.
3849 buffer[length] = '\0';
3850
3851 // Now, call strtod to parse the value. Note that CRuby has their own
3852 // version of strtod which avoids locales. We're okay using the locale-aware
3853 // version because we've already validated through the parser that the token
3854 // is in a valid format.
3855 errno = 0;
3856 char *eptr;
3857 double value = strtod(buffer, &eptr);
3858
3859 // This should never happen, because we've already checked that the token
3860 // is in a valid format. However it's good to be safe.
3861 if ((eptr != buffer + length) || (errno != 0 && errno != ERANGE)) {
3862 PM_PARSER_ERR_TOKEN_FORMAT_CONTENT(parser, (*token), PM_ERR_FLOAT_PARSE);
3863 xfree((void *) buffer);
3864 return 0.0;
3865 }
3866
3867 // If errno is set, then it should only be ERANGE. At this point we need to
3868 // check if it's infinity (it should be).
3869 if (errno == ERANGE && PRISM_ISINF(value)) {
3870 int warn_width;
3871 const char *ellipsis;
3872
3873 if (length > 20) {
3874 warn_width = 20;
3875 ellipsis = "...";
3876 } else {
3877 warn_width = (int) length;
3878 ellipsis = "";
3879 }
3880
3881 pm_diagnostic_list_append_format(&parser->warning_list, token->start, token->end, PM_WARN_FLOAT_OUT_OF_RANGE, warn_width, (const char *) token->start, ellipsis);
3882 value = (value < 0.0) ? -HUGE_VAL : HUGE_VAL;
3883 }
3884
3885 // Finally we can free the buffer and return the value.
3886 xfree((void *) buffer);
3887 return value;
3888 }
3889
3890 /**
3891 * Allocate and initialize a new FloatNode node.
3892 */
3893 static pm_float_node_t *
3894 pm_float_node_create(pm_parser_t *parser, const pm_token_t *token) {
3895 assert(token->type == PM_TOKEN_FLOAT);
3896 pm_float_node_t *node = PM_NODE_ALLOC(parser, pm_float_node_t);
3897
3898 *node = (pm_float_node_t) {
3899 .base = PM_NODE_INIT_TOKEN(parser, PM_FLOAT_NODE, PM_NODE_FLAG_STATIC_LITERAL, token),
3900 .value = pm_double_parse(parser, token)
3901 };
3902
3903 return node;
3904 }
3905
3906 /**
3907 * Allocate and initialize a new FloatNode node from a FLOAT_IMAGINARY token.
3908 */
3909 static pm_imaginary_node_t *
3910 pm_float_node_imaginary_create(pm_parser_t *parser, const pm_token_t *token) {
3911 assert(token->type == PM_TOKEN_FLOAT_IMAGINARY);
3912
3913 pm_imaginary_node_t *node = PM_NODE_ALLOC(parser, pm_imaginary_node_t);
3914 *node = (pm_imaginary_node_t) {
3915 .base = PM_NODE_INIT_TOKEN(parser, PM_IMAGINARY_NODE, PM_NODE_FLAG_STATIC_LITERAL, token),
3916 .numeric = UP(pm_float_node_create(parser, &((pm_token_t) {
3917 .type = PM_TOKEN_FLOAT,
3918 .start = token->start,
3919 .end = token->end - 1
3920 })))
3921 };
3922
3923 return node;
3924 }
3925
3926 /**
3927 * Allocate and initialize a new RationalNode node from a FLOAT_RATIONAL token.
3928 */
3929 static pm_rational_node_t *
3930 pm_float_node_rational_create(pm_parser_t *parser, const pm_token_t *token) {
3931 assert(token->type == PM_TOKEN_FLOAT_RATIONAL);
3932
3933 pm_rational_node_t *node = PM_NODE_ALLOC(parser, pm_rational_node_t);
3934 *node = (pm_rational_node_t) {
3935 .base = PM_NODE_INIT_TOKEN(parser, PM_RATIONAL_NODE, PM_INTEGER_BASE_FLAGS_DECIMAL | PM_NODE_FLAG_STATIC_LITERAL, token),
3936 .numerator = { 0 },
3937 .denominator = { 0 }
3938 };
3939
3940 const uint8_t *start = token->start;
3941 const uint8_t *end = token->end - 1; // r
3942
3943 while (start < end && *start == '0') start++; // 0.1 -> .1
3944 while (end > start && end[-1] == '0') end--; // 1.0 -> 1.
3945
3946 size_t length = (size_t) (end - start);
3947 if (length == 1) {
3948 node->denominator.value = 1;
3949 return node;
3950 }
3951
3952 const uint8_t *point = memchr(start, '.', length);
3953 assert(point && "should have a decimal point");
3954
3955 uint8_t *digits = xmalloc(length);
3956 if (digits == NULL) {
3957 fputs("[pm_float_node_rational_create] Failed to allocate memory", stderr);
3958 abort();
3959 }
3960
3961 memcpy(digits, start, (unsigned long) (point - start));
3962 memcpy(digits + (point - start), point + 1, (unsigned long) (end - point - 1));
3963 pm_integer_parse(&node->numerator, PM_INTEGER_BASE_DEFAULT, digits, digits + length - 1);
3964
3965 size_t fract_length = 0;
3966 for (const uint8_t *fract = point; fract < end; ++fract) {
3967 if (*fract != '_') ++fract_length;
3968 }
3969 digits[0] = '1';
3970 if (fract_length > 1) memset(digits + 1, '0', fract_length - 1);
3971 pm_integer_parse(&node->denominator, PM_INTEGER_BASE_DEFAULT, digits, digits + fract_length);
3972 xfree(digits);
3973
3974 pm_integers_reduce(&node->numerator, &node->denominator);
3975 return node;
3976 }
3977
3978 /**
3979 * Allocate and initialize a new FloatNode node from a FLOAT_RATIONAL_IMAGINARY
3980 * token.
3981 */
3982 static pm_imaginary_node_t *
3983 pm_float_node_rational_imaginary_create(pm_parser_t *parser, const pm_token_t *token) {
3984 assert(token->type == PM_TOKEN_FLOAT_RATIONAL_IMAGINARY);
3985
3986 pm_imaginary_node_t *node = PM_NODE_ALLOC(parser, pm_imaginary_node_t);
3987 *node = (pm_imaginary_node_t) {
3988 .base = PM_NODE_INIT_TOKEN(parser, PM_IMAGINARY_NODE, PM_NODE_FLAG_STATIC_LITERAL, token),
3989 .numeric = UP(pm_float_node_rational_create(parser, &((pm_token_t) {
3990 .type = PM_TOKEN_FLOAT_RATIONAL,
3991 .start = token->start,
3992 .end = token->end - 1
3993 })))
3994 };
3995
3996 return node;
3997 }
3998
3999 /**
4000 * Allocate and initialize a new ForNode node.
4001 */
4002 static pm_for_node_t *
4003 pm_for_node_create(
4004 pm_parser_t *parser,
4005 pm_node_t *index,
4006 pm_node_t *collection,
4007 pm_statements_node_t *statements,
4008 const pm_token_t *for_keyword,
4009 const pm_token_t *in_keyword,
4010 const pm_token_t *do_keyword,
4011 const pm_token_t *end_keyword
4012 ) {
4013 pm_for_node_t *node = PM_NODE_ALLOC(parser, pm_for_node_t);
4014
4015 *node = (pm_for_node_t) {
4016 .base = PM_NODE_INIT_TOKENS(parser, PM_FOR_NODE, 0, for_keyword, end_keyword),
4017 .index = index,
4018 .collection = collection,
4019 .statements = statements,
4020 .for_keyword_loc = PM_LOCATION_TOKEN_VALUE(for_keyword),
4021 .in_keyword_loc = PM_LOCATION_TOKEN_VALUE(in_keyword),
4022 .do_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(do_keyword),
4023 .end_keyword_loc = PM_LOCATION_TOKEN_VALUE(end_keyword)
4024 };
4025
4026 return node;
4027 }
4028
4029 /**
4030 * Allocate and initialize a new ForwardingArgumentsNode node.
4031 */
4032 static pm_forwarding_arguments_node_t *
4033 pm_forwarding_arguments_node_create(pm_parser_t *parser, const pm_token_t *token) {
4034 assert(token->type == PM_TOKEN_UDOT_DOT_DOT);
4035 pm_forwarding_arguments_node_t *node = PM_NODE_ALLOC(parser, pm_forwarding_arguments_node_t);
4036
4037 *node = (pm_forwarding_arguments_node_t) {
4038 .base = PM_NODE_INIT_TOKEN(parser, PM_FORWARDING_ARGUMENTS_NODE, 0, token)
4039 };
4040
4041 return node;
4042 }
4043
4044 /**
4045 * Allocate and initialize a new ForwardingParameterNode node.
4046 */
4047 static pm_forwarding_parameter_node_t *
4048 pm_forwarding_parameter_node_create(pm_parser_t *parser, const pm_token_t *token) {
4049 assert(token->type == PM_TOKEN_UDOT_DOT_DOT);
4050 pm_forwarding_parameter_node_t *node = PM_NODE_ALLOC(parser, pm_forwarding_parameter_node_t);
4051
4052 *node = (pm_forwarding_parameter_node_t) {
4053 .base = PM_NODE_INIT_TOKEN(parser, PM_FORWARDING_PARAMETER_NODE, 0, token)
4054 };
4055
4056 return node;
4057 }
4058
4059 /**
4060 * Allocate and initialize a new ForwardingSuper node.
4061 */
4062 static pm_forwarding_super_node_t *
4063 pm_forwarding_super_node_create(pm_parser_t *parser, const pm_token_t *token, pm_arguments_t *arguments) {
4064 assert(arguments->block == NULL || PM_NODE_TYPE_P(arguments->block, PM_BLOCK_NODE));
4065 assert(token->type == PM_TOKEN_KEYWORD_SUPER);
4066 pm_forwarding_super_node_t *node = PM_NODE_ALLOC(parser, pm_forwarding_super_node_t);
4067
4068 pm_block_node_t *block = NULL;
4069 if (arguments->block != NULL) {
4070 block = (pm_block_node_t *) arguments->block;
4071 }
4072
4073 *node = (pm_forwarding_super_node_t) {
4074 .base = (
4075 (block == NULL)
4076 ? PM_NODE_INIT_TOKEN(parser, PM_FORWARDING_SUPER_NODE, 0, token)
4077 : PM_NODE_INIT_TOKEN_NODE(parser, PM_FORWARDING_SUPER_NODE, 0, token, block)
4078 ),
4079 .block = block
4080 };
4081
4082 return node;
4083 }
4084
4085 /**
4086 * Allocate and initialize a new hash pattern node from an opening and closing
4087 * token.
4088 */
4089 static pm_hash_pattern_node_t *
4090 pm_hash_pattern_node_empty_create(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *closing) {
4091 pm_hash_pattern_node_t *node = PM_NODE_ALLOC(parser, pm_hash_pattern_node_t);
4092
4093 *node = (pm_hash_pattern_node_t) {
4094 .base = PM_NODE_INIT_TOKENS(parser, PM_HASH_PATTERN_NODE, 0, opening, closing),
4095 .constant = NULL,
4096 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
4097 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing),
4098 .elements = { 0 },
4099 .rest = NULL
4100 };
4101
4102 return node;
4103 }
4104
4105 /**
4106 * Allocate and initialize a new hash pattern node.
4107 */
4108 static pm_hash_pattern_node_t *
4109 pm_hash_pattern_node_node_list_create(pm_parser_t *parser, pm_node_list_t *elements, pm_node_t *rest) {
4110 pm_hash_pattern_node_t *node = PM_NODE_ALLOC(parser, pm_hash_pattern_node_t);
4111
4112 const uint8_t *start;
4113 const uint8_t *end;
4114
4115 if (elements->size > 0) {
4116 if (rest) {
4117 start = MIN(rest->location.start, elements->nodes[0]->location.start);
4118 end = MAX(rest->location.end, elements->nodes[elements->size - 1]->location.end);
4119 } else {
4120 start = elements->nodes[0]->location.start;
4121 end = elements->nodes[elements->size - 1]->location.end;
4122 }
4123 } else {
4124 assert(rest != NULL);
4125 start = rest->location.start;
4126 end = rest->location.end;
4127 }
4128
4129 *node = (pm_hash_pattern_node_t) {
4130 .base = PM_NODE_INIT(parser, PM_HASH_PATTERN_NODE, 0, start, end),
4131 .constant = NULL,
4132 .elements = { 0 },
4133 .rest = rest,
4134 .opening_loc = { 0 },
4135 .closing_loc = { 0 }
4136 };
4137
4138 pm_node_list_concat(&node->elements, elements);
4139 return node;
4140 }
4141
4142 /**
4143 * Retrieve the name from a node that will become a global variable write node.
4144 */
4145 static pm_constant_id_t
4146 pm_global_variable_write_name(pm_parser_t *parser, const pm_node_t *target) {
4147 switch (PM_NODE_TYPE(target)) {
4148 case PM_GLOBAL_VARIABLE_READ_NODE:
4149 return ((pm_global_variable_read_node_t *) target)->name;
4150 case PM_BACK_REFERENCE_READ_NODE:
4151 return ((pm_back_reference_read_node_t *) target)->name;
4152 case PM_NUMBERED_REFERENCE_READ_NODE:
4153 // This will only ever happen in the event of a syntax error, but we
4154 // still need to provide something for the node.
4155 return pm_parser_constant_id_location(parser, target->location.start, target->location.end);
4156 default:
4157 assert(false && "unreachable");
4158 return (pm_constant_id_t) -1;
4159 }
4160 }
4161
4162 /**
4163 * Allocate and initialize a new GlobalVariableAndWriteNode node.
4164 */
4165 static pm_global_variable_and_write_node_t *
4166 pm_global_variable_and_write_node_create(pm_parser_t *parser, pm_node_t *target, const pm_token_t *operator, pm_node_t *value) {
4167 assert(operator->type == PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL);
4168 pm_global_variable_and_write_node_t *node = PM_NODE_ALLOC(parser, pm_global_variable_and_write_node_t);
4169
4170 *node = (pm_global_variable_and_write_node_t) {
4171 .base = PM_NODE_INIT_NODES(parser, PM_GLOBAL_VARIABLE_AND_WRITE_NODE, 0, target, value),
4172 .name = pm_global_variable_write_name(parser, target),
4173 .name_loc = target->location,
4174 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
4175 .value = value
4176 };
4177
4178 return node;
4179 }
4180
4181 /**
4182 * Allocate and initialize a new GlobalVariableOperatorWriteNode node.
4183 */
4184 static pm_global_variable_operator_write_node_t *
4185 pm_global_variable_operator_write_node_create(pm_parser_t *parser, pm_node_t *target, const pm_token_t *operator, pm_node_t *value) {
4186 pm_global_variable_operator_write_node_t *node = PM_NODE_ALLOC(parser, pm_global_variable_operator_write_node_t);
4187
4188 *node = (pm_global_variable_operator_write_node_t) {
4189 .base = PM_NODE_INIT_NODES(parser, PM_GLOBAL_VARIABLE_OPERATOR_WRITE_NODE, 0, target, value),
4190 .name = pm_global_variable_write_name(parser, target),
4191 .name_loc = target->location,
4192 .binary_operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
4193 .value = value,
4194 .binary_operator = pm_parser_constant_id_location(parser, operator->start, operator->end - 1)
4195 };
4196
4197 return node;
4198 }
4199
4200 /**
4201 * Allocate and initialize a new GlobalVariableOrWriteNode node.
4202 */
4203 static pm_global_variable_or_write_node_t *
4204 pm_global_variable_or_write_node_create(pm_parser_t *parser, pm_node_t *target, const pm_token_t *operator, pm_node_t *value) {
4205 assert(operator->type == PM_TOKEN_PIPE_PIPE_EQUAL);
4206 pm_global_variable_or_write_node_t *node = PM_NODE_ALLOC(parser, pm_global_variable_or_write_node_t);
4207
4208 *node = (pm_global_variable_or_write_node_t) {
4209 .base = PM_NODE_INIT_NODES(parser, PM_GLOBAL_VARIABLE_OR_WRITE_NODE, 0, target, value),
4210 .name = pm_global_variable_write_name(parser, target),
4211 .name_loc = target->location,
4212 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
4213 .value = value
4214 };
4215
4216 return node;
4217 }
4218
4219 /**
4220 * Allocate a new GlobalVariableReadNode node.
4221 */
4222 static pm_global_variable_read_node_t *
4223 pm_global_variable_read_node_create(pm_parser_t *parser, const pm_token_t *name) {
4224 pm_global_variable_read_node_t *node = PM_NODE_ALLOC(parser, pm_global_variable_read_node_t);
4225
4226 *node = (pm_global_variable_read_node_t) {
4227 .base = PM_NODE_INIT_TOKEN(parser, PM_GLOBAL_VARIABLE_READ_NODE, 0, name),
4228 .name = pm_parser_constant_id_token(parser, name)
4229 };
4230
4231 return node;
4232 }
4233
4234 /**
4235 * Allocate and initialize a new synthesized GlobalVariableReadNode node.
4236 */
4237 static pm_global_variable_read_node_t *
4238 pm_global_variable_read_node_synthesized_create(pm_parser_t *parser, pm_constant_id_t name) {
4239 pm_global_variable_read_node_t *node = PM_NODE_ALLOC(parser, pm_global_variable_read_node_t);
4240
4241 *node = (pm_global_variable_read_node_t) {
4242 .base = PM_NODE_INIT_BASE(parser, PM_GLOBAL_VARIABLE_READ_NODE, 0),
4243 .name = name
4244 };
4245
4246 return node;
4247 }
4248
4249 /**
4250 * Allocate and initialize a new GlobalVariableWriteNode node.
4251 */
4252 static pm_global_variable_write_node_t *
4253 pm_global_variable_write_node_create(pm_parser_t *parser, pm_node_t *target, const pm_token_t *operator, pm_node_t *value) {
4254 pm_global_variable_write_node_t *node = PM_NODE_ALLOC(parser, pm_global_variable_write_node_t);
4255 pm_node_flags_t flags = pm_implicit_array_write_flags(value, PM_WRITE_NODE_FLAGS_IMPLICIT_ARRAY);
4256
4257 *node = (pm_global_variable_write_node_t) {
4258 .base = PM_NODE_INIT_NODES(parser, PM_GLOBAL_VARIABLE_WRITE_NODE, flags, target, value),
4259 .name = pm_global_variable_write_name(parser, target),
4260 .name_loc = PM_LOCATION_NODE_VALUE(target),
4261 .operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator),
4262 .value = value
4263 };
4264
4265 return node;
4266 }
4267
4268 /**
4269 * Allocate and initialize a new synthesized GlobalVariableWriteNode node.
4270 */
4271 static pm_global_variable_write_node_t *
4272 pm_global_variable_write_node_synthesized_create(pm_parser_t *parser, pm_constant_id_t name, pm_node_t *value) {
4273 pm_global_variable_write_node_t *node = PM_NODE_ALLOC(parser, pm_global_variable_write_node_t);
4274
4275 *node = (pm_global_variable_write_node_t) {
4276 .base = PM_NODE_INIT_BASE(parser, PM_GLOBAL_VARIABLE_WRITE_NODE, 0),
4277 .name = name,
4278 .name_loc = PM_LOCATION_NULL_VALUE(parser),
4279 .operator_loc = PM_LOCATION_NULL_VALUE(parser),
4280 .value = value
4281 };
4282
4283 return node;
4284 }
4285
4286 /**
4287 * Allocate a new HashNode node.
4288 */
4289 static pm_hash_node_t *
4290 pm_hash_node_create(pm_parser_t *parser, const pm_token_t *opening) {
4291 assert(opening != NULL);
4292 pm_hash_node_t *node = PM_NODE_ALLOC(parser, pm_hash_node_t);
4293
4294 *node = (pm_hash_node_t) {
4295 .base = PM_NODE_INIT_TOKEN(parser, PM_HASH_NODE, PM_NODE_FLAG_STATIC_LITERAL, opening),
4296 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
4297 .closing_loc = PM_LOCATION_NULL_VALUE(parser),
4298 .elements = { 0 }
4299 };
4300
4301 return node;
4302 }
4303
4304 /**
4305 * Append a new element to a hash node.
4306 */
4307 static inline void
4308 pm_hash_node_elements_append(pm_hash_node_t *hash, pm_node_t *element) {
4309 pm_node_list_append(&hash->elements, element);
4310
4311 bool static_literal = PM_NODE_TYPE_P(element, PM_ASSOC_NODE);
4312 if (static_literal) {
4313 pm_assoc_node_t *assoc = (pm_assoc_node_t *) element;
4314 static_literal = !PM_NODE_TYPE_P(assoc->key, PM_ARRAY_NODE) && !PM_NODE_TYPE_P(assoc->key, PM_HASH_NODE) && !PM_NODE_TYPE_P(assoc->key, PM_RANGE_NODE);
4315 static_literal = static_literal && PM_NODE_FLAG_P(assoc->key, PM_NODE_FLAG_STATIC_LITERAL);
4316 static_literal = static_literal && PM_NODE_FLAG_P(assoc, PM_NODE_FLAG_STATIC_LITERAL);
4317 }
4318
4319 if (!static_literal) {
4320 pm_node_flag_unset(UP(hash), PM_NODE_FLAG_STATIC_LITERAL);
4321 }
4322 }
4323
4324 static inline void
4325 pm_hash_node_closing_loc_set(pm_hash_node_t *hash, pm_token_t *token) {
4326 hash->base.location.end = token->end;
4327 hash->closing_loc = PM_LOCATION_TOKEN_VALUE(token);
4328 }
4329
4330 /**
4331 * Allocate a new IfNode node.
4332 */
4333 static pm_if_node_t *
4334 pm_if_node_create(pm_parser_t *parser,
4335 const pm_token_t *if_keyword,
4336 pm_node_t *predicate,
4337 const pm_token_t *then_keyword,
4338 pm_statements_node_t *statements,
4339 pm_node_t *subsequent,
4340 const pm_token_t *end_keyword
4341 ) {
4342 pm_conditional_predicate(parser, predicate, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
4343 pm_if_node_t *node = PM_NODE_ALLOC(parser, pm_if_node_t);
4344
4345 const uint8_t *end;
4346 if (end_keyword->type != PM_TOKEN_NOT_PROVIDED) {
4347 end = end_keyword->end;
4348 } else if (subsequent != NULL) {
4349 end = subsequent->location.end;
4350 } else if (pm_statements_node_body_length(statements) != 0) {
4351 end = statements->base.location.end;
4352 } else {
4353 end = predicate->location.end;
4354 }
4355
4356 *node = (pm_if_node_t) {
4357 .base = PM_NODE_INIT(parser, PM_IF_NODE, PM_NODE_FLAG_NEWLINE, if_keyword->start, end),
4358 .if_keyword_loc = PM_LOCATION_TOKEN_VALUE(if_keyword),
4359 .predicate = predicate,
4360 .then_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(then_keyword),
4361 .statements = statements,
4362 .subsequent = subsequent,
4363 .end_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(end_keyword)
4364 };
4365
4366 return node;
4367 }
4368
4369 /**
4370 * Allocate and initialize new IfNode node in the modifier form.
4371 */
4372 static pm_if_node_t *
4373 pm_if_node_modifier_create(pm_parser_t *parser, pm_node_t *statement, const pm_token_t *if_keyword, pm_node_t *predicate) {
4374 pm_conditional_predicate(parser, predicate, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
4375 pm_if_node_t *node = PM_NODE_ALLOC(parser, pm_if_node_t);
4376
4377 pm_statements_node_t *statements = pm_statements_node_create(parser);
4378 pm_statements_node_body_append(parser, statements, statement, true);
4379
4380 *node = (pm_if_node_t) {
4381 .base = PM_NODE_INIT_NODES(parser, PM_IF_NODE, PM_NODE_FLAG_NEWLINE, statement, predicate),
4382 .if_keyword_loc = PM_LOCATION_TOKEN_VALUE(if_keyword),
4383 .predicate = predicate,
4384 .then_keyword_loc = { 0 },
4385 .statements = statements,
4386 .subsequent = NULL,
4387 .end_keyword_loc = { 0 }
4388 };
4389
4390 return node;
4391 }
4392
4393 /**
4394 * Allocate and initialize an if node from a ternary expression.
4395 */
4396 static pm_if_node_t *
4397 pm_if_node_ternary_create(pm_parser_t *parser, pm_node_t *predicate, const pm_token_t *qmark, pm_node_t *true_expression, const pm_token_t *colon, pm_node_t *false_expression) {
4398 pm_assert_value_expression(parser, predicate);
4399 pm_conditional_predicate(parser, predicate, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
4400
4401 pm_statements_node_t *if_statements = pm_statements_node_create(parser);
4402 pm_statements_node_body_append(parser, if_statements, true_expression, true);
4403
4404 pm_statements_node_t *else_statements = pm_statements_node_create(parser);
4405 pm_statements_node_body_append(parser, else_statements, false_expression, true);
4406
4407 pm_token_t end_keyword = not_provided(parser);
4408 pm_else_node_t *else_node = pm_else_node_create(parser, colon, else_statements, &end_keyword);
4409
4410 pm_if_node_t *node = PM_NODE_ALLOC(parser, pm_if_node_t);
4411
4412 *node = (pm_if_node_t) {
4413 .base = PM_NODE_INIT_NODES(parser, PM_IF_NODE, PM_NODE_FLAG_NEWLINE, predicate, false_expression),
4414 .if_keyword_loc = { 0 },
4415 .predicate = predicate,
4416 .then_keyword_loc = PM_LOCATION_TOKEN_VALUE(qmark),
4417 .statements = if_statements,
4418 .subsequent = UP(else_node),
4419 .end_keyword_loc = { 0 }
4420 };
4421
4422 return node;
4423
4424 }
4425
4426 static inline void
4427 pm_if_node_end_keyword_loc_set(pm_if_node_t *node, const pm_token_t *keyword) {
4428 node->base.location.end = keyword->end;
4429 node->end_keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword);
4430 }
4431
4432 static inline void
4433 pm_else_node_end_keyword_loc_set(pm_else_node_t *node, const pm_token_t *keyword) {
4434 node->base.location.end = keyword->end;
4435 node->end_keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword);
4436 }
4437
4438 /**
4439 * Allocate and initialize a new ImplicitNode node.
4440 */
4441 static pm_implicit_node_t *
4442 pm_implicit_node_create(pm_parser_t *parser, pm_node_t *value) {
4443 pm_implicit_node_t *node = PM_NODE_ALLOC(parser, pm_implicit_node_t);
4444
4445 *node = (pm_implicit_node_t) {
4446 .base = PM_NODE_INIT_NODE(parser, PM_IMPLICIT_NODE, 0, value),
4447 .value = value
4448 };
4449
4450 return node;
4451 }
4452
4453 /**
4454 * Allocate and initialize a new ImplicitRestNode node.
4455 */
4456 static pm_implicit_rest_node_t *
4457 pm_implicit_rest_node_create(pm_parser_t *parser, const pm_token_t *token) {
4458 assert(token->type == PM_TOKEN_COMMA);
4459
4460 pm_implicit_rest_node_t *node = PM_NODE_ALLOC(parser, pm_implicit_rest_node_t);
4461
4462 *node = (pm_implicit_rest_node_t) {
4463 .base = PM_NODE_INIT_TOKEN(parser, PM_IMPLICIT_REST_NODE, 0, token)
4464 };
4465
4466 return node;
4467 }
4468
4469 /**
4470 * Allocate and initialize a new IntegerNode node.
4471 */
4472 static pm_integer_node_t *
4473 pm_integer_node_create(pm_parser_t *parser, pm_node_flags_t base, const pm_token_t *token) {
4474 assert(token->type == PM_TOKEN_INTEGER);
4475 pm_integer_node_t *node = PM_NODE_ALLOC(parser, pm_integer_node_t);
4476
4477 *node = (pm_integer_node_t) {
4478 .base = PM_NODE_INIT_TOKEN(parser, PM_INTEGER_NODE, base | PM_NODE_FLAG_STATIC_LITERAL, token),
4479 .value = { 0 }
4480 };
4481
4482 pm_integer_base_t integer_base = PM_INTEGER_BASE_DECIMAL;
4483 switch (base) {
4484 case PM_INTEGER_BASE_FLAGS_BINARY: integer_base = PM_INTEGER_BASE_BINARY; break;
4485 case PM_INTEGER_BASE_FLAGS_OCTAL: integer_base = PM_INTEGER_BASE_OCTAL; break;
4486 case PM_INTEGER_BASE_FLAGS_DECIMAL: break;
4487 case PM_INTEGER_BASE_FLAGS_HEXADECIMAL: integer_base = PM_INTEGER_BASE_HEXADECIMAL; break;
4488 default: assert(false && "unreachable"); break;
4489 }
4490
4491 pm_integer_parse(&node->value, integer_base, token->start, token->end);
4492 return node;
4493 }
4494
4495 /**
4496 * Allocate and initialize a new IntegerNode node from an INTEGER_IMAGINARY
4497 * token.
4498 */
4499 static pm_imaginary_node_t *
4500 pm_integer_node_imaginary_create(pm_parser_t *parser, pm_node_flags_t base, const pm_token_t *token) {
4501 assert(token->type == PM_TOKEN_INTEGER_IMAGINARY);
4502
4503 pm_imaginary_node_t *node = PM_NODE_ALLOC(parser, pm_imaginary_node_t);
4504 *node = (pm_imaginary_node_t) {
4505 .base = PM_NODE_INIT_TOKEN(parser, PM_IMAGINARY_NODE, PM_NODE_FLAG_STATIC_LITERAL, token),
4506 .numeric = UP(pm_integer_node_create(parser, base, &((pm_token_t) {
4507 .type = PM_TOKEN_INTEGER,
4508 .start = token->start,
4509 .end = token->end - 1
4510 })))
4511 };
4512
4513 return node;
4514 }
4515
4516 /**
4517 * Allocate and initialize a new RationalNode node from an INTEGER_RATIONAL
4518 * token.
4519 */
4520 static pm_rational_node_t *
4521 pm_integer_node_rational_create(pm_parser_t *parser, pm_node_flags_t base, const pm_token_t *token) {
4522 assert(token->type == PM_TOKEN_INTEGER_RATIONAL);
4523
4524 pm_rational_node_t *node = PM_NODE_ALLOC(parser, pm_rational_node_t);
4525 *node = (pm_rational_node_t) {
4526 .base = PM_NODE_INIT_TOKEN(parser, PM_RATIONAL_NODE, base | PM_NODE_FLAG_STATIC_LITERAL, token),
4527 .numerator = { 0 },
4528 .denominator = { .value = 1, 0 }
4529 };
4530
4531 pm_integer_base_t integer_base = PM_INTEGER_BASE_DECIMAL;
4532 switch (base) {
4533 case PM_INTEGER_BASE_FLAGS_BINARY: integer_base = PM_INTEGER_BASE_BINARY; break;
4534 case PM_INTEGER_BASE_FLAGS_OCTAL: integer_base = PM_INTEGER_BASE_OCTAL; break;
4535 case PM_INTEGER_BASE_FLAGS_DECIMAL: break;
4536 case PM_INTEGER_BASE_FLAGS_HEXADECIMAL: integer_base = PM_INTEGER_BASE_HEXADECIMAL; break;
4537 default: assert(false && "unreachable"); break;
4538 }
4539
4540 pm_integer_parse(&node->numerator, integer_base, token->start, token->end - 1);
4541
4542 return node;
4543 }
4544
4545 /**
4546 * Allocate and initialize a new IntegerNode node from an
4547 * INTEGER_RATIONAL_IMAGINARY token.
4548 */
4549 static pm_imaginary_node_t *
4550 pm_integer_node_rational_imaginary_create(pm_parser_t *parser, pm_node_flags_t base, const pm_token_t *token) {
4551 assert(token->type == PM_TOKEN_INTEGER_RATIONAL_IMAGINARY);
4552
4553 pm_imaginary_node_t *node = PM_NODE_ALLOC(parser, pm_imaginary_node_t);
4554 *node = (pm_imaginary_node_t) {
4555 .base = PM_NODE_INIT_TOKEN(parser, PM_IMAGINARY_NODE, PM_NODE_FLAG_STATIC_LITERAL, token),
4556 .numeric = UP(pm_integer_node_rational_create(parser, base, &((pm_token_t) {
4557 .type = PM_TOKEN_INTEGER_RATIONAL,
4558 .start = token->start,
4559 .end = token->end - 1
4560 })))
4561 };
4562
4563 return node;
4564 }
4565
4566 /**
4567 * Allocate and initialize a new InNode node.
4568 */
4569 static pm_in_node_t *
4570 pm_in_node_create(pm_parser_t *parser, pm_node_t *pattern, pm_statements_node_t *statements, const pm_token_t *in_keyword, const pm_token_t *then_keyword) {
4571 pm_in_node_t *node = PM_NODE_ALLOC(parser, pm_in_node_t);
4572
4573 const uint8_t *end;
4574 if (statements != NULL) {
4575 end = statements->base.location.end;
4576 } else if (then_keyword->type != PM_TOKEN_NOT_PROVIDED) {
4577 end = then_keyword->end;
4578 } else {
4579 end = pattern->location.end;
4580 }
4581
4582 *node = (pm_in_node_t) {
4583 .base = PM_NODE_INIT(parser, PM_IN_NODE, 0, in_keyword->start, end),
4584 .pattern = pattern,
4585 .statements = statements,
4586 .in_loc = PM_LOCATION_TOKEN_VALUE(in_keyword),
4587 .then_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(then_keyword)
4588 };
4589
4590 return node;
4591 }
4592
4593 /**
4594 * Allocate and initialize a new InstanceVariableAndWriteNode node.
4595 */
4596 static pm_instance_variable_and_write_node_t *
4597 pm_instance_variable_and_write_node_create(pm_parser_t *parser, pm_instance_variable_read_node_t *target, const pm_token_t *operator, pm_node_t *value) {
4598 assert(operator->type == PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL);
4599 pm_instance_variable_and_write_node_t *node = PM_NODE_ALLOC(parser, pm_instance_variable_and_write_node_t);
4600
4601 *node = (pm_instance_variable_and_write_node_t) {
4602 .base = PM_NODE_INIT_NODES(parser, PM_INSTANCE_VARIABLE_AND_WRITE_NODE, 0, target, value),
4603 .name = target->name,
4604 .name_loc = target->base.location,
4605 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
4606 .value = value
4607 };
4608
4609 return node;
4610 }
4611
4612 /**
4613 * Allocate and initialize a new InstanceVariableOperatorWriteNode node.
4614 */
4615 static pm_instance_variable_operator_write_node_t *
4616 pm_instance_variable_operator_write_node_create(pm_parser_t *parser, pm_instance_variable_read_node_t *target, const pm_token_t *operator, pm_node_t *value) {
4617 pm_instance_variable_operator_write_node_t *node = PM_NODE_ALLOC(parser, pm_instance_variable_operator_write_node_t);
4618
4619 *node = (pm_instance_variable_operator_write_node_t) {
4620 .base = PM_NODE_INIT_NODES(parser, PM_INSTANCE_VARIABLE_OPERATOR_WRITE_NODE, 0, target, value),
4621 .name = target->name,
4622 .name_loc = target->base.location,
4623 .binary_operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
4624 .value = value,
4625 .binary_operator = pm_parser_constant_id_location(parser, operator->start, operator->end - 1)
4626 };
4627
4628 return node;
4629 }
4630
4631 /**
4632 * Allocate and initialize a new InstanceVariableOrWriteNode node.
4633 */
4634 static pm_instance_variable_or_write_node_t *
4635 pm_instance_variable_or_write_node_create(pm_parser_t *parser, pm_instance_variable_read_node_t *target, const pm_token_t *operator, pm_node_t *value) {
4636 assert(operator->type == PM_TOKEN_PIPE_PIPE_EQUAL);
4637 pm_instance_variable_or_write_node_t *node = PM_NODE_ALLOC(parser, pm_instance_variable_or_write_node_t);
4638
4639 *node = (pm_instance_variable_or_write_node_t) {
4640 .base = PM_NODE_INIT_NODES(parser, PM_INSTANCE_VARIABLE_OR_WRITE_NODE, 0, target, value),
4641 .name = target->name,
4642 .name_loc = target->base.location,
4643 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
4644 .value = value
4645 };
4646
4647 return node;
4648 }
4649
4650 /**
4651 * Allocate and initialize a new InstanceVariableReadNode node.
4652 */
4653 static pm_instance_variable_read_node_t *
4654 pm_instance_variable_read_node_create(pm_parser_t *parser, const pm_token_t *token) {
4655 assert(token->type == PM_TOKEN_INSTANCE_VARIABLE);
4656 pm_instance_variable_read_node_t *node = PM_NODE_ALLOC(parser, pm_instance_variable_read_node_t);
4657
4658 *node = (pm_instance_variable_read_node_t) {
4659 .base = PM_NODE_INIT_TOKEN(parser, PM_INSTANCE_VARIABLE_READ_NODE, 0, token),
4660 .name = pm_parser_constant_id_token(parser, token)
4661 };
4662
4663 return node;
4664 }
4665
4666 /**
4667 * Initialize a new InstanceVariableWriteNode node from an InstanceVariableRead
4668 * node.
4669 */
4670 static pm_instance_variable_write_node_t *
4671 pm_instance_variable_write_node_create(pm_parser_t *parser, pm_instance_variable_read_node_t *read_node, pm_token_t *operator, pm_node_t *value) {
4672 pm_instance_variable_write_node_t *node = PM_NODE_ALLOC(parser, pm_instance_variable_write_node_t);
4673 pm_node_flags_t flags = pm_implicit_array_write_flags(value, PM_WRITE_NODE_FLAGS_IMPLICIT_ARRAY);
4674
4675 *node = (pm_instance_variable_write_node_t) {
4676 .base = PM_NODE_INIT_NODES(parser, PM_INSTANCE_VARIABLE_WRITE_NODE, flags, read_node, value),
4677 .name = read_node->name,
4678 .name_loc = PM_LOCATION_NODE_VALUE(read_node),
4679 .operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator),
4680 .value = value
4681 };
4682
4683 return node;
4684 }
4685
4686 /**
4687 * Append a part into a list of string parts. Importantly this handles nested
4688 * interpolated strings by not necessarily removing the marker for static
4689 * literals.
4690 */
4691 static void
4692 pm_interpolated_node_append(pm_node_t *node, pm_node_list_t *parts, pm_node_t *part) {
4693 switch (PM_NODE_TYPE(part)) {
4694 case PM_STRING_NODE:
4695 pm_node_flag_set(part, PM_NODE_FLAG_STATIC_LITERAL | PM_STRING_FLAGS_FROZEN);
4696 break;
4697 case PM_EMBEDDED_STATEMENTS_NODE: {
4698 pm_embedded_statements_node_t *cast = (pm_embedded_statements_node_t *) part;
4699 pm_node_t *embedded = (cast->statements != NULL && cast->statements->body.size == 1) ? cast->statements->body.nodes[0] : NULL;
4700
4701 if (embedded == NULL) {
4702 // If there are no statements or more than one statement, then
4703 // we lose the static literal flag.
4704 pm_node_flag_unset(node, PM_NODE_FLAG_STATIC_LITERAL);
4705 } else if (PM_NODE_TYPE_P(embedded, PM_STRING_NODE)) {
4706 // If the embedded statement is a string, then we can keep the
4707 // static literal flag and mark the string as frozen.
4708 pm_node_flag_set(embedded, PM_NODE_FLAG_STATIC_LITERAL | PM_STRING_FLAGS_FROZEN);
4709 } else if (PM_NODE_TYPE_P(embedded, PM_INTERPOLATED_STRING_NODE) && PM_NODE_FLAG_P(embedded, PM_NODE_FLAG_STATIC_LITERAL)) {
4710 // If the embedded statement is an interpolated string and it's
4711 // a static literal, then we can keep the static literal flag.
4712 } else {
4713 // Otherwise we lose the static literal flag.
4714 pm_node_flag_unset(node, PM_NODE_FLAG_STATIC_LITERAL);
4715 }
4716
4717 break;
4718 }
4719 case PM_EMBEDDED_VARIABLE_NODE:
4720 pm_node_flag_unset(UP(node), PM_NODE_FLAG_STATIC_LITERAL);
4721 break;
4722 default:
4723 assert(false && "unexpected node type");
4724 break;
4725 }
4726
4727 pm_node_list_append(parts, part);
4728 }
4729
4730 /**
4731 * Allocate a new InterpolatedRegularExpressionNode node.
4732 */
4733 static pm_interpolated_regular_expression_node_t *
4734 pm_interpolated_regular_expression_node_create(pm_parser_t *parser, const pm_token_t *opening) {
4735 pm_interpolated_regular_expression_node_t *node = PM_NODE_ALLOC(parser, pm_interpolated_regular_expression_node_t);
4736
4737 *node = (pm_interpolated_regular_expression_node_t) {
4738 .base = PM_NODE_INIT_TOKEN(parser, PM_INTERPOLATED_REGULAR_EXPRESSION_NODE, PM_NODE_FLAG_STATIC_LITERAL, opening),
4739 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
4740 .closing_loc = PM_LOCATION_TOKEN_VALUE(opening),
4741 .parts = { 0 }
4742 };
4743
4744 return node;
4745 }
4746
4747 static inline void
4748 pm_interpolated_regular_expression_node_append(pm_interpolated_regular_expression_node_t *node, pm_node_t *part) {
4749 if (node->base.location.start > part->location.start) {
4750 node->base.location.start = part->location.start;
4751 }
4752 if (node->base.location.end < part->location.end) {
4753 node->base.location.end = part->location.end;
4754 }
4755
4756 pm_interpolated_node_append(UP(node), &node->parts, part);
4757 }
4758
4759 static inline void
4760 pm_interpolated_regular_expression_node_closing_set(pm_parser_t *parser, pm_interpolated_regular_expression_node_t *node, const pm_token_t *closing) {
4761 node->closing_loc = PM_LOCATION_TOKEN_VALUE(closing);
4762 node->base.location.end = closing->end;
4763 pm_node_flag_set(UP(node), pm_regular_expression_flags_create(parser, closing));
4764 }
4765
4766 /**
4767 * Append a part to an InterpolatedStringNode node.
4768 *
4769 * This has some somewhat complicated semantics, because we need to update
4770 * multiple flags that have somewhat confusing interactions.
4771 *
4772 * PM_NODE_FLAG_STATIC_LITERAL indicates that the node should be treated as a
4773 * single static literal string that can be pushed onto the stack on its own.
4774 * Note that this doesn't necessarily mean that the string will be frozen or
4775 * not; the instructions in CRuby will be either putobject or putstring,
4776 * depending on the combination of `--enable-frozen-string-literal`,
4777 * `# frozen_string_literal: true`, and whether or not there is interpolation.
4778 *
4779 * PM_INTERPOLATED_STRING_NODE_FLAGS_FROZEN indicates that the string should be
4780 * explicitly frozen. This will only happen if the string is comprised entirely
4781 * of string parts that are themselves static literals and frozen.
4782 *
4783 * PM_INTERPOLATED_STRING_NODE_FLAGS_MUTABLE indicates that the string should
4784 * be explicitly marked as mutable. This will happen from
4785 * `--disable-frozen-string-literal` or `# frozen_string_literal: false`. This
4786 * is necessary to indicate that the string should be left up to the runtime,
4787 * which could potentially use a chilled string otherwise.
4788 */
4789 static inline void
4790 pm_interpolated_string_node_append(pm_interpolated_string_node_t *node, pm_node_t *part) {
4791 #define CLEAR_FLAGS(node) \
4792 node->base.flags = (pm_node_flags_t) (FL(node) & ~(PM_NODE_FLAG_STATIC_LITERAL | PM_INTERPOLATED_STRING_NODE_FLAGS_FROZEN | PM_INTERPOLATED_STRING_NODE_FLAGS_MUTABLE))
4793
4794 #define MUTABLE_FLAGS(node) \
4795 node->base.flags = (pm_node_flags_t) ((FL(node) | PM_INTERPOLATED_STRING_NODE_FLAGS_MUTABLE) & ~PM_INTERPOLATED_STRING_NODE_FLAGS_FROZEN);
4796
4797 if (node->parts.size == 0 && node->opening_loc.start == NULL) {
4798 node->base.location.start = part->location.start;
4799 }
4800
4801 node->base.location.end = MAX(node->base.location.end, part->location.end);
4802
4803 switch (PM_NODE_TYPE(part)) {
4804 case PM_STRING_NODE:
4805 // If inner string is not frozen, it stops being a static literal. We should *not* clear other flags,
4806 // because concatenating two frozen strings (`'foo' 'bar'`) is still frozen. This holds true for
4807 // as long as this interpolation only consists of other string literals.
4808 if (!PM_NODE_FLAG_P(part, PM_STRING_FLAGS_FROZEN)) {
4809 pm_node_flag_unset(UP(node), PM_NODE_FLAG_STATIC_LITERAL);
4810 }
4811 part->flags = (pm_node_flags_t) ((part->flags | PM_NODE_FLAG_STATIC_LITERAL | PM_STRING_FLAGS_FROZEN) & ~PM_STRING_FLAGS_MUTABLE);
4812 break;
4813 case PM_INTERPOLATED_STRING_NODE:
4814 if (PM_NODE_FLAG_P(part, PM_NODE_FLAG_STATIC_LITERAL)) {
4815 // If the string that we're concatenating is a static literal,
4816 // then we can keep the static literal flag for this string.
4817 } else {
4818 // Otherwise, we lose the static literal flag here and we should
4819 // also clear the mutability flags.
4820 CLEAR_FLAGS(node);
4821 }
4822 break;
4823 case PM_EMBEDDED_STATEMENTS_NODE: {
4824 pm_embedded_statements_node_t *cast = (pm_embedded_statements_node_t *) part;
4825 pm_node_t *embedded = (cast->statements != NULL && cast->statements->body.size == 1) ? cast->statements->body.nodes[0] : NULL;
4826
4827 if (embedded == NULL) {
4828 // If we're embedding multiple statements or no statements, then
4829 // the string is not longer a static literal.
4830 CLEAR_FLAGS(node);
4831 } else if (PM_NODE_TYPE_P(embedded, PM_STRING_NODE)) {
4832 // If the embedded statement is a string, then we can make that
4833 // string as frozen and static literal, and not touch the static
4834 // literal status of this string.
4835 embedded->flags = (pm_node_flags_t) ((embedded->flags | PM_NODE_FLAG_STATIC_LITERAL | PM_STRING_FLAGS_FROZEN) & ~PM_STRING_FLAGS_MUTABLE);
4836
4837 if (PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL)) {
4838 MUTABLE_FLAGS(node);
4839 }
4840 } else if (PM_NODE_TYPE_P(embedded, PM_INTERPOLATED_STRING_NODE) && PM_NODE_FLAG_P(embedded, PM_NODE_FLAG_STATIC_LITERAL)) {
4841 // If the embedded statement is an interpolated string, but that
4842 // string is marked as static literal, then we can keep our
4843 // static literal status for this string.
4844 if (PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL)) {
4845 MUTABLE_FLAGS(node);
4846 }
4847 } else {
4848 // In all other cases, we lose the static literal flag here and
4849 // become mutable.
4850 CLEAR_FLAGS(node);
4851 }
4852
4853 break;
4854 }
4855 case PM_EMBEDDED_VARIABLE_NODE:
4856 // Embedded variables clear static literal, which means we also
4857 // should clear the mutability flags.
4858 CLEAR_FLAGS(node);
4859 break;
4860 case PM_X_STRING_NODE:
4861 case PM_INTERPOLATED_X_STRING_NODE:
4862 case PM_SYMBOL_NODE:
4863 case PM_INTERPOLATED_SYMBOL_NODE:
4864 // These will only happen in error cases. But we want to handle it
4865 // here so that we don't fail the assertion.
4866 CLEAR_FLAGS(node);
4867 break;
4868 default:
4869 assert(false && "unexpected node type");
4870 break;
4871 }
4872
4873 pm_node_list_append(&node->parts, part);
4874
4875 #undef CLEAR_FLAGS
4876 #undef MUTABLE_FLAGS
4877 }
4878
4879 /**
4880 * Allocate and initialize a new InterpolatedStringNode node.
4881 */
4882 static pm_interpolated_string_node_t *
4883 pm_interpolated_string_node_create(pm_parser_t *parser, const pm_token_t *opening, const pm_node_list_t *parts, const pm_token_t *closing) {
4884 pm_interpolated_string_node_t *node = PM_NODE_ALLOC(parser, pm_interpolated_string_node_t);
4885 pm_node_flags_t flags = PM_NODE_FLAG_STATIC_LITERAL;
4886
4887 switch (parser->frozen_string_literal) {
4888 case PM_OPTIONS_FROZEN_STRING_LITERAL_DISABLED:
4889 flags |= PM_INTERPOLATED_STRING_NODE_FLAGS_MUTABLE;
4890 break;
4891 case PM_OPTIONS_FROZEN_STRING_LITERAL_ENABLED:
4892 flags |= PM_INTERPOLATED_STRING_NODE_FLAGS_FROZEN;
4893 break;
4894 }
4895
4896 *node = (pm_interpolated_string_node_t) {
4897 .base = PM_NODE_INIT_TOKENS(parser, PM_INTERPOLATED_STRING_NODE, flags, opening, closing),
4898 .opening_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(opening),
4899 .closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing),
4900 .parts = { 0 }
4901 };
4902
4903 if (parts != NULL) {
4904 pm_node_t *part;
4905 PM_NODE_LIST_FOREACH(parts, index, part) {
4906 pm_interpolated_string_node_append(node, part);
4907 }
4908 }
4909
4910 return node;
4911 }
4912
4913 /**
4914 * Set the closing token of the given InterpolatedStringNode node.
4915 */
4916 static void
4917 pm_interpolated_string_node_closing_set(pm_interpolated_string_node_t *node, const pm_token_t *closing) {
4918 node->closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing);
4919 node->base.location.end = closing->end;
4920 }
4921
4922 static void
4923 pm_interpolated_symbol_node_append(pm_interpolated_symbol_node_t *node, pm_node_t *part) {
4924 if (node->parts.size == 0 && node->opening_loc.start == NULL) {
4925 node->base.location.start = part->location.start;
4926 }
4927
4928 pm_interpolated_node_append(UP(node), &node->parts, part);
4929 node->base.location.end = MAX(node->base.location.end, part->location.end);
4930 }
4931
4932 static void
4933 pm_interpolated_symbol_node_closing_loc_set(pm_interpolated_symbol_node_t *node, const pm_token_t *closing) {
4934 node->closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing);
4935 node->base.location.end = closing->end;
4936 }
4937
4938 /**
4939 * Allocate and initialize a new InterpolatedSymbolNode node.
4940 */
4941 static pm_interpolated_symbol_node_t *
4942 pm_interpolated_symbol_node_create(pm_parser_t *parser, const pm_token_t *opening, const pm_node_list_t *parts, const pm_token_t *closing) {
4943 pm_interpolated_symbol_node_t *node = PM_NODE_ALLOC(parser, pm_interpolated_symbol_node_t);
4944
4945 *node = (pm_interpolated_symbol_node_t) {
4946 .base = PM_NODE_INIT_TOKENS(parser, PM_INTERPOLATED_SYMBOL_NODE, PM_NODE_FLAG_STATIC_LITERAL, opening, closing),
4947 .opening_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(opening),
4948 .closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing),
4949 .parts = { 0 }
4950 };
4951
4952 if (parts != NULL) {
4953 pm_node_t *part;
4954 PM_NODE_LIST_FOREACH(parts, index, part) {
4955 pm_interpolated_symbol_node_append(node, part);
4956 }
4957 }
4958
4959 return node;
4960 }
4961
4962 /**
4963 * Allocate a new InterpolatedXStringNode node.
4964 */
4965 static pm_interpolated_x_string_node_t *
4966 pm_interpolated_xstring_node_create(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *closing) {
4967 pm_interpolated_x_string_node_t *node = PM_NODE_ALLOC(parser, pm_interpolated_x_string_node_t);
4968
4969 *node = (pm_interpolated_x_string_node_t) {
4970 .base = PM_NODE_INIT_TOKENS(parser, PM_INTERPOLATED_X_STRING_NODE, 0, opening, closing),
4971 .opening_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(opening),
4972 .closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing),
4973 .parts = { 0 }
4974 };
4975
4976 return node;
4977 }
4978
4979 static inline void
4980 pm_interpolated_xstring_node_append(pm_interpolated_x_string_node_t *node, pm_node_t *part) {
4981 pm_interpolated_node_append(UP(node), &node->parts, part);
4982 node->base.location.end = part->location.end;
4983 }
4984
4985 static inline void
4986 pm_interpolated_xstring_node_closing_set(pm_interpolated_x_string_node_t *node, const pm_token_t *closing) {
4987 node->closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing);
4988 node->base.location.end = closing->end;
4989 }
4990
4991 /**
4992 * Create a local variable read that is reading the implicit 'it' variable.
4993 */
4994 static pm_it_local_variable_read_node_t *
4995 pm_it_local_variable_read_node_create(pm_parser_t *parser, const pm_token_t *name) {
4996 pm_it_local_variable_read_node_t *node = PM_NODE_ALLOC(parser, pm_it_local_variable_read_node_t);
4997
4998 *node = (pm_it_local_variable_read_node_t) {
4999 .base = PM_NODE_INIT_TOKEN(parser, PM_IT_LOCAL_VARIABLE_READ_NODE, 0, name),
5000 };
5001
5002 return node;
5003 }
5004
5005 /**
5006 * Allocate and initialize a new ItParametersNode node.
5007 */
5008 static pm_it_parameters_node_t *
5009 pm_it_parameters_node_create(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *closing) {
5010 pm_it_parameters_node_t *node = PM_NODE_ALLOC(parser, pm_it_parameters_node_t);
5011
5012 *node = (pm_it_parameters_node_t) {
5013 .base = PM_NODE_INIT_TOKENS(parser, PM_IT_PARAMETERS_NODE, 0, opening, closing),
5014 };
5015
5016 return node;
5017 }
5018
5019 /**
5020 * Allocate a new KeywordHashNode node.
5021 */
5022 static pm_keyword_hash_node_t *
5023 pm_keyword_hash_node_create(pm_parser_t *parser) {
5024 pm_keyword_hash_node_t *node = PM_NODE_ALLOC(parser, pm_keyword_hash_node_t);
5025
5026 *node = (pm_keyword_hash_node_t) {
5027 .base = PM_NODE_INIT_UNSET(parser, PM_KEYWORD_HASH_NODE, PM_KEYWORD_HASH_NODE_FLAGS_SYMBOL_KEYS),
5028 .elements = { 0 }
5029 };
5030
5031 return node;
5032 }
5033
5034 /**
5035 * Append an element to a KeywordHashNode node.
5036 */
5037 static void
5038 pm_keyword_hash_node_elements_append(pm_keyword_hash_node_t *hash, pm_node_t *element) {
5039 // If the element being added is not an AssocNode or does not have a symbol
5040 // key, then we want to turn the SYMBOL_KEYS flag off.
5041 if (!PM_NODE_TYPE_P(element, PM_ASSOC_NODE) || !PM_NODE_TYPE_P(((pm_assoc_node_t *) element)->key, PM_SYMBOL_NODE)) {
5042 pm_node_flag_unset(UP(hash), PM_KEYWORD_HASH_NODE_FLAGS_SYMBOL_KEYS);
5043 }
5044
5045 pm_node_list_append(&hash->elements, element);
5046 if (hash->base.location.start == NULL) {
5047 hash->base.location.start = element->location.start;
5048 }
5049 hash->base.location.end = element->location.end;
5050 }
5051
5052 /**
5053 * Allocate and initialize a new RequiredKeywordParameterNode node.
5054 */
5055 static pm_required_keyword_parameter_node_t *
5056 pm_required_keyword_parameter_node_create(pm_parser_t *parser, const pm_token_t *name) {
5057 pm_required_keyword_parameter_node_t *node = PM_NODE_ALLOC(parser, pm_required_keyword_parameter_node_t);
5058
5059 *node = (pm_required_keyword_parameter_node_t) {
5060 .base = PM_NODE_INIT_TOKEN(parser, PM_REQUIRED_KEYWORD_PARAMETER_NODE, 0, name),
5061 .name = pm_parser_constant_id_location(parser, name->start, name->end - 1),
5062 .name_loc = PM_LOCATION_TOKEN_VALUE(name),
5063 };
5064
5065 return node;
5066 }
5067
5068 /**
5069 * Allocate a new OptionalKeywordParameterNode node.
5070 */
5071 static pm_optional_keyword_parameter_node_t *
5072 pm_optional_keyword_parameter_node_create(pm_parser_t *parser, const pm_token_t *name, pm_node_t *value) {
5073 pm_optional_keyword_parameter_node_t *node = PM_NODE_ALLOC(parser, pm_optional_keyword_parameter_node_t);
5074
5075 *node = (pm_optional_keyword_parameter_node_t) {
5076 .base = PM_NODE_INIT_TOKEN_NODE(parser, PM_OPTIONAL_KEYWORD_PARAMETER_NODE, 0, name, value),
5077 .name = pm_parser_constant_id_location(parser, name->start, name->end - 1),
5078 .name_loc = PM_LOCATION_TOKEN_VALUE(name),
5079 .value = value
5080 };
5081
5082 return node;
5083 }
5084
5085 /**
5086 * Allocate a new KeywordRestParameterNode node.
5087 */
5088 static pm_keyword_rest_parameter_node_t *
5089 pm_keyword_rest_parameter_node_create(pm_parser_t *parser, const pm_token_t *operator, const pm_token_t *name) {
5090 pm_keyword_rest_parameter_node_t *node = PM_NODE_ALLOC(parser, pm_keyword_rest_parameter_node_t);
5091
5092 *node = (pm_keyword_rest_parameter_node_t) {
5093 .base = (
5094 (name->type == PM_TOKEN_NOT_PROVIDED)
5095 ? PM_NODE_INIT_TOKEN(parser, PM_KEYWORD_REST_PARAMETER_NODE, 0, operator)
5096 : PM_NODE_INIT_TOKENS(parser, PM_KEYWORD_REST_PARAMETER_NODE, 0, operator, name)
5097 ),
5098 .name = pm_parser_optional_constant_id_token(parser, name),
5099 .name_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(name),
5100 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
5101 };
5102
5103 return node;
5104 }
5105
5106 /**
5107 * Allocate a new LambdaNode node.
5108 */
5109 static pm_lambda_node_t *
5110 pm_lambda_node_create(
5111 pm_parser_t *parser,
5112 pm_constant_id_list_t *locals,
5113 const pm_token_t *operator,
5114 const pm_token_t *opening,
5115 const pm_token_t *closing,
5116 pm_node_t *parameters,
5117 pm_node_t *body
5118 ) {
5119 pm_lambda_node_t *node = PM_NODE_ALLOC(parser, pm_lambda_node_t);
5120
5121 *node = (pm_lambda_node_t) {
5122 .base = PM_NODE_INIT_TOKENS(parser, PM_LAMBDA_NODE, 0, operator, closing),
5123 .locals = *locals,
5124 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
5125 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
5126 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing),
5127 .parameters = parameters,
5128 .body = body
5129 };
5130
5131 return node;
5132 }
5133
5134 /**
5135 * Allocate and initialize a new LocalVariableAndWriteNode node.
5136 */
5137 static pm_local_variable_and_write_node_t *
5138 pm_local_variable_and_write_node_create(pm_parser_t *parser, pm_node_t *target, const pm_token_t *operator, pm_node_t *value, pm_constant_id_t name, uint32_t depth) {
5139 assert(PM_NODE_TYPE_P(target, PM_LOCAL_VARIABLE_READ_NODE) || PM_NODE_TYPE_P(target, PM_IT_LOCAL_VARIABLE_READ_NODE) || PM_NODE_TYPE_P(target, PM_CALL_NODE));
5140 assert(operator->type == PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL);
5141 pm_local_variable_and_write_node_t *node = PM_NODE_ALLOC(parser, pm_local_variable_and_write_node_t);
5142
5143 *node = (pm_local_variable_and_write_node_t) {
5144 .base = PM_NODE_INIT_NODES(parser, PM_LOCAL_VARIABLE_AND_WRITE_NODE, 0, target, value),
5145 .name_loc = target->location,
5146 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
5147 .value = value,
5148 .name = name,
5149 .depth = depth
5150 };
5151
5152 return node;
5153 }
5154
5155 /**
5156 * Allocate and initialize a new LocalVariableOperatorWriteNode node.
5157 */
5158 static pm_local_variable_operator_write_node_t *
5159 pm_local_variable_operator_write_node_create(pm_parser_t *parser, pm_node_t *target, const pm_token_t *operator, pm_node_t *value, pm_constant_id_t name, uint32_t depth) {
5160 pm_local_variable_operator_write_node_t *node = PM_NODE_ALLOC(parser, pm_local_variable_operator_write_node_t);
5161
5162 *node = (pm_local_variable_operator_write_node_t) {
5163 .base = PM_NODE_INIT_NODES(parser, PM_LOCAL_VARIABLE_OPERATOR_WRITE_NODE, 0, target, value),
5164 .name_loc = target->location,
5165 .binary_operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
5166 .value = value,
5167 .name = name,
5168 .binary_operator = pm_parser_constant_id_location(parser, operator->start, operator->end - 1),
5169 .depth = depth
5170 };
5171
5172 return node;
5173 }
5174
5175 /**
5176 * Allocate and initialize a new LocalVariableOrWriteNode node.
5177 */
5178 static pm_local_variable_or_write_node_t *
5179 pm_local_variable_or_write_node_create(pm_parser_t *parser, pm_node_t *target, const pm_token_t *operator, pm_node_t *value, pm_constant_id_t name, uint32_t depth) {
5180 assert(PM_NODE_TYPE_P(target, PM_LOCAL_VARIABLE_READ_NODE) || PM_NODE_TYPE_P(target, PM_IT_LOCAL_VARIABLE_READ_NODE) || PM_NODE_TYPE_P(target, PM_CALL_NODE));
5181 assert(operator->type == PM_TOKEN_PIPE_PIPE_EQUAL);
5182 pm_local_variable_or_write_node_t *node = PM_NODE_ALLOC(parser, pm_local_variable_or_write_node_t);
5183
5184 *node = (pm_local_variable_or_write_node_t) {
5185 .base = PM_NODE_INIT_NODES(parser, PM_LOCAL_VARIABLE_OR_WRITE_NODE, 0, target, value),
5186 .name_loc = target->location,
5187 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
5188 .value = value,
5189 .name = name,
5190 .depth = depth
5191 };
5192
5193 return node;
5194 }
5195
5196 /**
5197 * Allocate a new LocalVariableReadNode node with constant_id.
5198 */
5199 static pm_local_variable_read_node_t *
5200 pm_local_variable_read_node_create_constant_id(pm_parser_t *parser, const pm_token_t *name, pm_constant_id_t name_id, uint32_t depth, bool missing) {
5201 if (!missing) pm_locals_read(&pm_parser_scope_find(parser, depth)->locals, name_id);
5202
5203 pm_local_variable_read_node_t *node = PM_NODE_ALLOC(parser, pm_local_variable_read_node_t);
5204
5205 *node = (pm_local_variable_read_node_t) {
5206 .base = PM_NODE_INIT_TOKEN(parser, PM_LOCAL_VARIABLE_READ_NODE, 0, name),
5207 .name = name_id,
5208 .depth = depth
5209 };
5210
5211 return node;
5212 }
5213
5214 /**
5215 * Allocate and initialize a new LocalVariableReadNode node.
5216 */
5217 static pm_local_variable_read_node_t *
5218 pm_local_variable_read_node_create(pm_parser_t *parser, const pm_token_t *name, uint32_t depth) {
5219 pm_constant_id_t name_id = pm_parser_constant_id_token(parser, name);
5220 return pm_local_variable_read_node_create_constant_id(parser, name, name_id, depth, false);
5221 }
5222
5223 /**
5224 * Allocate and initialize a new LocalVariableReadNode node for a missing local
5225 * variable. (This will only happen when there is a syntax error.)
5226 */
5227 static pm_local_variable_read_node_t *
5228 pm_local_variable_read_node_missing_create(pm_parser_t *parser, const pm_token_t *name, uint32_t depth) {
5229 pm_constant_id_t name_id = pm_parser_constant_id_token(parser, name);
5230 return pm_local_variable_read_node_create_constant_id(parser, name, name_id, depth, true);
5231 }
5232
5233 /**
5234 * Allocate and initialize a new LocalVariableWriteNode node.
5235 */
5236 static pm_local_variable_write_node_t *
5237 pm_local_variable_write_node_create(pm_parser_t *parser, pm_constant_id_t name, uint32_t depth, pm_node_t *value, const pm_location_t *name_loc, const pm_token_t *operator) {
5238 pm_local_variable_write_node_t *node = PM_NODE_ALLOC(parser, pm_local_variable_write_node_t);
5239 pm_node_flags_t flags = pm_implicit_array_write_flags(value, PM_WRITE_NODE_FLAGS_IMPLICIT_ARRAY);
5240
5241 *node = (pm_local_variable_write_node_t) {
5242 .base = PM_NODE_INIT_TOKEN_NODE(parser, PM_LOCAL_VARIABLE_WRITE_NODE, flags, name_loc, value),
5243 .name = name,
5244 .depth = depth,
5245 .value = value,
5246 .name_loc = *name_loc,
5247 .operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator)
5248 };
5249
5250 return node;
5251 }
5252
5253 /**
5254 * Returns true if the given bounds comprise `it`.
5255 */
5256 static inline bool
5257 pm_token_is_it(const uint8_t *start, const uint8_t *end) {
5258 return (end - start == 2) && (start[0] == 'i') && (start[1] == 't');
5259 }
5260
5261 /**
5262 * Returns true if the given bounds comprise a numbered parameter (i.e., they
5263 * are of the form /^_\d$/).
5264 */
5265 static inline bool
5266 pm_token_is_numbered_parameter(const uint8_t *start, const uint8_t *end) {
5267 return (end - start == 2) && (start[0] == '_') && (start[1] != '0') && (pm_char_is_decimal_digit(start[1]));
5268 }
5269
5270 /**
5271 * Ensure the given bounds do not comprise a numbered parameter. If they do, add
5272 * an appropriate error message to the parser.
5273 */
5274 static inline void
5275 pm_refute_numbered_parameter(pm_parser_t *parser, const uint8_t *start, const uint8_t *end) {
5276 if (pm_token_is_numbered_parameter(start, end)) {
5277 PM_PARSER_ERR_FORMAT(parser, start, end, PM_ERR_PARAMETER_NUMBERED_RESERVED, start);
5278 }
5279 }
5280
5281 /**
5282 * Allocate and initialize a new LocalVariableTargetNode node with the given
5283 * name and depth.
5284 */
5285 static pm_local_variable_target_node_t *
5286 pm_local_variable_target_node_create(pm_parser_t *parser, const pm_location_t *location, pm_constant_id_t name, uint32_t depth) {
5287 pm_refute_numbered_parameter(parser, location->start, location->end);
5288 pm_local_variable_target_node_t *node = PM_NODE_ALLOC(parser, pm_local_variable_target_node_t);
5289
5290 *node = (pm_local_variable_target_node_t) {
5291 .base = PM_NODE_INIT_TOKEN(parser, PM_LOCAL_VARIABLE_TARGET_NODE, 0, location),
5292 .name = name,
5293 .depth = depth
5294 };
5295
5296 return node;
5297 }
5298
5299 /**
5300 * Allocate and initialize a new MatchPredicateNode node.
5301 */
5302 static pm_match_predicate_node_t *
5303 pm_match_predicate_node_create(pm_parser_t *parser, pm_node_t *value, pm_node_t *pattern, const pm_token_t *operator) {
5304 pm_assert_value_expression(parser, value);
5305
5306 pm_match_predicate_node_t *node = PM_NODE_ALLOC(parser, pm_match_predicate_node_t);
5307
5308 *node = (pm_match_predicate_node_t) {
5309 .base = PM_NODE_INIT_NODES(parser, PM_MATCH_PREDICATE_NODE, 0, value, pattern),
5310 .value = value,
5311 .pattern = pattern,
5312 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
5313 };
5314
5315 return node;
5316 }
5317
5318 /**
5319 * Allocate and initialize a new MatchRequiredNode node.
5320 */
5321 static pm_match_required_node_t *
5322 pm_match_required_node_create(pm_parser_t *parser, pm_node_t *value, pm_node_t *pattern, const pm_token_t *operator) {
5323 pm_assert_value_expression(parser, value);
5324
5325 pm_match_required_node_t *node = PM_NODE_ALLOC(parser, pm_match_required_node_t);
5326
5327 *node = (pm_match_required_node_t) {
5328 .base = PM_NODE_INIT_NODES(parser, PM_MATCH_REQUIRED_NODE, 0, value, pattern),
5329 .value = value,
5330 .pattern = pattern,
5331 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
5332 };
5333
5334 return node;
5335 }
5336
5337 /**
5338 * Allocate and initialize a new MatchWriteNode node.
5339 */
5340 static pm_match_write_node_t *
5341 pm_match_write_node_create(pm_parser_t *parser, pm_call_node_t *call) {
5342 pm_match_write_node_t *node = PM_NODE_ALLOC(parser, pm_match_write_node_t);
5343
5344 *node = (pm_match_write_node_t) {
5345 .base = PM_NODE_INIT_NODE(parser, PM_MATCH_WRITE_NODE, 0, call),
5346 .call = call,
5347 .targets = { 0 }
5348 };
5349
5350 return node;
5351 }
5352
5353 /**
5354 * Allocate a new ModuleNode node.
5355 */
5356 static pm_module_node_t *
5357 pm_module_node_create(pm_parser_t *parser, pm_constant_id_list_t *locals, const pm_token_t *module_keyword, pm_node_t *constant_path, const pm_token_t *name, pm_node_t *body, const pm_token_t *end_keyword) {
5358 pm_module_node_t *node = PM_NODE_ALLOC(parser, pm_module_node_t);
5359
5360 *node = (pm_module_node_t) {
5361 .base = PM_NODE_INIT_TOKENS(parser, PM_MODULE_NODE, 0, module_keyword, end_keyword),
5362 .locals = (locals == NULL ? ((pm_constant_id_list_t) { .ids = NULL, .size = 0, .capacity = 0 }) : *locals),
5363 .module_keyword_loc = PM_LOCATION_TOKEN_VALUE(module_keyword),
5364 .constant_path = constant_path,
5365 .body = body,
5366 .end_keyword_loc = PM_LOCATION_TOKEN_VALUE(end_keyword),
5367 .name = pm_parser_constant_id_token(parser, name)
5368 };
5369
5370 return node;
5371 }
5372
5373 /**
5374 * Allocate and initialize new MultiTargetNode node.
5375 */
5376 static pm_multi_target_node_t *
5377 pm_multi_target_node_create(pm_parser_t *parser) {
5378 pm_multi_target_node_t *node = PM_NODE_ALLOC(parser, pm_multi_target_node_t);
5379
5380 *node = (pm_multi_target_node_t) {
5381 .base = PM_NODE_INIT_UNSET(parser, PM_MULTI_TARGET_NODE, 0),
5382 .lefts = { 0 },
5383 .rest = NULL,
5384 .rights = { 0 },
5385 .lparen_loc = { 0 },
5386 .rparen_loc = { 0 }
5387 };
5388
5389 return node;
5390 }
5391
5392 /**
5393 * Append a target to a MultiTargetNode node.
5394 */
5395 static void
5396 pm_multi_target_node_targets_append(pm_parser_t *parser, pm_multi_target_node_t *node, pm_node_t *target) {
5397 if (PM_NODE_TYPE_P(target, PM_SPLAT_NODE)) {
5398 if (node->rest == NULL) {
5399 node->rest = target;
5400 } else {
5401 pm_parser_err_node(parser, target, PM_ERR_MULTI_ASSIGN_MULTI_SPLATS);
5402 pm_node_list_append(&node->rights, target);
5403 }
5404 } else if (PM_NODE_TYPE_P(target, PM_IMPLICIT_REST_NODE)) {
5405 if (node->rest == NULL) {
5406 node->rest = target;
5407 } else {
5408 PM_PARSER_ERR_TOKEN_FORMAT_CONTENT(parser, parser->current, PM_ERR_MULTI_ASSIGN_UNEXPECTED_REST);
5409 pm_node_list_append(&node->rights, target);
5410 }
5411 } else if (node->rest == NULL) {
5412 pm_node_list_append(&node->lefts, target);
5413 } else {
5414 pm_node_list_append(&node->rights, target);
5415 }
5416
5417 if (node->base.location.start == NULL || (node->base.location.start > target->location.start)) {
5418 node->base.location.start = target->location.start;
5419 }
5420
5421 if (node->base.location.end == NULL || (node->base.location.end < target->location.end)) {
5422 node->base.location.end = target->location.end;
5423 }
5424 }
5425
5426 /**
5427 * Set the opening of a MultiTargetNode node.
5428 */
5429 static void
5430 pm_multi_target_node_opening_set(pm_multi_target_node_t *node, const pm_token_t *lparen) {
5431 node->base.location.start = lparen->start;
5432 node->lparen_loc = PM_LOCATION_TOKEN_VALUE(lparen);
5433 }
5434
5435 /**
5436 * Set the closing of a MultiTargetNode node.
5437 */
5438 static void
5439 pm_multi_target_node_closing_set(pm_multi_target_node_t *node, const pm_token_t *rparen) {
5440 node->base.location.end = rparen->end;
5441 node->rparen_loc = PM_LOCATION_TOKEN_VALUE(rparen);
5442 }
5443
5444 /**
5445 * Allocate a new MultiWriteNode node.
5446 */
5447 static pm_multi_write_node_t *
5448 pm_multi_write_node_create(pm_parser_t *parser, pm_multi_target_node_t *target, const pm_token_t *operator, pm_node_t *value) {
5449 pm_multi_write_node_t *node = PM_NODE_ALLOC(parser, pm_multi_write_node_t);
5450 pm_node_flags_t flags = pm_implicit_array_write_flags(value, PM_WRITE_NODE_FLAGS_IMPLICIT_ARRAY);
5451
5452 *node = (pm_multi_write_node_t) {
5453 .base = PM_NODE_INIT_NODES(parser, PM_MULTI_WRITE_NODE, flags, target, value),
5454 .lefts = target->lefts,
5455 .rest = target->rest,
5456 .rights = target->rights,
5457 .lparen_loc = target->lparen_loc,
5458 .rparen_loc = target->rparen_loc,
5459 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
5460 .value = value
5461 };
5462
5463 // Explicitly do not call pm_node_destroy here because we want to keep
5464 // around all of the information within the MultiWriteNode node.
5465 xfree(target);
5466
5467 return node;
5468 }
5469
5470 /**
5471 * Allocate and initialize a new NextNode node.
5472 */
5473 static pm_next_node_t *
5474 pm_next_node_create(pm_parser_t *parser, const pm_token_t *keyword, pm_arguments_node_t *arguments) {
5475 assert(keyword->type == PM_TOKEN_KEYWORD_NEXT);
5476 pm_next_node_t *node = PM_NODE_ALLOC(parser, pm_next_node_t);
5477
5478 *node = (pm_next_node_t) {
5479 .base = (
5480 (arguments == NULL)
5481 ? PM_NODE_INIT_TOKEN(parser, PM_NEXT_NODE, 0, keyword)
5482 : PM_NODE_INIT_TOKEN_NODE(parser, PM_NEXT_NODE, 0, keyword, arguments)
5483 ),
5484 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
5485 .arguments = arguments
5486 };
5487
5488 return node;
5489 }
5490
5491 /**
5492 * Allocate and initialize a new NilNode node.
5493 */
5494 static pm_nil_node_t *
5495 pm_nil_node_create(pm_parser_t *parser, const pm_token_t *token) {
5496 assert(token->type == PM_TOKEN_KEYWORD_NIL);
5497 pm_nil_node_t *node = PM_NODE_ALLOC(parser, pm_nil_node_t);
5498
5499 *node = (pm_nil_node_t) {
5500 .base = PM_NODE_INIT_TOKEN(parser, PM_NIL_NODE, PM_NODE_FLAG_STATIC_LITERAL, token)
5501 };
5502
5503 return node;
5504 }
5505
5506 /**
5507 * Allocate and initialize a new NoKeywordsParameterNode node.
5508 */
5509 static pm_no_keywords_parameter_node_t *
5510 pm_no_keywords_parameter_node_create(pm_parser_t *parser, const pm_token_t *operator, const pm_token_t *keyword) {
5511 assert(operator->type == PM_TOKEN_USTAR_STAR || operator->type == PM_TOKEN_STAR_STAR);
5512 assert(keyword->type == PM_TOKEN_KEYWORD_NIL);
5513 pm_no_keywords_parameter_node_t *node = PM_NODE_ALLOC(parser, pm_no_keywords_parameter_node_t);
5514
5515 *node = (pm_no_keywords_parameter_node_t) {
5516 .base = PM_NODE_INIT_TOKENS(parser, PM_NO_KEYWORDS_PARAMETER_NODE, 0, operator, keyword),
5517 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
5518 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword)
5519 };
5520
5521 return node;
5522 }
5523
5524 /**
5525 * Allocate and initialize a new NumberedParametersNode node.
5526 */
5527 static pm_numbered_parameters_node_t *
5528 pm_numbered_parameters_node_create(pm_parser_t *parser, const pm_location_t *location, uint8_t maximum) {
5529 pm_numbered_parameters_node_t *node = PM_NODE_ALLOC(parser, pm_numbered_parameters_node_t);
5530
5531 *node = (pm_numbered_parameters_node_t) {
5532 .base = PM_NODE_INIT_TOKEN(parser, PM_NUMBERED_PARAMETERS_NODE, 0, location),
5533 .maximum = maximum
5534 };
5535
5536 return node;
5537 }
5538
5539 /**
5540 * The maximum numbered reference value is defined as the maximum value that an
5541 * integer can hold minus 1 bit for CRuby instruction sequence operand tagging.
5542 */
5543 #define NTH_REF_MAX ((uint32_t) (INT_MAX >> 1))
5544
5545 /**
5546 * Parse the decimal number represented by the range of bytes. Returns
5547 * 0 if the number fails to parse or if the number is greater than the maximum
5548 * value representable by a numbered reference. This function assumes that the
5549 * range of bytes has already been validated to contain only decimal digits.
5550 */
5551 static uint32_t
5552 pm_numbered_reference_read_node_number(pm_parser_t *parser, const pm_token_t *token) {
5553 const uint8_t *start = token->start + 1;
5554 const uint8_t *end = token->end;
5555
5556 ptrdiff_t diff = end - start;
5557 assert(diff > 0);
5558 #if PTRDIFF_MAX > SIZE_MAX
5559 assert(diff < (ptrdiff_t) SIZE_MAX);
5560 #endif
5561 size_t length = (size_t) diff;
5562
5563 char *digits = xcalloc(length + 1, sizeof(char));
5564 memcpy(digits, start, length);
5565 digits[length] = '\0';
5566
5567 char *endptr;
5568 errno = 0;
5569 unsigned long value = strtoul(digits, &endptr, 10);
5570
5571 if ((digits == endptr) || (*endptr != '\0')) {
5572 pm_parser_err(parser, start, end, PM_ERR_INVALID_NUMBER_DECIMAL);
5573 value = 0;
5574 }
5575
5576 xfree(digits);
5577
5578 if ((errno == ERANGE) || (value > NTH_REF_MAX)) {
5579 PM_PARSER_WARN_FORMAT(parser, start, end, PM_WARN_INVALID_NUMBERED_REFERENCE, (int) (length + 1), (const char *) token->start);
5580 value = 0;
5581 }
5582
5583 return (uint32_t) value;
5584 }
5585
5586 #undef NTH_REF_MAX
5587
5588 /**
5589 * Allocate and initialize a new NthReferenceReadNode node.
5590 */
5591 static pm_numbered_reference_read_node_t *
5592 pm_numbered_reference_read_node_create(pm_parser_t *parser, const pm_token_t *name) {
5593 assert(name->type == PM_TOKEN_NUMBERED_REFERENCE);
5594 pm_numbered_reference_read_node_t *node = PM_NODE_ALLOC(parser, pm_numbered_reference_read_node_t);
5595
5596 *node = (pm_numbered_reference_read_node_t) {
5597 .base = PM_NODE_INIT_TOKEN(parser, PM_NUMBERED_REFERENCE_READ_NODE, 0, name),
5598 .number = pm_numbered_reference_read_node_number(parser, name)
5599 };
5600
5601 return node;
5602 }
5603
5604 /**
5605 * Allocate a new OptionalParameterNode node.
5606 */
5607 static pm_optional_parameter_node_t *
5608 pm_optional_parameter_node_create(pm_parser_t *parser, const pm_token_t *name, const pm_token_t *operator, pm_node_t *value) {
5609 pm_optional_parameter_node_t *node = PM_NODE_ALLOC(parser, pm_optional_parameter_node_t);
5610
5611 *node = (pm_optional_parameter_node_t) {
5612 .base = PM_NODE_INIT_TOKEN_NODE(parser, PM_OPTIONAL_PARAMETER_NODE, 0, name, value),
5613 .name = pm_parser_constant_id_token(parser, name),
5614 .name_loc = PM_LOCATION_TOKEN_VALUE(name),
5615 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
5616 .value = value
5617 };
5618
5619 return node;
5620 }
5621
5622 /**
5623 * Allocate and initialize a new OrNode node.
5624 */
5625 static pm_or_node_t *
5626 pm_or_node_create(pm_parser_t *parser, pm_node_t *left, const pm_token_t *operator, pm_node_t *right) {
5627 pm_assert_value_expression(parser, left);
5628
5629 pm_or_node_t *node = PM_NODE_ALLOC(parser, pm_or_node_t);
5630
5631 *node = (pm_or_node_t) {
5632 .base = PM_NODE_INIT_NODES(parser, PM_OR_NODE, 0, left, right),
5633 .left = left,
5634 .right = right,
5635 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
5636 };
5637
5638 return node;
5639 }
5640
5641 /**
5642 * Allocate and initialize a new ParametersNode node.
5643 */
5644 static pm_parameters_node_t *
5645 pm_parameters_node_create(pm_parser_t *parser) {
5646 pm_parameters_node_t *node = PM_NODE_ALLOC(parser, pm_parameters_node_t);
5647
5648 *node = (pm_parameters_node_t) {
5649 .base = PM_NODE_INIT_UNSET(parser, PM_PARAMETERS_NODE, 0),
5650 .rest = NULL,
5651 .keyword_rest = NULL,
5652 .block = NULL,
5653 .requireds = { 0 },
5654 .optionals = { 0 },
5655 .posts = { 0 },
5656 .keywords = { 0 }
5657 };
5658
5659 return node;
5660 }
5661
5662 /**
5663 * Set the location properly for the parameters node.
5664 */
5665 static void
5666 pm_parameters_node_location_set(pm_parameters_node_t *params, pm_node_t *param) {
5667 if (params->base.location.start == NULL) {
5668 params->base.location.start = param->location.start;
5669 } else {
5670 params->base.location.start = params->base.location.start < param->location.start ? params->base.location.start : param->location.start;
5671 }
5672
5673 if (params->base.location.end == NULL) {
5674 params->base.location.end = param->location.end;
5675 } else {
5676 params->base.location.end = params->base.location.end > param->location.end ? params->base.location.end : param->location.end;
5677 }
5678 }
5679
5680 /**
5681 * Append a required parameter to a ParametersNode node.
5682 */
5683 static void
5684 pm_parameters_node_requireds_append(pm_parameters_node_t *params, pm_node_t *param) {
5685 pm_parameters_node_location_set(params, param);
5686 pm_node_list_append(&params->requireds, param);
5687 }
5688
5689 /**
5690 * Append an optional parameter to a ParametersNode node.
5691 */
5692 static void
5693 pm_parameters_node_optionals_append(pm_parameters_node_t *params, pm_optional_parameter_node_t *param) {
5694 pm_parameters_node_location_set(params, UP(param));
5695 pm_node_list_append(&params->optionals, UP(param));
5696 }
5697
5698 /**
5699 * Append a post optional arguments parameter to a ParametersNode node.
5700 */
5701 static void
5702 pm_parameters_node_posts_append(pm_parameters_node_t *params, pm_node_t *param) {
5703 pm_parameters_node_location_set(params, param);
5704 pm_node_list_append(&params->posts, param);
5705 }
5706
5707 /**
5708 * Set the rest parameter on a ParametersNode node.
5709 */
5710 static void
5711 pm_parameters_node_rest_set(pm_parameters_node_t *params, pm_node_t *param) {
5712 pm_parameters_node_location_set(params, param);
5713 params->rest = param;
5714 }
5715
5716 /**
5717 * Append a keyword parameter to a ParametersNode node.
5718 */
5719 static void
5720 pm_parameters_node_keywords_append(pm_parameters_node_t *params, pm_node_t *param) {
5721 pm_parameters_node_location_set(params, param);
5722 pm_node_list_append(&params->keywords, param);
5723 }
5724
5725 /**
5726 * Set the keyword rest parameter on a ParametersNode node.
5727 */
5728 static void
5729 pm_parameters_node_keyword_rest_set(pm_parameters_node_t *params, pm_node_t *param) {
5730 assert(params->keyword_rest == NULL);
5731 pm_parameters_node_location_set(params, param);
5732 params->keyword_rest = param;
5733 }
5734
5735 /**
5736 * Set the block parameter on a ParametersNode node.
5737 */
5738 static void
5739 pm_parameters_node_block_set(pm_parameters_node_t *params, pm_block_parameter_node_t *param) {
5740 assert(params->block == NULL);
5741 pm_parameters_node_location_set(params, UP(param));
5742 params->block = param;
5743 }
5744
5745 /**
5746 * Allocate a new ProgramNode node.
5747 */
5748 static pm_program_node_t *
5749 pm_program_node_create(pm_parser_t *parser, pm_constant_id_list_t *locals, pm_statements_node_t *statements) {
5750 pm_program_node_t *node = PM_NODE_ALLOC(parser, pm_program_node_t);
5751
5752 *node = (pm_program_node_t) {
5753 .base = PM_NODE_INIT_NODE(parser, PM_PROGRAM_NODE, 0, statements),
5754 .locals = *locals,
5755 .statements = statements
5756 };
5757
5758 return node;
5759 }
5760
5761 /**
5762 * Allocate and initialize new ParenthesesNode node.
5763 */
5764 static pm_parentheses_node_t *
5765 pm_parentheses_node_create(pm_parser_t *parser, const pm_token_t *opening, pm_node_t *body, const pm_token_t *closing, pm_node_flags_t flags) {
5766 pm_parentheses_node_t *node = PM_NODE_ALLOC(parser, pm_parentheses_node_t);
5767
5768 *node = (pm_parentheses_node_t) {
5769 .base = PM_NODE_INIT_TOKENS(parser, PM_PARENTHESES_NODE, flags, opening, closing),
5770 .body = body,
5771 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
5772 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing)
5773 };
5774
5775 return node;
5776 }
5777
5778 /**
5779 * Allocate and initialize a new PinnedExpressionNode node.
5780 */
5781 static pm_pinned_expression_node_t *
5782 pm_pinned_expression_node_create(pm_parser_t *parser, pm_node_t *expression, const pm_token_t *operator, const pm_token_t *lparen, const pm_token_t *rparen) {
5783 pm_pinned_expression_node_t *node = PM_NODE_ALLOC(parser, pm_pinned_expression_node_t);
5784
5785 *node = (pm_pinned_expression_node_t) {
5786 .base = PM_NODE_INIT_TOKENS(parser, PM_PINNED_EXPRESSION_NODE, 0, operator, rparen),
5787 .expression = expression,
5788 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
5789 .lparen_loc = PM_LOCATION_TOKEN_VALUE(lparen),
5790 .rparen_loc = PM_LOCATION_TOKEN_VALUE(rparen)
5791 };
5792
5793 return node;
5794 }
5795
5796 /**
5797 * Allocate and initialize a new PinnedVariableNode node.
5798 */
5799 static pm_pinned_variable_node_t *
5800 pm_pinned_variable_node_create(pm_parser_t *parser, const pm_token_t *operator, pm_node_t *variable) {
5801 pm_pinned_variable_node_t *node = PM_NODE_ALLOC(parser, pm_pinned_variable_node_t);
5802
5803 *node = (pm_pinned_variable_node_t) {
5804 .base = PM_NODE_INIT_TOKEN_NODE(parser, PM_PINNED_VARIABLE_NODE, 0, operator, variable),
5805 .variable = variable,
5806 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
5807 };
5808
5809 return node;
5810 }
5811
5812 /**
5813 * Allocate and initialize a new PostExecutionNode node.
5814 */
5815 static pm_post_execution_node_t *
5816 pm_post_execution_node_create(pm_parser_t *parser, const pm_token_t *keyword, const pm_token_t *opening, pm_statements_node_t *statements, const pm_token_t *closing) {
5817 pm_post_execution_node_t *node = PM_NODE_ALLOC(parser, pm_post_execution_node_t);
5818
5819 *node = (pm_post_execution_node_t) {
5820 .base = PM_NODE_INIT_TOKENS(parser, PM_POST_EXECUTION_NODE, 0, keyword, closing),
5821 .statements = statements,
5822 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
5823 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
5824 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing)
5825 };
5826
5827 return node;
5828 }
5829
5830 /**
5831 * Allocate and initialize a new PreExecutionNode node.
5832 */
5833 static pm_pre_execution_node_t *
5834 pm_pre_execution_node_create(pm_parser_t *parser, const pm_token_t *keyword, const pm_token_t *opening, pm_statements_node_t *statements, const pm_token_t *closing) {
5835 pm_pre_execution_node_t *node = PM_NODE_ALLOC(parser, pm_pre_execution_node_t);
5836
5837 *node = (pm_pre_execution_node_t) {
5838 .base = PM_NODE_INIT_TOKENS(parser, PM_PRE_EXECUTION_NODE, 0, keyword, closing),
5839 .statements = statements,
5840 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
5841 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
5842 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing)
5843 };
5844
5845 return node;
5846 }
5847
5848 /**
5849 * Allocate and initialize new RangeNode node.
5850 */
5851 static pm_range_node_t *
5852 pm_range_node_create(pm_parser_t *parser, pm_node_t *left, const pm_token_t *operator, pm_node_t *right) {
5853 pm_assert_value_expression(parser, left);
5854 pm_assert_value_expression(parser, right);
5855
5856 pm_range_node_t *node = PM_NODE_ALLOC(parser, pm_range_node_t);
5857 pm_node_flags_t flags = 0;
5858
5859 // Indicate that this node is an exclusive range if the operator is `...`.
5860 if (operator->type == PM_TOKEN_DOT_DOT_DOT || operator->type == PM_TOKEN_UDOT_DOT_DOT) {
5861 flags |= PM_RANGE_FLAGS_EXCLUDE_END;
5862 }
5863
5864 // Indicate that this node is a static literal (i.e., can be compiled with
5865 // a putobject in CRuby) if the left and right are implicit nil, explicit
5866 // nil, or integers.
5867 if (
5868 (left == NULL || PM_NODE_TYPE_P(left, PM_NIL_NODE) || PM_NODE_TYPE_P(left, PM_INTEGER_NODE)) &&
5869 (right == NULL || PM_NODE_TYPE_P(right, PM_NIL_NODE) || PM_NODE_TYPE_P(right, PM_INTEGER_NODE))
5870 ) {
5871 flags |= PM_NODE_FLAG_STATIC_LITERAL;
5872 }
5873
5874 *node = (pm_range_node_t) {
5875 .base = PM_NODE_INIT(parser, PM_RANGE_NODE, flags, (left == NULL ? operator->start : left->location.start), (right == NULL ? operator->end : right->location.end)),
5876 .left = left,
5877 .right = right,
5878 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
5879 };
5880
5881 return node;
5882 }
5883
5884 /**
5885 * Allocate and initialize a new RedoNode node.
5886 */
5887 static pm_redo_node_t *
5888 pm_redo_node_create(pm_parser_t *parser, const pm_token_t *token) {
5889 assert(token->type == PM_TOKEN_KEYWORD_REDO);
5890 pm_redo_node_t *node = PM_NODE_ALLOC(parser, pm_redo_node_t);
5891
5892 *node = (pm_redo_node_t) {
5893 .base = PM_NODE_INIT_TOKEN(parser, PM_REDO_NODE, 0, token)
5894 };
5895
5896 return node;
5897 }
5898
5899 /**
5900 * Allocate a new initialize a new RegularExpressionNode node with the given
5901 * unescaped string.
5902 */
5903 static pm_regular_expression_node_t *
5904 pm_regular_expression_node_create_unescaped(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *content, const pm_token_t *closing, const pm_string_t *unescaped) {
5905 pm_regular_expression_node_t *node = PM_NODE_ALLOC(parser, pm_regular_expression_node_t);
5906 pm_node_flags_t flags = pm_regular_expression_flags_create(parser, closing) | PM_NODE_FLAG_STATIC_LITERAL;
5907
5908 *node = (pm_regular_expression_node_t) {
5909 .base = PM_NODE_INIT_TOKENS(parser, PM_REGULAR_EXPRESSION_NODE, flags, opening, closing),
5910 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
5911 .content_loc = PM_LOCATION_TOKEN_VALUE(content),
5912 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing),
5913 .unescaped = *unescaped
5914 };
5915
5916 return node;
5917 }
5918
5919 /**
5920 * Allocate a new initialize a new RegularExpressionNode node.
5921 */
5922 static inline pm_regular_expression_node_t *
5923 pm_regular_expression_node_create(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *content, const pm_token_t *closing) {
5924 return pm_regular_expression_node_create_unescaped(parser, opening, content, closing, &PM_STRING_EMPTY);
5925 }
5926
5927 /**
5928 * Allocate a new RequiredParameterNode node.
5929 */
5930 static pm_required_parameter_node_t *
5931 pm_required_parameter_node_create(pm_parser_t *parser, const pm_token_t *token) {
5932 pm_required_parameter_node_t *node = PM_NODE_ALLOC(parser, pm_required_parameter_node_t);
5933
5934 *node = (pm_required_parameter_node_t) {
5935 .base = PM_NODE_INIT_TOKEN(parser, PM_REQUIRED_PARAMETER_NODE, 0, token),
5936 .name = pm_parser_constant_id_token(parser, token)
5937 };
5938
5939 return node;
5940 }
5941
5942 /**
5943 * Allocate a new RescueModifierNode node.
5944 */
5945 static pm_rescue_modifier_node_t *
5946 pm_rescue_modifier_node_create(pm_parser_t *parser, pm_node_t *expression, const pm_token_t *keyword, pm_node_t *rescue_expression) {
5947 pm_rescue_modifier_node_t *node = PM_NODE_ALLOC(parser, pm_rescue_modifier_node_t);
5948
5949 *node = (pm_rescue_modifier_node_t) {
5950 .base = PM_NODE_INIT_NODES(parser, PM_RESCUE_MODIFIER_NODE, 0, expression, rescue_expression),
5951 .expression = expression,
5952 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
5953 .rescue_expression = rescue_expression
5954 };
5955
5956 return node;
5957 }
5958
5959 /**
5960 * Allocate and initialize a new RescueNode node.
5961 */
5962 static pm_rescue_node_t *
5963 pm_rescue_node_create(pm_parser_t *parser, const pm_token_t *keyword) {
5964 pm_rescue_node_t *node = PM_NODE_ALLOC(parser, pm_rescue_node_t);
5965
5966 *node = (pm_rescue_node_t) {
5967 .base = PM_NODE_INIT_TOKEN(parser, PM_RESCUE_NODE, 0, keyword),
5968 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
5969 .operator_loc = { 0 },
5970 .then_keyword_loc = { 0 },
5971 .reference = NULL,
5972 .statements = NULL,
5973 .subsequent = NULL,
5974 .exceptions = { 0 }
5975 };
5976
5977 return node;
5978 }
5979
5980 static inline void
5981 pm_rescue_node_operator_set(pm_rescue_node_t *node, const pm_token_t *operator) {
5982 node->operator_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(operator);
5983 }
5984
5985 /**
5986 * Set the reference of a rescue node, and update the location of the node.
5987 */
5988 static void
5989 pm_rescue_node_reference_set(pm_rescue_node_t *node, pm_node_t *reference) {
5990 node->reference = reference;
5991 node->base.location.end = reference->location.end;
5992 }
5993
5994 /**
5995 * Set the statements of a rescue node, and update the location of the node.
5996 */
5997 static void
5998 pm_rescue_node_statements_set(pm_rescue_node_t *node, pm_statements_node_t *statements) {
5999 node->statements = statements;
6000 if (pm_statements_node_body_length(statements) > 0) {
6001 node->base.location.end = statements->base.location.end;
6002 }
6003 }
6004
6005 /**
6006 * Set the subsequent of a rescue node, and update the location.
6007 */
6008 static void
6009 pm_rescue_node_subsequent_set(pm_rescue_node_t *node, pm_rescue_node_t *subsequent) {
6010 node->subsequent = subsequent;
6011 node->base.location.end = subsequent->base.location.end;
6012 }
6013
6014 /**
6015 * Append an exception node to a rescue node, and update the location.
6016 */
6017 static void
6018 pm_rescue_node_exceptions_append(pm_rescue_node_t *node, pm_node_t *exception) {
6019 pm_node_list_append(&node->exceptions, exception);
6020 node->base.location.end = exception->location.end;
6021 }
6022
6023 /**
6024 * Allocate a new RestParameterNode node.
6025 */
6026 static pm_rest_parameter_node_t *
6027 pm_rest_parameter_node_create(pm_parser_t *parser, const pm_token_t *operator, const pm_token_t *name) {
6028 pm_rest_parameter_node_t *node = PM_NODE_ALLOC(parser, pm_rest_parameter_node_t);
6029
6030 *node = (pm_rest_parameter_node_t) {
6031 .base = (
6032 (name->type == PM_TOKEN_NOT_PROVIDED)
6033 ? PM_NODE_INIT_TOKEN(parser, PM_REST_PARAMETER_NODE, 0, operator)
6034 : PM_NODE_INIT_TOKENS(parser, PM_REST_PARAMETER_NODE, 0, operator, name)
6035 ),
6036 .name = pm_parser_optional_constant_id_token(parser, name),
6037 .name_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(name),
6038 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator)
6039 };
6040
6041 return node;
6042 }
6043
6044 /**
6045 * Allocate and initialize a new RetryNode node.
6046 */
6047 static pm_retry_node_t *
6048 pm_retry_node_create(pm_parser_t *parser, const pm_token_t *token) {
6049 assert(token->type == PM_TOKEN_KEYWORD_RETRY);
6050 pm_retry_node_t *node = PM_NODE_ALLOC(parser, pm_retry_node_t);
6051
6052 *node = (pm_retry_node_t) {
6053 .base = PM_NODE_INIT_TOKEN(parser, PM_RETRY_NODE, 0, token)
6054 };
6055
6056 return node;
6057 }
6058
6059 /**
6060 * Allocate a new ReturnNode node.
6061 */
6062 static pm_return_node_t *
6063 pm_return_node_create(pm_parser_t *parser, const pm_token_t *keyword, pm_arguments_node_t *arguments) {
6064 pm_return_node_t *node = PM_NODE_ALLOC(parser, pm_return_node_t);
6065
6066 *node = (pm_return_node_t) {
6067 .base = (
6068 (arguments == NULL)
6069 ? PM_NODE_INIT_TOKEN(parser, PM_RETURN_NODE, 0, keyword)
6070 : PM_NODE_INIT_TOKEN_NODE(parser, PM_RETURN_NODE, 0, keyword, arguments)
6071 ),
6072 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
6073 .arguments = arguments
6074 };
6075
6076 return node;
6077 }
6078
6079 /**
6080 * Allocate and initialize a new SelfNode node.
6081 */
6082 static pm_self_node_t *
6083 pm_self_node_create(pm_parser_t *parser, const pm_token_t *token) {
6084 assert(token->type == PM_TOKEN_KEYWORD_SELF);
6085 pm_self_node_t *node = PM_NODE_ALLOC(parser, pm_self_node_t);
6086
6087 *node = (pm_self_node_t) {
6088 .base = PM_NODE_INIT_TOKEN(parser, PM_SELF_NODE, 0, token)
6089 };
6090
6091 return node;
6092 }
6093
6094 /**
6095 * Allocate and initialize a new ShareableConstantNode node.
6096 */
6097 static pm_shareable_constant_node_t *
6098 pm_shareable_constant_node_create(pm_parser_t *parser, pm_node_t *write, pm_shareable_constant_value_t value) {
6099 pm_shareable_constant_node_t *node = PM_NODE_ALLOC(parser, pm_shareable_constant_node_t);
6100
6101 *node = (pm_shareable_constant_node_t) {
6102 .base = PM_NODE_INIT_NODE(parser, PM_SHAREABLE_CONSTANT_NODE, (pm_node_flags_t) value, write),
6103 .write = write
6104 };
6105
6106 return node;
6107 }
6108
6109 /**
6110 * Allocate a new SingletonClassNode node.
6111 */
6112 static pm_singleton_class_node_t *
6113 pm_singleton_class_node_create(pm_parser_t *parser, pm_constant_id_list_t *locals, const pm_token_t *class_keyword, const pm_token_t *operator, pm_node_t *expression, pm_node_t *body, const pm_token_t *end_keyword) {
6114 pm_singleton_class_node_t *node = PM_NODE_ALLOC(parser, pm_singleton_class_node_t);
6115
6116 *node = (pm_singleton_class_node_t) {
6117 .base = PM_NODE_INIT_TOKENS(parser, PM_SINGLETON_CLASS_NODE, 0, class_keyword, end_keyword),
6118 .locals = *locals,
6119 .class_keyword_loc = PM_LOCATION_TOKEN_VALUE(class_keyword),
6120 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
6121 .expression = expression,
6122 .body = body,
6123 .end_keyword_loc = PM_LOCATION_TOKEN_VALUE(end_keyword)
6124 };
6125
6126 return node;
6127 }
6128
6129 /**
6130 * Allocate and initialize a new SourceEncodingNode node.
6131 */
6132 static pm_source_encoding_node_t *
6133 pm_source_encoding_node_create(pm_parser_t *parser, const pm_token_t *token) {
6134 assert(token->type == PM_TOKEN_KEYWORD___ENCODING__);
6135 pm_source_encoding_node_t *node = PM_NODE_ALLOC(parser, pm_source_encoding_node_t);
6136
6137 *node = (pm_source_encoding_node_t) {
6138 .base = PM_NODE_INIT_TOKEN(parser, PM_SOURCE_ENCODING_NODE, PM_NODE_FLAG_STATIC_LITERAL, token)
6139 };
6140
6141 return node;
6142 }
6143
6144 /**
6145 * Allocate and initialize a new SourceFileNode node.
6146 */
6147 static pm_source_file_node_t*
6148 pm_source_file_node_create(pm_parser_t *parser, const pm_token_t *file_keyword) {
6149 pm_source_file_node_t *node = PM_NODE_ALLOC(parser, pm_source_file_node_t);
6150 assert(file_keyword->type == PM_TOKEN_KEYWORD___FILE__);
6151
6152 pm_node_flags_t flags = 0;
6153
6154 switch (parser->frozen_string_literal) {
6155 case PM_OPTIONS_FROZEN_STRING_LITERAL_DISABLED:
6156 flags |= PM_STRING_FLAGS_MUTABLE;
6157 break;
6158 case PM_OPTIONS_FROZEN_STRING_LITERAL_ENABLED:
6159 flags |= PM_NODE_FLAG_STATIC_LITERAL | PM_STRING_FLAGS_FROZEN;
6160 break;
6161 }
6162
6163 *node = (pm_source_file_node_t) {
6164 .base = PM_NODE_INIT_TOKEN(parser, PM_SOURCE_FILE_NODE, flags, file_keyword),
6165 .filepath = parser->filepath
6166 };
6167
6168 return node;
6169 }
6170
6171 /**
6172 * Allocate and initialize a new SourceLineNode node.
6173 */
6174 static pm_source_line_node_t *
6175 pm_source_line_node_create(pm_parser_t *parser, const pm_token_t *token) {
6176 assert(token->type == PM_TOKEN_KEYWORD___LINE__);
6177 pm_source_line_node_t *node = PM_NODE_ALLOC(parser, pm_source_line_node_t);
6178
6179 *node = (pm_source_line_node_t) {
6180 .base = PM_NODE_INIT_TOKEN(parser, PM_SOURCE_LINE_NODE, PM_NODE_FLAG_STATIC_LITERAL, token)
6181 };
6182
6183 return node;
6184 }
6185
6186 /**
6187 * Allocate a new SplatNode node.
6188 */
6189 static pm_splat_node_t *
6190 pm_splat_node_create(pm_parser_t *parser, const pm_token_t *operator, pm_node_t *expression) {
6191 pm_splat_node_t *node = PM_NODE_ALLOC(parser, pm_splat_node_t);
6192
6193 *node = (pm_splat_node_t) {
6194 .base = (
6195 (expression == NULL)
6196 ? PM_NODE_INIT_TOKEN(parser, PM_SPLAT_NODE, 0, operator)
6197 : PM_NODE_INIT_TOKEN_NODE(parser, PM_SPLAT_NODE, 0, operator, expression)
6198 ),
6199 .operator_loc = PM_LOCATION_TOKEN_VALUE(operator),
6200 .expression = expression
6201 };
6202
6203 return node;
6204 }
6205
6206 /**
6207 * Allocate and initialize a new StatementsNode node.
6208 */
6209 static pm_statements_node_t *
6210 pm_statements_node_create(pm_parser_t *parser) {
6211 pm_statements_node_t *node = PM_NODE_ALLOC(parser, pm_statements_node_t);
6212
6213 *node = (pm_statements_node_t) {
6214 .base = PM_NODE_INIT_BASE(parser, PM_STATEMENTS_NODE, 0),
6215 .body = { 0 }
6216 };
6217
6218 return node;
6219 }
6220
6221 /**
6222 * Get the length of the given StatementsNode node's body.
6223 */
6224 static size_t
6225 pm_statements_node_body_length(pm_statements_node_t *node) {
6226 return node && node->body.size;
6227 }
6228
6229 /**
6230 * Set the location of the given StatementsNode.
6231 */
6232 static void
6233 pm_statements_node_location_set(pm_statements_node_t *node, const uint8_t *start, const uint8_t *end) {
6234 node->base.location = (pm_location_t) { .start = start, .end = end };
6235 }
6236
6237 /**
6238 * Update the location of the statements node based on the statement that is
6239 * being added to the list.
6240 */
6241 static inline void
6242 pm_statements_node_body_update(pm_statements_node_t *node, pm_node_t *statement) {
6243 if (pm_statements_node_body_length(node) == 0 || statement->location.start < node->base.location.start) {
6244 node->base.location.start = statement->location.start;
6245 }
6246
6247 if (statement->location.end > node->base.location.end) {
6248 node->base.location.end = statement->location.end;
6249 }
6250 }
6251
6252 /**
6253 * Append a new node to the given StatementsNode node's body.
6254 */
6255 static void
6256 pm_statements_node_body_append(pm_parser_t *parser, pm_statements_node_t *node, pm_node_t *statement, bool newline) {
6257 pm_statements_node_body_update(node, statement);
6258
6259 if (node->body.size > 0) {
6260 const pm_node_t *previous = node->body.nodes[node->body.size - 1];
6261
6262 switch (PM_NODE_TYPE(previous)) {
6263 case PM_BREAK_NODE:
6264 case PM_NEXT_NODE:
6265 case PM_REDO_NODE:
6266 case PM_RETRY_NODE:
6267 case PM_RETURN_NODE:
6268 pm_parser_warn_node(parser, statement, PM_WARN_UNREACHABLE_STATEMENT);
6269 break;
6270 default:
6271 break;
6272 }
6273 }
6274
6275 pm_node_list_append(&node->body, statement);
6276 if (newline) pm_node_flag_set(statement, PM_NODE_FLAG_NEWLINE);
6277 }
6278
6279 /**
6280 * Prepend a new node to the given StatementsNode node's body.
6281 */
6282 static void
6283 pm_statements_node_body_prepend(pm_statements_node_t *node, pm_node_t *statement) {
6284 pm_statements_node_body_update(node, statement);
6285 pm_node_list_prepend(&node->body, statement);
6286 pm_node_flag_set(statement, PM_NODE_FLAG_NEWLINE);
6287 }
6288
6289 /**
6290 * Allocate a new StringNode node with the current string on the parser.
6291 */
6292 static inline pm_string_node_t *
6293 pm_string_node_create_unescaped(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *content, const pm_token_t *closing, const pm_string_t *string) {
6294 pm_string_node_t *node = PM_NODE_ALLOC(parser, pm_string_node_t);
6295 pm_node_flags_t flags = 0;
6296
6297 switch (parser->frozen_string_literal) {
6298 case PM_OPTIONS_FROZEN_STRING_LITERAL_DISABLED:
6299 flags = PM_STRING_FLAGS_MUTABLE;
6300 break;
6301 case PM_OPTIONS_FROZEN_STRING_LITERAL_ENABLED:
6302 flags = PM_NODE_FLAG_STATIC_LITERAL | PM_STRING_FLAGS_FROZEN;
6303 break;
6304 }
6305
6306 const uint8_t *start = (opening->type == PM_TOKEN_NOT_PROVIDED ? content->start : opening->start);
6307 const uint8_t *end = (closing->type == PM_TOKEN_NOT_PROVIDED ? content->end : closing->end);
6308
6309 *node = (pm_string_node_t) {
6310 .base = PM_NODE_INIT(parser, PM_STRING_NODE, flags, start, end),
6311 .opening_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(opening),
6312 .content_loc = PM_LOCATION_TOKEN_VALUE(content),
6313 .closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing),
6314 .unescaped = *string
6315 };
6316
6317 return node;
6318 }
6319
6320 /**
6321 * Allocate a new StringNode node.
6322 */
6323 static pm_string_node_t *
6324 pm_string_node_create(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *content, const pm_token_t *closing) {
6325 return pm_string_node_create_unescaped(parser, opening, content, closing, &PM_STRING_EMPTY);
6326 }
6327
6328 /**
6329 * Allocate a new StringNode node and create it using the current string on the
6330 * parser.
6331 */
6332 static pm_string_node_t *
6333 pm_string_node_create_current_string(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *content, const pm_token_t *closing) {
6334 pm_string_node_t *node = pm_string_node_create_unescaped(parser, opening, content, closing, &parser->current_string);
6335 parser->current_string = PM_STRING_EMPTY;
6336 return node;
6337 }
6338
6339 /**
6340 * Allocate and initialize a new SuperNode node.
6341 */
6342 static pm_super_node_t *
6343 pm_super_node_create(pm_parser_t *parser, const pm_token_t *keyword, pm_arguments_t *arguments) {
6344 assert(keyword->type == PM_TOKEN_KEYWORD_SUPER);
6345 pm_super_node_t *node = PM_NODE_ALLOC(parser, pm_super_node_t);
6346
6347 const uint8_t *end = pm_arguments_end(arguments);
6348 if (end == NULL) {
6349 assert(false && "unreachable");
6350 }
6351
6352 *node = (pm_super_node_t) {
6353 .base = PM_NODE_INIT(parser, PM_SUPER_NODE, 0, keyword->start, end),
6354 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
6355 .lparen_loc = arguments->opening_loc,
6356 .arguments = arguments->arguments,
6357 .rparen_loc = arguments->closing_loc,
6358 .block = arguments->block
6359 };
6360
6361 return node;
6362 }
6363
6364 /**
6365 * Read through the contents of a string and check if it consists solely of
6366 * US-ASCII code points.
6367 */
6368 static bool
6369 pm_ascii_only_p(const pm_string_t *contents) {
6370 const size_t length = pm_string_length(contents);
6371 const uint8_t *source = pm_string_source(contents);
6372
6373 for (size_t index = 0; index < length; index++) {
6374 if (source[index] & 0x80) return false;
6375 }
6376
6377 return true;
6378 }
6379
6380 /**
6381 * Validate that the contents of the given symbol are all valid UTF-8.
6382 */
6383 static void
6384 parse_symbol_encoding_validate_utf8(pm_parser_t *parser, const pm_token_t *location, const pm_string_t *contents) {
6385 for (const uint8_t *cursor = pm_string_source(contents), *end = cursor + pm_string_length(contents); cursor < end;) {
6386 size_t width = pm_encoding_utf_8_char_width(cursor, end - cursor);
6387
6388 if (width == 0) {
6389 pm_parser_err(parser, location->start, location->end, PM_ERR_INVALID_SYMBOL);
6390 break;
6391 }
6392
6393 cursor += width;
6394 }
6395 }
6396
6397 /**
6398 * Validate that the contents of the given symbol are all valid in the encoding
6399 * of the parser.
6400 */
6401 static void
6402 parse_symbol_encoding_validate_other(pm_parser_t *parser, const pm_token_t *location, const pm_string_t *contents) {
6403 const pm_encoding_t *encoding = parser->encoding;
6404
6405 for (const uint8_t *cursor = pm_string_source(contents), *end = cursor + pm_string_length(contents); cursor < end;) {
6406 size_t width = encoding->char_width(cursor, end - cursor);
6407
6408 if (width == 0) {
6409 pm_parser_err(parser, location->start, location->end, PM_ERR_INVALID_SYMBOL);
6410 break;
6411 }
6412
6413 cursor += width;
6414 }
6415 }
6416
6417 /**
6418 * Ruby "downgrades" the encoding of Symbols to US-ASCII if the associated
6419 * encoding is ASCII-compatible and the Symbol consists only of US-ASCII code
6420 * points. Otherwise, the encoding may be explicitly set with an escape
6421 * sequence.
6422 *
6423 * If the validate flag is set, then it will check the contents of the symbol
6424 * to ensure that all characters are valid in the encoding.
6425 */
6426 static inline pm_node_flags_t
6427 parse_symbol_encoding(pm_parser_t *parser, const pm_token_t *location, const pm_string_t *contents, bool validate) {
6428 if (parser->explicit_encoding != NULL) {
6429 // A Symbol may optionally have its encoding explicitly set. This will
6430 // happen if an escape sequence results in a non-ASCII code point.
6431 if (parser->explicit_encoding == PM_ENCODING_UTF_8_ENTRY) {
6432 if (validate) parse_symbol_encoding_validate_utf8(parser, location, contents);
6433 return PM_SYMBOL_FLAGS_FORCED_UTF8_ENCODING;
6434 } else if (parser->encoding == PM_ENCODING_US_ASCII_ENTRY) {
6435 return PM_SYMBOL_FLAGS_FORCED_BINARY_ENCODING;
6436 } else if (validate) {
6437 parse_symbol_encoding_validate_other(parser, location, contents);
6438 }
6439 } else if (pm_ascii_only_p(contents)) {
6440 // Ruby stipulates that all source files must use an ASCII-compatible
6441 // encoding. Thus, all symbols appearing in source are eligible for
6442 // "downgrading" to US-ASCII.
6443 return PM_SYMBOL_FLAGS_FORCED_US_ASCII_ENCODING;
6444 } else if (validate) {
6445 parse_symbol_encoding_validate_other(parser, location, contents);
6446 }
6447
6448 return 0;
6449 }
6450
6451 static pm_node_flags_t
6452 parse_and_validate_regular_expression_encoding_modifier(pm_parser_t *parser, const pm_string_t *source, bool ascii_only, pm_node_flags_t flags, char modifier, const pm_encoding_t *modifier_encoding) {
6453 assert ((modifier == 'n' && modifier_encoding == PM_ENCODING_ASCII_8BIT_ENTRY) ||
6454 (modifier == 'u' && modifier_encoding == PM_ENCODING_UTF_8_ENTRY) ||
6455 (modifier == 'e' && modifier_encoding == PM_ENCODING_EUC_JP_ENTRY) ||
6456 (modifier == 's' && modifier_encoding == PM_ENCODING_WINDOWS_31J_ENTRY));
6457
6458 // There's special validation logic used if a string does not contain any character escape sequences.
6459 if (parser->explicit_encoding == NULL) {
6460 // If an ASCII-only string without character escapes is used with an encoding modifier, then resulting Regexp
6461 // has the modifier encoding, unless the ASCII-8BIT modifier is used, in which case the Regexp "downgrades" to
6462 // the US-ASCII encoding.
6463 if (ascii_only) {
6464 return modifier == 'n' ? PM_REGULAR_EXPRESSION_FLAGS_FORCED_US_ASCII_ENCODING : flags;
6465 }
6466
6467 if (parser->encoding == PM_ENCODING_US_ASCII_ENTRY) {
6468 if (!ascii_only) {
6469 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_INVALID_MULTIBYTE_CHAR, parser->encoding->name);
6470 }
6471 } else if (parser->encoding != modifier_encoding) {
6472 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_REGEXP_ENCODING_OPTION_MISMATCH, modifier, parser->encoding->name);
6473
6474 if (modifier == 'n' && !ascii_only) {
6475 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_REGEXP_NON_ESCAPED_MBC, (int) pm_string_length(source), (const char *) pm_string_source(source));
6476 }
6477 }
6478
6479 return flags;
6480 }
6481
6482 // TODO (nirvdrum 21-Feb-2024): To validate regexp sources with character escape sequences we need to know whether hex or Unicode escape sequences were used and Prism doesn't currently provide that data. We handle a subset of unambiguous cases in the meanwhile.
6483 bool mixed_encoding = false;
6484
6485 if (mixed_encoding) {
6486 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_INVALID_MULTIBYTE_ESCAPE, (int) pm_string_length(source), (const char *) pm_string_source(source));
6487 } else if (modifier != 'n' && parser->explicit_encoding == PM_ENCODING_ASCII_8BIT_ENTRY) {
6488 // TODO (nirvdrum 21-Feb-2024): Validate the content is valid in the modifier encoding. Do this on-demand so we don't pay the cost of computation unnecessarily.
6489 bool valid_string_in_modifier_encoding = true;
6490
6491 if (!valid_string_in_modifier_encoding) {
6492 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_INVALID_MULTIBYTE_ESCAPE, (int) pm_string_length(source), (const char *) pm_string_source(source));
6493 }
6494 } else if (modifier != 'u' && parser->explicit_encoding == PM_ENCODING_UTF_8_ENTRY) {
6495 // TODO (nirvdrum 21-Feb-2024): There's currently no way to tell if the source used hex or Unicode character escapes from `explicit_encoding` alone. If the source encoding was already UTF-8, both character escape types would set `explicit_encoding` to UTF-8, but need to be processed differently. Skip for now.
6496 if (parser->encoding != PM_ENCODING_UTF_8_ENTRY) {
6497 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_REGEXP_INCOMPAT_CHAR_ENCODING, (int) pm_string_length(source), (const char *) pm_string_source(source));
6498 }
6499 }
6500
6501 // We've determined the encoding would naturally be EUC-JP and there is no need to force the encoding to anything else.
6502 return flags;
6503 }
6504
6505 /**
6506 * Ruby "downgrades" the encoding of Regexps to US-ASCII if the associated encoding is ASCII-compatible and
6507 * the unescaped representation of a Regexp source consists only of US-ASCII code points. This is true even
6508 * when the Regexp is explicitly given an ASCII-8BIT encoding via the (/n) modifier. Otherwise, the encoding
6509 * may be explicitly set with an escape sequence.
6510 */
6511 static pm_node_flags_t
6512 parse_and_validate_regular_expression_encoding(pm_parser_t *parser, const pm_string_t *source, bool ascii_only, pm_node_flags_t flags) {
6513 // TODO (nirvdrum 22-Feb-2024): CRuby reports a special Regexp-specific error for invalid Unicode ranges. We either need to scan again or modify the "invalid Unicode escape sequence" message we already report.
6514 bool valid_unicode_range = true;
6515 if (parser->explicit_encoding == PM_ENCODING_UTF_8_ENTRY && !valid_unicode_range) {
6516 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_REGEXP_INVALID_UNICODE_RANGE, (int) pm_string_length(source), (const char *) pm_string_source(source));
6517 return flags;
6518 }
6519
6520 // US-ASCII strings do not admit multi-byte character literals. However, character escape sequences corresponding
6521 // to multi-byte characters are allowed.
6522 if (parser->encoding == PM_ENCODING_US_ASCII_ENTRY && parser->explicit_encoding == NULL && !ascii_only) {
6523 // CRuby will continue processing even though a SyntaxError has already been detected. It may result in the
6524 // following error message appearing twice. We do the same for compatibility.
6525 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_INVALID_MULTIBYTE_CHAR, parser->encoding->name);
6526 }
6527
6528 /**
6529 * Start checking modifier flags. We need to process these before considering any explicit encodings that may have
6530 * been set by character literals. The order in which the encoding modifiers is checked does not matter. In the
6531 * event that both an encoding modifier and an explicit encoding would result in the same encoding we do not set
6532 * the corresponding "forced_<encoding>" flag. Instead, the caller should check the encoding modifier flag and
6533 * determine the encoding that way.
6534 */
6535
6536 if (flags & PM_REGULAR_EXPRESSION_FLAGS_ASCII_8BIT) {
6537 return parse_and_validate_regular_expression_encoding_modifier(parser, source, ascii_only, flags, 'n', PM_ENCODING_ASCII_8BIT_ENTRY);
6538 }
6539
6540 if (flags & PM_REGULAR_EXPRESSION_FLAGS_UTF_8) {
6541 return parse_and_validate_regular_expression_encoding_modifier(parser, source, ascii_only, flags, 'u', PM_ENCODING_UTF_8_ENTRY);
6542 }
6543
6544 if (flags & PM_REGULAR_EXPRESSION_FLAGS_EUC_JP) {
6545 return parse_and_validate_regular_expression_encoding_modifier(parser, source, ascii_only, flags, 'e', PM_ENCODING_EUC_JP_ENTRY);
6546 }
6547
6548 if (flags & PM_REGULAR_EXPRESSION_FLAGS_WINDOWS_31J) {
6549 return parse_and_validate_regular_expression_encoding_modifier(parser, source, ascii_only, flags, 's', PM_ENCODING_WINDOWS_31J_ENTRY);
6550 }
6551
6552 // At this point no encoding modifiers will be present on the regular expression as they would have already
6553 // been processed. Ruby stipulates that all source files must use an ASCII-compatible encoding. Thus, all
6554 // regular expressions without an encoding modifier appearing in source are eligible for "downgrading" to US-ASCII.
6555 if (ascii_only) {
6556 return PM_REGULAR_EXPRESSION_FLAGS_FORCED_US_ASCII_ENCODING;
6557 }
6558
6559 // A Regexp may optionally have its encoding explicitly set via a character escape sequence in the source string
6560 // or by specifying a modifier.
6561 //
6562 // NB: an explicitly set encoding is ignored by Ruby if the Regexp consists of only US ASCII code points.
6563 if (parser->explicit_encoding != NULL) {
6564 if (parser->explicit_encoding == PM_ENCODING_UTF_8_ENTRY) {
6565 return PM_REGULAR_EXPRESSION_FLAGS_FORCED_UTF8_ENCODING;
6566 } else if (parser->encoding == PM_ENCODING_US_ASCII_ENTRY) {
6567 return PM_REGULAR_EXPRESSION_FLAGS_FORCED_BINARY_ENCODING;
6568 }
6569 }
6570
6571 return 0;
6572 }
6573
6574 /**
6575 * Allocate and initialize a new SymbolNode node with the given unescaped
6576 * string.
6577 */
6578 static pm_symbol_node_t *
6579 pm_symbol_node_create_unescaped(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *value, const pm_token_t *closing, const pm_string_t *unescaped, pm_node_flags_t flags) {
6580 pm_symbol_node_t *node = PM_NODE_ALLOC(parser, pm_symbol_node_t);
6581
6582 const uint8_t *start = (opening->type == PM_TOKEN_NOT_PROVIDED ? value->start : opening->start);
6583 const uint8_t *end = (closing->type == PM_TOKEN_NOT_PROVIDED ? value->end : closing->end);
6584
6585 *node = (pm_symbol_node_t) {
6586 .base = PM_NODE_INIT(parser, PM_SYMBOL_NODE, PM_NODE_FLAG_STATIC_LITERAL | flags, start, end),
6587 .opening_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(opening),
6588 .value_loc = PM_LOCATION_TOKEN_VALUE(value),
6589 .closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing),
6590 .unescaped = *unescaped
6591 };
6592
6593 return node;
6594 }
6595
6596 /**
6597 * Allocate and initialize a new SymbolNode node.
6598 */
6599 static inline pm_symbol_node_t *
6600 pm_symbol_node_create(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *value, const pm_token_t *closing) {
6601 return pm_symbol_node_create_unescaped(parser, opening, value, closing, &PM_STRING_EMPTY, 0);
6602 }
6603
6604 /**
6605 * Allocate and initialize a new SymbolNode node with the current string.
6606 */
6607 static pm_symbol_node_t *
6608 pm_symbol_node_create_current_string(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *value, const pm_token_t *closing) {
6609 pm_symbol_node_t *node = pm_symbol_node_create_unescaped(parser, opening, value, closing, &parser->current_string, parse_symbol_encoding(parser, value, &parser->current_string, false));
6610 parser->current_string = PM_STRING_EMPTY;
6611 return node;
6612 }
6613
6614 /**
6615 * Allocate and initialize a new SymbolNode node from a label.
6616 */
6617 static pm_symbol_node_t *
6618 pm_symbol_node_label_create(pm_parser_t *parser, const pm_token_t *token) {
6619 pm_symbol_node_t *node;
6620
6621 switch (token->type) {
6622 case PM_TOKEN_LABEL: {
6623 pm_token_t opening = not_provided(parser);
6624 pm_token_t closing = { .type = PM_TOKEN_LABEL_END, .start = token->end - 1, .end = token->end };
6625
6626 pm_token_t label = { .type = PM_TOKEN_LABEL, .start = token->start, .end = token->end - 1 };
6627 node = pm_symbol_node_create(parser, &opening, &label, &closing);
6628
6629 assert((label.end - label.start) >= 0);
6630 pm_string_shared_init(&node->unescaped, label.start, label.end);
6631 pm_node_flag_set(UP(node), parse_symbol_encoding(parser, &label, &node->unescaped, false));
6632
6633 break;
6634 }
6635 case PM_TOKEN_MISSING: {
6636 pm_token_t opening = not_provided(parser);
6637 pm_token_t closing = not_provided(parser);
6638
6639 pm_token_t label = { .type = PM_TOKEN_LABEL, .start = token->start, .end = token->end };
6640 node = pm_symbol_node_create(parser, &opening, &label, &closing);
6641 break;
6642 }
6643 default:
6644 assert(false && "unreachable");
6645 node = NULL;
6646 break;
6647 }
6648
6649 return node;
6650 }
6651
6652 /**
6653 * Allocate and initialize a new synthesized SymbolNode node.
6654 */
6655 static pm_symbol_node_t *
6656 pm_symbol_node_synthesized_create(pm_parser_t *parser, const char *content) {
6657 pm_symbol_node_t *node = PM_NODE_ALLOC(parser, pm_symbol_node_t);
6658
6659 *node = (pm_symbol_node_t) {
6660 .base = PM_NODE_INIT_BASE(parser, PM_SYMBOL_NODE, PM_NODE_FLAG_STATIC_LITERAL | PM_SYMBOL_FLAGS_FORCED_US_ASCII_ENCODING),
6661 .value_loc = PM_LOCATION_NULL_VALUE(parser),
6662 .unescaped = { 0 }
6663 };
6664
6665 pm_string_constant_init(&node->unescaped, content, strlen(content));
6666 return node;
6667 }
6668
6669 /**
6670 * Check if the given node is a label in a hash.
6671 */
6672 static bool
6673 pm_symbol_node_label_p(pm_node_t *node) {
6674 const uint8_t *end = NULL;
6675
6676 switch (PM_NODE_TYPE(node)) {
6677 case PM_SYMBOL_NODE:
6678 end = ((pm_symbol_node_t *) node)->closing_loc.end;
6679 break;
6680 case PM_INTERPOLATED_SYMBOL_NODE:
6681 end = ((pm_interpolated_symbol_node_t *) node)->closing_loc.end;
6682 break;
6683 default:
6684 return false;
6685 }
6686
6687 return (end != NULL) && (end[-1] == ':');
6688 }
6689
6690 /**
6691 * Convert the given StringNode node to a SymbolNode node.
6692 */
6693 static pm_symbol_node_t *
6694 pm_string_node_to_symbol_node(pm_parser_t *parser, pm_string_node_t *node, const pm_token_t *opening, const pm_token_t *closing) {
6695 pm_symbol_node_t *new_node = PM_NODE_ALLOC(parser, pm_symbol_node_t);
6696
6697 *new_node = (pm_symbol_node_t) {
6698 .base = PM_NODE_INIT_TOKENS(parser, PM_SYMBOL_NODE, PM_NODE_FLAG_STATIC_LITERAL, opening, closing),
6699 .opening_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(opening),
6700 .value_loc = node->content_loc,
6701 .closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing),
6702 .unescaped = node->unescaped
6703 };
6704
6705 pm_token_t content = { .type = PM_TOKEN_IDENTIFIER, .start = node->content_loc.start, .end = node->content_loc.end };
6706 pm_node_flag_set(UP(new_node), parse_symbol_encoding(parser, &content, &node->unescaped, true));
6707
6708 // We are explicitly _not_ using pm_node_destroy here because we don't want
6709 // to trash the unescaped string. We could instead copy the string if we
6710 // know that it is owned, but we're taking the fast path for now.
6711 xfree(node);
6712
6713 return new_node;
6714 }
6715
6716 /**
6717 * Convert the given SymbolNode node to a StringNode node.
6718 */
6719 static pm_string_node_t *
6720 pm_symbol_node_to_string_node(pm_parser_t *parser, pm_symbol_node_t *node) {
6721 pm_string_node_t *new_node = PM_NODE_ALLOC(parser, pm_string_node_t);
6722 pm_node_flags_t flags = 0;
6723
6724 switch (parser->frozen_string_literal) {
6725 case PM_OPTIONS_FROZEN_STRING_LITERAL_DISABLED:
6726 flags = PM_STRING_FLAGS_MUTABLE;
6727 break;
6728 case PM_OPTIONS_FROZEN_STRING_LITERAL_ENABLED:
6729 flags = PM_NODE_FLAG_STATIC_LITERAL | PM_STRING_FLAGS_FROZEN;
6730 break;
6731 }
6732
6733 *new_node = (pm_string_node_t) {
6734 .base = PM_NODE_INIT_NODE(parser, PM_STRING_NODE, flags, node),
6735 .opening_loc = node->opening_loc,
6736 .content_loc = node->value_loc,
6737 .closing_loc = node->closing_loc,
6738 .unescaped = node->unescaped
6739 };
6740
6741 // We are explicitly _not_ using pm_node_destroy here because we don't want
6742 // to trash the unescaped string. We could instead copy the string if we
6743 // know that it is owned, but we're taking the fast path for now.
6744 xfree(node);
6745
6746 return new_node;
6747 }
6748
6749 /**
6750 * Allocate and initialize a new TrueNode node.
6751 */
6752 static pm_true_node_t *
6753 pm_true_node_create(pm_parser_t *parser, const pm_token_t *token) {
6754 assert(token->type == PM_TOKEN_KEYWORD_TRUE);
6755 pm_true_node_t *node = PM_NODE_ALLOC(parser, pm_true_node_t);
6756
6757 *node = (pm_true_node_t) {
6758 .base = PM_NODE_INIT_TOKEN(parser, PM_TRUE_NODE, PM_NODE_FLAG_STATIC_LITERAL, token)
6759 };
6760
6761 return node;
6762 }
6763
6764 /**
6765 * Allocate and initialize a new synthesized TrueNode node.
6766 */
6767 static pm_true_node_t *
6768 pm_true_node_synthesized_create(pm_parser_t *parser) {
6769 pm_true_node_t *node = PM_NODE_ALLOC(parser, pm_true_node_t);
6770
6771 *node = (pm_true_node_t) {
6772 .base = PM_NODE_INIT_BASE(parser, PM_TRUE_NODE, PM_NODE_FLAG_STATIC_LITERAL)
6773 };
6774
6775 return node;
6776 }
6777
6778 /**
6779 * Allocate and initialize a new UndefNode node.
6780 */
6781 static pm_undef_node_t *
6782 pm_undef_node_create(pm_parser_t *parser, const pm_token_t *token) {
6783 assert(token->type == PM_TOKEN_KEYWORD_UNDEF);
6784 pm_undef_node_t *node = PM_NODE_ALLOC(parser, pm_undef_node_t);
6785
6786 *node = (pm_undef_node_t) {
6787 .base = PM_NODE_INIT_TOKEN(parser, PM_UNDEF_NODE, 0, token),
6788 .keyword_loc = PM_LOCATION_TOKEN_VALUE(token),
6789 .names = { 0 }
6790 };
6791
6792 return node;
6793 }
6794
6795 /**
6796 * Append a name to an undef node.
6797 */
6798 static void
6799 pm_undef_node_append(pm_undef_node_t *node, pm_node_t *name) {
6800 node->base.location.end = name->location.end;
6801 pm_node_list_append(&node->names, name);
6802 }
6803
6804 /**
6805 * Allocate a new UnlessNode node.
6806 */
6807 static pm_unless_node_t *
6808 pm_unless_node_create(pm_parser_t *parser, const pm_token_t *keyword, pm_node_t *predicate, const pm_token_t *then_keyword, pm_statements_node_t *statements) {
6809 pm_conditional_predicate(parser, predicate, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
6810
6811 pm_unless_node_t *node = PM_NODE_ALLOC(parser, pm_unless_node_t);
6812 pm_node_t *end = statements == NULL ? predicate : UP(statements);
6813
6814 *node = (pm_unless_node_t) {
6815 .base = PM_NODE_INIT_TOKEN_NODE(parser, PM_UNLESS_NODE, PM_NODE_FLAG_NEWLINE, keyword, end),
6816 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
6817 .predicate = predicate,
6818 .then_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(then_keyword),
6819 .statements = statements,
6820 .else_clause = NULL,
6821 .end_keyword_loc = { 0 }
6822 };
6823
6824 return node;
6825 }
6826
6827 /**
6828 * Allocate and initialize new UnlessNode node in the modifier form.
6829 */
6830 static pm_unless_node_t *
6831 pm_unless_node_modifier_create(pm_parser_t *parser, pm_node_t *statement, const pm_token_t *unless_keyword, pm_node_t *predicate) {
6832 pm_conditional_predicate(parser, predicate, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
6833 pm_unless_node_t *node = PM_NODE_ALLOC(parser, pm_unless_node_t);
6834
6835 pm_statements_node_t *statements = pm_statements_node_create(parser);
6836 pm_statements_node_body_append(parser, statements, statement, true);
6837
6838 *node = (pm_unless_node_t) {
6839 .base = PM_NODE_INIT_NODES(parser, PM_UNLESS_NODE, PM_NODE_FLAG_NEWLINE, statement, predicate),
6840 .keyword_loc = PM_LOCATION_TOKEN_VALUE(unless_keyword),
6841 .predicate = predicate,
6842 .then_keyword_loc = { 0 },
6843 .statements = statements,
6844 .else_clause = NULL,
6845 .end_keyword_loc = { 0 }
6846 };
6847
6848 return node;
6849 }
6850
6851 static inline void
6852 pm_unless_node_end_keyword_loc_set(pm_unless_node_t *node, const pm_token_t *end_keyword) {
6853 node->end_keyword_loc = PM_LOCATION_TOKEN_VALUE(end_keyword);
6854 node->base.location.end = end_keyword->end;
6855 }
6856
6857 /**
6858 * Loop modifiers could potentially modify an expression that contains block
6859 * exits. In this case we need to loop through them and remove them from the
6860 * list of block exits so that they do not later get marked as invalid.
6861 */
6862 static void
6863 pm_loop_modifier_block_exits(pm_parser_t *parser, pm_statements_node_t *statements) {
6864 assert(parser->current_block_exits != NULL);
6865
6866 // All of the block exits that we want to remove should be within the
6867 // statements, and since we are modifying the statements, we shouldn't have
6868 // to check the end location.
6869 const uint8_t *start = statements->base.location.start;
6870
6871 for (size_t index = parser->current_block_exits->size; index > 0; index--) {
6872 pm_node_t *block_exit = parser->current_block_exits->nodes[index - 1];
6873 if (block_exit->location.start < start) break;
6874
6875 // Implicitly remove from the list by lowering the size.
6876 parser->current_block_exits->size--;
6877 }
6878 }
6879
6880 /**
6881 * Allocate a new UntilNode node.
6882 */
6883 static pm_until_node_t *
6884 pm_until_node_create(pm_parser_t *parser, const pm_token_t *keyword, const pm_token_t *do_keyword, const pm_token_t *closing, pm_node_t *predicate, pm_statements_node_t *statements, pm_node_flags_t flags) {
6885 pm_until_node_t *node = PM_NODE_ALLOC(parser, pm_until_node_t);
6886 pm_conditional_predicate(parser, predicate, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
6887
6888 *node = (pm_until_node_t) {
6889 .base = PM_NODE_INIT_TOKENS(parser, PM_UNTIL_NODE, flags, keyword, closing),
6890 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
6891 .do_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(do_keyword),
6892 .closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing),
6893 .predicate = predicate,
6894 .statements = statements
6895 };
6896
6897 return node;
6898 }
6899
6900 /**
6901 * Allocate a new UntilNode node.
6902 */
6903 static pm_until_node_t *
6904 pm_until_node_modifier_create(pm_parser_t *parser, const pm_token_t *keyword, pm_node_t *predicate, pm_statements_node_t *statements, pm_node_flags_t flags) {
6905 pm_until_node_t *node = PM_NODE_ALLOC(parser, pm_until_node_t);
6906 pm_conditional_predicate(parser, predicate, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
6907 pm_loop_modifier_block_exits(parser, statements);
6908
6909 *node = (pm_until_node_t) {
6910 .base = PM_NODE_INIT_NODES(parser, PM_UNTIL_NODE, flags, statements, predicate),
6911 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
6912 .do_keyword_loc = { 0 },
6913 .closing_loc = { 0 },
6914 .predicate = predicate,
6915 .statements = statements
6916 };
6917
6918 return node;
6919 }
6920
6921 /**
6922 * Allocate and initialize a new WhenNode node.
6923 */
6924 static pm_when_node_t *
6925 pm_when_node_create(pm_parser_t *parser, const pm_token_t *keyword) {
6926 pm_when_node_t *node = PM_NODE_ALLOC(parser, pm_when_node_t);
6927
6928 *node = (pm_when_node_t) {
6929 .base = PM_NODE_INIT_TOKEN(parser, PM_WHEN_NODE, 0, keyword),
6930 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
6931 .statements = NULL,
6932 .then_keyword_loc = { 0 },
6933 .conditions = { 0 }
6934 };
6935
6936 return node;
6937 }
6938
6939 /**
6940 * Append a new condition to a when node.
6941 */
6942 static void
6943 pm_when_node_conditions_append(pm_when_node_t *node, pm_node_t *condition) {
6944 node->base.location.end = condition->location.end;
6945 pm_node_list_append(&node->conditions, condition);
6946 }
6947
6948 /**
6949 * Set the location of the then keyword of a when node.
6950 */
6951 static inline void
6952 pm_when_node_then_keyword_loc_set(pm_when_node_t *node, const pm_token_t *then_keyword) {
6953 node->base.location.end = then_keyword->end;
6954 node->then_keyword_loc = PM_LOCATION_TOKEN_VALUE(then_keyword);
6955 }
6956
6957 /**
6958 * Set the statements list of a when node.
6959 */
6960 static void
6961 pm_when_node_statements_set(pm_when_node_t *node, pm_statements_node_t *statements) {
6962 if (statements->base.location.end > node->base.location.end) {
6963 node->base.location.end = statements->base.location.end;
6964 }
6965
6966 node->statements = statements;
6967 }
6968
6969 /**
6970 * Allocate a new WhileNode node.
6971 */
6972 static pm_while_node_t *
6973 pm_while_node_create(pm_parser_t *parser, const pm_token_t *keyword, const pm_token_t *do_keyword, const pm_token_t *closing, pm_node_t *predicate, pm_statements_node_t *statements, pm_node_flags_t flags) {
6974 pm_while_node_t *node = PM_NODE_ALLOC(parser, pm_while_node_t);
6975 pm_conditional_predicate(parser, predicate, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
6976
6977 *node = (pm_while_node_t) {
6978 .base = PM_NODE_INIT_TOKENS(parser, PM_WHILE_NODE, flags, keyword, closing),
6979 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
6980 .do_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(do_keyword),
6981 .closing_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(closing),
6982 .predicate = predicate,
6983 .statements = statements
6984 };
6985
6986 return node;
6987 }
6988
6989 /**
6990 * Allocate a new WhileNode node.
6991 */
6992 static pm_while_node_t *
6993 pm_while_node_modifier_create(pm_parser_t *parser, const pm_token_t *keyword, pm_node_t *predicate, pm_statements_node_t *statements, pm_node_flags_t flags) {
6994 pm_while_node_t *node = PM_NODE_ALLOC(parser, pm_while_node_t);
6995 pm_conditional_predicate(parser, predicate, PM_CONDITIONAL_PREDICATE_TYPE_CONDITIONAL);
6996 pm_loop_modifier_block_exits(parser, statements);
6997
6998 *node = (pm_while_node_t) {
6999 .base = PM_NODE_INIT_NODES(parser, PM_WHILE_NODE, flags, statements, predicate),
7000 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
7001 .do_keyword_loc = { 0 },
7002 .closing_loc = { 0 },
7003 .predicate = predicate,
7004 .statements = statements
7005 };
7006
7007 return node;
7008 }
7009
7010 /**
7011 * Allocate and initialize a new synthesized while loop.
7012 */
7013 static pm_while_node_t *
7014 pm_while_node_synthesized_create(pm_parser_t *parser, pm_node_t *predicate, pm_statements_node_t *statements) {
7015 pm_while_node_t *node = PM_NODE_ALLOC(parser, pm_while_node_t);
7016
7017 *node = (pm_while_node_t) {
7018 .base = PM_NODE_INIT_BASE(parser, PM_WHILE_NODE, 0),
7019 .keyword_loc = PM_LOCATION_NULL_VALUE(parser),
7020 .do_keyword_loc = PM_LOCATION_NULL_VALUE(parser),
7021 .closing_loc = PM_LOCATION_NULL_VALUE(parser),
7022 .predicate = predicate,
7023 .statements = statements
7024 };
7025
7026 return node;
7027 }
7028
7029 /**
7030 * Allocate and initialize a new XStringNode node with the given unescaped
7031 * string.
7032 */
7033 static pm_x_string_node_t *
7034 pm_xstring_node_create_unescaped(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *content, const pm_token_t *closing, const pm_string_t *unescaped) {
7035 pm_x_string_node_t *node = PM_NODE_ALLOC(parser, pm_x_string_node_t);
7036
7037 *node = (pm_x_string_node_t) {
7038 .base = PM_NODE_INIT_TOKENS(parser, PM_X_STRING_NODE, PM_STRING_FLAGS_FROZEN, opening, closing),
7039 .opening_loc = PM_LOCATION_TOKEN_VALUE(opening),
7040 .content_loc = PM_LOCATION_TOKEN_VALUE(content),
7041 .closing_loc = PM_LOCATION_TOKEN_VALUE(closing),
7042 .unescaped = *unescaped
7043 };
7044
7045 return node;
7046 }
7047
7048 /**
7049 * Allocate and initialize a new XStringNode node.
7050 */
7051 static inline pm_x_string_node_t *
7052 pm_xstring_node_create(pm_parser_t *parser, const pm_token_t *opening, const pm_token_t *content, const pm_token_t *closing) {
7053 return pm_xstring_node_create_unescaped(parser, opening, content, closing, &PM_STRING_EMPTY);
7054 }
7055
7056 /**
7057 * Allocate a new YieldNode node.
7058 */
7059 static pm_yield_node_t *
7060 pm_yield_node_create(pm_parser_t *parser, const pm_token_t *keyword, const pm_location_t *lparen_loc, pm_arguments_node_t *arguments, const pm_location_t *rparen_loc) {
7061 pm_yield_node_t *node = PM_NODE_ALLOC(parser, pm_yield_node_t);
7062
7063 const uint8_t *end;
7064 if (rparen_loc->start != NULL) {
7065 end = rparen_loc->end;
7066 } else if (arguments != NULL) {
7067 end = arguments->base.location.end;
7068 } else if (lparen_loc->start != NULL) {
7069 end = lparen_loc->end;
7070 } else {
7071 end = keyword->end;
7072 }
7073
7074 *node = (pm_yield_node_t) {
7075 .base = PM_NODE_INIT(parser, PM_YIELD_NODE, 0, keyword->start, end),
7076 .keyword_loc = PM_LOCATION_TOKEN_VALUE(keyword),
7077 .lparen_loc = *lparen_loc,
7078 .arguments = arguments,
7079 .rparen_loc = *rparen_loc
7080 };
7081
7082 return node;
7083 }
7084
7085 /**
7086 * Check if any of the currently visible scopes contain a local variable
7087 * described by the given constant id.
7088 */
7089 static int
7090 pm_parser_local_depth_constant_id(pm_parser_t *parser, pm_constant_id_t constant_id) {
7091 pm_scope_t *scope = parser->current_scope;
7092 int depth = 0;
7093
7094 while (scope != NULL) {
7095 if (pm_locals_find(&scope->locals, constant_id) != UINT32_MAX) return depth;
7096 if (scope->closed) break;
7097
7098 scope = scope->previous;
7099 depth++;
7100 }
7101
7102 return -1;
7103 }
7104
7105 /**
7106 * Check if any of the currently visible scopes contain a local variable
7107 * described by the given token. This function implicitly inserts a constant
7108 * into the constant pool.
7109 */
7110 static inline int
7111 pm_parser_local_depth(pm_parser_t *parser, pm_token_t *token) {
7112 return pm_parser_local_depth_constant_id(parser, pm_parser_constant_id_token(parser, token));
7113 }
7114
7115 /**
7116 * Add a constant id to the local table of the current scope.
7117 */
7118 static inline void
7119 pm_parser_local_add(pm_parser_t *parser, pm_constant_id_t constant_id, const uint8_t *start, const uint8_t *end, uint32_t reads) {
7120 pm_locals_write(&parser->current_scope->locals, constant_id, start, end, reads);
7121 }
7122
7123 /**
7124 * Add a local variable from a location to the current scope.
7125 */
7126 static pm_constant_id_t
7127 pm_parser_local_add_location(pm_parser_t *parser, const uint8_t *start, const uint8_t *end, uint32_t reads) {
7128 pm_constant_id_t constant_id = pm_parser_constant_id_location(parser, start, end);
7129 if (constant_id != 0) pm_parser_local_add(parser, constant_id, start, end, reads);
7130 return constant_id;
7131 }
7132
7133 /**
7134 * Add a local variable from a token to the current scope.
7135 */
7136 static inline pm_constant_id_t
7137 pm_parser_local_add_token(pm_parser_t *parser, pm_token_t *token, uint32_t reads) {
7138 return pm_parser_local_add_location(parser, token->start, token->end, reads);
7139 }
7140
7141 /**
7142 * Add a local variable from an owned string to the current scope.
7143 */
7144 static pm_constant_id_t
7145 pm_parser_local_add_owned(pm_parser_t *parser, uint8_t *start, size_t length) {
7146 pm_constant_id_t constant_id = pm_parser_constant_id_owned(parser, start, length);
7147 if (constant_id != 0) pm_parser_local_add(parser, constant_id, parser->start, parser->start, 1);
7148 return constant_id;
7149 }
7150
7151 /**
7152 * Add a local variable from a constant string to the current scope.
7153 */
7154 static pm_constant_id_t
7155 pm_parser_local_add_constant(pm_parser_t *parser, const char *start, size_t length) {
7156 pm_constant_id_t constant_id = pm_parser_constant_id_constant(parser, start, length);
7157 if (constant_id != 0) pm_parser_local_add(parser, constant_id, parser->start, parser->start, 1);
7158 return constant_id;
7159 }
7160
7161 /**
7162 * Add a parameter name to the current scope and check whether the name of the
7163 * parameter is unique or not.
7164 *
7165 * Returns `true` if this is a duplicate parameter name, otherwise returns
7166 * false.
7167 */
7168 static bool
7169 pm_parser_parameter_name_check(pm_parser_t *parser, const pm_token_t *name) {
7170 // We want to check whether the parameter name is a numbered parameter or
7171 // not.
7172 pm_refute_numbered_parameter(parser, name->start, name->end);
7173
7174 // Otherwise we'll fetch the constant id for the parameter name and check
7175 // whether it's already in the current scope.
7176 pm_constant_id_t constant_id = pm_parser_constant_id_token(parser, name);
7177
7178 if (pm_locals_find(&parser->current_scope->locals, constant_id) != UINT32_MAX) {
7179 // Add an error if the parameter doesn't start with _ and has been seen before
7180 if ((name->start < name->end) && (*name->start != '_')) {
7181 pm_parser_err_token(parser, name, PM_ERR_PARAMETER_NAME_DUPLICATED);
7182 }
7183 return true;
7184 }
7185 return false;
7186 }
7187
7188 /**
7189 * Pop the current scope off the scope stack.
7190 */
7191 static void
7192 pm_parser_scope_pop(pm_parser_t *parser) {
7193 pm_scope_t *scope = parser->current_scope;
7194 parser->current_scope = scope->previous;
7195 pm_locals_free(&scope->locals);
7196 pm_node_list_free(&scope->implicit_parameters);
7197 xfree(scope);
7198 }
7199
7200 /******************************************************************************/
7201 /* Stack helpers */
7202 /******************************************************************************/
7203
7204 /**
7205 * Pushes a value onto the stack.
7206 */
7207 static inline void
7208 pm_state_stack_push(pm_state_stack_t *stack, bool value) {
7209 *stack = (*stack << 1) | (value & 1);
7210 }
7211
7212 /**
7213 * Pops a value off the stack.
7214 */
7215 static inline void
7216 pm_state_stack_pop(pm_state_stack_t *stack) {
7217 *stack >>= 1;
7218 }
7219
7220 /**
7221 * Returns the value at the top of the stack.
7222 */
7223 static inline bool
7224 pm_state_stack_p(const pm_state_stack_t *stack) {
7225 return *stack & 1;
7226 }
7227
7228 static inline void
7229 pm_accepts_block_stack_push(pm_parser_t *parser, bool value) {
7230 // Use the negation of the value to prevent stack overflow.
7231 pm_state_stack_push(&parser->accepts_block_stack, !value);
7232 }
7233
7234 static inline void
7235 pm_accepts_block_stack_pop(pm_parser_t *parser) {
7236 pm_state_stack_pop(&parser->accepts_block_stack);
7237 }
7238
7239 static inline bool
7240 pm_accepts_block_stack_p(pm_parser_t *parser) {
7241 return !pm_state_stack_p(&parser->accepts_block_stack);
7242 }
7243
7244 static inline void
7245 pm_do_loop_stack_push(pm_parser_t *parser, bool value) {
7246 pm_state_stack_push(&parser->do_loop_stack, value);
7247 }
7248
7249 static inline void
7250 pm_do_loop_stack_pop(pm_parser_t *parser) {
7251 pm_state_stack_pop(&parser->do_loop_stack);
7252 }
7253
7254 static inline bool
7255 pm_do_loop_stack_p(pm_parser_t *parser) {
7256 return pm_state_stack_p(&parser->do_loop_stack);
7257 }
7258
7259 /******************************************************************************/
7260 /* Lexer check helpers */
7261 /******************************************************************************/
7262
7263 /**
7264 * Get the next character in the source starting from +cursor+. If that position
7265 * is beyond the end of the source then return '\0'.
7266 */
7267 static inline uint8_t
7268 peek_at(const pm_parser_t *parser, const uint8_t *cursor) {
7269 if (cursor < parser->end) {
7270 return *cursor;
7271 } else {
7272 return '\0';
7273 }
7274 }
7275
7276 /**
7277 * Get the next character in the source starting from parser->current.end and
7278 * adding the given offset. If that position is beyond the end of the source
7279 * then return '\0'.
7280 */
7281 static inline uint8_t
7282 peek_offset(pm_parser_t *parser, ptrdiff_t offset) {
7283 return peek_at(parser, parser->current.end + offset);
7284 }
7285
7286 /**
7287 * Get the next character in the source starting from parser->current.end. If
7288 * that position is beyond the end of the source then return '\0'.
7289 */
7290 static inline uint8_t
7291 peek(const pm_parser_t *parser) {
7292 return peek_at(parser, parser->current.end);
7293 }
7294
7295 /**
7296 * If the character to be read matches the given value, then returns true and
7297 * advances the current pointer.
7298 */
7299 static inline bool
7300 match(pm_parser_t *parser, uint8_t value) {
7301 if (peek(parser) == value) {
7302 parser->current.end++;
7303 return true;
7304 }
7305 return false;
7306 }
7307
7308 /**
7309 * Return the length of the line ending string starting at +cursor+, or 0 if it
7310 * is not a line ending. This function is intended to be CRLF/LF agnostic.
7311 */
7312 static inline size_t
7313 match_eol_at(pm_parser_t *parser, const uint8_t *cursor) {
7314 if (peek_at(parser, cursor) == '\n') {
7315 return 1;
7316 }
7317 if (peek_at(parser, cursor) == '\r' && peek_at(parser, cursor + 1) == '\n') {
7318 return 2;
7319 }
7320 return 0;
7321 }
7322
7323 /**
7324 * Return the length of the line ending string starting at
7325 * `parser->current.end + offset`, or 0 if it is not a line ending. This
7326 * function is intended to be CRLF/LF agnostic.
7327 */
7328 static inline size_t
7329 match_eol_offset(pm_parser_t *parser, ptrdiff_t offset) {
7330 return match_eol_at(parser, parser->current.end + offset);
7331 }
7332
7333 /**
7334 * Return the length of the line ending string starting at parser->current.end,
7335 * or 0 if it is not a line ending. This function is intended to be CRLF/LF
7336 * agnostic.
7337 */
7338 static inline size_t
7339 match_eol(pm_parser_t *parser) {
7340 return match_eol_at(parser, parser->current.end);
7341 }
7342
7343 /**
7344 * Skip to the next newline character or NUL byte.
7345 */
7346 static inline const uint8_t *
7347 next_newline(const uint8_t *cursor, ptrdiff_t length) {
7348 assert(length >= 0);
7349
7350 // Note that it's okay for us to use memchr here to look for \n because none
7351 // of the encodings that we support have \n as a component of a multi-byte
7352 // character.
7353 return memchr(cursor, '\n', (size_t) length);
7354 }
7355
7356 /**
7357 * This is equivalent to the predicate of warn_balanced in CRuby.
7358 */
7359 static inline bool
7360 ambiguous_operator_p(const pm_parser_t *parser, bool space_seen) {
7361 return !lex_state_p(parser, PM_LEX_STATE_CLASS | PM_LEX_STATE_DOT | PM_LEX_STATE_FNAME | PM_LEX_STATE_ENDFN) && space_seen && !pm_char_is_whitespace(peek(parser));
7362 }
7363
7364 /**
7365 * Here we're going to check if this is a "magic" comment, and perform whatever
7366 * actions are necessary for it here.
7367 */
7368 static bool
7369 parser_lex_magic_comment_encoding_value(pm_parser_t *parser, const uint8_t *start, const uint8_t *end) {
7370 const pm_encoding_t *encoding = pm_encoding_find(start, end);
7371
7372 if (encoding != NULL) {
7373 if (parser->encoding != encoding) {
7374 parser->encoding = encoding;
7375 if (parser->encoding_changed_callback != NULL) parser->encoding_changed_callback(parser);
7376 }
7377
7378 parser->encoding_changed = (encoding != PM_ENCODING_UTF_8_ENTRY);
7379 return true;
7380 }
7381
7382 return false;
7383 }
7384
7385 /**
7386 * Look for a specific pattern of "coding" and potentially set the encoding on
7387 * the parser.
7388 */
7389 static void
7390 parser_lex_magic_comment_encoding(pm_parser_t *parser) {
7391 const uint8_t *cursor = parser->current.start + 1;
7392 const uint8_t *end = parser->current.end;
7393
7394 bool separator = false;
7395 while (true) {
7396 if (end - cursor <= 6) return;
7397 switch (cursor[6]) {
7398 case 'C': case 'c': cursor += 6; continue;
7399 case 'O': case 'o': cursor += 5; continue;
7400 case 'D': case 'd': cursor += 4; continue;
7401 case 'I': case 'i': cursor += 3; continue;
7402 case 'N': case 'n': cursor += 2; continue;
7403 case 'G': case 'g': cursor += 1; continue;
7404 case '=': case ':':
7405 separator = true;
7406 cursor += 6;
7407 break;
7408 default:
7409 cursor += 6;
7410 if (pm_char_is_whitespace(*cursor)) break;
7411 continue;
7412 }
7413 if (pm_strncasecmp(cursor - 6, (const uint8_t *) "coding", 6) == 0) break;
7414 separator = false;
7415 }
7416
7417 while (true) {
7418 do {
7419 if (++cursor >= end) return;
7420 } while (pm_char_is_whitespace(*cursor));
7421
7422 if (separator) break;
7423 if (*cursor != '=' && *cursor != ':') return;
7424
7425 separator = true;
7426 cursor++;
7427 }
7428
7429 const uint8_t *value_start = cursor;
7430 while ((*cursor == '-' || *cursor == '_' || parser->encoding->alnum_char(cursor, 1)) && ++cursor < end);
7431
7432 if (!parser_lex_magic_comment_encoding_value(parser, value_start, cursor)) {
7433 // If we were unable to parse the encoding value, then we've got an
7434 // issue because we didn't understand the encoding that the user was
7435 // trying to use. In this case we'll keep using the default encoding but
7436 // add an error to the parser to indicate an unsuccessful parse.
7437 pm_parser_err(parser, value_start, cursor, PM_ERR_INVALID_ENCODING_MAGIC_COMMENT);
7438 }
7439 }
7440
7441 typedef enum {
7442 PM_MAGIC_COMMENT_BOOLEAN_VALUE_TRUE,
7443 PM_MAGIC_COMMENT_BOOLEAN_VALUE_FALSE,
7444 PM_MAGIC_COMMENT_BOOLEAN_VALUE_INVALID
7445 } pm_magic_comment_boolean_value_t;
7446
7447 /**
7448 * Check if this is a magic comment that includes the frozen_string_literal
7449 * pragma. If it does, set that field on the parser.
7450 */
7451 static pm_magic_comment_boolean_value_t
7452 parser_lex_magic_comment_boolean_value(const uint8_t *value_start, uint32_t value_length) {
7453 if (value_length == 4 && pm_strncasecmp(value_start, (const uint8_t *) "true", 4) == 0) {
7454 return PM_MAGIC_COMMENT_BOOLEAN_VALUE_TRUE;
7455 } else if (value_length == 5 && pm_strncasecmp(value_start, (const uint8_t *) "false", 5) == 0) {
7456 return PM_MAGIC_COMMENT_BOOLEAN_VALUE_FALSE;
7457 } else {
7458 return PM_MAGIC_COMMENT_BOOLEAN_VALUE_INVALID;
7459 }
7460 }
7461
7462 static inline bool
7463 pm_char_is_magic_comment_key_delimiter(const uint8_t b) {
7464 return b == '\'' || b == '"' || b == ':' || b == ';';
7465 }
7466
7467 /**
7468 * Find an emacs magic comment marker (-*-) within the given bounds. If one is
7469 * found, it returns a pointer to the start of the marker. Otherwise it returns
7470 * NULL.
7471 */
7472 static inline const uint8_t *
7473 parser_lex_magic_comment_emacs_marker(pm_parser_t *parser, const uint8_t *cursor, const uint8_t *end) {
7474 while ((cursor + 3 <= end) && (cursor = pm_memchr(cursor, '-', (size_t) (end - cursor), parser->encoding_changed, parser->encoding)) != NULL) {
7475 if (cursor + 3 <= end && cursor[1] == '*' && cursor[2] == '-') {
7476 return cursor;
7477 }
7478 cursor++;
7479 }
7480 return NULL;
7481 }
7482
7483 /**
7484 * Parse the current token on the parser to see if it's a magic comment and
7485 * potentially perform some action based on that. A regular expression that this
7486 * function is effectively matching is:
7487 *
7488 * %r"([^\\s\'\":;]+)\\s*:\\s*(\"(?:\\\\.|[^\"])*\"|[^\"\\s;]+)[\\s;]*"
7489 *
7490 * It returns true if it consumes the entire comment. Otherwise it returns
7491 * false.
7492 */
7493 static inline bool
7494 parser_lex_magic_comment(pm_parser_t *parser, bool semantic_token_seen) {
7495 bool result = true;
7496
7497 const uint8_t *start = parser->current.start + 1;
7498 const uint8_t *end = parser->current.end;
7499 if (end - start <= 7) return false;
7500
7501 const uint8_t *cursor;
7502 bool indicator = false;
7503
7504 if ((cursor = parser_lex_magic_comment_emacs_marker(parser, start, end)) != NULL) {
7505 start = cursor + 3;
7506
7507 if ((cursor = parser_lex_magic_comment_emacs_marker(parser, start, end)) != NULL) {
7508 end = cursor;
7509 indicator = true;
7510 } else {
7511 // If we have a start marker but not an end marker, then we cannot
7512 // have a magic comment.
7513 return false;
7514 }
7515 }
7516
7517 cursor = start;
7518 while (cursor < end) {
7519 while (cursor < end && (pm_char_is_magic_comment_key_delimiter(*cursor) || pm_char_is_whitespace(*cursor))) cursor++;
7520
7521 const uint8_t *key_start = cursor;
7522 while (cursor < end && (!pm_char_is_magic_comment_key_delimiter(*cursor) && !pm_char_is_whitespace(*cursor))) cursor++;
7523
7524 const uint8_t *key_end = cursor;
7525 while (cursor < end && pm_char_is_whitespace(*cursor)) cursor++;
7526 if (cursor == end) break;
7527
7528 if (*cursor == ':') {
7529 cursor++;
7530 } else {
7531 if (!indicator) return false;
7532 continue;
7533 }
7534
7535 while (cursor < end && pm_char_is_whitespace(*cursor)) cursor++;
7536 if (cursor == end) break;
7537
7538 const uint8_t *value_start;
7539 const uint8_t *value_end;
7540
7541 if (*cursor == '"') {
7542 value_start = ++cursor;
7543 for (; cursor < end && *cursor != '"'; cursor++) {
7544 if (*cursor == '\\' && (cursor + 1 < end)) cursor++;
7545 }
7546 value_end = cursor;
7547 if (cursor < end && *cursor == '"') cursor++;
7548 } else {
7549 value_start = cursor;
7550 while (cursor < end && *cursor != '"' && *cursor != ';' && !pm_char_is_whitespace(*cursor)) cursor++;
7551 value_end = cursor;
7552 }
7553
7554 if (indicator) {
7555 while (cursor < end && (*cursor == ';' || pm_char_is_whitespace(*cursor))) cursor++;
7556 } else {
7557 while (cursor < end && pm_char_is_whitespace(*cursor)) cursor++;
7558 if (cursor != end) return false;
7559 }
7560
7561 // Here, we need to do some processing on the key to swap out dashes for
7562 // underscores. We only need to do this if there _is_ a dash in the key.
7563 pm_string_t key;
7564 const size_t key_length = (size_t) (key_end - key_start);
7565 const uint8_t *dash = pm_memchr(key_start, '-', key_length, parser->encoding_changed, parser->encoding);
7566
7567 if (dash == NULL) {
7568 pm_string_shared_init(&key, key_start, key_end);
7569 } else {
7570 uint8_t *buffer = xmalloc(key_length);
7571 if (buffer == NULL) break;
7572
7573 memcpy(buffer, key_start, key_length);
7574 buffer[dash - key_start] = '_';
7575
7576 while ((dash = pm_memchr(dash + 1, '-', (size_t) (key_end - dash - 1), parser->encoding_changed, parser->encoding)) != NULL) {
7577 buffer[dash - key_start] = '_';
7578 }
7579
7580 pm_string_owned_init(&key, buffer, key_length);
7581 }
7582
7583 // Finally, we can start checking the key against the list of known
7584 // magic comment keys, and potentially change state based on that.
7585 const uint8_t *key_source = pm_string_source(&key);
7586 uint32_t value_length = (uint32_t) (value_end - value_start);
7587
7588 // We only want to attempt to compare against encoding comments if it's
7589 // the first line in the file (or the second in the case of a shebang).
7590 if (parser->current.start == parser->encoding_comment_start && !parser->encoding_locked) {
7591 if (
7592 (key_length == 8 && pm_strncasecmp(key_source, (const uint8_t *) "encoding", 8) == 0) ||
7593 (key_length == 6 && pm_strncasecmp(key_source, (const uint8_t *) "coding", 6) == 0)
7594 ) {
7595 result = parser_lex_magic_comment_encoding_value(parser, value_start, value_end);
7596 }
7597 }
7598
7599 if (key_length == 11) {
7600 if (pm_strncasecmp(key_source, (const uint8_t *) "warn_indent", 11) == 0) {
7601 switch (parser_lex_magic_comment_boolean_value(value_start, value_length)) {
7602 case PM_MAGIC_COMMENT_BOOLEAN_VALUE_INVALID:
7603 PM_PARSER_WARN_TOKEN_FORMAT(
7604 parser,
7605 parser->current,
7606 PM_WARN_INVALID_MAGIC_COMMENT_VALUE,
7607 (int) key_length,
7608 (const char *) key_source,
7609 (int) value_length,
7610 (const char *) value_start
7611 );
7612 break;
7613 case PM_MAGIC_COMMENT_BOOLEAN_VALUE_FALSE:
7614 parser->warn_mismatched_indentation = false;
7615 break;
7616 case PM_MAGIC_COMMENT_BOOLEAN_VALUE_TRUE:
7617 parser->warn_mismatched_indentation = true;
7618 break;
7619 }
7620 }
7621 } else if (key_length == 21) {
7622 if (pm_strncasecmp(key_source, (const uint8_t *) "frozen_string_literal", 21) == 0) {
7623 // We only want to handle frozen string literal comments if it's
7624 // before any semantic tokens have been seen.
7625 if (semantic_token_seen) {
7626 pm_parser_warn_token(parser, &parser->current, PM_WARN_IGNORED_FROZEN_STRING_LITERAL);
7627 } else {
7628 switch (parser_lex_magic_comment_boolean_value(value_start, value_length)) {
7629 case PM_MAGIC_COMMENT_BOOLEAN_VALUE_INVALID:
7630 PM_PARSER_WARN_TOKEN_FORMAT(
7631 parser,
7632 parser->current,
7633 PM_WARN_INVALID_MAGIC_COMMENT_VALUE,
7634 (int) key_length,
7635 (const char *) key_source,
7636 (int) value_length,
7637 (const char *) value_start
7638 );
7639 break;
7640 case PM_MAGIC_COMMENT_BOOLEAN_VALUE_FALSE:
7641 parser->frozen_string_literal = PM_OPTIONS_FROZEN_STRING_LITERAL_DISABLED;
7642 break;
7643 case PM_MAGIC_COMMENT_BOOLEAN_VALUE_TRUE:
7644 parser->frozen_string_literal = PM_OPTIONS_FROZEN_STRING_LITERAL_ENABLED;
7645 break;
7646 }
7647 }
7648 }
7649 } else if (key_length == 24) {
7650 if (pm_strncasecmp(key_source, (const uint8_t *) "shareable_constant_value", 24) == 0) {
7651 const uint8_t *cursor = parser->current.start;
7652 while ((cursor > parser->start) && ((cursor[-1] == ' ') || (cursor[-1] == '\t'))) cursor--;
7653
7654 if (!((cursor == parser->start) || (cursor[-1] == '\n'))) {
7655 pm_parser_warn_token(parser, &parser->current, PM_WARN_SHAREABLE_CONSTANT_VALUE_LINE);
7656 } else if (value_length == 4 && pm_strncasecmp(value_start, (const uint8_t *) "none", 4) == 0) {
7657 pm_parser_scope_shareable_constant_set(parser, PM_SCOPE_SHAREABLE_CONSTANT_NONE);
7658 } else if (value_length == 7 && pm_strncasecmp(value_start, (const uint8_t *) "literal", 7) == 0) {
7659 pm_parser_scope_shareable_constant_set(parser, PM_SCOPE_SHAREABLE_CONSTANT_LITERAL);
7660 } else if (value_length == 23 && pm_strncasecmp(value_start, (const uint8_t *) "experimental_everything", 23) == 0) {
7661 pm_parser_scope_shareable_constant_set(parser, PM_SCOPE_SHAREABLE_CONSTANT_EXPERIMENTAL_EVERYTHING);
7662 } else if (value_length == 17 && pm_strncasecmp(value_start, (const uint8_t *) "experimental_copy", 17) == 0) {
7663 pm_parser_scope_shareable_constant_set(parser, PM_SCOPE_SHAREABLE_CONSTANT_EXPERIMENTAL_COPY);
7664 } else {
7665 PM_PARSER_WARN_TOKEN_FORMAT(
7666 parser,
7667 parser->current,
7668 PM_WARN_INVALID_MAGIC_COMMENT_VALUE,
7669 (int) key_length,
7670 (const char *) key_source,
7671 (int) value_length,
7672 (const char *) value_start
7673 );
7674 }
7675 }
7676 }
7677
7678 // When we're done, we want to free the string in case we had to
7679 // allocate memory for it.
7680 pm_string_free(&key);
7681
7682 // Allocate a new magic comment node to append to the parser's list.
7683 pm_magic_comment_t *magic_comment;
7684 if ((magic_comment = (pm_magic_comment_t *) xcalloc(1, sizeof(pm_magic_comment_t))) != NULL) {
7685 magic_comment->key_start = key_start;
7686 magic_comment->value_start = value_start;
7687 magic_comment->key_length = (uint32_t) key_length;
7688 magic_comment->value_length = value_length;
7689 pm_list_append(&parser->magic_comment_list, (pm_list_node_t *) magic_comment);
7690 }
7691 }
7692
7693 return result;
7694 }
7695
7696 /******************************************************************************/
7697 /* Context manipulations */
7698 /******************************************************************************/
7699
7700 static const uint32_t context_terminators[] = {
7701 [PM_CONTEXT_NONE] = 0,
7702 [PM_CONTEXT_BEGIN] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_END),
7703 [PM_CONTEXT_BEGIN_ENSURE] = (1U << PM_TOKEN_KEYWORD_END),
7704 [PM_CONTEXT_BEGIN_ELSE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_END),
7705 [PM_CONTEXT_BEGIN_RESCUE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_END),
7706 [PM_CONTEXT_BLOCK_BRACES] = (1U << PM_TOKEN_BRACE_RIGHT),
7707 [PM_CONTEXT_BLOCK_KEYWORDS] = (1U << PM_TOKEN_KEYWORD_END) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ENSURE),
7708 [PM_CONTEXT_BLOCK_ENSURE] = (1U << PM_TOKEN_KEYWORD_END),
7709 [PM_CONTEXT_BLOCK_ELSE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_END),
7710 [PM_CONTEXT_BLOCK_PARAMETERS] = (1U << PM_TOKEN_PIPE),
7711 [PM_CONTEXT_BLOCK_RESCUE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_END),
7712 [PM_CONTEXT_CASE_WHEN] = (1U << PM_TOKEN_KEYWORD_WHEN) | (1U << PM_TOKEN_KEYWORD_END) | (1U << PM_TOKEN_KEYWORD_ELSE),
7713 [PM_CONTEXT_CASE_IN] = (1U << PM_TOKEN_KEYWORD_IN) | (1U << PM_TOKEN_KEYWORD_END) | (1U << PM_TOKEN_KEYWORD_ELSE),
7714 [PM_CONTEXT_CLASS] = (1U << PM_TOKEN_KEYWORD_END) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ENSURE),
7715 [PM_CONTEXT_CLASS_ENSURE] = (1U << PM_TOKEN_KEYWORD_END),
7716 [PM_CONTEXT_CLASS_ELSE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_END),
7717 [PM_CONTEXT_CLASS_RESCUE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_END),
7718 [PM_CONTEXT_DEF] = (1U << PM_TOKEN_KEYWORD_END) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ENSURE),
7719 [PM_CONTEXT_DEF_ENSURE] = (1U << PM_TOKEN_KEYWORD_END),
7720 [PM_CONTEXT_DEF_ELSE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_END),
7721 [PM_CONTEXT_DEF_RESCUE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_END),
7722 [PM_CONTEXT_DEF_PARAMS] = (1U << PM_TOKEN_EOF),
7723 [PM_CONTEXT_DEFINED] = (1U << PM_TOKEN_EOF),
7724 [PM_CONTEXT_DEFAULT_PARAMS] = (1U << PM_TOKEN_COMMA) | (1U << PM_TOKEN_PARENTHESIS_RIGHT),
7725 [PM_CONTEXT_ELSE] = (1U << PM_TOKEN_KEYWORD_END),
7726 [PM_CONTEXT_ELSIF] = (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_ELSIF) | (1U << PM_TOKEN_KEYWORD_END),
7727 [PM_CONTEXT_EMBEXPR] = (1U << PM_TOKEN_EMBEXPR_END),
7728 [PM_CONTEXT_FOR] = (1U << PM_TOKEN_KEYWORD_END),
7729 [PM_CONTEXT_FOR_INDEX] = (1U << PM_TOKEN_KEYWORD_IN),
7730 [PM_CONTEXT_IF] = (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_ELSIF) | (1U << PM_TOKEN_KEYWORD_END),
7731 [PM_CONTEXT_LAMBDA_BRACES] = (1U << PM_TOKEN_BRACE_RIGHT),
7732 [PM_CONTEXT_LAMBDA_DO_END] = (1U << PM_TOKEN_KEYWORD_END) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ENSURE),
7733 [PM_CONTEXT_LAMBDA_ENSURE] = (1U << PM_TOKEN_KEYWORD_END),
7734 [PM_CONTEXT_LAMBDA_ELSE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_END),
7735 [PM_CONTEXT_LAMBDA_RESCUE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_END),
7736 [PM_CONTEXT_LOOP_PREDICATE] = (1U << PM_TOKEN_KEYWORD_DO) | (1U << PM_TOKEN_KEYWORD_THEN),
7737 [PM_CONTEXT_MAIN] = (1U << PM_TOKEN_EOF),
7738 [PM_CONTEXT_MODULE] = (1U << PM_TOKEN_KEYWORD_END) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ENSURE),
7739 [PM_CONTEXT_MODULE_ENSURE] = (1U << PM_TOKEN_KEYWORD_END),
7740 [PM_CONTEXT_MODULE_ELSE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_END),
7741 [PM_CONTEXT_MODULE_RESCUE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_END),
7742 [PM_CONTEXT_MULTI_TARGET] = (1U << PM_TOKEN_EOF),
7743 [PM_CONTEXT_PARENS] = (1U << PM_TOKEN_PARENTHESIS_RIGHT),
7744 [PM_CONTEXT_POSTEXE] = (1U << PM_TOKEN_BRACE_RIGHT),
7745 [PM_CONTEXT_PREDICATE] = (1U << PM_TOKEN_KEYWORD_THEN) | (1U << PM_TOKEN_NEWLINE) | (1U << PM_TOKEN_SEMICOLON),
7746 [PM_CONTEXT_PREEXE] = (1U << PM_TOKEN_BRACE_RIGHT),
7747 [PM_CONTEXT_RESCUE_MODIFIER] = (1U << PM_TOKEN_EOF),
7748 [PM_CONTEXT_SCLASS] = (1U << PM_TOKEN_KEYWORD_END) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ENSURE),
7749 [PM_CONTEXT_SCLASS_ENSURE] = (1U << PM_TOKEN_KEYWORD_END),
7750 [PM_CONTEXT_SCLASS_ELSE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_END),
7751 [PM_CONTEXT_SCLASS_RESCUE] = (1U << PM_TOKEN_KEYWORD_ENSURE) | (1U << PM_TOKEN_KEYWORD_RESCUE) | (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_END),
7752 [PM_CONTEXT_TERNARY] = (1U << PM_TOKEN_EOF),
7753 [PM_CONTEXT_UNLESS] = (1U << PM_TOKEN_KEYWORD_ELSE) | (1U << PM_TOKEN_KEYWORD_END),
7754 [PM_CONTEXT_UNTIL] = (1U << PM_TOKEN_KEYWORD_END),
7755 [PM_CONTEXT_WHILE] = (1U << PM_TOKEN_KEYWORD_END),
7756 };
7757
7758 static inline bool
7759 context_terminator(pm_context_t context, pm_token_t *token) {
7760 return token->type < 32 && (context_terminators[context] & (1U << token->type));
7761 }
7762
7763 /**
7764 * Returns the context that the given token is found to be terminating, or
7765 * returns PM_CONTEXT_NONE.
7766 */
7767 static pm_context_t
7768 context_recoverable(const pm_parser_t *parser, pm_token_t *token) {
7769 pm_context_node_t *context_node = parser->current_context;
7770
7771 while (context_node != NULL) {
7772 if (context_terminator(context_node->context, token)) return context_node->context;
7773 context_node = context_node->prev;
7774 }
7775
7776 return PM_CONTEXT_NONE;
7777 }
7778
7779 static bool
7780 context_push(pm_parser_t *parser, pm_context_t context) {
7781 pm_context_node_t *context_node = (pm_context_node_t *) xmalloc(sizeof(pm_context_node_t));
7782 if (context_node == NULL) return false;
7783
7784 *context_node = (pm_context_node_t) { .context = context, .prev = NULL };
7785
7786 if (parser->current_context == NULL) {
7787 parser->current_context = context_node;
7788 } else {
7789 context_node->prev = parser->current_context;
7790 parser->current_context = context_node;
7791 }
7792
7793 return true;
7794 }
7795
7796 static void
7797 context_pop(pm_parser_t *parser) {
7798 pm_context_node_t *prev = parser->current_context->prev;
7799 xfree(parser->current_context);
7800 parser->current_context = prev;
7801 }
7802
7803 static bool
7804 context_p(const pm_parser_t *parser, pm_context_t context) {
7805 pm_context_node_t *context_node = parser->current_context;
7806
7807 while (context_node != NULL) {
7808 if (context_node->context == context) return true;
7809 context_node = context_node->prev;
7810 }
7811
7812 return false;
7813 }
7814
7815 static bool
7816 context_def_p(const pm_parser_t *parser) {
7817 pm_context_node_t *context_node = parser->current_context;
7818
7819 while (context_node != NULL) {
7820 switch (context_node->context) {
7821 case PM_CONTEXT_DEF:
7822 case PM_CONTEXT_DEF_PARAMS:
7823 case PM_CONTEXT_DEF_ENSURE:
7824 case PM_CONTEXT_DEF_RESCUE:
7825 case PM_CONTEXT_DEF_ELSE:
7826 return true;
7827 case PM_CONTEXT_CLASS:
7828 case PM_CONTEXT_CLASS_ENSURE:
7829 case PM_CONTEXT_CLASS_RESCUE:
7830 case PM_CONTEXT_CLASS_ELSE:
7831 case PM_CONTEXT_MODULE:
7832 case PM_CONTEXT_MODULE_ENSURE:
7833 case PM_CONTEXT_MODULE_RESCUE:
7834 case PM_CONTEXT_MODULE_ELSE:
7835 case PM_CONTEXT_SCLASS:
7836 case PM_CONTEXT_SCLASS_ENSURE:
7837 case PM_CONTEXT_SCLASS_RESCUE:
7838 case PM_CONTEXT_SCLASS_ELSE:
7839 return false;
7840 default:
7841 context_node = context_node->prev;
7842 }
7843 }
7844
7845 return false;
7846 }
7847
7848 /**
7849 * Returns a human readable string for the given context, used in error
7850 * messages.
7851 */
7852 static const char *
7853 context_human(pm_context_t context) {
7854 switch (context) {
7855 case PM_CONTEXT_NONE:
7856 assert(false && "unreachable");
7857 return "";
7858 case PM_CONTEXT_BEGIN: return "begin statement";
7859 case PM_CONTEXT_BLOCK_BRACES: return "'{'..'}' block";
7860 case PM_CONTEXT_BLOCK_KEYWORDS: return "'do'..'end' block";
7861 case PM_CONTEXT_BLOCK_PARAMETERS: return "'|'..'|' block parameter";
7862 case PM_CONTEXT_CASE_WHEN: return "'when' clause";
7863 case PM_CONTEXT_CASE_IN: return "'in' clause";
7864 case PM_CONTEXT_CLASS: return "class definition";
7865 case PM_CONTEXT_DEF: return "method definition";
7866 case PM_CONTEXT_DEF_PARAMS: return "method parameters";
7867 case PM_CONTEXT_DEFAULT_PARAMS: return "parameter default value";
7868 case PM_CONTEXT_DEFINED: return "'defined?' expression";
7869 case PM_CONTEXT_ELSE:
7870 case PM_CONTEXT_BEGIN_ELSE:
7871 case PM_CONTEXT_BLOCK_ELSE:
7872 case PM_CONTEXT_CLASS_ELSE:
7873 case PM_CONTEXT_DEF_ELSE:
7874 case PM_CONTEXT_LAMBDA_ELSE:
7875 case PM_CONTEXT_MODULE_ELSE:
7876 case PM_CONTEXT_SCLASS_ELSE: return "'else' clause";
7877 case PM_CONTEXT_ELSIF: return "'elsif' clause";
7878 case PM_CONTEXT_EMBEXPR: return "embedded expression";
7879 case PM_CONTEXT_BEGIN_ENSURE:
7880 case PM_CONTEXT_BLOCK_ENSURE:
7881 case PM_CONTEXT_CLASS_ENSURE:
7882 case PM_CONTEXT_DEF_ENSURE:
7883 case PM_CONTEXT_LAMBDA_ENSURE:
7884 case PM_CONTEXT_MODULE_ENSURE:
7885 case PM_CONTEXT_SCLASS_ENSURE: return "'ensure' clause";
7886 case PM_CONTEXT_FOR: return "for loop";
7887 case PM_CONTEXT_FOR_INDEX: return "for loop index";
7888 case PM_CONTEXT_IF: return "if statement";
7889 case PM_CONTEXT_LAMBDA_BRACES: return "'{'..'}' lambda block";
7890 case PM_CONTEXT_LAMBDA_DO_END: return "'do'..'end' lambda block";
7891 case PM_CONTEXT_LOOP_PREDICATE: return "loop predicate";
7892 case PM_CONTEXT_MAIN: return "top level context";
7893 case PM_CONTEXT_MODULE: return "module definition";
7894 case PM_CONTEXT_MULTI_TARGET: return "multiple targets";
7895 case PM_CONTEXT_PARENS: return "parentheses";
7896 case PM_CONTEXT_POSTEXE: return "'END' block";
7897 case PM_CONTEXT_PREDICATE: return "predicate";
7898 case PM_CONTEXT_PREEXE: return "'BEGIN' block";
7899 case PM_CONTEXT_BEGIN_RESCUE:
7900 case PM_CONTEXT_BLOCK_RESCUE:
7901 case PM_CONTEXT_CLASS_RESCUE:
7902 case PM_CONTEXT_DEF_RESCUE:
7903 case PM_CONTEXT_LAMBDA_RESCUE:
7904 case PM_CONTEXT_MODULE_RESCUE:
7905 case PM_CONTEXT_RESCUE_MODIFIER:
7906 case PM_CONTEXT_SCLASS_RESCUE: return "'rescue' clause";
7907 case PM_CONTEXT_SCLASS: return "singleton class definition";
7908 case PM_CONTEXT_TERNARY: return "ternary expression";
7909 case PM_CONTEXT_UNLESS: return "unless statement";
7910 case PM_CONTEXT_UNTIL: return "until statement";
7911 case PM_CONTEXT_WHILE: return "while statement";
7912 }
7913
7914 assert(false && "unreachable");
7915 return "";
7916 }
7917
7918 /******************************************************************************/
7919 /* Specific token lexers */
7920 /******************************************************************************/
7921
7922 static inline void
7923 pm_strspn_number_validate(pm_parser_t *parser, const uint8_t *string, size_t length, const uint8_t *invalid) {
7924 if (invalid != NULL) {
7925 pm_diagnostic_id_t diag_id = (invalid == (string + length - 1)) ? PM_ERR_INVALID_NUMBER_UNDERSCORE_TRAILING : PM_ERR_INVALID_NUMBER_UNDERSCORE_INNER;
7926 pm_parser_err(parser, invalid, invalid + 1, diag_id);
7927 }
7928 }
7929
7930 static size_t
7931 pm_strspn_binary_number_validate(pm_parser_t *parser, const uint8_t *string) {
7932 const uint8_t *invalid = NULL;
7933 size_t length = pm_strspn_binary_number(string, parser->end - string, &invalid);
7934 pm_strspn_number_validate(parser, string, length, invalid);
7935 return length;
7936 }
7937
7938 static size_t
7939 pm_strspn_octal_number_validate(pm_parser_t *parser, const uint8_t *string) {
7940 const uint8_t *invalid = NULL;
7941 size_t length = pm_strspn_octal_number(string, parser->end - string, &invalid);
7942 pm_strspn_number_validate(parser, string, length, invalid);
7943 return length;
7944 }
7945
7946 static size_t
7947 pm_strspn_decimal_number_validate(pm_parser_t *parser, const uint8_t *string) {
7948 const uint8_t *invalid = NULL;
7949 size_t length = pm_strspn_decimal_number(string, parser->end - string, &invalid);
7950 pm_strspn_number_validate(parser, string, length, invalid);
7951 return length;
7952 }
7953
7954 static size_t
7955 pm_strspn_hexadecimal_number_validate(pm_parser_t *parser, const uint8_t *string) {
7956 const uint8_t *invalid = NULL;
7957 size_t length = pm_strspn_hexadecimal_number(string, parser->end - string, &invalid);
7958 pm_strspn_number_validate(parser, string, length, invalid);
7959 return length;
7960 }
7961
7962 static pm_token_type_t
7963 lex_optional_float_suffix(pm_parser_t *parser, bool* seen_e) {
7964 pm_token_type_t type = PM_TOKEN_INTEGER;
7965
7966 // Here we're going to attempt to parse the optional decimal portion of a
7967 // float. If it's not there, then it's okay and we'll just continue on.
7968 if (peek(parser) == '.') {
7969 if (pm_char_is_decimal_digit(peek_offset(parser, 1))) {
7970 parser->current.end += 2;
7971 parser->current.end += pm_strspn_decimal_number_validate(parser, parser->current.end);
7972 type = PM_TOKEN_FLOAT;
7973 } else {
7974 // If we had a . and then something else, then it's not a float
7975 // suffix on a number it's a method call or something else.
7976 return type;
7977 }
7978 }
7979
7980 // Here we're going to attempt to parse the optional exponent portion of a
7981 // float. If it's not there, it's okay and we'll just continue on.
7982 if ((peek(parser) == 'e') || (peek(parser) == 'E')) {
7983 if ((peek_offset(parser, 1) == '+') || (peek_offset(parser, 1) == '-')) {
7984 parser->current.end += 2;
7985
7986 if (pm_char_is_decimal_digit(peek(parser))) {
7987 parser->current.end++;
7988 parser->current.end += pm_strspn_decimal_number_validate(parser, parser->current.end);
7989 } else {
7990 pm_parser_err_current(parser, PM_ERR_INVALID_FLOAT_EXPONENT);
7991 }
7992 } else if (pm_char_is_decimal_digit(peek_offset(parser, 1))) {
7993 parser->current.end++;
7994 parser->current.end += pm_strspn_decimal_number_validate(parser, parser->current.end);
7995 } else {
7996 return type;
7997 }
7998
7999 *seen_e = true;
8000 type = PM_TOKEN_FLOAT;
8001 }
8002
8003 return type;
8004 }
8005
8006 static pm_token_type_t
8007 lex_numeric_prefix(pm_parser_t *parser, bool* seen_e) {
8008 pm_token_type_t type = PM_TOKEN_INTEGER;
8009 *seen_e = false;
8010
8011 if (peek_offset(parser, -1) == '0') {
8012 switch (*parser->current.end) {
8013 // 0d1111 is a decimal number
8014 case 'd':
8015 case 'D':
8016 parser->current.end++;
8017 if (pm_char_is_decimal_digit(peek(parser))) {
8018 parser->current.end += pm_strspn_decimal_number_validate(parser, parser->current.end);
8019 } else {
8020 match(parser, '_');
8021 pm_parser_err_current(parser, PM_ERR_INVALID_NUMBER_DECIMAL);
8022 }
8023
8024 break;
8025
8026 // 0b1111 is a binary number
8027 case 'b':
8028 case 'B':
8029 parser->current.end++;
8030 if (pm_char_is_binary_digit(peek(parser))) {
8031 parser->current.end += pm_strspn_binary_number_validate(parser, parser->current.end);
8032 } else {
8033 match(parser, '_');
8034 pm_parser_err_current(parser, PM_ERR_INVALID_NUMBER_BINARY);
8035 }
8036
8037 parser->integer_base = PM_INTEGER_BASE_FLAGS_BINARY;
8038 break;
8039
8040 // 0o1111 is an octal number
8041 case 'o':
8042 case 'O':
8043 parser->current.end++;
8044 if (pm_char_is_octal_digit(peek(parser))) {
8045 parser->current.end += pm_strspn_octal_number_validate(parser, parser->current.end);
8046 } else {
8047 match(parser, '_');
8048 pm_parser_err_current(parser, PM_ERR_INVALID_NUMBER_OCTAL);
8049 }
8050
8051 parser->integer_base = PM_INTEGER_BASE_FLAGS_OCTAL;
8052 break;
8053
8054 // 01111 is an octal number
8055 case '_':
8056 case '0':
8057 case '1':
8058 case '2':
8059 case '3':
8060 case '4':
8061 case '5':
8062 case '6':
8063 case '7':
8064 parser->current.end += pm_strspn_octal_number_validate(parser, parser->current.end);
8065 parser->integer_base = PM_INTEGER_BASE_FLAGS_OCTAL;
8066 break;
8067
8068 // 0x1111 is a hexadecimal number
8069 case 'x':
8070 case 'X':
8071 parser->current.end++;
8072 if (pm_char_is_hexadecimal_digit(peek(parser))) {
8073 parser->current.end += pm_strspn_hexadecimal_number_validate(parser, parser->current.end);
8074 } else {
8075 match(parser, '_');
8076 pm_parser_err_current(parser, PM_ERR_INVALID_NUMBER_HEXADECIMAL);
8077 }
8078
8079 parser->integer_base = PM_INTEGER_BASE_FLAGS_HEXADECIMAL;
8080 break;
8081
8082 // 0.xxx is a float
8083 case '.': {
8084 type = lex_optional_float_suffix(parser, seen_e);
8085 break;
8086 }
8087
8088 // 0exxx is a float
8089 case 'e':
8090 case 'E': {
8091 type = lex_optional_float_suffix(parser, seen_e);
8092 break;
8093 }
8094 }
8095 } else {
8096 // If it didn't start with a 0, then we'll lex as far as we can into a
8097 // decimal number.
8098 parser->current.end += pm_strspn_decimal_number_validate(parser, parser->current.end);
8099
8100 // Afterward, we'll lex as far as we can into an optional float suffix.
8101 type = lex_optional_float_suffix(parser, seen_e);
8102 }
8103
8104 // At this point we have a completed number, but we want to provide the user
8105 // with a good experience if they put an additional .xxx fractional
8106 // component on the end, so we'll check for that here.
8107 if (peek_offset(parser, 0) == '.' && pm_char_is_decimal_digit(peek_offset(parser, 1))) {
8108 const uint8_t *fraction_start = parser->current.end;
8109 const uint8_t *fraction_end = parser->current.end + 2;
8110 fraction_end += pm_strspn_decimal_digit(fraction_end, parser->end - fraction_end);
8111 pm_parser_err(parser, fraction_start, fraction_end, PM_ERR_INVALID_NUMBER_FRACTION);
8112 }
8113
8114 return type;
8115 }
8116
8117 static pm_token_type_t
8118 lex_numeric(pm_parser_t *parser) {
8119 pm_token_type_t type = PM_TOKEN_INTEGER;
8120 parser->integer_base = PM_INTEGER_BASE_FLAGS_DECIMAL;
8121
8122 if (parser->current.end < parser->end) {
8123 bool seen_e = false;
8124 type = lex_numeric_prefix(parser, &seen_e);
8125
8126 const uint8_t *end = parser->current.end;
8127 pm_token_type_t suffix_type = type;
8128
8129 if (type == PM_TOKEN_INTEGER) {
8130 if (match(parser, 'r')) {
8131 suffix_type = PM_TOKEN_INTEGER_RATIONAL;
8132
8133 if (match(parser, 'i')) {
8134 suffix_type = PM_TOKEN_INTEGER_RATIONAL_IMAGINARY;
8135 }
8136 } else if (match(parser, 'i')) {
8137 suffix_type = PM_TOKEN_INTEGER_IMAGINARY;
8138 }
8139 } else {
8140 if (!seen_e && match(parser, 'r')) {
8141 suffix_type = PM_TOKEN_FLOAT_RATIONAL;
8142
8143 if (match(parser, 'i')) {
8144 suffix_type = PM_TOKEN_FLOAT_RATIONAL_IMAGINARY;
8145 }
8146 } else if (match(parser, 'i')) {
8147 suffix_type = PM_TOKEN_FLOAT_IMAGINARY;
8148 }
8149 }
8150
8151 const uint8_t b = peek(parser);
8152 if (b != '\0' && (b >= 0x80 || ((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')) || b == '_')) {
8153 parser->current.end = end;
8154 } else {
8155 type = suffix_type;
8156 }
8157 }
8158
8159 return type;
8160 }
8161
8162 static pm_token_type_t
8163 lex_global_variable(pm_parser_t *parser) {
8164 if (parser->current.end >= parser->end) {
8165 pm_parser_err_token(parser, &parser->current, PM_ERR_GLOBAL_VARIABLE_BARE);
8166 return PM_TOKEN_GLOBAL_VARIABLE;
8167 }
8168
8169 // True if multiple characters are allowed after the declaration of the
8170 // global variable. Not true when it starts with "$-".
8171 bool allow_multiple = true;
8172
8173 switch (*parser->current.end) {
8174 case '~': // $~: match-data
8175 case '*': // $*: argv
8176 case '$': // $$: pid
8177 case '?': // $?: last status
8178 case '!': // $!: error string
8179 case '@': // $@: error position
8180 case '/': // $/: input record separator
8181 case '\\': // $\: output record separator
8182 case ';': // $;: field separator
8183 case ',': // $,: output field separator
8184 case '.': // $.: last read line number
8185 case '=': // $=: ignorecase
8186 case ':': // $:: load path
8187 case '<': // $<: reading filename
8188 case '>': // $>: default output handle
8189 case '\"': // $": already loaded files
8190 parser->current.end++;
8191 return PM_TOKEN_GLOBAL_VARIABLE;
8192
8193 case '&': // $&: last match
8194 case '`': // $`: string before last match
8195 case '\'': // $': string after last match
8196 case '+': // $+: string matches last paren.
8197 parser->current.end++;
8198 return lex_state_p(parser, PM_LEX_STATE_FNAME) ? PM_TOKEN_GLOBAL_VARIABLE : PM_TOKEN_BACK_REFERENCE;
8199
8200 case '0': {
8201 parser->current.end++;
8202 size_t width;
8203
8204 if ((width = char_is_identifier(parser, parser->current.end, parser->end - parser->current.end)) > 0) {
8205 do {
8206 parser->current.end += width;
8207 } while ((width = char_is_identifier(parser, parser->current.end, parser->end - parser->current.end)) > 0);
8208
8209 // $0 isn't allowed to be followed by anything.
8210 pm_diagnostic_id_t diag_id = parser->version <= PM_OPTIONS_VERSION_CRUBY_3_3 ? PM_ERR_INVALID_VARIABLE_GLOBAL_3_3 : PM_ERR_INVALID_VARIABLE_GLOBAL;
8211 PM_PARSER_ERR_TOKEN_FORMAT_CONTENT(parser, parser->current, diag_id);
8212 }
8213
8214 return PM_TOKEN_GLOBAL_VARIABLE;
8215 }
8216
8217 case '1':
8218 case '2':
8219 case '3':
8220 case '4':
8221 case '5':
8222 case '6':
8223 case '7':
8224 case '8':
8225 case '9':
8226 parser->current.end += pm_strspn_decimal_digit(parser->current.end, parser->end - parser->current.end);
8227 return lex_state_p(parser, PM_LEX_STATE_FNAME) ? PM_TOKEN_GLOBAL_VARIABLE : PM_TOKEN_NUMBERED_REFERENCE;
8228
8229 case '-':
8230 parser->current.end++;
8231 allow_multiple = false;
8232 PRISM_FALLTHROUGH
8233 default: {
8234 size_t width;
8235
8236 if ((width = char_is_identifier(parser, parser->current.end, parser->end - parser->current.end)) > 0) {
8237 do {
8238 parser->current.end += width;
8239 } while (allow_multiple && (width = char_is_identifier(parser, parser->current.end, parser->end - parser->current.end)) > 0);
8240 } else if (pm_char_is_whitespace(peek(parser))) {
8241 // If we get here, then we have a $ followed by whitespace,
8242 // which is not allowed.
8243 pm_parser_err_token(parser, &parser->current, PM_ERR_GLOBAL_VARIABLE_BARE);
8244 } else {
8245 // If we get here, then we have a $ followed by something that
8246 // isn't recognized as a global variable.
8247 pm_diagnostic_id_t diag_id = parser->version <= PM_OPTIONS_VERSION_CRUBY_3_3 ? PM_ERR_INVALID_VARIABLE_GLOBAL_3_3 : PM_ERR_INVALID_VARIABLE_GLOBAL;
8248 const uint8_t *end = parser->current.end + parser->encoding->char_width(parser->current.end, parser->end - parser->current.end);
8249 PM_PARSER_ERR_FORMAT(parser, parser->current.start, end, diag_id, (int) (end - parser->current.start), (const char *) parser->current.start);
8250 }
8251
8252 return PM_TOKEN_GLOBAL_VARIABLE;
8253 }
8254 }
8255 }
8256
8257 /**
8258 * This function checks if the current token matches a keyword. If it does, it
8259 * returns the token type. Otherwise, it returns PM_TOKEN_EOF. The arguments are as follows:
8260 *
8261 * * `parser` - the parser object
8262 * * `current_start` - pointer to the start of the current token
8263 * * `value` - the literal string that we're checking for
8264 * * `vlen` - the length of the token
8265 * * `state` - the state that we should transition to if the token matches
8266 * * `type` - the expected token type
8267 * * `modifier_type` - the expected modifier token type
8268 */
8269 static inline pm_token_type_t
8270 lex_keyword(pm_parser_t *parser, const uint8_t *current_start, const char *value, size_t vlen, pm_lex_state_t state, pm_token_type_t type, pm_token_type_t modifier_type) {
8271 if (memcmp(current_start, value, vlen) == 0) {
8272 pm_lex_state_t last_state = parser->lex_state;
8273
8274 if (parser->lex_state & PM_LEX_STATE_FNAME) {
8275 lex_state_set(parser, PM_LEX_STATE_ENDFN);
8276 } else {
8277 lex_state_set(parser, state);
8278 if (state == PM_LEX_STATE_BEG) {
8279 parser->command_start = true;
8280 }
8281
8282 if ((modifier_type != PM_TOKEN_EOF) && !(last_state & (PM_LEX_STATE_BEG | PM_LEX_STATE_LABELED | PM_LEX_STATE_CLASS))) {
8283 lex_state_set(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_LABEL);
8284 return modifier_type;
8285 }
8286 }
8287
8288 return type;
8289 }
8290
8291 return PM_TOKEN_EOF;
8292 }
8293
8294 static pm_token_type_t
8295 lex_identifier(pm_parser_t *parser, bool previous_command_start) {
8296 // Lex as far as we can into the current identifier.
8297 size_t width;
8298 const uint8_t *end = parser->end;
8299 const uint8_t *current_start = parser->current.start;
8300 const uint8_t *current_end = parser->current.end;
8301 bool encoding_changed = parser->encoding_changed;
8302
8303 if (encoding_changed) {
8304 while ((width = char_is_identifier(parser, current_end, end - current_end)) > 0) {
8305 current_end += width;
8306 }
8307 } else {
8308 while ((width = char_is_identifier_utf8(current_end, end - current_end)) > 0) {
8309 current_end += width;
8310 }
8311 }
8312 parser->current.end = current_end;
8313
8314 // Now cache the length of the identifier so that we can quickly compare it
8315 // against known keywords.
8316 width = (size_t) (current_end - current_start);
8317
8318 if (current_end < end) {
8319 if (((current_end + 1 >= end) || (current_end[1] != '=')) && (match(parser, '!') || match(parser, '?'))) {
8320 // First we'll attempt to extend the identifier by a ! or ?. Then we'll
8321 // check if we're returning the defined? keyword or just an identifier.
8322 width++;
8323
8324 if (
8325 ((lex_state_p(parser, PM_LEX_STATE_LABEL | PM_LEX_STATE_ENDFN) && !previous_command_start) || lex_state_arg_p(parser)) &&
8326 (peek(parser) == ':') && (peek_offset(parser, 1) != ':')
8327 ) {
8328 // If we're in a position where we can accept a : at the end of an
8329 // identifier, then we'll optionally accept it.
8330 lex_state_set(parser, PM_LEX_STATE_ARG | PM_LEX_STATE_LABELED);
8331 (void) match(parser, ':');
8332 return PM_TOKEN_LABEL;
8333 }
8334
8335 if (parser->lex_state != PM_LEX_STATE_DOT) {
8336 if (width == 8 && (lex_keyword(parser, current_start, "defined?", width, PM_LEX_STATE_ARG, PM_TOKEN_KEYWORD_DEFINED, PM_TOKEN_EOF) != PM_TOKEN_EOF)) {
8337 return PM_TOKEN_KEYWORD_DEFINED;
8338 }
8339 }
8340
8341 return PM_TOKEN_METHOD_NAME;
8342 }
8343
8344 if (lex_state_p(parser, PM_LEX_STATE_FNAME) && peek_offset(parser, 1) != '~' && peek_offset(parser, 1) != '>' && (peek_offset(parser, 1) != '=' || peek_offset(parser, 2) == '>') && match(parser, '=')) {
8345 // If we're in a position where we can accept a = at the end of an
8346 // identifier, then we'll optionally accept it.
8347 return PM_TOKEN_IDENTIFIER;
8348 }
8349
8350 if (
8351 ((lex_state_p(parser, PM_LEX_STATE_LABEL | PM_LEX_STATE_ENDFN) && !previous_command_start) || lex_state_arg_p(parser)) &&
8352 peek(parser) == ':' && peek_offset(parser, 1) != ':'
8353 ) {
8354 // If we're in a position where we can accept a : at the end of an
8355 // identifier, then we'll optionally accept it.
8356 lex_state_set(parser, PM_LEX_STATE_ARG | PM_LEX_STATE_LABELED);
8357 (void) match(parser, ':');
8358 return PM_TOKEN_LABEL;
8359 }
8360 }
8361
8362 if (parser->lex_state != PM_LEX_STATE_DOT) {
8363 pm_token_type_t type;
8364 switch (width) {
8365 case 2:
8366 if (lex_keyword(parser, current_start, "do", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_DO, PM_TOKEN_EOF) != PM_TOKEN_EOF) {
8367 if (pm_do_loop_stack_p(parser)) {
8368 return PM_TOKEN_KEYWORD_DO_LOOP;
8369 }
8370 return PM_TOKEN_KEYWORD_DO;
8371 }
8372
8373 if ((type = lex_keyword(parser, current_start, "if", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_IF, PM_TOKEN_KEYWORD_IF_MODIFIER)) != PM_TOKEN_EOF) return type;
8374 if ((type = lex_keyword(parser, current_start, "in", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_IN, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8375 if ((type = lex_keyword(parser, current_start, "or", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_OR, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8376 break;
8377 case 3:
8378 if ((type = lex_keyword(parser, current_start, "and", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_AND, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8379 if ((type = lex_keyword(parser, current_start, "def", width, PM_LEX_STATE_FNAME, PM_TOKEN_KEYWORD_DEF, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8380 if ((type = lex_keyword(parser, current_start, "end", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD_END, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8381 if ((type = lex_keyword(parser, current_start, "END", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD_END_UPCASE, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8382 if ((type = lex_keyword(parser, current_start, "for", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_FOR, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8383 if ((type = lex_keyword(parser, current_start, "nil", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD_NIL, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8384 if ((type = lex_keyword(parser, current_start, "not", width, PM_LEX_STATE_ARG, PM_TOKEN_KEYWORD_NOT, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8385 break;
8386 case 4:
8387 if ((type = lex_keyword(parser, current_start, "case", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_CASE, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8388 if ((type = lex_keyword(parser, current_start, "else", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8389 if ((type = lex_keyword(parser, current_start, "next", width, PM_LEX_STATE_MID, PM_TOKEN_KEYWORD_NEXT, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8390 if ((type = lex_keyword(parser, current_start, "redo", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD_REDO, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8391 if ((type = lex_keyword(parser, current_start, "self", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD_SELF, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8392 if ((type = lex_keyword(parser, current_start, "then", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_THEN, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8393 if ((type = lex_keyword(parser, current_start, "true", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD_TRUE, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8394 if ((type = lex_keyword(parser, current_start, "when", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_WHEN, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8395 break;
8396 case 5:
8397 if ((type = lex_keyword(parser, current_start, "alias", width, PM_LEX_STATE_FNAME | PM_LEX_STATE_FITEM, PM_TOKEN_KEYWORD_ALIAS, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8398 if ((type = lex_keyword(parser, current_start, "begin", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_BEGIN, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8399 if ((type = lex_keyword(parser, current_start, "BEGIN", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD_BEGIN_UPCASE, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8400 if ((type = lex_keyword(parser, current_start, "break", width, PM_LEX_STATE_MID, PM_TOKEN_KEYWORD_BREAK, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8401 if ((type = lex_keyword(parser, current_start, "class", width, PM_LEX_STATE_CLASS, PM_TOKEN_KEYWORD_CLASS, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8402 if ((type = lex_keyword(parser, current_start, "elsif", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_ELSIF, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8403 if ((type = lex_keyword(parser, current_start, "false", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD_FALSE, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8404 if ((type = lex_keyword(parser, current_start, "retry", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD_RETRY, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8405 if ((type = lex_keyword(parser, current_start, "super", width, PM_LEX_STATE_ARG, PM_TOKEN_KEYWORD_SUPER, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8406 if ((type = lex_keyword(parser, current_start, "undef", width, PM_LEX_STATE_FNAME | PM_LEX_STATE_FITEM, PM_TOKEN_KEYWORD_UNDEF, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8407 if ((type = lex_keyword(parser, current_start, "until", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_UNTIL, PM_TOKEN_KEYWORD_UNTIL_MODIFIER)) != PM_TOKEN_EOF) return type;
8408 if ((type = lex_keyword(parser, current_start, "while", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_WHILE, PM_TOKEN_KEYWORD_WHILE_MODIFIER)) != PM_TOKEN_EOF) return type;
8409 if ((type = lex_keyword(parser, current_start, "yield", width, PM_LEX_STATE_ARG, PM_TOKEN_KEYWORD_YIELD, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8410 break;
8411 case 6:
8412 if ((type = lex_keyword(parser, current_start, "ensure", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_ENSURE, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8413 if ((type = lex_keyword(parser, current_start, "module", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_MODULE, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8414 if ((type = lex_keyword(parser, current_start, "rescue", width, PM_LEX_STATE_MID, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_RESCUE_MODIFIER)) != PM_TOKEN_EOF) return type;
8415 if ((type = lex_keyword(parser, current_start, "return", width, PM_LEX_STATE_MID, PM_TOKEN_KEYWORD_RETURN, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8416 if ((type = lex_keyword(parser, current_start, "unless", width, PM_LEX_STATE_BEG, PM_TOKEN_KEYWORD_UNLESS, PM_TOKEN_KEYWORD_UNLESS_MODIFIER)) != PM_TOKEN_EOF) return type;
8417 break;
8418 case 8:
8419 if ((type = lex_keyword(parser, current_start, "__LINE__", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD___LINE__, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8420 if ((type = lex_keyword(parser, current_start, "__FILE__", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD___FILE__, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8421 break;
8422 case 12:
8423 if ((type = lex_keyword(parser, current_start, "__ENCODING__", width, PM_LEX_STATE_END, PM_TOKEN_KEYWORD___ENCODING__, PM_TOKEN_EOF)) != PM_TOKEN_EOF) return type;
8424 break;
8425 }
8426 }
8427
8428 if (encoding_changed) {
8429 return parser->encoding->isupper_char(current_start, end - current_start) ? PM_TOKEN_CONSTANT : PM_TOKEN_IDENTIFIER;
8430 }
8431 return pm_encoding_utf_8_isupper_char(current_start, end - current_start) ? PM_TOKEN_CONSTANT : PM_TOKEN_IDENTIFIER;
8432 }
8433
8434 /**
8435 * Returns true if the current token that the parser is considering is at the
8436 * beginning of a line or the beginning of the source.
8437 */
8438 static bool
8439 current_token_starts_line(pm_parser_t *parser) {
8440 return (parser->current.start == parser->start) || (parser->current.start[-1] == '\n');
8441 }
8442
8443 /**
8444 * When we hit a # while lexing something like a string, we need to potentially
8445 * handle interpolation. This function performs that check. It returns a token
8446 * type representing what it found. Those cases are:
8447 *
8448 * * PM_TOKEN_NOT_PROVIDED - No interpolation was found at this point. The
8449 * caller should keep lexing.
8450 * * PM_TOKEN_STRING_CONTENT - No interpolation was found at this point. The
8451 * caller should return this token type.
8452 * * PM_TOKEN_EMBEXPR_BEGIN - An embedded expression was found. The caller
8453 * should return this token type.
8454 * * PM_TOKEN_EMBVAR - An embedded variable was found. The caller should return
8455 * this token type.
8456 */
8457 static pm_token_type_t
8458 lex_interpolation(pm_parser_t *parser, const uint8_t *pound) {
8459 // If there is no content following this #, then we're at the end of
8460 // the string and we can safely return string content.
8461 if (pound + 1 >= parser->end) {
8462 parser->current.end = pound + 1;
8463 return PM_TOKEN_STRING_CONTENT;
8464 }
8465
8466 // Now we'll check against the character that follows the #. If it constitutes
8467 // valid interplation, we'll handle that, otherwise we'll return
8468 // PM_TOKEN_NOT_PROVIDED.
8469 switch (pound[1]) {
8470 case '@': {
8471 // In this case we may have hit an embedded instance or class variable.
8472 if (pound + 2 >= parser->end) {
8473 parser->current.end = pound + 1;
8474 return PM_TOKEN_STRING_CONTENT;
8475 }
8476
8477 // If we're looking at a @ and there's another @, then we'll skip past the
8478 // second @.
8479 const uint8_t *variable = pound + 2;
8480 if (*variable == '@' && pound + 3 < parser->end) variable++;
8481
8482 if (char_is_identifier_start(parser, variable, parser->end - variable)) {
8483 // At this point we're sure that we've either hit an embedded instance
8484 // or class variable. In this case we'll first need to check if we've
8485 // already consumed content.
8486 if (pound > parser->current.start) {
8487 parser->current.end = pound;
8488 return PM_TOKEN_STRING_CONTENT;
8489 }
8490
8491 // Otherwise we need to return the embedded variable token
8492 // and then switch to the embedded variable lex mode.
8493 lex_mode_push(parser, (pm_lex_mode_t) { .mode = PM_LEX_EMBVAR });
8494 parser->current.end = pound + 1;
8495 return PM_TOKEN_EMBVAR;
8496 }
8497
8498 // If we didn't get a valid interpolation, then this is just regular
8499 // string content. This is like if we get "#@-". In this case the caller
8500 // should keep lexing.
8501 parser->current.end = pound + 1;
8502 return PM_TOKEN_NOT_PROVIDED;
8503 }
8504 case '$':
8505 // In this case we may have hit an embedded global variable. If there's
8506 // not enough room, then we'll just return string content.
8507 if (pound + 2 >= parser->end) {
8508 parser->current.end = pound + 1;
8509 return PM_TOKEN_STRING_CONTENT;
8510 }
8511
8512 // This is the character that we're going to check to see if it is the
8513 // start of an identifier that would indicate that this is a global
8514 // variable.
8515 const uint8_t *check = pound + 2;
8516
8517 if (pound[2] == '-') {
8518 if (pound + 3 >= parser->end) {
8519 parser->current.end = pound + 2;
8520 return PM_TOKEN_STRING_CONTENT;
8521 }
8522
8523 check++;
8524 }
8525
8526 // If the character that we're going to check is the start of an
8527 // identifier, or we don't have a - and the character is a decimal number
8528 // or a global name punctuation character, then we've hit an embedded
8529 // global variable.
8530 if (
8531 char_is_identifier_start(parser, check, parser->end - check) ||
8532 (pound[2] != '-' && (pm_char_is_decimal_digit(pound[2]) || char_is_global_name_punctuation(pound[2])))
8533 ) {
8534 // In this case we've hit an embedded global variable. First check to
8535 // see if we've already consumed content. If we have, then we need to
8536 // return that content as string content first.
8537 if (pound > parser->current.start) {
8538 parser->current.end = pound;
8539 return PM_TOKEN_STRING_CONTENT;
8540 }
8541
8542 // Otherwise, we need to return the embedded variable token and switch
8543 // to the embedded variable lex mode.
8544 lex_mode_push(parser, (pm_lex_mode_t) { .mode = PM_LEX_EMBVAR });
8545 parser->current.end = pound + 1;
8546 return PM_TOKEN_EMBVAR;
8547 }
8548
8549 // In this case we've hit a #$ that does not indicate a global variable.
8550 // In this case we'll continue lexing past it.
8551 parser->current.end = pound + 1;
8552 return PM_TOKEN_NOT_PROVIDED;
8553 case '{':
8554 // In this case it's the start of an embedded expression. If we have
8555 // already consumed content, then we need to return that content as string
8556 // content first.
8557 if (pound > parser->current.start) {
8558 parser->current.end = pound;
8559 return PM_TOKEN_STRING_CONTENT;
8560 }
8561
8562 parser->enclosure_nesting++;
8563
8564 // Otherwise we'll skip past the #{ and begin lexing the embedded
8565 // expression.
8566 lex_mode_push(parser, (pm_lex_mode_t) { .mode = PM_LEX_EMBEXPR });
8567 parser->current.end = pound + 2;
8568 parser->command_start = true;
8569 pm_do_loop_stack_push(parser, false);
8570 return PM_TOKEN_EMBEXPR_BEGIN;
8571 default:
8572 // In this case we've hit a # that doesn't constitute interpolation. We'll
8573 // mark that by returning the not provided token type. This tells the
8574 // consumer to keep lexing forward.
8575 parser->current.end = pound + 1;
8576 return PM_TOKEN_NOT_PROVIDED;
8577 }
8578 }
8579
8580 static const uint8_t PM_ESCAPE_FLAG_NONE = 0x0;
8581 static const uint8_t PM_ESCAPE_FLAG_CONTROL = 0x1;
8582 static const uint8_t PM_ESCAPE_FLAG_META = 0x2;
8583 static const uint8_t PM_ESCAPE_FLAG_SINGLE = 0x4;
8584 static const uint8_t PM_ESCAPE_FLAG_REGEXP = 0x8;
8585
8586 /**
8587 * This is a lookup table for whether or not an ASCII character is printable.
8588 */
8589 static const bool ascii_printable_chars[] = {
8590 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0,
8591 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8592 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8593 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8594 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8595 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1,
8596 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8597 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0
8598 };
8599
8600 static inline bool
8601 char_is_ascii_printable(const uint8_t b) {
8602 return (b < 0x80) && ascii_printable_chars[b];
8603 }
8604
8605 /**
8606 * Return the value that a hexadecimal digit character represents. For example,
8607 * transform 'a' into 10, 'b' into 11, etc.
8608 */
8609 static inline uint8_t
8610 escape_hexadecimal_digit(const uint8_t value) {
8611 return (uint8_t) ((value <= '9') ? (value - '0') : (value & 0x7) + 9);
8612 }
8613
8614 /**
8615 * Scan the 4 digits of a Unicode escape into the value. Returns the number of
8616 * digits scanned. This function assumes that the characters have already been
8617 * validated.
8618 */
8619 static inline uint32_t
8620 escape_unicode(pm_parser_t *parser, const uint8_t *string, size_t length, const pm_location_t *error_location) {
8621 uint32_t value = 0;
8622 for (size_t index = 0; index < length; index++) {
8623 if (index != 0) value <<= 4;
8624 value |= escape_hexadecimal_digit(string[index]);
8625 }
8626
8627 // Here we're going to verify that the value is actually a valid Unicode
8628 // codepoint and not a surrogate pair.
8629 if (value >= 0xD800 && value <= 0xDFFF) {
8630 if (error_location != NULL) {
8631 pm_parser_err(parser, error_location->start, error_location->end, PM_ERR_ESCAPE_INVALID_UNICODE);
8632 } else {
8633 pm_parser_err(parser, string, string + length, PM_ERR_ESCAPE_INVALID_UNICODE);
8634 }
8635 return 0xFFFD;
8636 }
8637
8638 return value;
8639 }
8640
8641 /**
8642 * Escape a single character value based on the given flags.
8643 */
8644 static inline uint8_t
8645 escape_byte(uint8_t value, const uint8_t flags) {
8646 if (flags & PM_ESCAPE_FLAG_CONTROL) value &= 0x9f;
8647 if (flags & PM_ESCAPE_FLAG_META) value |= 0x80;
8648 return value;
8649 }
8650
8651 /**
8652 * Write a unicode codepoint to the given buffer.
8653 */
8654 static inline void
8655 escape_write_unicode(pm_parser_t *parser, pm_buffer_t *buffer, const uint8_t flags, const uint8_t *start, const uint8_t *end, uint32_t value) {
8656 // \u escape sequences in string-like structures implicitly change the
8657 // encoding to UTF-8 if they are >= 0x80 or if they are used in a character
8658 // literal.
8659 if (value >= 0x80 || flags & PM_ESCAPE_FLAG_SINGLE) {
8660 if (parser->explicit_encoding != NULL && parser->explicit_encoding != PM_ENCODING_UTF_8_ENTRY) {
8661 PM_PARSER_ERR_FORMAT(parser, start, end, PM_ERR_MIXED_ENCODING, parser->explicit_encoding->name);
8662 }
8663
8664 parser->explicit_encoding = PM_ENCODING_UTF_8_ENTRY;
8665 }
8666
8667 if (!pm_buffer_append_unicode_codepoint(buffer, value)) {
8668 pm_parser_err(parser, start, end, PM_ERR_ESCAPE_INVALID_UNICODE);
8669 pm_buffer_append_byte(buffer, 0xEF);
8670 pm_buffer_append_byte(buffer, 0xBF);
8671 pm_buffer_append_byte(buffer, 0xBD);
8672 }
8673 }
8674
8675 /**
8676 * When you're writing a byte to the unescape buffer, if the byte is non-ASCII
8677 * (i.e., the top bit is set) then it locks in the encoding.
8678 */
8679 static inline void
8680 escape_write_byte_encoded(pm_parser_t *parser, pm_buffer_t *buffer, uint8_t byte) {
8681 if (byte >= 0x80) {
8682 if (parser->explicit_encoding != NULL && parser->explicit_encoding == PM_ENCODING_UTF_8_ENTRY && parser->encoding != PM_ENCODING_UTF_8_ENTRY) {
8683 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_MIXED_ENCODING, parser->encoding->name);
8684 }
8685
8686 parser->explicit_encoding = parser->encoding;
8687 }
8688
8689 pm_buffer_append_byte(buffer, byte);
8690 }
8691
8692 /**
8693 * The regular expression engine doesn't support the same escape sequences as
8694 * Ruby does. So first we have to read the escape sequence, and then we have to
8695 * format it like the regular expression engine expects it. For example, in Ruby
8696 * if we have:
8697 *
8698 * /\M-\C-?/
8699 *
8700 * then the first byte is actually 255, so we have to rewrite this as:
8701 *
8702 * /\xFF/
8703 *
8704 * Note that in this case there is a literal \ byte in the regular expression
8705 * source so that the regular expression engine will perform its own unescaping.
8706 */
8707 static inline void
8708 escape_write_byte(pm_parser_t *parser, pm_buffer_t *buffer, pm_buffer_t *regular_expression_buffer, uint8_t flags, uint8_t byte) {
8709 if (flags & PM_ESCAPE_FLAG_REGEXP) {
8710 pm_buffer_append_format(regular_expression_buffer, "\\x%02X", byte);
8711 }
8712
8713 escape_write_byte_encoded(parser, buffer, byte);
8714 }
8715
8716 /**
8717 * Write each byte of the given escaped character into the buffer.
8718 */
8719 static inline void
8720 escape_write_escape_encoded(pm_parser_t *parser, pm_buffer_t *buffer, pm_buffer_t *regular_expression_buffer, uint8_t flags) {
8721 size_t width;
8722 if (parser->encoding_changed) {
8723 width = parser->encoding->char_width(parser->current.end, parser->end - parser->current.end);
8724 } else {
8725 width = pm_encoding_utf_8_char_width(parser->current.end, parser->end - parser->current.end);
8726 }
8727
8728 if (width == 1) {
8729 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(*parser->current.end++, flags));
8730 } else if (width > 1) {
8731 // Valid multibyte character. Just ignore escape.
8732 pm_buffer_t *b = (flags & PM_ESCAPE_FLAG_REGEXP) ? regular_expression_buffer : buffer;
8733 pm_buffer_append_bytes(b, parser->current.end, width);
8734 parser->current.end += width;
8735 } else {
8736 // Assume the next character wasn't meant to be part of this escape
8737 // sequence since it is invalid. Add an error and move on.
8738 parser->current.end++;
8739 pm_parser_err_current(parser, PM_ERR_ESCAPE_INVALID_CONTROL);
8740 }
8741 }
8742
8743 /**
8744 * Warn about using a space or a tab character in an escape, as opposed to using
8745 * \\s or \\t. Note that we can quite copy the source because the warning
8746 * message replaces \\c with \\C.
8747 */
8748 static void
8749 escape_read_warn(pm_parser_t *parser, uint8_t flags, uint8_t flag, const char *type) {
8750 #define FLAG(value) ((value & PM_ESCAPE_FLAG_CONTROL) ? "\\C-" : (value & PM_ESCAPE_FLAG_META) ? "\\M-" : "")
8751
8752 PM_PARSER_WARN_TOKEN_FORMAT(
8753 parser,
8754 parser->current,
8755 PM_WARN_INVALID_CHARACTER,
8756 FLAG(flags),
8757 FLAG(flag),
8758 type
8759 );
8760
8761 #undef FLAG
8762 }
8763
8764 /**
8765 * Read the value of an escape into the buffer.
8766 */
8767 static void
8768 escape_read(pm_parser_t *parser, pm_buffer_t *buffer, pm_buffer_t *regular_expression_buffer, uint8_t flags) {
8769 uint8_t peeked = peek(parser);
8770 switch (peeked) {
8771 case '\\': {
8772 parser->current.end++;
8773 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte('\\', flags));
8774 return;
8775 }
8776 case '\'': {
8777 parser->current.end++;
8778 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte('\'', flags));
8779 return;
8780 }
8781 case 'a': {
8782 parser->current.end++;
8783 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte('\a', flags));
8784 return;
8785 }
8786 case 'b': {
8787 parser->current.end++;
8788 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte('\b', flags));
8789 return;
8790 }
8791 case 'e': {
8792 parser->current.end++;
8793 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte('\033', flags));
8794 return;
8795 }
8796 case 'f': {
8797 parser->current.end++;
8798 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte('\f', flags));
8799 return;
8800 }
8801 case 'n': {
8802 parser->current.end++;
8803 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte('\n', flags));
8804 return;
8805 }
8806 case 'r': {
8807 parser->current.end++;
8808 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte('\r', flags));
8809 return;
8810 }
8811 case 's': {
8812 parser->current.end++;
8813 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(' ', flags));
8814 return;
8815 }
8816 case 't': {
8817 parser->current.end++;
8818 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte('\t', flags));
8819 return;
8820 }
8821 case 'v': {
8822 parser->current.end++;
8823 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte('\v', flags));
8824 return;
8825 }
8826 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': {
8827 uint8_t value = (uint8_t) (*parser->current.end - '0');
8828 parser->current.end++;
8829
8830 if (pm_char_is_octal_digit(peek(parser))) {
8831 value = ((uint8_t) (value << 3)) | ((uint8_t) (*parser->current.end - '0'));
8832 parser->current.end++;
8833
8834 if (pm_char_is_octal_digit(peek(parser))) {
8835 value = ((uint8_t) (value << 3)) | ((uint8_t) (*parser->current.end - '0'));
8836 parser->current.end++;
8837 }
8838 }
8839
8840 value = escape_byte(value, flags);
8841 escape_write_byte(parser, buffer, regular_expression_buffer, flags, value);
8842 return;
8843 }
8844 case 'x': {
8845 const uint8_t *start = parser->current.end - 1;
8846
8847 parser->current.end++;
8848 uint8_t byte = peek(parser);
8849
8850 if (pm_char_is_hexadecimal_digit(byte)) {
8851 uint8_t value = escape_hexadecimal_digit(byte);
8852 parser->current.end++;
8853
8854 byte = peek(parser);
8855 if (pm_char_is_hexadecimal_digit(byte)) {
8856 value = (uint8_t) ((value << 4) | escape_hexadecimal_digit(byte));
8857 parser->current.end++;
8858 }
8859
8860 value = escape_byte(value, flags);
8861 if (flags & PM_ESCAPE_FLAG_REGEXP) {
8862 if (flags & (PM_ESCAPE_FLAG_CONTROL | PM_ESCAPE_FLAG_META)) {
8863 pm_buffer_append_format(regular_expression_buffer, "\\x%02X", value);
8864 } else {
8865 pm_buffer_append_bytes(regular_expression_buffer, start, (size_t) (parser->current.end - start));
8866 }
8867 }
8868
8869 escape_write_byte_encoded(parser, buffer, value);
8870 } else {
8871 pm_parser_err_current(parser, PM_ERR_ESCAPE_INVALID_HEXADECIMAL);
8872 }
8873
8874 return;
8875 }
8876 case 'u': {
8877 const uint8_t *start = parser->current.end - 1;
8878 parser->current.end++;
8879
8880 if (parser->current.end == parser->end) {
8881 const uint8_t *start = parser->current.end - 2;
8882 PM_PARSER_ERR_FORMAT(parser, start, parser->current.end, PM_ERR_ESCAPE_INVALID_UNICODE_SHORT, 2, start);
8883 } else if (peek(parser) == '{') {
8884 const uint8_t *unicode_codepoints_start = parser->current.end - 2;
8885 parser->current.end++;
8886
8887 size_t whitespace;
8888 while (true) {
8889 if ((whitespace = pm_strspn_inline_whitespace(parser->current.end, parser->end - parser->current.end)) > 0) {
8890 parser->current.end += whitespace;
8891 } else if (peek(parser) == '\\' && peek_offset(parser, 1) == 'n') {
8892 // This is super hacky, but it gets us nicer error
8893 // messages because we can still pass it off to the
8894 // regular expression engine even if we hit an
8895 // unterminated regular expression.
8896 parser->current.end += 2;
8897 } else {
8898 break;
8899 }
8900 }
8901
8902 const uint8_t *extra_codepoints_start = NULL;
8903 int codepoints_count = 0;
8904
8905 while ((parser->current.end < parser->end) && (*parser->current.end != '}')) {
8906 const uint8_t *unicode_start = parser->current.end;
8907 size_t hexadecimal_length = pm_strspn_hexadecimal_digit(parser->current.end, parser->end - parser->current.end);
8908
8909 if (hexadecimal_length > 6) {
8910 // \u{nnnn} character literal allows only 1-6 hexadecimal digits
8911 pm_parser_err(parser, unicode_start, unicode_start + hexadecimal_length, PM_ERR_ESCAPE_INVALID_UNICODE_LONG);
8912 } else if (hexadecimal_length == 0) {
8913 // there are not hexadecimal characters
8914
8915 if (flags & PM_ESCAPE_FLAG_REGEXP) {
8916 // If this is a regular expression, we are going to
8917 // let the regular expression engine handle this
8918 // error instead of us.
8919 pm_buffer_append_bytes(regular_expression_buffer, start, (size_t) (parser->current.end - start));
8920 } else {
8921 pm_parser_err(parser, parser->current.end, parser->current.end, PM_ERR_ESCAPE_INVALID_UNICODE);
8922 pm_parser_err(parser, parser->current.end, parser->current.end, PM_ERR_ESCAPE_INVALID_UNICODE_TERM);
8923 }
8924
8925 return;
8926 }
8927
8928 parser->current.end += hexadecimal_length;
8929 codepoints_count++;
8930 if (flags & PM_ESCAPE_FLAG_SINGLE && codepoints_count == 2) {
8931 extra_codepoints_start = unicode_start;
8932 }
8933
8934 uint32_t value = escape_unicode(parser, unicode_start, hexadecimal_length, NULL);
8935 escape_write_unicode(parser, buffer, flags, unicode_start, parser->current.end, value);
8936
8937 parser->current.end += pm_strspn_inline_whitespace(parser->current.end, parser->end - parser->current.end);
8938 }
8939
8940 // ?\u{nnnn} character literal should contain only one codepoint
8941 // and cannot be like ?\u{nnnn mmmm}.
8942 if (flags & PM_ESCAPE_FLAG_SINGLE && codepoints_count > 1) {
8943 pm_parser_err(parser, extra_codepoints_start, parser->current.end - 1, PM_ERR_ESCAPE_INVALID_UNICODE_LITERAL);
8944 }
8945
8946 if (parser->current.end == parser->end) {
8947 PM_PARSER_ERR_FORMAT(parser, start, parser->current.end, PM_ERR_ESCAPE_INVALID_UNICODE_LIST, (int) (parser->current.end - start), start);
8948 } else if (peek(parser) == '}') {
8949 parser->current.end++;
8950 } else {
8951 if (flags & PM_ESCAPE_FLAG_REGEXP) {
8952 // If this is a regular expression, we are going to let
8953 // the regular expression engine handle this error
8954 // instead of us.
8955 pm_buffer_append_bytes(regular_expression_buffer, start, (size_t) (parser->current.end - start));
8956 } else {
8957 pm_parser_err(parser, unicode_codepoints_start, parser->current.end, PM_ERR_ESCAPE_INVALID_UNICODE_TERM);
8958 }
8959 }
8960
8961 if (flags & PM_ESCAPE_FLAG_REGEXP) {
8962 pm_buffer_append_bytes(regular_expression_buffer, unicode_codepoints_start, (size_t) (parser->current.end - unicode_codepoints_start));
8963 }
8964 } else {
8965 size_t length = pm_strspn_hexadecimal_digit(parser->current.end, MIN(parser->end - parser->current.end, 4));
8966
8967 if (length == 0) {
8968 if (flags & PM_ESCAPE_FLAG_REGEXP) {
8969 pm_buffer_append_bytes(regular_expression_buffer, start, (size_t) (parser->current.end - start));
8970 } else {
8971 const uint8_t *start = parser->current.end - 2;
8972 PM_PARSER_ERR_FORMAT(parser, start, parser->current.end, PM_ERR_ESCAPE_INVALID_UNICODE_SHORT, 2, start);
8973 }
8974 } else if (length == 4) {
8975 uint32_t value = escape_unicode(parser, parser->current.end, 4, NULL);
8976
8977 if (flags & PM_ESCAPE_FLAG_REGEXP) {
8978 pm_buffer_append_bytes(regular_expression_buffer, start, (size_t) (parser->current.end + 4 - start));
8979 }
8980
8981 escape_write_unicode(parser, buffer, flags, start, parser->current.end + 4, value);
8982 parser->current.end += 4;
8983 } else {
8984 parser->current.end += length;
8985
8986 if (flags & PM_ESCAPE_FLAG_REGEXP) {
8987 // If this is a regular expression, we are going to let
8988 // the regular expression engine handle this error
8989 // instead of us.
8990 pm_buffer_append_bytes(regular_expression_buffer, start, (size_t) (parser->current.end - start));
8991 } else {
8992 pm_parser_err_current(parser, PM_ERR_ESCAPE_INVALID_UNICODE);
8993 }
8994 }
8995 }
8996
8997 return;
8998 }
8999 case 'c': {
9000 parser->current.end++;
9001 if (flags & PM_ESCAPE_FLAG_CONTROL) {
9002 pm_parser_err_current(parser, PM_ERR_ESCAPE_INVALID_CONTROL_REPEAT);
9003 }
9004
9005 if (parser->current.end == parser->end) {
9006 pm_parser_err_current(parser, PM_ERR_ESCAPE_INVALID_CONTROL);
9007 return;
9008 }
9009
9010 uint8_t peeked = peek(parser);
9011 switch (peeked) {
9012 case '?': {
9013 parser->current.end++;
9014 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(0x7f, flags));
9015 return;
9016 }
9017 case '\\':
9018 parser->current.end++;
9019
9020 if (match(parser, 'u') || match(parser, 'U')) {
9021 pm_parser_err(parser, parser->current.start, parser->current.end, PM_ERR_INVALID_ESCAPE_CHARACTER);
9022 return;
9023 }
9024
9025 escape_read(parser, buffer, regular_expression_buffer, flags | PM_ESCAPE_FLAG_CONTROL);
9026 return;
9027 case ' ':
9028 parser->current.end++;
9029 escape_read_warn(parser, flags, PM_ESCAPE_FLAG_CONTROL, "\\s");
9030 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(peeked, flags | PM_ESCAPE_FLAG_CONTROL));
9031 return;
9032 case '\t':
9033 parser->current.end++;
9034 escape_read_warn(parser, flags, 0, "\\t");
9035 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(peeked, flags | PM_ESCAPE_FLAG_CONTROL));
9036 return;
9037 default: {
9038 if (!char_is_ascii_printable(peeked)) {
9039 pm_parser_err_current(parser, PM_ERR_ESCAPE_INVALID_CONTROL);
9040 return;
9041 }
9042
9043 parser->current.end++;
9044 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(peeked, flags | PM_ESCAPE_FLAG_CONTROL));
9045 return;
9046 }
9047 }
9048 }
9049 case 'C': {
9050 parser->current.end++;
9051 if (flags & PM_ESCAPE_FLAG_CONTROL) {
9052 pm_parser_err_current(parser, PM_ERR_ESCAPE_INVALID_CONTROL_REPEAT);
9053 }
9054
9055 if (peek(parser) != '-') {
9056 size_t width = parser->encoding->char_width(parser->current.end, parser->end - parser->current.end);
9057 pm_parser_err(parser, parser->current.start, parser->current.end + width, PM_ERR_ESCAPE_INVALID_CONTROL);
9058 return;
9059 }
9060
9061 parser->current.end++;
9062 if (parser->current.end == parser->end) {
9063 pm_parser_err_current(parser, PM_ERR_ESCAPE_INVALID_CONTROL);
9064 return;
9065 }
9066
9067 uint8_t peeked = peek(parser);
9068 switch (peeked) {
9069 case '?': {
9070 parser->current.end++;
9071 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(0x7f, flags));
9072 return;
9073 }
9074 case '\\':
9075 parser->current.end++;
9076
9077 if (match(parser, 'u') || match(parser, 'U')) {
9078 pm_parser_err(parser, parser->current.start, parser->current.end, PM_ERR_INVALID_ESCAPE_CHARACTER);
9079 return;
9080 }
9081
9082 escape_read(parser, buffer, regular_expression_buffer, flags | PM_ESCAPE_FLAG_CONTROL);
9083 return;
9084 case ' ':
9085 parser->current.end++;
9086 escape_read_warn(parser, flags, PM_ESCAPE_FLAG_CONTROL, "\\s");
9087 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(peeked, flags | PM_ESCAPE_FLAG_CONTROL));
9088 return;
9089 case '\t':
9090 parser->current.end++;
9091 escape_read_warn(parser, flags, 0, "\\t");
9092 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(peeked, flags | PM_ESCAPE_FLAG_CONTROL));
9093 return;
9094 default: {
9095 if (!char_is_ascii_printable(peeked)) {
9096 size_t width = parser->encoding->char_width(parser->current.end, parser->end - parser->current.end);
9097 pm_parser_err(parser, parser->current.start, parser->current.end + width, PM_ERR_ESCAPE_INVALID_CONTROL);
9098 return;
9099 }
9100
9101 parser->current.end++;
9102 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(peeked, flags | PM_ESCAPE_FLAG_CONTROL));
9103 return;
9104 }
9105 }
9106 }
9107 case 'M': {
9108 parser->current.end++;
9109 if (flags & PM_ESCAPE_FLAG_META) {
9110 pm_parser_err_current(parser, PM_ERR_ESCAPE_INVALID_META_REPEAT);
9111 }
9112
9113 if (peek(parser) != '-') {
9114 size_t width = parser->encoding->char_width(parser->current.end, parser->end - parser->current.end);
9115 pm_parser_err(parser, parser->current.start, parser->current.end + width, PM_ERR_ESCAPE_INVALID_META);
9116 return;
9117 }
9118
9119 parser->current.end++;
9120 if (parser->current.end == parser->end) {
9121 pm_parser_err_current(parser, PM_ERR_ESCAPE_INVALID_META);
9122 return;
9123 }
9124
9125 uint8_t peeked = peek(parser);
9126 switch (peeked) {
9127 case '\\':
9128 parser->current.end++;
9129
9130 if (match(parser, 'u') || match(parser, 'U')) {
9131 pm_parser_err(parser, parser->current.start, parser->current.end, PM_ERR_INVALID_ESCAPE_CHARACTER);
9132 return;
9133 }
9134
9135 escape_read(parser, buffer, regular_expression_buffer, flags | PM_ESCAPE_FLAG_META);
9136 return;
9137 case ' ':
9138 parser->current.end++;
9139 escape_read_warn(parser, flags, PM_ESCAPE_FLAG_META, "\\s");
9140 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(peeked, flags | PM_ESCAPE_FLAG_META));
9141 return;
9142 case '\t':
9143 parser->current.end++;
9144 escape_read_warn(parser, flags & ((uint8_t) ~PM_ESCAPE_FLAG_CONTROL), PM_ESCAPE_FLAG_META, "\\t");
9145 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(peeked, flags | PM_ESCAPE_FLAG_META));
9146 return;
9147 default:
9148 if (!char_is_ascii_printable(peeked)) {
9149 size_t width = parser->encoding->char_width(parser->current.end, parser->end - parser->current.end);
9150 pm_parser_err(parser, parser->current.start, parser->current.end + width, PM_ERR_ESCAPE_INVALID_META);
9151 return;
9152 }
9153
9154 parser->current.end++;
9155 escape_write_byte(parser, buffer, regular_expression_buffer, flags, escape_byte(peeked, flags | PM_ESCAPE_FLAG_META));
9156 return;
9157 }
9158 }
9159 case '\r': {
9160 if (peek_offset(parser, 1) == '\n') {
9161 parser->current.end += 2;
9162 escape_write_byte_encoded(parser, buffer, escape_byte('\n', flags));
9163 return;
9164 }
9165 PRISM_FALLTHROUGH
9166 }
9167 default: {
9168 if ((flags & (PM_ESCAPE_FLAG_CONTROL | PM_ESCAPE_FLAG_META)) && !char_is_ascii_printable(peeked)) {
9169 size_t width = parser->encoding->char_width(parser->current.end, parser->end - parser->current.end);
9170 pm_parser_err(parser, parser->current.start, parser->current.end + width, PM_ERR_ESCAPE_INVALID_META);
9171 return;
9172 }
9173 if (parser->current.end < parser->end) {
9174 escape_write_escape_encoded(parser, buffer, regular_expression_buffer, flags);
9175 } else {
9176 pm_parser_err_current(parser, PM_ERR_INVALID_ESCAPE_CHARACTER);
9177 }
9178 return;
9179 }
9180 }
9181 }
9182
9183 /**
9184 * This function is responsible for lexing either a character literal or the ?
9185 * operator. The supported character literals are described below.
9186 *
9187 * \\a bell, ASCII 07h (BEL)
9188 * \\b backspace, ASCII 08h (BS)
9189 * \t horizontal tab, ASCII 09h (TAB)
9190 * \\n newline (line feed), ASCII 0Ah (LF)
9191 * \v vertical tab, ASCII 0Bh (VT)
9192 * \f form feed, ASCII 0Ch (FF)
9193 * \r carriage return, ASCII 0Dh (CR)
9194 * \\e escape, ASCII 1Bh (ESC)
9195 * \s space, ASCII 20h (SPC)
9196 * \\ backslash
9197 * \nnn octal bit pattern, where nnn is 1-3 octal digits ([0-7])
9198 * \xnn hexadecimal bit pattern, where nn is 1-2 hexadecimal digits ([0-9a-fA-F])
9199 * \unnnn Unicode character, where nnnn is exactly 4 hexadecimal digits ([0-9a-fA-F])
9200 * \u{nnnn ...} Unicode character(s), where each nnnn is 1-6 hexadecimal digits ([0-9a-fA-F])
9201 * \cx or \C-x control character, where x is an ASCII printable character
9202 * \M-x meta character, where x is an ASCII printable character
9203 * \M-\C-x meta control character, where x is an ASCII printable character
9204 * \M-\cx same as above
9205 * \\c\M-x same as above
9206 * \\c? or \C-? delete, ASCII 7Fh (DEL)
9207 */
9208 static pm_token_type_t
9209 lex_question_mark(pm_parser_t *parser) {
9210 if (lex_state_end_p(parser)) {
9211 lex_state_set(parser, PM_LEX_STATE_BEG);
9212 return PM_TOKEN_QUESTION_MARK;
9213 }
9214
9215 if (parser->current.end >= parser->end) {
9216 pm_parser_err_current(parser, PM_ERR_INCOMPLETE_QUESTION_MARK);
9217 pm_string_shared_init(&parser->current_string, parser->current.start + 1, parser->current.end);
9218 return PM_TOKEN_CHARACTER_LITERAL;
9219 }
9220
9221 if (pm_char_is_whitespace(*parser->current.end)) {
9222 lex_state_set(parser, PM_LEX_STATE_BEG);
9223 return PM_TOKEN_QUESTION_MARK;
9224 }
9225
9226 lex_state_set(parser, PM_LEX_STATE_BEG);
9227
9228 if (match(parser, '\\')) {
9229 lex_state_set(parser, PM_LEX_STATE_END);
9230
9231 pm_buffer_t buffer;
9232 pm_buffer_init_capacity(&buffer, 3);
9233
9234 escape_read(parser, &buffer, NULL, PM_ESCAPE_FLAG_SINGLE);
9235 pm_string_owned_init(&parser->current_string, (uint8_t *) buffer.value, buffer.length);
9236
9237 return PM_TOKEN_CHARACTER_LITERAL;
9238 } else {
9239 size_t encoding_width = parser->encoding->char_width(parser->current.end, parser->end - parser->current.end);
9240
9241 // Ternary operators can have a ? immediately followed by an identifier
9242 // which starts with an underscore. We check for this case here.
9243 if (
9244 !(parser->encoding->alnum_char(parser->current.end, parser->end - parser->current.end) || peek(parser) == '_') ||
9245 (
9246 (parser->current.end + encoding_width >= parser->end) ||
9247 !char_is_identifier(parser, parser->current.end + encoding_width, parser->end - (parser->current.end + encoding_width))
9248 )
9249 ) {
9250 lex_state_set(parser, PM_LEX_STATE_END);
9251 parser->current.end += encoding_width;
9252 pm_string_shared_init(&parser->current_string, parser->current.start + 1, parser->current.end);
9253 return PM_TOKEN_CHARACTER_LITERAL;
9254 }
9255 }
9256
9257 return PM_TOKEN_QUESTION_MARK;
9258 }
9259
9260 /**
9261 * Lex a variable that starts with an @ sign (either an instance or class
9262 * variable).
9263 */
9264 static pm_token_type_t
9265 lex_at_variable(pm_parser_t *parser) {
9266 pm_token_type_t type = match(parser, '@') ? PM_TOKEN_CLASS_VARIABLE : PM_TOKEN_INSTANCE_VARIABLE;
9267 const uint8_t *end = parser->end;
9268
9269 size_t width;
9270 if ((width = char_is_identifier_start(parser, parser->current.end, end - parser->current.end)) > 0) {
9271 parser->current.end += width;
9272
9273 while ((width = char_is_identifier(parser, parser->current.end, end - parser->current.end)) > 0) {
9274 parser->current.end += width;
9275 }
9276 } else if (parser->current.end < end && pm_char_is_decimal_digit(*parser->current.end)) {
9277 pm_diagnostic_id_t diag_id = (type == PM_TOKEN_CLASS_VARIABLE) ? PM_ERR_INCOMPLETE_VARIABLE_CLASS : PM_ERR_INCOMPLETE_VARIABLE_INSTANCE;
9278 if (parser->version <= PM_OPTIONS_VERSION_CRUBY_3_3) {
9279 diag_id = (type == PM_TOKEN_CLASS_VARIABLE) ? PM_ERR_INCOMPLETE_VARIABLE_CLASS_3_3 : PM_ERR_INCOMPLETE_VARIABLE_INSTANCE_3_3;
9280 }
9281
9282 size_t width = parser->encoding->char_width(parser->current.end, end - parser->current.end);
9283 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, diag_id, (int) ((parser->current.end + width) - parser->current.start), (const char *) parser->current.start);
9284 } else {
9285 pm_diagnostic_id_t diag_id = (type == PM_TOKEN_CLASS_VARIABLE) ? PM_ERR_CLASS_VARIABLE_BARE : PM_ERR_INSTANCE_VARIABLE_BARE;
9286 pm_parser_err_token(parser, &parser->current, diag_id);
9287 }
9288
9289 // If we're lexing an embedded variable, then we need to pop back into the
9290 // parent lex context.
9291 if (parser->lex_modes.current->mode == PM_LEX_EMBVAR) {
9292 lex_mode_pop(parser);
9293 }
9294
9295 return type;
9296 }
9297
9298 /**
9299 * Optionally call out to the lex callback if one is provided.
9300 */
9301 static inline void
9302 parser_lex_callback(pm_parser_t *parser) {
9303 if (parser->lex_callback) {
9304 parser->lex_callback->callback(parser->lex_callback->data, parser, &parser->current);
9305 }
9306 }
9307
9308 /**
9309 * Return a new comment node of the specified type.
9310 */
9311 static inline pm_comment_t *
9312 parser_comment(pm_parser_t *parser, pm_comment_type_t type) {
9313 pm_comment_t *comment = (pm_comment_t *) xcalloc(1, sizeof(pm_comment_t));
9314 if (comment == NULL) return NULL;
9315
9316 *comment = (pm_comment_t) {
9317 .type = type,
9318 .location = { parser->current.start, parser->current.end }
9319 };
9320
9321 return comment;
9322 }
9323
9324 /**
9325 * Lex out embedded documentation, and return when we have either hit the end of
9326 * the file or the end of the embedded documentation. This calls the callback
9327 * manually because only the lexer should see these tokens, not the parser.
9328 */
9329 static pm_token_type_t
9330 lex_embdoc(pm_parser_t *parser) {
9331 // First, lex out the EMBDOC_BEGIN token.
9332 const uint8_t *newline = next_newline(parser->current.end, parser->end - parser->current.end);
9333
9334 if (newline == NULL) {
9335 parser->current.end = parser->end;
9336 } else {
9337 pm_newline_list_append(&parser->newline_list, newline);
9338 parser->current.end = newline + 1;
9339 }
9340
9341 parser->current.type = PM_TOKEN_EMBDOC_BEGIN;
9342 parser_lex_callback(parser);
9343
9344 // Now, create a comment that is going to be attached to the parser.
9345 pm_comment_t *comment = parser_comment(parser, PM_COMMENT_EMBDOC);
9346 if (comment == NULL) return PM_TOKEN_EOF;
9347
9348 // Now, loop until we find the end of the embedded documentation or the end
9349 // of the file.
9350 while (parser->current.end + 4 <= parser->end) {
9351 parser->current.start = parser->current.end;
9352
9353 // If we've hit the end of the embedded documentation then we'll return
9354 // that token here.
9355 if (
9356 (memcmp(parser->current.end, "=end", 4) == 0) &&
9357 (
9358 (parser->current.end + 4 == parser->end) || // end of file
9359 pm_char_is_whitespace(parser->current.end[4]) || // whitespace
9360 (parser->current.end[4] == '\0') || // NUL or end of script
9361 (parser->current.end[4] == '\004') || // ^D
9362 (parser->current.end[4] == '\032') // ^Z
9363 )
9364 ) {
9365 const uint8_t *newline = next_newline(parser->current.end, parser->end - parser->current.end);
9366
9367 if (newline == NULL) {
9368 parser->current.end = parser->end;
9369 } else {
9370 pm_newline_list_append(&parser->newline_list, newline);
9371 parser->current.end = newline + 1;
9372 }
9373
9374 parser->current.type = PM_TOKEN_EMBDOC_END;
9375 parser_lex_callback(parser);
9376
9377 comment->location.end = parser->current.end;
9378 pm_list_append(&parser->comment_list, (pm_list_node_t *) comment);
9379
9380 return PM_TOKEN_EMBDOC_END;
9381 }
9382
9383 // Otherwise, we'll parse until the end of the line and return a line of
9384 // embedded documentation.
9385 const uint8_t *newline = next_newline(parser->current.end, parser->end - parser->current.end);
9386
9387 if (newline == NULL) {
9388 parser->current.end = parser->end;
9389 } else {
9390 pm_newline_list_append(&parser->newline_list, newline);
9391 parser->current.end = newline + 1;
9392 }
9393
9394 parser->current.type = PM_TOKEN_EMBDOC_LINE;
9395 parser_lex_callback(parser);
9396 }
9397
9398 pm_parser_err_current(parser, PM_ERR_EMBDOC_TERM);
9399
9400 comment->location.end = parser->current.end;
9401 pm_list_append(&parser->comment_list, (pm_list_node_t *) comment);
9402
9403 return PM_TOKEN_EOF;
9404 }
9405
9406 /**
9407 * Set the current type to an ignored newline and then call the lex callback.
9408 * This happens in a couple places depending on whether or not we have already
9409 * lexed a comment.
9410 */
9411 static inline void
9412 parser_lex_ignored_newline(pm_parser_t *parser) {
9413 parser->current.type = PM_TOKEN_IGNORED_NEWLINE;
9414 parser_lex_callback(parser);
9415 }
9416
9417 /**
9418 * This function will be called when a newline is encountered. In some newlines,
9419 * we need to check if there is a heredoc or heredocs that we have already lexed
9420 * the body of that we need to now skip past. That will be indicated by the
9421 * heredoc_end field on the parser.
9422 *
9423 * If it is set, then we need to skip past the heredoc body and then clear the
9424 * heredoc_end field.
9425 */
9426 static inline void
9427 parser_flush_heredoc_end(pm_parser_t *parser) {
9428 assert(parser->heredoc_end <= parser->end);
9429 parser->next_start = parser->heredoc_end;
9430 parser->heredoc_end = NULL;
9431 }
9432
9433 /**
9434 * Returns true if the parser has lexed the last token on the current line.
9435 */
9436 static bool
9437 parser_end_of_line_p(const pm_parser_t *parser) {
9438 const uint8_t *cursor = parser->current.end;
9439
9440 while (cursor < parser->end && *cursor != '\n' && *cursor != '#') {
9441 if (!pm_char_is_inline_whitespace(*cursor++)) return false;
9442 }
9443
9444 return true;
9445 }
9446
9447 /**
9448 * When we're lexing certain types (strings, symbols, lists, etc.) we have
9449 * string content associated with the tokens. For example:
9450 *
9451 * "foo"
9452 *
9453 * In this case, the string content is foo. Since there is no escaping, there's
9454 * no need to track additional information and the token can be returned as
9455 * normal. However, if we have escape sequences:
9456 *
9457 * "foo\n"
9458 *
9459 * then the bytes in the string are "f", "o", "o", "\", "n", but we want to
9460 * provide our consumers with the string content "f", "o", "o", "\n". In these
9461 * cases, when we find the first escape sequence, we initialize a pm_buffer_t
9462 * to keep track of the string content. Then in the parser, it will
9463 * automatically attach the string content to the node that it belongs to.
9464 */
9465 typedef struct {
9466 /**
9467 * The buffer that we're using to keep track of the string content. It will
9468 * only be initialized if we receive an escape sequence.
9469 */
9470 pm_buffer_t buffer;
9471
9472 /**
9473 * The cursor into the source string that points to how far we have
9474 * currently copied into the buffer.
9475 */
9476 const uint8_t *cursor;
9477 } pm_token_buffer_t;
9478
9479 /**
9480 * In order to properly set a regular expression's encoding and to validate
9481 * the byte sequence for the underlying encoding we must process any escape
9482 * sequences. The unescaped byte sequence will be stored in `buffer` just like
9483 * for other string-like types. However, we also need to store the regular
9484 * expression's source string. That string may be different from what we see
9485 * during lexing because some escape sequences rewrite the source.
9486 *
9487 * This value will only be initialized for regular expressions and only if we
9488 * receive an escape sequence. It will contain the regular expression's source
9489 * string's byte sequence.
9490 */
9491 typedef struct {
9492 /** The embedded base buffer. */
9493 pm_token_buffer_t base;
9494
9495 /** The buffer holding the regexp source. */
9496 pm_buffer_t regexp_buffer;
9497 } pm_regexp_token_buffer_t;
9498
9499 /**
9500 * Push the given byte into the token buffer.
9501 */
9502 static inline void
9503 pm_token_buffer_push_byte(pm_token_buffer_t *token_buffer, uint8_t byte) {
9504 pm_buffer_append_byte(&token_buffer->buffer, byte);
9505 }
9506
9507 static inline void
9508 pm_regexp_token_buffer_push_byte(pm_regexp_token_buffer_t *token_buffer, uint8_t byte) {
9509 pm_buffer_append_byte(&token_buffer->regexp_buffer, byte);
9510 }
9511
9512 /**
9513 * Return the width of the character at the end of the current token.
9514 */
9515 static inline size_t
9516 parser_char_width(const pm_parser_t *parser) {
9517 size_t width;
9518 if (parser->encoding_changed) {
9519 width = parser->encoding->char_width(parser->current.end, parser->end - parser->current.end);
9520 } else {
9521 width = pm_encoding_utf_8_char_width(parser->current.end, parser->end - parser->current.end);
9522 }
9523
9524 // TODO: If the character is invalid in the given encoding, then we'll just
9525 // push one byte into the buffer. This should actually be an error.
9526 return (width == 0 ? 1 : width);
9527 }
9528
9529 /**
9530 * Push an escaped character into the token buffer.
9531 */
9532 static void
9533 pm_token_buffer_push_escaped(pm_token_buffer_t *token_buffer, pm_parser_t *parser) {
9534 size_t width = parser_char_width(parser);
9535 pm_buffer_append_bytes(&token_buffer->buffer, parser->current.end, width);
9536 parser->current.end += width;
9537 }
9538
9539 static void
9540 pm_regexp_token_buffer_push_escaped(pm_regexp_token_buffer_t *token_buffer, pm_parser_t *parser) {
9541 size_t width = parser_char_width(parser);
9542 pm_buffer_append_bytes(&token_buffer->base.buffer, parser->current.end, width);
9543 pm_buffer_append_bytes(&token_buffer->regexp_buffer, parser->current.end, width);
9544 parser->current.end += width;
9545 }
9546
9547 static bool
9548 pm_slice_ascii_only_p(const uint8_t *value, size_t length) {
9549 for (size_t index = 0; index < length; index++) {
9550 if (value[index] & 0x80) return false;
9551 }
9552
9553 return true;
9554 }
9555
9556 /**
9557 * When we're about to return from lexing the current token and we know for sure
9558 * that we have found an escape sequence, this function is called to copy the
9559 * contents of the token buffer into the current string on the parser so that it
9560 * can be attached to the correct node.
9561 */
9562 static inline void
9563 pm_token_buffer_copy(pm_parser_t *parser, pm_token_buffer_t *token_buffer) {
9564 pm_string_owned_init(&parser->current_string, (uint8_t *) pm_buffer_value(&token_buffer->buffer), pm_buffer_length(&token_buffer->buffer));
9565 }
9566
9567 static inline void
9568 pm_regexp_token_buffer_copy(pm_parser_t *parser, pm_regexp_token_buffer_t *token_buffer) {
9569 pm_string_owned_init(&parser->current_string, (uint8_t *) pm_buffer_value(&token_buffer->base.buffer), pm_buffer_length(&token_buffer->base.buffer));
9570 parser->current_regular_expression_ascii_only = pm_slice_ascii_only_p((const uint8_t *) pm_buffer_value(&token_buffer->regexp_buffer), pm_buffer_length(&token_buffer->regexp_buffer));
9571 pm_buffer_free(&token_buffer->regexp_buffer);
9572 }
9573
9574 /**
9575 * When we're about to return from lexing the current token, we need to flush
9576 * all of the content that we have pushed into the buffer into the current
9577 * string. If we haven't pushed anything into the buffer, this means that we
9578 * never found an escape sequence, so we can directly reference the bounds of
9579 * the current string. Either way, at the return of this function it is expected
9580 * that parser->current_string is established in such a way that it can be
9581 * attached to a node.
9582 */
9583 static void
9584 pm_token_buffer_flush(pm_parser_t *parser, pm_token_buffer_t *token_buffer) {
9585 if (token_buffer->cursor == NULL) {
9586 pm_string_shared_init(&parser->current_string, parser->current.start, parser->current.end);
9587 } else {
9588 pm_buffer_append_bytes(&token_buffer->buffer, token_buffer->cursor, (size_t) (parser->current.end - token_buffer->cursor));
9589 pm_token_buffer_copy(parser, token_buffer);
9590 }
9591 }
9592
9593 static void
9594 pm_regexp_token_buffer_flush(pm_parser_t *parser, pm_regexp_token_buffer_t *token_buffer) {
9595 if (token_buffer->base.cursor == NULL) {
9596 pm_string_shared_init(&parser->current_string, parser->current.start, parser->current.end);
9597 parser->current_regular_expression_ascii_only = pm_slice_ascii_only_p(parser->current.start, (size_t) (parser->current.end - parser->current.start));
9598 } else {
9599 pm_buffer_append_bytes(&token_buffer->base.buffer, token_buffer->base.cursor, (size_t) (parser->current.end - token_buffer->base.cursor));
9600 pm_buffer_append_bytes(&token_buffer->regexp_buffer, token_buffer->base.cursor, (size_t) (parser->current.end - token_buffer->base.cursor));
9601 pm_regexp_token_buffer_copy(parser, token_buffer);
9602 }
9603 }
9604
9605 #define PM_TOKEN_BUFFER_DEFAULT_SIZE 16
9606
9607 /**
9608 * When we've found an escape sequence, we need to copy everything up to this
9609 * point into the buffer because we're about to provide a string that has
9610 * different content than a direct slice of the source.
9611 *
9612 * It is expected that the parser's current token end will be pointing at one
9613 * byte past the backslash that starts the escape sequence.
9614 */
9615 static void
9616 pm_token_buffer_escape(pm_parser_t *parser, pm_token_buffer_t *token_buffer) {
9617 const uint8_t *start;
9618 if (token_buffer->cursor == NULL) {
9619 pm_buffer_init_capacity(&token_buffer->buffer, PM_TOKEN_BUFFER_DEFAULT_SIZE);
9620 start = parser->current.start;
9621 } else {
9622 start = token_buffer->cursor;
9623 }
9624
9625 const uint8_t *end = parser->current.end - 1;
9626 assert(end >= start);
9627 pm_buffer_append_bytes(&token_buffer->buffer, start, (size_t) (end - start));
9628
9629 token_buffer->cursor = end;
9630 }
9631
9632 static void
9633 pm_regexp_token_buffer_escape(pm_parser_t *parser, pm_regexp_token_buffer_t *token_buffer) {
9634 const uint8_t *start;
9635 if (token_buffer->base.cursor == NULL) {
9636 pm_buffer_init_capacity(&token_buffer->base.buffer, PM_TOKEN_BUFFER_DEFAULT_SIZE);
9637 pm_buffer_init_capacity(&token_buffer->regexp_buffer, PM_TOKEN_BUFFER_DEFAULT_SIZE);
9638 start = parser->current.start;
9639 } else {
9640 start = token_buffer->base.cursor;
9641 }
9642
9643 const uint8_t *end = parser->current.end - 1;
9644 pm_buffer_append_bytes(&token_buffer->base.buffer, start, (size_t) (end - start));
9645 pm_buffer_append_bytes(&token_buffer->regexp_buffer, start, (size_t) (end - start));
9646
9647 token_buffer->base.cursor = end;
9648 }
9649
9650 #undef PM_TOKEN_BUFFER_DEFAULT_SIZE
9651
9652 /**
9653 * Effectively the same thing as pm_strspn_inline_whitespace, but in the case of
9654 * a tilde heredoc expands out tab characters to the nearest tab boundaries.
9655 */
9656 static inline size_t
9657 pm_heredoc_strspn_inline_whitespace(pm_parser_t *parser, const uint8_t **cursor, pm_heredoc_indent_t indent) {
9658 size_t whitespace = 0;
9659
9660 switch (indent) {
9661 case PM_HEREDOC_INDENT_NONE:
9662 // Do nothing, we can't match a terminator with
9663 // indentation and there's no need to calculate common
9664 // whitespace.
9665 break;
9666 case PM_HEREDOC_INDENT_DASH:
9667 // Skip past inline whitespace.
9668 *cursor += pm_strspn_inline_whitespace(*cursor, parser->end - *cursor);
9669 break;
9670 case PM_HEREDOC_INDENT_TILDE:
9671 // Skip past inline whitespace and calculate common
9672 // whitespace.
9673 while (*cursor < parser->end && pm_char_is_inline_whitespace(**cursor)) {
9674 if (**cursor == '\t') {
9675 whitespace = (whitespace / PM_TAB_WHITESPACE_SIZE + 1) * PM_TAB_WHITESPACE_SIZE;
9676 } else {
9677 whitespace++;
9678 }
9679 (*cursor)++;
9680 }
9681
9682 break;
9683 }
9684
9685 return whitespace;
9686 }
9687
9688 /**
9689 * Lex past the delimiter of a percent literal. Handle newlines and heredocs
9690 * appropriately.
9691 */
9692 static uint8_t
9693 pm_lex_percent_delimiter(pm_parser_t *parser) {
9694 size_t eol_length = match_eol(parser);
9695
9696 if (eol_length) {
9697 if (parser->heredoc_end) {
9698 // If we have already lexed a heredoc, then the newline has already
9699 // been added to the list. In this case we want to just flush the
9700 // heredoc end.
9701 parser_flush_heredoc_end(parser);
9702 } else {
9703 // Otherwise, we'll add the newline to the list of newlines.
9704 pm_newline_list_append(&parser->newline_list, parser->current.end + eol_length - 1);
9705 }
9706
9707 uint8_t delimiter = *parser->current.end;
9708
9709 // If our delimiter is \r\n, we want to treat it as if it's \n.
9710 // For example, %\r\nfoo\r\n should be "foo"
9711 if (eol_length == 2) {
9712 delimiter = *(parser->current.end + 1);
9713 }
9714
9715 parser->current.end += eol_length;
9716 return delimiter;
9717 }
9718
9719 return *parser->current.end++;
9720 }
9721
9722 /**
9723 * This is a convenience macro that will set the current token type, call the
9724 * lex callback, and then return from the parser_lex function.
9725 */
9726 #define LEX(token_type) parser->current.type = token_type; parser_lex_callback(parser); return
9727
9728 /**
9729 * Called when the parser requires a new token. The parser maintains a moving
9730 * window of two tokens at a time: parser.previous and parser.current. This
9731 * function will move the current token into the previous token and then
9732 * lex a new token into the current token.
9733 */
9734 static void
9735 parser_lex(pm_parser_t *parser) {
9736 assert(parser->current.end <= parser->end);
9737 parser->previous = parser->current;
9738
9739 // This value mirrors cmd_state from CRuby.
9740 bool previous_command_start = parser->command_start;
9741 parser->command_start = false;
9742
9743 // This is used to communicate to the newline lexing function that we've
9744 // already seen a comment.
9745 bool lexed_comment = false;
9746
9747 // Here we cache the current value of the semantic token seen flag. This is
9748 // used to reset it in case we find a token that shouldn't flip this flag.
9749 unsigned int semantic_token_seen = parser->semantic_token_seen;
9750 parser->semantic_token_seen = true;
9751
9752 switch (parser->lex_modes.current->mode) {
9753 case PM_LEX_DEFAULT:
9754 case PM_LEX_EMBEXPR:
9755 case PM_LEX_EMBVAR:
9756
9757 // We have a specific named label here because we are going to jump back to
9758 // this location in the event that we have lexed a token that should not be
9759 // returned to the parser. This includes comments, ignored newlines, and
9760 // invalid tokens of some form.
9761 lex_next_token: {
9762 // If we have the special next_start pointer set, then we're going to jump
9763 // to that location and start lexing from there.
9764 if (parser->next_start != NULL) {
9765 parser->current.end = parser->next_start;
9766 parser->next_start = NULL;
9767 }
9768
9769 // This value mirrors space_seen from CRuby. It tracks whether or not
9770 // space has been eaten before the start of the next token.
9771 bool space_seen = false;
9772
9773 // First, we're going to skip past any whitespace at the front of the next
9774 // token.
9775 bool chomping = true;
9776 while (parser->current.end < parser->end && chomping) {
9777 switch (*parser->current.end) {
9778 case ' ':
9779 case '\t':
9780 case '\f':
9781 case '\v':
9782 parser->current.end++;
9783 space_seen = true;
9784 break;
9785 case '\r':
9786 if (match_eol_offset(parser, 1)) {
9787 chomping = false;
9788 } else {
9789 pm_parser_warn(parser, parser->current.end, parser->current.end + 1, PM_WARN_UNEXPECTED_CARRIAGE_RETURN);
9790 parser->current.end++;
9791 space_seen = true;
9792 }
9793 break;
9794 case '\\': {
9795 size_t eol_length = match_eol_offset(parser, 1);
9796 if (eol_length) {
9797 if (parser->heredoc_end) {
9798 parser->current.end = parser->heredoc_end;
9799 parser->heredoc_end = NULL;
9800 } else {
9801 parser->current.end += eol_length + 1;
9802 pm_newline_list_append(&parser->newline_list, parser->current.end - 1);
9803 space_seen = true;
9804 }
9805 } else if (pm_char_is_inline_whitespace(*parser->current.end)) {
9806 parser->current.end += 2;
9807 } else {
9808 chomping = false;
9809 }
9810
9811 break;
9812 }
9813 default:
9814 chomping = false;
9815 break;
9816 }
9817 }
9818
9819 // Next, we'll set to start of this token to be the current end.
9820 parser->current.start = parser->current.end;
9821
9822 // We'll check if we're at the end of the file. If we are, then we
9823 // need to return the EOF token.
9824 if (parser->current.end >= parser->end) {
9825 // If we hit EOF, but the EOF came immediately after a newline,
9826 // set the start of the token to the newline. This way any EOF
9827 // errors will be reported as happening on that line rather than
9828 // a line after. For example "foo(\n" should report an error
9829 // on line 1 even though EOF technically occurs on line 2.
9830 if (parser->current.start > parser->start && (*(parser->current.start - 1) == '\n')) {
9831 parser->current.start -= 1;
9832 }
9833 LEX(PM_TOKEN_EOF);
9834 }
9835
9836 // Finally, we'll check the current character to determine the next
9837 // token.
9838 switch (*parser->current.end++) {
9839 case '\0': // NUL or end of script
9840 case '\004': // ^D
9841 case '\032': // ^Z
9842 parser->current.end--;
9843 LEX(PM_TOKEN_EOF);
9844
9845 case '#': { // comments
9846 const uint8_t *ending = next_newline(parser->current.end, parser->end - parser->current.end);
9847 parser->current.end = ending == NULL ? parser->end : ending;
9848
9849 // If we found a comment while lexing, then we're going to
9850 // add it to the list of comments in the file and keep
9851 // lexing.
9852 pm_comment_t *comment = parser_comment(parser, PM_COMMENT_INLINE);
9853 pm_list_append(&parser->comment_list, (pm_list_node_t *) comment);
9854
9855 if (ending) parser->current.end++;
9856 parser->current.type = PM_TOKEN_COMMENT;
9857 parser_lex_callback(parser);
9858
9859 // Here, parse the comment to see if it's a magic comment
9860 // and potentially change state on the parser.
9861 if (!parser_lex_magic_comment(parser, semantic_token_seen) && (parser->current.start == parser->encoding_comment_start)) {
9862 ptrdiff_t length = parser->current.end - parser->current.start;
9863
9864 // If we didn't find a magic comment within the first
9865 // pass and we're at the start of the file, then we need
9866 // to do another pass to potentially find other patterns
9867 // for encoding comments.
9868 if (length >= 10 && !parser->encoding_locked) {
9869 parser_lex_magic_comment_encoding(parser);
9870 }
9871 }
9872
9873 lexed_comment = true;
9874 }
9875 PRISM_FALLTHROUGH
9876 case '\r':
9877 case '\n': {
9878 parser->semantic_token_seen = semantic_token_seen & 0x1;
9879 size_t eol_length = match_eol_at(parser, parser->current.end - 1);
9880
9881 if (eol_length) {
9882 // The only way you can have carriage returns in this
9883 // particular loop is if you have a carriage return
9884 // followed by a newline. In that case we'll just skip
9885 // over the carriage return and continue lexing, in
9886 // order to make it so that the newline token
9887 // encapsulates both the carriage return and the
9888 // newline. Note that we need to check that we haven't
9889 // already lexed a comment here because that falls
9890 // through into here as well.
9891 if (!lexed_comment) {
9892 parser->current.end += eol_length - 1; // skip CR
9893 }
9894
9895 if (parser->heredoc_end == NULL) {
9896 pm_newline_list_append(&parser->newline_list, parser->current.end - 1);
9897 }
9898 }
9899
9900 if (parser->heredoc_end) {
9901 parser_flush_heredoc_end(parser);
9902 }
9903
9904 // If this is an ignored newline, then we can continue lexing after
9905 // calling the callback with the ignored newline token.
9906 switch (lex_state_ignored_p(parser)) {
9907 case PM_IGNORED_NEWLINE_NONE:
9908 break;
9909 case PM_IGNORED_NEWLINE_PATTERN:
9910 if (parser->pattern_matching_newlines || parser->in_keyword_arg) {
9911 if (!lexed_comment) parser_lex_ignored_newline(parser);
9912 lex_state_set(parser, PM_LEX_STATE_BEG);
9913 parser->command_start = true;
9914 parser->current.type = PM_TOKEN_NEWLINE;
9915 return;
9916 }
9917 PRISM_FALLTHROUGH
9918 case PM_IGNORED_NEWLINE_ALL:
9919 if (!lexed_comment) parser_lex_ignored_newline(parser);
9920 lexed_comment = false;
9921 goto lex_next_token;
9922 }
9923
9924 // Here we need to look ahead and see if there is a call operator
9925 // (either . or &.) that starts the next line. If there is, then this
9926 // is going to become an ignored newline and we're going to instead
9927 // return the call operator.
9928 const uint8_t *next_content = parser->next_start == NULL ? parser->current.end : parser->next_start;
9929 next_content += pm_strspn_inline_whitespace(next_content, parser->end - next_content);
9930
9931 if (next_content < parser->end) {
9932 // If we hit a comment after a newline, then we're going to check
9933 // if it's ignored or if it's followed by a method call ('.').
9934 // If it is, then we're going to call the
9935 // callback with an ignored newline and then continue lexing.
9936 // Otherwise we'll return a regular newline.
9937 if (next_content[0] == '#') {
9938 // Here we look for a "." or "&." following a "\n".
9939 const uint8_t *following = next_newline(next_content, parser->end - next_content);
9940
9941 while (following && (following + 1 < parser->end)) {
9942 following++;
9943 following += pm_strspn_inline_whitespace(following, parser->end - following);
9944
9945 // If this is not followed by a comment, then we can break out
9946 // of this loop.
9947 if (peek_at(parser, following) != '#') break;
9948
9949 // If there is a comment, then we need to find the end of the
9950 // comment and continue searching from there.
9951 following = next_newline(following, parser->end - following);
9952 }
9953
9954 // If the lex state was ignored, we will lex the
9955 // ignored newline.
9956 if (lex_state_ignored_p(parser)) {
9957 if (!lexed_comment) parser_lex_ignored_newline(parser);
9958 lexed_comment = false;
9959 goto lex_next_token;
9960 }
9961
9962 // If we hit a '.' or a '&.' we will lex the ignored
9963 // newline.
9964 if (following && (
9965 (peek_at(parser, following) == '.') ||
9966 (peek_at(parser, following) == '&' && peek_at(parser, following + 1) == '.')
9967 )) {
9968 if (!lexed_comment) parser_lex_ignored_newline(parser);
9969 lexed_comment = false;
9970 goto lex_next_token;
9971 }
9972
9973
9974 // If we are parsing as CRuby 4.0 or later and we
9975 // hit a '&&' or a '||' then we will lex the ignored
9976 // newline.
9977 if (
9978 (parser->version >= PM_OPTIONS_VERSION_CRUBY_4_0) &&
9979 following && (
9980 (peek_at(parser, following) == '&' && peek_at(parser, following + 1) == '&') ||
9981 (peek_at(parser, following) == '|' && peek_at(parser, following + 1) == '|') ||
9982 (peek_at(parser, following) == 'a' && peek_at(parser, following + 1) == 'n' && peek_at(parser, following + 2) == 'd' && !char_is_identifier(parser, following + 3, parser->end - (following + 3))) ||
9983 (peek_at(parser, following) == 'o' && peek_at(parser, following + 1) == 'r' && !char_is_identifier(parser, following + 2, parser->end - (following + 2)))
9984 )
9985 ) {
9986 if (!lexed_comment) parser_lex_ignored_newline(parser);
9987 lexed_comment = false;
9988 goto lex_next_token;
9989 }
9990 }
9991
9992 // If we hit a . after a newline, then we're in a call chain and
9993 // we need to return the call operator.
9994 if (next_content[0] == '.') {
9995 // To match ripper, we need to emit an ignored newline even though
9996 // it's a real newline in the case that we have a beginless range
9997 // on a subsequent line.
9998 if (peek_at(parser, next_content + 1) == '.') {
9999 if (!lexed_comment) parser_lex_ignored_newline(parser);
10000 lex_state_set(parser, PM_LEX_STATE_BEG);
10001 parser->command_start = true;
10002 parser->current.type = PM_TOKEN_NEWLINE;
10003 return;
10004 }
10005
10006 if (!lexed_comment) parser_lex_ignored_newline(parser);
10007 lex_state_set(parser, PM_LEX_STATE_DOT);
10008 parser->current.start = next_content;
10009 parser->current.end = next_content + 1;
10010 parser->next_start = NULL;
10011 LEX(PM_TOKEN_DOT);
10012 }
10013
10014 // If we hit a &. after a newline, then we're in a call chain and
10015 // we need to return the call operator.
10016 if (peek_at(parser, next_content) == '&' && peek_at(parser, next_content + 1) == '.') {
10017 if (!lexed_comment) parser_lex_ignored_newline(parser);
10018 lex_state_set(parser, PM_LEX_STATE_DOT);
10019 parser->current.start = next_content;
10020 parser->current.end = next_content + 2;
10021 parser->next_start = NULL;
10022 LEX(PM_TOKEN_AMPERSAND_DOT);
10023 }
10024
10025 if (parser->version >= PM_OPTIONS_VERSION_CRUBY_4_0) {
10026 // If we hit an && then we are in a logical chain
10027 // and we need to return the logical operator.
10028 if (peek_at(parser, next_content) == '&' && peek_at(parser, next_content + 1) == '&') {
10029 if (!lexed_comment) parser_lex_ignored_newline(parser);
10030 lex_state_set(parser, PM_LEX_STATE_BEG);
10031 parser->current.start = next_content;
10032 parser->current.end = next_content + 2;
10033 parser->next_start = NULL;
10034 LEX(PM_TOKEN_AMPERSAND_AMPERSAND);
10035 }
10036
10037 // If we hit a || then we are in a logical chain and
10038 // we need to return the logical operator.
10039 if (peek_at(parser, next_content) == '|' && peek_at(parser, next_content + 1) == '|') {
10040 if (!lexed_comment) parser_lex_ignored_newline(parser);
10041 lex_state_set(parser, PM_LEX_STATE_BEG);
10042 parser->current.start = next_content;
10043 parser->current.end = next_content + 2;
10044 parser->next_start = NULL;
10045 LEX(PM_TOKEN_PIPE_PIPE);
10046 }
10047
10048 // If we hit an 'and' then we are in a logical chain
10049 // and we need to return the logical operator.
10050 if (
10051 peek_at(parser, next_content) == 'a' &&
10052 peek_at(parser, next_content + 1) == 'n' &&
10053 peek_at(parser, next_content + 2) == 'd' &&
10054 !char_is_identifier(parser, next_content + 3, parser->end - (next_content + 3))
10055 ) {
10056 if (!lexed_comment) parser_lex_ignored_newline(parser);
10057 lex_state_set(parser, PM_LEX_STATE_BEG);
10058 parser->current.start = next_content;
10059 parser->current.end = next_content + 3;
10060 parser->next_start = NULL;
10061 parser->command_start = true;
10062 LEX(PM_TOKEN_KEYWORD_AND);
10063 }
10064
10065 // If we hit a 'or' then we are in a logical chain
10066 // and we need to return the logical operator.
10067 if (
10068 peek_at(parser, next_content) == 'o' &&
10069 peek_at(parser, next_content + 1) == 'r' &&
10070 !char_is_identifier(parser, next_content + 2, parser->end - (next_content + 2))
10071 ) {
10072 if (!lexed_comment) parser_lex_ignored_newline(parser);
10073 lex_state_set(parser, PM_LEX_STATE_BEG);
10074 parser->current.start = next_content;
10075 parser->current.end = next_content + 2;
10076 parser->next_start = NULL;
10077 parser->command_start = true;
10078 LEX(PM_TOKEN_KEYWORD_OR);
10079 }
10080 }
10081 }
10082
10083 // At this point we know this is a regular newline, and we can set the
10084 // necessary state and return the token.
10085 lex_state_set(parser, PM_LEX_STATE_BEG);
10086 parser->command_start = true;
10087 parser->current.type = PM_TOKEN_NEWLINE;
10088 if (!lexed_comment) parser_lex_callback(parser);
10089 return;
10090 }
10091
10092 // ,
10093 case ',':
10094 if ((parser->previous.type == PM_TOKEN_COMMA) && (parser->enclosure_nesting > 0)) {
10095 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_ARRAY_TERM, pm_token_type_human(parser->current.type));
10096 }
10097
10098 lex_state_set(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_LABEL);
10099 LEX(PM_TOKEN_COMMA);
10100
10101 // (
10102 case '(': {
10103 pm_token_type_t type = PM_TOKEN_PARENTHESIS_LEFT;
10104
10105 if (space_seen && (lex_state_arg_p(parser) || parser->lex_state == (PM_LEX_STATE_END | PM_LEX_STATE_LABEL))) {
10106 type = PM_TOKEN_PARENTHESIS_LEFT_PARENTHESES;
10107 }
10108
10109 parser->enclosure_nesting++;
10110 lex_state_set(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_LABEL);
10111 pm_do_loop_stack_push(parser, false);
10112 LEX(type);
10113 }
10114
10115 // )
10116 case ')':
10117 parser->enclosure_nesting--;
10118 lex_state_set(parser, PM_LEX_STATE_ENDFN);
10119 pm_do_loop_stack_pop(parser);
10120 LEX(PM_TOKEN_PARENTHESIS_RIGHT);
10121
10122 // ;
10123 case ';':
10124 lex_state_set(parser, PM_LEX_STATE_BEG);
10125 parser->command_start = true;
10126 LEX(PM_TOKEN_SEMICOLON);
10127
10128 // [ [] []=
10129 case '[':
10130 parser->enclosure_nesting++;
10131 pm_token_type_t type = PM_TOKEN_BRACKET_LEFT;
10132
10133 if (lex_state_operator_p(parser)) {
10134 if (match(parser, ']')) {
10135 parser->enclosure_nesting--;
10136 lex_state_set(parser, PM_LEX_STATE_ARG);
10137 LEX(match(parser, '=') ? PM_TOKEN_BRACKET_LEFT_RIGHT_EQUAL : PM_TOKEN_BRACKET_LEFT_RIGHT);
10138 }
10139
10140 lex_state_set(parser, PM_LEX_STATE_ARG | PM_LEX_STATE_LABEL);
10141 LEX(type);
10142 }
10143
10144 if (lex_state_beg_p(parser) || (lex_state_arg_p(parser) && (space_seen || lex_state_p(parser, PM_LEX_STATE_LABELED)))) {
10145 type = PM_TOKEN_BRACKET_LEFT_ARRAY;
10146 }
10147
10148 lex_state_set(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_LABEL);
10149 pm_do_loop_stack_push(parser, false);
10150 LEX(type);
10151
10152 // ]
10153 case ']':
10154 parser->enclosure_nesting--;
10155 lex_state_set(parser, PM_LEX_STATE_END);
10156 pm_do_loop_stack_pop(parser);
10157 LEX(PM_TOKEN_BRACKET_RIGHT);
10158
10159 // {
10160 case '{': {
10161 pm_token_type_t type = PM_TOKEN_BRACE_LEFT;
10162
10163 if (parser->enclosure_nesting == parser->lambda_enclosure_nesting) {
10164 // This { begins a lambda
10165 parser->command_start = true;
10166 lex_state_set(parser, PM_LEX_STATE_BEG);
10167 type = PM_TOKEN_LAMBDA_BEGIN;
10168 } else if (lex_state_p(parser, PM_LEX_STATE_LABELED)) {
10169 // This { begins a hash literal
10170 lex_state_set(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_LABEL);
10171 } else if (lex_state_p(parser, PM_LEX_STATE_ARG_ANY | PM_LEX_STATE_END | PM_LEX_STATE_ENDFN)) {
10172 // This { begins a block
10173 parser->command_start = true;
10174 lex_state_set(parser, PM_LEX_STATE_BEG);
10175 } else if (lex_state_p(parser, PM_LEX_STATE_ENDARG)) {
10176 // This { begins a block on a command
10177 parser->command_start = true;
10178 lex_state_set(parser, PM_LEX_STATE_BEG);
10179 } else {
10180 // This { begins a hash literal
10181 lex_state_set(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_LABEL);
10182 }
10183
10184 parser->enclosure_nesting++;
10185 parser->brace_nesting++;
10186 pm_do_loop_stack_push(parser, false);
10187
10188 LEX(type);
10189 }
10190
10191 // }
10192 case '}':
10193 parser->enclosure_nesting--;
10194 pm_do_loop_stack_pop(parser);
10195
10196 if ((parser->lex_modes.current->mode == PM_LEX_EMBEXPR) && (parser->brace_nesting == 0)) {
10197 lex_mode_pop(parser);
10198 LEX(PM_TOKEN_EMBEXPR_END);
10199 }
10200
10201 parser->brace_nesting--;
10202 lex_state_set(parser, PM_LEX_STATE_END);
10203 LEX(PM_TOKEN_BRACE_RIGHT);
10204
10205 // * ** **= *=
10206 case '*': {
10207 if (match(parser, '*')) {
10208 if (match(parser, '=')) {
10209 lex_state_set(parser, PM_LEX_STATE_BEG);
10210 LEX(PM_TOKEN_STAR_STAR_EQUAL);
10211 }
10212
10213 pm_token_type_t type = PM_TOKEN_STAR_STAR;
10214
10215 if (lex_state_spcarg_p(parser, space_seen)) {
10216 pm_parser_warn_token(parser, &parser->current, PM_WARN_AMBIGUOUS_PREFIX_STAR_STAR);
10217 type = PM_TOKEN_USTAR_STAR;
10218 } else if (lex_state_beg_p(parser)) {
10219 type = PM_TOKEN_USTAR_STAR;
10220 } else if (ambiguous_operator_p(parser, space_seen)) {
10221 PM_PARSER_WARN_TOKEN_FORMAT(parser, parser->current, PM_WARN_AMBIGUOUS_BINARY_OPERATOR, "**", "argument prefix");
10222 }
10223
10224 if (lex_state_operator_p(parser)) {
10225 lex_state_set(parser, PM_LEX_STATE_ARG);
10226 } else {
10227 lex_state_set(parser, PM_LEX_STATE_BEG);
10228 }
10229
10230 LEX(type);
10231 }
10232
10233 if (match(parser, '=')) {
10234 lex_state_set(parser, PM_LEX_STATE_BEG);
10235 LEX(PM_TOKEN_STAR_EQUAL);
10236 }
10237
10238 pm_token_type_t type = PM_TOKEN_STAR;
10239
10240 if (lex_state_spcarg_p(parser, space_seen)) {
10241 pm_parser_warn_token(parser, &parser->current, PM_WARN_AMBIGUOUS_PREFIX_STAR);
10242 type = PM_TOKEN_USTAR;
10243 } else if (lex_state_beg_p(parser)) {
10244 type = PM_TOKEN_USTAR;
10245 } else if (ambiguous_operator_p(parser, space_seen)) {
10246 PM_PARSER_WARN_TOKEN_FORMAT(parser, parser->current, PM_WARN_AMBIGUOUS_BINARY_OPERATOR, "*", "argument prefix");
10247 }
10248
10249 if (lex_state_operator_p(parser)) {
10250 lex_state_set(parser, PM_LEX_STATE_ARG);
10251 } else {
10252 lex_state_set(parser, PM_LEX_STATE_BEG);
10253 }
10254
10255 LEX(type);
10256 }
10257
10258 // ! != !~ !@
10259 case '!':
10260 if (lex_state_operator_p(parser)) {
10261 lex_state_set(parser, PM_LEX_STATE_ARG);
10262 if (match(parser, '@')) {
10263 LEX(PM_TOKEN_BANG);
10264 }
10265 } else {
10266 lex_state_set(parser, PM_LEX_STATE_BEG);
10267 }
10268
10269 if (match(parser, '=')) {
10270 LEX(PM_TOKEN_BANG_EQUAL);
10271 }
10272
10273 if (match(parser, '~')) {
10274 LEX(PM_TOKEN_BANG_TILDE);
10275 }
10276
10277 LEX(PM_TOKEN_BANG);
10278
10279 // = => =~ == === =begin
10280 case '=':
10281 if (
10282 current_token_starts_line(parser) &&
10283 (parser->current.end + 5 <= parser->end) &&
10284 memcmp(parser->current.end, "begin", 5) == 0 &&
10285 (pm_char_is_whitespace(peek_offset(parser, 5)) || (peek_offset(parser, 5) == '\0'))
10286 ) {
10287 pm_token_type_t type = lex_embdoc(parser);
10288 if (type == PM_TOKEN_EOF) {
10289 LEX(type);
10290 }
10291
10292 goto lex_next_token;
10293 }
10294
10295 if (lex_state_operator_p(parser)) {
10296 lex_state_set(parser, PM_LEX_STATE_ARG);
10297 } else {
10298 lex_state_set(parser, PM_LEX_STATE_BEG);
10299 }
10300
10301 if (match(parser, '>')) {
10302 LEX(PM_TOKEN_EQUAL_GREATER);
10303 }
10304
10305 if (match(parser, '~')) {
10306 LEX(PM_TOKEN_EQUAL_TILDE);
10307 }
10308
10309 if (match(parser, '=')) {
10310 LEX(match(parser, '=') ? PM_TOKEN_EQUAL_EQUAL_EQUAL : PM_TOKEN_EQUAL_EQUAL);
10311 }
10312
10313 LEX(PM_TOKEN_EQUAL);
10314
10315 // < << <<= <= <=>
10316 case '<':
10317 if (match(parser, '<')) {
10318 if (
10319 !lex_state_p(parser, PM_LEX_STATE_DOT | PM_LEX_STATE_CLASS) &&
10320 !lex_state_end_p(parser) &&
10321 (!lex_state_p(parser, PM_LEX_STATE_ARG_ANY) || lex_state_p(parser, PM_LEX_STATE_LABELED) || space_seen)
10322 ) {
10323 const uint8_t *end = parser->current.end;
10324
10325 pm_heredoc_quote_t quote = PM_HEREDOC_QUOTE_NONE;
10326 pm_heredoc_indent_t indent = PM_HEREDOC_INDENT_NONE;
10327
10328 if (match(parser, '-')) {
10329 indent = PM_HEREDOC_INDENT_DASH;
10330 }
10331 else if (match(parser, '~')) {
10332 indent = PM_HEREDOC_INDENT_TILDE;
10333 }
10334
10335 if (match(parser, '`')) {
10336 quote = PM_HEREDOC_QUOTE_BACKTICK;
10337 }
10338 else if (match(parser, '"')) {
10339 quote = PM_HEREDOC_QUOTE_DOUBLE;
10340 }
10341 else if (match(parser, '\'')) {
10342 quote = PM_HEREDOC_QUOTE_SINGLE;
10343 }
10344
10345 const uint8_t *ident_start = parser->current.end;
10346 size_t width = 0;
10347
10348 if (parser->current.end >= parser->end) {
10349 parser->current.end = end;
10350 } else if (quote == PM_HEREDOC_QUOTE_NONE && (width = char_is_identifier(parser, parser->current.end, parser->end - parser->current.end)) == 0) {
10351 parser->current.end = end;
10352 } else {
10353 if (quote == PM_HEREDOC_QUOTE_NONE) {
10354 parser->current.end += width;
10355
10356 while ((width = char_is_identifier(parser, parser->current.end, parser->end - parser->current.end))) {
10357 parser->current.end += width;
10358 }
10359 } else {
10360 // If we have quotes, then we're going to go until we find the
10361 // end quote.
10362 while ((parser->current.end < parser->end) && quote != (pm_heredoc_quote_t) (*parser->current.end)) {
10363 if (*parser->current.end == '\r' || *parser->current.end == '\n') break;
10364 parser->current.end++;
10365 }
10366 }
10367
10368 size_t ident_length = (size_t) (parser->current.end - ident_start);
10369 bool ident_error = false;
10370
10371 if (quote != PM_HEREDOC_QUOTE_NONE && !match(parser, (uint8_t) quote)) {
10372 pm_parser_err(parser, ident_start, ident_start + ident_length, PM_ERR_HEREDOC_IDENTIFIER);
10373 ident_error = true;
10374 }
10375
10376 parser->explicit_encoding = NULL;
10377 lex_mode_push(parser, (pm_lex_mode_t) {
10378 .mode = PM_LEX_HEREDOC,
10379 .as.heredoc = {
10380 .base = {
10381 .ident_start = ident_start,
10382 .ident_length = ident_length,
10383 .quote = quote,
10384 .indent = indent
10385 },
10386 .next_start = parser->current.end,
10387 .common_whitespace = NULL,
10388 .line_continuation = false
10389 }
10390 });
10391
10392 if (parser->heredoc_end == NULL) {
10393 const uint8_t *body_start = next_newline(parser->current.end, parser->end - parser->current.end);
10394
10395 if (body_start == NULL) {
10396 // If there is no newline after the heredoc identifier, then
10397 // this is not a valid heredoc declaration. In this case we
10398 // will add an error, but we will still return a heredoc
10399 // start.
10400 if (!ident_error) pm_parser_err_heredoc_term(parser, ident_start, ident_length);
10401 body_start = parser->end;
10402 } else {
10403 // Otherwise, we want to indicate that the body of the
10404 // heredoc starts on the character after the next newline.
10405 pm_newline_list_append(&parser->newline_list, body_start);
10406 body_start++;
10407 }
10408
10409 parser->next_start = body_start;
10410 } else {
10411 parser->next_start = parser->heredoc_end;
10412 }
10413
10414 LEX(PM_TOKEN_HEREDOC_START);
10415 }
10416 }
10417
10418 if (match(parser, '=')) {
10419 lex_state_set(parser, PM_LEX_STATE_BEG);
10420 LEX(PM_TOKEN_LESS_LESS_EQUAL);
10421 }
10422
10423 if (ambiguous_operator_p(parser, space_seen)) {
10424 PM_PARSER_WARN_TOKEN_FORMAT(parser, parser->current, PM_WARN_AMBIGUOUS_BINARY_OPERATOR, "<<", "here document");
10425 }
10426
10427 if (lex_state_operator_p(parser)) {
10428 lex_state_set(parser, PM_LEX_STATE_ARG);
10429 } else {
10430 if (lex_state_p(parser, PM_LEX_STATE_CLASS)) parser->command_start = true;
10431 lex_state_set(parser, PM_LEX_STATE_BEG);
10432 }
10433
10434 LEX(PM_TOKEN_LESS_LESS);
10435 }
10436
10437 if (lex_state_operator_p(parser)) {
10438 lex_state_set(parser, PM_LEX_STATE_ARG);
10439 } else {
10440 if (lex_state_p(parser, PM_LEX_STATE_CLASS)) parser->command_start = true;
10441 lex_state_set(parser, PM_LEX_STATE_BEG);
10442 }
10443
10444 if (match(parser, '=')) {
10445 if (match(parser, '>')) {
10446 LEX(PM_TOKEN_LESS_EQUAL_GREATER);
10447 }
10448
10449 LEX(PM_TOKEN_LESS_EQUAL);
10450 }
10451
10452 LEX(PM_TOKEN_LESS);
10453
10454 // > >> >>= >=
10455 case '>':
10456 if (match(parser, '>')) {
10457 if (lex_state_operator_p(parser)) {
10458 lex_state_set(parser, PM_LEX_STATE_ARG);
10459 } else {
10460 lex_state_set(parser, PM_LEX_STATE_BEG);
10461 }
10462 LEX(match(parser, '=') ? PM_TOKEN_GREATER_GREATER_EQUAL : PM_TOKEN_GREATER_GREATER);
10463 }
10464
10465 if (lex_state_operator_p(parser)) {
10466 lex_state_set(parser, PM_LEX_STATE_ARG);
10467 } else {
10468 lex_state_set(parser, PM_LEX_STATE_BEG);
10469 }
10470
10471 LEX(match(parser, '=') ? PM_TOKEN_GREATER_EQUAL : PM_TOKEN_GREATER);
10472
10473 // double-quoted string literal
10474 case '"': {
10475 bool label_allowed = (lex_state_p(parser, PM_LEX_STATE_LABEL | PM_LEX_STATE_ENDFN) && !previous_command_start) || lex_state_arg_p(parser);
10476 lex_mode_push_string(parser, true, label_allowed, '\0', '"');
10477 LEX(PM_TOKEN_STRING_BEGIN);
10478 }
10479
10480 // xstring literal
10481 case '`': {
10482 if (lex_state_p(parser, PM_LEX_STATE_FNAME)) {
10483 lex_state_set(parser, PM_LEX_STATE_ENDFN);
10484 LEX(PM_TOKEN_BACKTICK);
10485 }
10486
10487 if (lex_state_p(parser, PM_LEX_STATE_DOT)) {
10488 if (previous_command_start) {
10489 lex_state_set(parser, PM_LEX_STATE_CMDARG);
10490 } else {
10491 lex_state_set(parser, PM_LEX_STATE_ARG);
10492 }
10493
10494 LEX(PM_TOKEN_BACKTICK);
10495 }
10496
10497 lex_mode_push_string(parser, true, false, '\0', '`');
10498 LEX(PM_TOKEN_BACKTICK);
10499 }
10500
10501 // single-quoted string literal
10502 case '\'': {
10503 bool label_allowed = (lex_state_p(parser, PM_LEX_STATE_LABEL | PM_LEX_STATE_ENDFN) && !previous_command_start) || lex_state_arg_p(parser);
10504 lex_mode_push_string(parser, false, label_allowed, '\0', '\'');
10505 LEX(PM_TOKEN_STRING_BEGIN);
10506 }
10507
10508 // ? character literal
10509 case '?':
10510 LEX(lex_question_mark(parser));
10511
10512 // & && &&= &=
10513 case '&': {
10514 if (match(parser, '&')) {
10515 lex_state_set(parser, PM_LEX_STATE_BEG);
10516
10517 if (match(parser, '=')) {
10518 LEX(PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL);
10519 }
10520
10521 LEX(PM_TOKEN_AMPERSAND_AMPERSAND);
10522 }
10523
10524 if (match(parser, '=')) {
10525 lex_state_set(parser, PM_LEX_STATE_BEG);
10526 LEX(PM_TOKEN_AMPERSAND_EQUAL);
10527 }
10528
10529 if (match(parser, '.')) {
10530 lex_state_set(parser, PM_LEX_STATE_DOT);
10531 LEX(PM_TOKEN_AMPERSAND_DOT);
10532 }
10533
10534 pm_token_type_t type = PM_TOKEN_AMPERSAND;
10535 if (lex_state_spcarg_p(parser, space_seen)) {
10536 if ((peek(parser) != ':') || (peek_offset(parser, 1) == '\0')) {
10537 pm_parser_warn_token(parser, &parser->current, PM_WARN_AMBIGUOUS_PREFIX_AMPERSAND);
10538 } else {
10539 const uint8_t delim = peek_offset(parser, 1);
10540
10541 if ((delim != '\'') && (delim != '"') && !char_is_identifier(parser, parser->current.end + 1, parser->end - (parser->current.end + 1))) {
10542 pm_parser_warn_token(parser, &parser->current, PM_WARN_AMBIGUOUS_PREFIX_AMPERSAND);
10543 }
10544 }
10545
10546 type = PM_TOKEN_UAMPERSAND;
10547 } else if (lex_state_beg_p(parser)) {
10548 type = PM_TOKEN_UAMPERSAND;
10549 } else if (ambiguous_operator_p(parser, space_seen)) {
10550 PM_PARSER_WARN_TOKEN_FORMAT(parser, parser->current, PM_WARN_AMBIGUOUS_BINARY_OPERATOR, "&", "argument prefix");
10551 }
10552
10553 if (lex_state_operator_p(parser)) {
10554 lex_state_set(parser, PM_LEX_STATE_ARG);
10555 } else {
10556 lex_state_set(parser, PM_LEX_STATE_BEG);
10557 }
10558
10559 LEX(type);
10560 }
10561
10562 // | || ||= |=
10563 case '|':
10564 if (match(parser, '|')) {
10565 if (match(parser, '=')) {
10566 lex_state_set(parser, PM_LEX_STATE_BEG);
10567 LEX(PM_TOKEN_PIPE_PIPE_EQUAL);
10568 }
10569
10570 if (lex_state_p(parser, PM_LEX_STATE_BEG)) {
10571 parser->current.end--;
10572 LEX(PM_TOKEN_PIPE);
10573 }
10574
10575 lex_state_set(parser, PM_LEX_STATE_BEG);
10576 LEX(PM_TOKEN_PIPE_PIPE);
10577 }
10578
10579 if (match(parser, '=')) {
10580 lex_state_set(parser, PM_LEX_STATE_BEG);
10581 LEX(PM_TOKEN_PIPE_EQUAL);
10582 }
10583
10584 if (lex_state_operator_p(parser)) {
10585 lex_state_set(parser, PM_LEX_STATE_ARG);
10586 } else {
10587 lex_state_set(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_LABEL);
10588 }
10589
10590 LEX(PM_TOKEN_PIPE);
10591
10592 // + += +@
10593 case '+': {
10594 if (lex_state_operator_p(parser)) {
10595 lex_state_set(parser, PM_LEX_STATE_ARG);
10596
10597 if (match(parser, '@')) {
10598 LEX(PM_TOKEN_UPLUS);
10599 }
10600
10601 LEX(PM_TOKEN_PLUS);
10602 }
10603
10604 if (match(parser, '=')) {
10605 lex_state_set(parser, PM_LEX_STATE_BEG);
10606 LEX(PM_TOKEN_PLUS_EQUAL);
10607 }
10608
10609 if (
10610 lex_state_beg_p(parser) ||
10611 (lex_state_spcarg_p(parser, space_seen) ? (pm_parser_warn_token(parser, &parser->current, PM_WARN_AMBIGUOUS_FIRST_ARGUMENT_PLUS), true) : false)
10612 ) {
10613 lex_state_set(parser, PM_LEX_STATE_BEG);
10614
10615 if (pm_char_is_decimal_digit(peek(parser))) {
10616 parser->current.end++;
10617 pm_token_type_t type = lex_numeric(parser);
10618 lex_state_set(parser, PM_LEX_STATE_END);
10619 LEX(type);
10620 }
10621
10622 LEX(PM_TOKEN_UPLUS);
10623 }
10624
10625 if (ambiguous_operator_p(parser, space_seen)) {
10626 PM_PARSER_WARN_TOKEN_FORMAT(parser, parser->current, PM_WARN_AMBIGUOUS_BINARY_OPERATOR, "+", "unary operator");
10627 }
10628
10629 lex_state_set(parser, PM_LEX_STATE_BEG);
10630 LEX(PM_TOKEN_PLUS);
10631 }
10632
10633 // - -= -@
10634 case '-': {
10635 if (lex_state_operator_p(parser)) {
10636 lex_state_set(parser, PM_LEX_STATE_ARG);
10637
10638 if (match(parser, '@')) {
10639 LEX(PM_TOKEN_UMINUS);
10640 }
10641
10642 LEX(PM_TOKEN_MINUS);
10643 }
10644
10645 if (match(parser, '=')) {
10646 lex_state_set(parser, PM_LEX_STATE_BEG);
10647 LEX(PM_TOKEN_MINUS_EQUAL);
10648 }
10649
10650 if (match(parser, '>')) {
10651 lex_state_set(parser, PM_LEX_STATE_ENDFN);
10652 LEX(PM_TOKEN_MINUS_GREATER);
10653 }
10654
10655 bool spcarg = lex_state_spcarg_p(parser, space_seen);
10656 bool is_beg = lex_state_beg_p(parser);
10657 if (!is_beg && spcarg) {
10658 pm_parser_warn_token(parser, &parser->current, PM_WARN_AMBIGUOUS_FIRST_ARGUMENT_MINUS);
10659 }
10660
10661 if (is_beg || spcarg) {
10662 lex_state_set(parser, PM_LEX_STATE_BEG);
10663 LEX(pm_char_is_decimal_digit(peek(parser)) ? PM_TOKEN_UMINUS_NUM : PM_TOKEN_UMINUS);
10664 }
10665
10666 if (ambiguous_operator_p(parser, space_seen)) {
10667 PM_PARSER_WARN_TOKEN_FORMAT(parser, parser->current, PM_WARN_AMBIGUOUS_BINARY_OPERATOR, "-", "unary operator");
10668 }
10669
10670 lex_state_set(parser, PM_LEX_STATE_BEG);
10671 LEX(PM_TOKEN_MINUS);
10672 }
10673
10674 // . .. ...
10675 case '.': {
10676 bool beg_p = lex_state_beg_p(parser);
10677
10678 if (match(parser, '.')) {
10679 if (match(parser, '.')) {
10680 // If we're _not_ inside a range within default parameters
10681 if (!context_p(parser, PM_CONTEXT_DEFAULT_PARAMS) && context_p(parser, PM_CONTEXT_DEF_PARAMS)) {
10682 if (lex_state_p(parser, PM_LEX_STATE_END)) {
10683 lex_state_set(parser, PM_LEX_STATE_BEG);
10684 } else {
10685 lex_state_set(parser, PM_LEX_STATE_ENDARG);
10686 }
10687 LEX(PM_TOKEN_UDOT_DOT_DOT);
10688 }
10689
10690 if (parser->enclosure_nesting == 0 && parser_end_of_line_p(parser)) {
10691 pm_parser_warn_token(parser, &parser->current, PM_WARN_DOT_DOT_DOT_EOL);
10692 }
10693
10694 lex_state_set(parser, PM_LEX_STATE_BEG);
10695 LEX(beg_p ? PM_TOKEN_UDOT_DOT_DOT : PM_TOKEN_DOT_DOT_DOT);
10696 }
10697
10698 lex_state_set(parser, PM_LEX_STATE_BEG);
10699 LEX(beg_p ? PM_TOKEN_UDOT_DOT : PM_TOKEN_DOT_DOT);
10700 }
10701
10702 lex_state_set(parser, PM_LEX_STATE_DOT);
10703 LEX(PM_TOKEN_DOT);
10704 }
10705
10706 // integer
10707 case '0':
10708 case '1':
10709 case '2':
10710 case '3':
10711 case '4':
10712 case '5':
10713 case '6':
10714 case '7':
10715 case '8':
10716 case '9': {
10717 pm_token_type_t type = lex_numeric(parser);
10718 lex_state_set(parser, PM_LEX_STATE_END);
10719 LEX(type);
10720 }
10721
10722 // :: symbol
10723 case ':':
10724 if (match(parser, ':')) {
10725 if (lex_state_beg_p(parser) || lex_state_p(parser, PM_LEX_STATE_CLASS) || (lex_state_p(parser, PM_LEX_STATE_ARG_ANY) && space_seen)) {
10726 lex_state_set(parser, PM_LEX_STATE_BEG);
10727 LEX(PM_TOKEN_UCOLON_COLON);
10728 }
10729
10730 lex_state_set(parser, PM_LEX_STATE_DOT);
10731 LEX(PM_TOKEN_COLON_COLON);
10732 }
10733
10734 if (lex_state_end_p(parser) || pm_char_is_whitespace(peek(parser)) || peek(parser) == '#') {
10735 lex_state_set(parser, PM_LEX_STATE_BEG);
10736 LEX(PM_TOKEN_COLON);
10737 }
10738
10739 if (peek(parser) == '"' || peek(parser) == '\'') {
10740 lex_mode_push_string(parser, peek(parser) == '"', false, '\0', *parser->current.end);
10741 parser->current.end++;
10742 }
10743
10744 lex_state_set(parser, PM_LEX_STATE_FNAME);
10745 LEX(PM_TOKEN_SYMBOL_BEGIN);
10746
10747 // / /=
10748 case '/':
10749 if (lex_state_beg_p(parser)) {
10750 lex_mode_push_regexp(parser, '\0', '/');
10751 LEX(PM_TOKEN_REGEXP_BEGIN);
10752 }
10753
10754 if (match(parser, '=')) {
10755 lex_state_set(parser, PM_LEX_STATE_BEG);
10756 LEX(PM_TOKEN_SLASH_EQUAL);
10757 }
10758
10759 if (lex_state_spcarg_p(parser, space_seen)) {
10760 pm_parser_warn_token(parser, &parser->current, PM_WARN_AMBIGUOUS_SLASH);
10761 lex_mode_push_regexp(parser, '\0', '/');
10762 LEX(PM_TOKEN_REGEXP_BEGIN);
10763 }
10764
10765 if (ambiguous_operator_p(parser, space_seen)) {
10766 PM_PARSER_WARN_TOKEN_FORMAT(parser, parser->current, PM_WARN_AMBIGUOUS_BINARY_OPERATOR, "/", "regexp literal");
10767 }
10768
10769 if (lex_state_operator_p(parser)) {
10770 lex_state_set(parser, PM_LEX_STATE_ARG);
10771 } else {
10772 lex_state_set(parser, PM_LEX_STATE_BEG);
10773 }
10774
10775 LEX(PM_TOKEN_SLASH);
10776
10777 // ^ ^=
10778 case '^':
10779 if (lex_state_operator_p(parser)) {
10780 lex_state_set(parser, PM_LEX_STATE_ARG);
10781 } else {
10782 lex_state_set(parser, PM_LEX_STATE_BEG);
10783 }
10784 LEX(match(parser, '=') ? PM_TOKEN_CARET_EQUAL : PM_TOKEN_CARET);
10785
10786 // ~ ~@
10787 case '~':
10788 if (lex_state_operator_p(parser)) {
10789 (void) match(parser, '@');
10790 lex_state_set(parser, PM_LEX_STATE_ARG);
10791 } else {
10792 lex_state_set(parser, PM_LEX_STATE_BEG);
10793 }
10794
10795 LEX(PM_TOKEN_TILDE);
10796
10797 // % %= %i %I %q %Q %w %W
10798 case '%': {
10799 // If there is no subsequent character then we have an
10800 // invalid token. We're going to say it's the percent
10801 // operator because we don't want to move into the string
10802 // lex mode unnecessarily.
10803 if ((lex_state_beg_p(parser) || lex_state_arg_p(parser)) && (parser->current.end >= parser->end)) {
10804 pm_parser_err_current(parser, PM_ERR_INVALID_PERCENT_EOF);
10805 LEX(PM_TOKEN_PERCENT);
10806 }
10807
10808 if (!lex_state_beg_p(parser) && match(parser, '=')) {
10809 lex_state_set(parser, PM_LEX_STATE_BEG);
10810 LEX(PM_TOKEN_PERCENT_EQUAL);
10811 } else if (
10812 lex_state_beg_p(parser) ||
10813 (lex_state_p(parser, PM_LEX_STATE_FITEM) && (peek(parser) == 's')) ||
10814 lex_state_spcarg_p(parser, space_seen)
10815 ) {
10816 if (!parser->encoding->alnum_char(parser->current.end, parser->end - parser->current.end)) {
10817 if (*parser->current.end >= 0x80) {
10818 pm_parser_err_current(parser, PM_ERR_INVALID_PERCENT);
10819 }
10820
10821 const uint8_t delimiter = pm_lex_percent_delimiter(parser);
10822 lex_mode_push_string(parser, true, false, lex_mode_incrementor(delimiter), lex_mode_terminator(delimiter));
10823 LEX(PM_TOKEN_STRING_BEGIN);
10824 }
10825
10826 // Delimiters for %-literals cannot be alphanumeric. We
10827 // validate that here.
10828 uint8_t delimiter = peek_offset(parser, 1);
10829 if (delimiter >= 0x80 || parser->encoding->alnum_char(&delimiter, 1)) {
10830 pm_parser_err_current(parser, PM_ERR_INVALID_PERCENT);
10831 goto lex_next_token;
10832 }
10833
10834 switch (peek(parser)) {
10835 case 'i': {
10836 parser->current.end++;
10837
10838 if (parser->current.end < parser->end) {
10839 lex_mode_push_list(parser, false, pm_lex_percent_delimiter(parser));
10840 } else {
10841 lex_mode_push_list_eof(parser);
10842 }
10843
10844 LEX(PM_TOKEN_PERCENT_LOWER_I);
10845 }
10846 case 'I': {
10847 parser->current.end++;
10848
10849 if (parser->current.end < parser->end) {
10850 lex_mode_push_list(parser, true, pm_lex_percent_delimiter(parser));
10851 } else {
10852 lex_mode_push_list_eof(parser);
10853 }
10854
10855 LEX(PM_TOKEN_PERCENT_UPPER_I);
10856 }
10857 case 'r': {
10858 parser->current.end++;
10859
10860 if (parser->current.end < parser->end) {
10861 const uint8_t delimiter = pm_lex_percent_delimiter(parser);
10862 lex_mode_push_regexp(parser, lex_mode_incrementor(delimiter), lex_mode_terminator(delimiter));
10863 } else {
10864 lex_mode_push_regexp(parser, '\0', '\0');
10865 }
10866
10867 LEX(PM_TOKEN_REGEXP_BEGIN);
10868 }
10869 case 'q': {
10870 parser->current.end++;
10871
10872 if (parser->current.end < parser->end) {
10873 const uint8_t delimiter = pm_lex_percent_delimiter(parser);
10874 lex_mode_push_string(parser, false, false, lex_mode_incrementor(delimiter), lex_mode_terminator(delimiter));
10875 } else {
10876 lex_mode_push_string_eof(parser);
10877 }
10878
10879 LEX(PM_TOKEN_STRING_BEGIN);
10880 }
10881 case 'Q': {
10882 parser->current.end++;
10883
10884 if (parser->current.end < parser->end) {
10885 const uint8_t delimiter = pm_lex_percent_delimiter(parser);
10886 lex_mode_push_string(parser, true, false, lex_mode_incrementor(delimiter), lex_mode_terminator(delimiter));
10887 } else {
10888 lex_mode_push_string_eof(parser);
10889 }
10890
10891 LEX(PM_TOKEN_STRING_BEGIN);
10892 }
10893 case 's': {
10894 parser->current.end++;
10895
10896 if (parser->current.end < parser->end) {
10897 const uint8_t delimiter = pm_lex_percent_delimiter(parser);
10898 lex_mode_push_string(parser, false, false, lex_mode_incrementor(delimiter), lex_mode_terminator(delimiter));
10899 lex_state_set(parser, PM_LEX_STATE_FNAME | PM_LEX_STATE_FITEM);
10900 } else {
10901 lex_mode_push_string_eof(parser);
10902 }
10903
10904 LEX(PM_TOKEN_SYMBOL_BEGIN);
10905 }
10906 case 'w': {
10907 parser->current.end++;
10908
10909 if (parser->current.end < parser->end) {
10910 lex_mode_push_list(parser, false, pm_lex_percent_delimiter(parser));
10911 } else {
10912 lex_mode_push_list_eof(parser);
10913 }
10914
10915 LEX(PM_TOKEN_PERCENT_LOWER_W);
10916 }
10917 case 'W': {
10918 parser->current.end++;
10919
10920 if (parser->current.end < parser->end) {
10921 lex_mode_push_list(parser, true, pm_lex_percent_delimiter(parser));
10922 } else {
10923 lex_mode_push_list_eof(parser);
10924 }
10925
10926 LEX(PM_TOKEN_PERCENT_UPPER_W);
10927 }
10928 case 'x': {
10929 parser->current.end++;
10930
10931 if (parser->current.end < parser->end) {
10932 const uint8_t delimiter = pm_lex_percent_delimiter(parser);
10933 lex_mode_push_string(parser, true, false, lex_mode_incrementor(delimiter), lex_mode_terminator(delimiter));
10934 } else {
10935 lex_mode_push_string_eof(parser);
10936 }
10937
10938 LEX(PM_TOKEN_PERCENT_LOWER_X);
10939 }
10940 default:
10941 // If we get to this point, then we have a % that is completely
10942 // unparsable. In this case we'll just drop it from the parser
10943 // and skip past it and hope that the next token is something
10944 // that we can parse.
10945 pm_parser_err_current(parser, PM_ERR_INVALID_PERCENT);
10946 goto lex_next_token;
10947 }
10948 }
10949
10950 if (ambiguous_operator_p(parser, space_seen)) {
10951 PM_PARSER_WARN_TOKEN_FORMAT(parser, parser->current, PM_WARN_AMBIGUOUS_BINARY_OPERATOR, "%", "string literal");
10952 }
10953
10954 lex_state_set(parser, lex_state_operator_p(parser) ? PM_LEX_STATE_ARG : PM_LEX_STATE_BEG);
10955 LEX(PM_TOKEN_PERCENT);
10956 }
10957
10958 // global variable
10959 case '$': {
10960 pm_token_type_t type = lex_global_variable(parser);
10961
10962 // If we're lexing an embedded variable, then we need to pop back into
10963 // the parent lex context.
10964 if (parser->lex_modes.current->mode == PM_LEX_EMBVAR) {
10965 lex_mode_pop(parser);
10966 }
10967
10968 lex_state_set(parser, PM_LEX_STATE_END);
10969 LEX(type);
10970 }
10971
10972 // instance variable, class variable
10973 case '@':
10974 lex_state_set(parser, parser->lex_state & PM_LEX_STATE_FNAME ? PM_LEX_STATE_ENDFN : PM_LEX_STATE_END);
10975 LEX(lex_at_variable(parser));
10976
10977 default: {
10978 if (*parser->current.start != '_') {
10979 size_t width = char_is_identifier_start(parser, parser->current.start, parser->end - parser->current.start);
10980
10981 // If this isn't the beginning of an identifier, then
10982 // it's an invalid token as we've exhausted all of the
10983 // other options. We'll skip past it and return the next
10984 // token after adding an appropriate error message.
10985 if (!width) {
10986 if (*parser->current.start >= 0x80) {
10987 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_INVALID_MULTIBYTE_CHARACTER, *parser->current.start);
10988 } else if (*parser->current.start == '\\') {
10989 switch (peek_at(parser, parser->current.start + 1)) {
10990 case ' ':
10991 parser->current.end++;
10992 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_UNEXPECTED_TOKEN_IGNORE, "escaped space");
10993 break;
10994 case '\f':
10995 parser->current.end++;
10996 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_UNEXPECTED_TOKEN_IGNORE, "escaped form feed");
10997 break;
10998 case '\t':
10999 parser->current.end++;
11000 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_UNEXPECTED_TOKEN_IGNORE, "escaped horizontal tab");
11001 break;
11002 case '\v':
11003 parser->current.end++;
11004 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_UNEXPECTED_TOKEN_IGNORE, "escaped vertical tab");
11005 break;
11006 case '\r':
11007 if (peek_at(parser, parser->current.start + 2) != '\n') {
11008 parser->current.end++;
11009 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_UNEXPECTED_TOKEN_IGNORE, "escaped carriage return");
11010 break;
11011 }
11012 PRISM_FALLTHROUGH
11013 default:
11014 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_UNEXPECTED_TOKEN_IGNORE, "backslash");
11015 break;
11016 }
11017 } else if (char_is_ascii_printable(*parser->current.start)) {
11018 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_INVALID_PRINTABLE_CHARACTER, *parser->current.start);
11019 } else {
11020 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_INVALID_CHARACTER, *parser->current.start);
11021 }
11022
11023 goto lex_next_token;
11024 }
11025
11026 parser->current.end = parser->current.start + width;
11027 }
11028
11029 pm_token_type_t type = lex_identifier(parser, previous_command_start);
11030
11031 // If we've hit a __END__ and it was at the start of the
11032 // line or the start of the file and it is followed by
11033 // either a \n or a \r\n, then this is the last token of the
11034 // file.
11035 if (
11036 ((parser->current.end - parser->current.start) == 7) &&
11037 current_token_starts_line(parser) &&
11038 (memcmp(parser->current.start, "__END__", 7) == 0) &&
11039 (parser->current.end == parser->end || match_eol(parser))
11040 ) {
11041 // Since we know we're about to add an __END__ comment,
11042 // we know we need to add all of the newlines to get the
11043 // correct column information for it.
11044 const uint8_t *cursor = parser->current.end;
11045 while ((cursor = next_newline(cursor, parser->end - cursor)) != NULL) {
11046 pm_newline_list_append(&parser->newline_list, cursor++);
11047 }
11048
11049 parser->current.end = parser->end;
11050 parser->current.type = PM_TOKEN___END__;
11051 parser_lex_callback(parser);
11052
11053 parser->data_loc.start = parser->current.start;
11054 parser->data_loc.end = parser->current.end;
11055
11056 LEX(PM_TOKEN_EOF);
11057 }
11058
11059 pm_lex_state_t last_state = parser->lex_state;
11060
11061 if (type == PM_TOKEN_IDENTIFIER || type == PM_TOKEN_CONSTANT || type == PM_TOKEN_METHOD_NAME) {
11062 if (lex_state_p(parser, PM_LEX_STATE_BEG_ANY | PM_LEX_STATE_ARG_ANY | PM_LEX_STATE_DOT)) {
11063 if (previous_command_start) {
11064 lex_state_set(parser, PM_LEX_STATE_CMDARG);
11065 } else {
11066 lex_state_set(parser, PM_LEX_STATE_ARG);
11067 }
11068 } else if (parser->lex_state == PM_LEX_STATE_FNAME) {
11069 lex_state_set(parser, PM_LEX_STATE_ENDFN);
11070 } else {
11071 lex_state_set(parser, PM_LEX_STATE_END);
11072 }
11073 }
11074
11075 if (
11076 !(last_state & (PM_LEX_STATE_DOT | PM_LEX_STATE_FNAME)) &&
11077 (type == PM_TOKEN_IDENTIFIER) &&
11078 ((pm_parser_local_depth(parser, &parser->current) != -1) ||
11079 pm_token_is_numbered_parameter(parser->current.start, parser->current.end))
11080 ) {
11081 lex_state_set(parser, PM_LEX_STATE_END | PM_LEX_STATE_LABEL);
11082 }
11083
11084 LEX(type);
11085 }
11086 }
11087 }
11088 case PM_LEX_LIST: {
11089 if (parser->next_start != NULL) {
11090 parser->current.end = parser->next_start;
11091 parser->next_start = NULL;
11092 }
11093
11094 // First we'll set the beginning of the token.
11095 parser->current.start = parser->current.end;
11096
11097 // If there's any whitespace at the start of the list, then we're
11098 // going to trim it off the beginning and create a new token.
11099 size_t whitespace;
11100
11101 if (parser->heredoc_end) {
11102 whitespace = pm_strspn_inline_whitespace(parser->current.end, parser->end - parser->current.end);
11103 if (peek_offset(parser, (ptrdiff_t)whitespace) == '\n') {
11104 whitespace += 1;
11105 }
11106 } else {
11107 whitespace = pm_strspn_whitespace_newlines(parser->current.end, parser->end - parser->current.end, &parser->newline_list);
11108 }
11109
11110 if (whitespace > 0) {
11111 parser->current.end += whitespace;
11112 if (peek_offset(parser, -1) == '\n') {
11113 // mutates next_start
11114 parser_flush_heredoc_end(parser);
11115 }
11116 LEX(PM_TOKEN_WORDS_SEP);
11117 }
11118
11119 // We'll check if we're at the end of the file. If we are, then we
11120 // need to return the EOF token.
11121 if (parser->current.end >= parser->end) {
11122 LEX(PM_TOKEN_EOF);
11123 }
11124
11125 // Here we'll get a list of the places where strpbrk should break,
11126 // and then find the first one.
11127 pm_lex_mode_t *lex_mode = parser->lex_modes.current;
11128 const uint8_t *breakpoints = lex_mode->as.list.breakpoints;
11129 const uint8_t *breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11130
11131 // If we haven't found an escape yet, then this buffer will be
11132 // unallocated since we can refer directly to the source string.
11133 pm_token_buffer_t token_buffer = { 0 };
11134
11135 while (breakpoint != NULL) {
11136 // If we hit whitespace, then we must have received content by
11137 // now, so we can return an element of the list.
11138 if (pm_char_is_whitespace(*breakpoint)) {
11139 parser->current.end = breakpoint;
11140 pm_token_buffer_flush(parser, &token_buffer);
11141 LEX(PM_TOKEN_STRING_CONTENT);
11142 }
11143
11144 // If we hit the terminator, we need to check which token to
11145 // return.
11146 if (*breakpoint == lex_mode->as.list.terminator) {
11147 // If this terminator doesn't actually close the list, then
11148 // we need to continue on past it.
11149 if (lex_mode->as.list.nesting > 0) {
11150 parser->current.end = breakpoint + 1;
11151 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11152 lex_mode->as.list.nesting--;
11153 continue;
11154 }
11155
11156 // If we've hit the terminator and we've already skipped
11157 // past content, then we can return a list node.
11158 if (breakpoint > parser->current.start) {
11159 parser->current.end = breakpoint;
11160 pm_token_buffer_flush(parser, &token_buffer);
11161 LEX(PM_TOKEN_STRING_CONTENT);
11162 }
11163
11164 // Otherwise, switch back to the default state and return
11165 // the end of the list.
11166 parser->current.end = breakpoint + 1;
11167 lex_mode_pop(parser);
11168 lex_state_set(parser, PM_LEX_STATE_END);
11169 LEX(PM_TOKEN_STRING_END);
11170 }
11171
11172 // If we hit a null byte, skip directly past it.
11173 if (*breakpoint == '\0') {
11174 breakpoint = pm_strpbrk(parser, breakpoint + 1, breakpoints, parser->end - (breakpoint + 1), true);
11175 continue;
11176 }
11177
11178 // If we hit escapes, then we need to treat the next token
11179 // literally. In this case we'll skip past the next character
11180 // and find the next breakpoint.
11181 if (*breakpoint == '\\') {
11182 parser->current.end = breakpoint + 1;
11183
11184 // If we've hit the end of the file, then break out of the
11185 // loop by setting the breakpoint to NULL.
11186 if (parser->current.end == parser->end) {
11187 breakpoint = NULL;
11188 continue;
11189 }
11190
11191 pm_token_buffer_escape(parser, &token_buffer);
11192 uint8_t peeked = peek(parser);
11193
11194 switch (peeked) {
11195 case ' ':
11196 case '\f':
11197 case '\t':
11198 case '\v':
11199 case '\\':
11200 pm_token_buffer_push_byte(&token_buffer, peeked);
11201 parser->current.end++;
11202 break;
11203 case '\r':
11204 parser->current.end++;
11205 if (peek(parser) != '\n') {
11206 pm_token_buffer_push_byte(&token_buffer, '\r');
11207 break;
11208 }
11209 PRISM_FALLTHROUGH
11210 case '\n':
11211 pm_token_buffer_push_byte(&token_buffer, '\n');
11212
11213 if (parser->heredoc_end) {
11214 // ... if we are on the same line as a heredoc,
11215 // flush the heredoc and continue parsing after
11216 // heredoc_end.
11217 parser_flush_heredoc_end(parser);
11218 pm_token_buffer_copy(parser, &token_buffer);
11219 LEX(PM_TOKEN_STRING_CONTENT);
11220 } else {
11221 // ... else track the newline.
11222 pm_newline_list_append(&parser->newline_list, parser->current.end);
11223 }
11224
11225 parser->current.end++;
11226 break;
11227 default:
11228 if (peeked == lex_mode->as.list.incrementor || peeked == lex_mode->as.list.terminator) {
11229 pm_token_buffer_push_byte(&token_buffer, peeked);
11230 parser->current.end++;
11231 } else if (lex_mode->as.list.interpolation) {
11232 escape_read(parser, &token_buffer.buffer, NULL, PM_ESCAPE_FLAG_NONE);
11233 } else {
11234 pm_token_buffer_push_byte(&token_buffer, '\\');
11235 pm_token_buffer_push_escaped(&token_buffer, parser);
11236 }
11237
11238 break;
11239 }
11240
11241 token_buffer.cursor = parser->current.end;
11242 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11243 continue;
11244 }
11245
11246 // If we hit a #, then we will attempt to lex interpolation.
11247 if (*breakpoint == '#') {
11248 pm_token_type_t type = lex_interpolation(parser, breakpoint);
11249
11250 if (type == PM_TOKEN_NOT_PROVIDED) {
11251 // If we haven't returned at this point then we had something
11252 // that looked like an interpolated class or instance variable
11253 // like "#@" but wasn't actually. In this case we'll just skip
11254 // to the next breakpoint.
11255 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11256 continue;
11257 }
11258
11259 if (type == PM_TOKEN_STRING_CONTENT) {
11260 pm_token_buffer_flush(parser, &token_buffer);
11261 }
11262
11263 LEX(type);
11264 }
11265
11266 // If we've hit the incrementor, then we need to skip past it
11267 // and find the next breakpoint.
11268 assert(*breakpoint == lex_mode->as.list.incrementor);
11269 parser->current.end = breakpoint + 1;
11270 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11271 lex_mode->as.list.nesting++;
11272 continue;
11273 }
11274
11275 if (parser->current.end > parser->current.start) {
11276 pm_token_buffer_flush(parser, &token_buffer);
11277 LEX(PM_TOKEN_STRING_CONTENT);
11278 }
11279
11280 // If we were unable to find a breakpoint, then this token hits the
11281 // end of the file.
11282 parser->current.end = parser->end;
11283 pm_token_buffer_flush(parser, &token_buffer);
11284 LEX(PM_TOKEN_STRING_CONTENT);
11285 }
11286 case PM_LEX_REGEXP: {
11287 // First, we'll set to start of this token to be the current end.
11288 if (parser->next_start == NULL) {
11289 parser->current.start = parser->current.end;
11290 } else {
11291 parser->current.start = parser->next_start;
11292 parser->current.end = parser->next_start;
11293 parser->next_start = NULL;
11294 }
11295
11296 // We'll check if we're at the end of the file. If we are, then we
11297 // need to return the EOF token.
11298 if (parser->current.end >= parser->end) {
11299 LEX(PM_TOKEN_EOF);
11300 }
11301
11302 // Get a reference to the current mode.
11303 pm_lex_mode_t *lex_mode = parser->lex_modes.current;
11304
11305 // These are the places where we need to split up the content of the
11306 // regular expression. We'll use strpbrk to find the first of these
11307 // characters.
11308 const uint8_t *breakpoints = lex_mode->as.regexp.breakpoints;
11309 const uint8_t *breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, false);
11310 pm_regexp_token_buffer_t token_buffer = { 0 };
11311
11312 while (breakpoint != NULL) {
11313 uint8_t term = lex_mode->as.regexp.terminator;
11314 bool is_terminator = (*breakpoint == term);
11315
11316 // If the terminator is newline, we need to consider \r\n _also_ a newline
11317 // For example: `%\nfoo\r\n`
11318 // The string should be "foo", not "foo\r"
11319 if (*breakpoint == '\r' && peek_at(parser, breakpoint + 1) == '\n') {
11320 if (term == '\n') {
11321 is_terminator = true;
11322 }
11323
11324 // If the terminator is a CR, but we see a CRLF, we need to
11325 // treat the CRLF as a newline, meaning this is _not_ the
11326 // terminator
11327 if (term == '\r') {
11328 is_terminator = false;
11329 }
11330 }
11331
11332 // If we hit the terminator, we need to determine what kind of
11333 // token to return.
11334 if (is_terminator) {
11335 if (lex_mode->as.regexp.nesting > 0) {
11336 parser->current.end = breakpoint + 1;
11337 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, false);
11338 lex_mode->as.regexp.nesting--;
11339 continue;
11340 }
11341
11342 // Here we've hit the terminator. If we have already consumed
11343 // content then we need to return that content as string content
11344 // first.
11345 if (breakpoint > parser->current.start) {
11346 parser->current.end = breakpoint;
11347 pm_regexp_token_buffer_flush(parser, &token_buffer);
11348 LEX(PM_TOKEN_STRING_CONTENT);
11349 }
11350
11351 // Check here if we need to track the newline.
11352 size_t eol_length = match_eol_at(parser, breakpoint);
11353 if (eol_length) {
11354 parser->current.end = breakpoint + eol_length;
11355
11356 // Track the newline if we're not in a heredoc that
11357 // would have already have added the newline to the
11358 // list.
11359 if (parser->heredoc_end == NULL) {
11360 pm_newline_list_append(&parser->newline_list, parser->current.end - 1);
11361 }
11362 } else {
11363 parser->current.end = breakpoint + 1;
11364 }
11365
11366 // Since we've hit the terminator of the regular expression,
11367 // we now need to parse the options.
11368 parser->current.end += pm_strspn_regexp_option(parser->current.end, parser->end - parser->current.end);
11369
11370 lex_mode_pop(parser);
11371 lex_state_set(parser, PM_LEX_STATE_END);
11372 LEX(PM_TOKEN_REGEXP_END);
11373 }
11374
11375 // If we've hit the incrementor, then we need to skip past it
11376 // and find the next breakpoint.
11377 if (*breakpoint && *breakpoint == lex_mode->as.regexp.incrementor) {
11378 parser->current.end = breakpoint + 1;
11379 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, false);
11380 lex_mode->as.regexp.nesting++;
11381 continue;
11382 }
11383
11384 switch (*breakpoint) {
11385 case '\0':
11386 // If we hit a null byte, skip directly past it.
11387 parser->current.end = breakpoint + 1;
11388 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, false);
11389 break;
11390 case '\r':
11391 if (peek_at(parser, breakpoint + 1) != '\n') {
11392 parser->current.end = breakpoint + 1;
11393 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, false);
11394 break;
11395 }
11396
11397 breakpoint++;
11398 parser->current.end = breakpoint;
11399 pm_regexp_token_buffer_escape(parser, &token_buffer);
11400 token_buffer.base.cursor = breakpoint;
11401
11402 PRISM_FALLTHROUGH
11403 case '\n':
11404 // If we've hit a newline, then we need to track that in
11405 // the list of newlines.
11406 if (parser->heredoc_end == NULL) {
11407 pm_newline_list_append(&parser->newline_list, breakpoint);
11408 parser->current.end = breakpoint + 1;
11409 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, false);
11410 break;
11411 }
11412
11413 parser->current.end = breakpoint + 1;
11414 parser_flush_heredoc_end(parser);
11415 pm_regexp_token_buffer_flush(parser, &token_buffer);
11416 LEX(PM_TOKEN_STRING_CONTENT);
11417 case '\\': {
11418 // If we hit escapes, then we need to treat the next
11419 // token literally. In this case we'll skip past the
11420 // next character and find the next breakpoint.
11421 parser->current.end = breakpoint + 1;
11422
11423 // If we've hit the end of the file, then break out of
11424 // the loop by setting the breakpoint to NULL.
11425 if (parser->current.end == parser->end) {
11426 breakpoint = NULL;
11427 break;
11428 }
11429
11430 pm_regexp_token_buffer_escape(parser, &token_buffer);
11431 uint8_t peeked = peek(parser);
11432
11433 switch (peeked) {
11434 case '\r':
11435 parser->current.end++;
11436 if (peek(parser) != '\n') {
11437 if (lex_mode->as.regexp.terminator != '\r') {
11438 pm_token_buffer_push_byte(&token_buffer.base, '\\');
11439 }
11440 pm_regexp_token_buffer_push_byte(&token_buffer, '\r');
11441 pm_token_buffer_push_byte(&token_buffer.base, '\r');
11442 break;
11443 }
11444 PRISM_FALLTHROUGH
11445 case '\n':
11446 if (parser->heredoc_end) {
11447 // ... if we are on the same line as a heredoc,
11448 // flush the heredoc and continue parsing after
11449 // heredoc_end.
11450 parser_flush_heredoc_end(parser);
11451 pm_regexp_token_buffer_copy(parser, &token_buffer);
11452 LEX(PM_TOKEN_STRING_CONTENT);
11453 } else {
11454 // ... else track the newline.
11455 pm_newline_list_append(&parser->newline_list, parser->current.end);
11456 }
11457
11458 parser->current.end++;
11459 break;
11460 case 'c':
11461 case 'C':
11462 case 'M':
11463 case 'u':
11464 case 'x':
11465 escape_read(parser, &token_buffer.regexp_buffer, &token_buffer.base.buffer, PM_ESCAPE_FLAG_REGEXP);
11466 break;
11467 default:
11468 if (lex_mode->as.regexp.terminator == peeked) {
11469 // Some characters when they are used as the
11470 // terminator also receive an escape. They are
11471 // enumerated here.
11472 switch (peeked) {
11473 case '$': case ')': case '*': case '+':
11474 case '.': case '>': case '?': case ']':
11475 case '^': case '|': case '}':
11476 pm_token_buffer_push_byte(&token_buffer.base, '\\');
11477 break;
11478 default:
11479 break;
11480 }
11481
11482 pm_regexp_token_buffer_push_byte(&token_buffer, peeked);
11483 pm_token_buffer_push_byte(&token_buffer.base, peeked);
11484 parser->current.end++;
11485 break;
11486 }
11487
11488 if (peeked < 0x80) pm_token_buffer_push_byte(&token_buffer.base, '\\');
11489 pm_regexp_token_buffer_push_escaped(&token_buffer, parser);
11490 break;
11491 }
11492
11493 token_buffer.base.cursor = parser->current.end;
11494 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, false);
11495 break;
11496 }
11497 case '#': {
11498 // If we hit a #, then we will attempt to lex
11499 // interpolation.
11500 pm_token_type_t type = lex_interpolation(parser, breakpoint);
11501
11502 if (type == PM_TOKEN_NOT_PROVIDED) {
11503 // If we haven't returned at this point then we had
11504 // something that looked like an interpolated class or
11505 // instance variable like "#@" but wasn't actually. In
11506 // this case we'll just skip to the next breakpoint.
11507 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, false);
11508 break;
11509 }
11510
11511 if (type == PM_TOKEN_STRING_CONTENT) {
11512 pm_regexp_token_buffer_flush(parser, &token_buffer);
11513 }
11514
11515 LEX(type);
11516 }
11517 default:
11518 assert(false && "unreachable");
11519 break;
11520 }
11521 }
11522
11523 if (parser->current.end > parser->current.start) {
11524 pm_regexp_token_buffer_flush(parser, &token_buffer);
11525 LEX(PM_TOKEN_STRING_CONTENT);
11526 }
11527
11528 // If we were unable to find a breakpoint, then this token hits the
11529 // end of the file.
11530 parser->current.end = parser->end;
11531 pm_regexp_token_buffer_flush(parser, &token_buffer);
11532 LEX(PM_TOKEN_STRING_CONTENT);
11533 }
11534 case PM_LEX_STRING: {
11535 // First, we'll set to start of this token to be the current end.
11536 if (parser->next_start == NULL) {
11537 parser->current.start = parser->current.end;
11538 } else {
11539 parser->current.start = parser->next_start;
11540 parser->current.end = parser->next_start;
11541 parser->next_start = NULL;
11542 }
11543
11544 // We'll check if we're at the end of the file. If we are, then we need to
11545 // return the EOF token.
11546 if (parser->current.end >= parser->end) {
11547 LEX(PM_TOKEN_EOF);
11548 }
11549
11550 // These are the places where we need to split up the content of the
11551 // string. We'll use strpbrk to find the first of these characters.
11552 pm_lex_mode_t *lex_mode = parser->lex_modes.current;
11553 const uint8_t *breakpoints = lex_mode->as.string.breakpoints;
11554 const uint8_t *breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11555
11556 // If we haven't found an escape yet, then this buffer will be
11557 // unallocated since we can refer directly to the source string.
11558 pm_token_buffer_t token_buffer = { 0 };
11559
11560 while (breakpoint != NULL) {
11561 // If we hit the incrementor, then we'll increment then nesting and
11562 // continue lexing.
11563 if (lex_mode->as.string.incrementor != '\0' && *breakpoint == lex_mode->as.string.incrementor) {
11564 lex_mode->as.string.nesting++;
11565 parser->current.end = breakpoint + 1;
11566 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11567 continue;
11568 }
11569
11570 uint8_t term = lex_mode->as.string.terminator;
11571 bool is_terminator = (*breakpoint == term);
11572
11573 // If the terminator is newline, we need to consider \r\n _also_ a newline
11574 // For example: `%r\nfoo\r\n`
11575 // The string should be /foo/, not /foo\r/
11576 if (*breakpoint == '\r' && peek_at(parser, breakpoint + 1) == '\n') {
11577 if (term == '\n') {
11578 is_terminator = true;
11579 }
11580
11581 // If the terminator is a CR, but we see a CRLF, we need to
11582 // treat the CRLF as a newline, meaning this is _not_ the
11583 // terminator
11584 if (term == '\r') {
11585 is_terminator = false;
11586 }
11587 }
11588
11589 // Note that we have to check the terminator here first because we could
11590 // potentially be parsing a % string that has a # character as the
11591 // terminator.
11592 if (is_terminator) {
11593 // If this terminator doesn't actually close the string, then we need
11594 // to continue on past it.
11595 if (lex_mode->as.string.nesting > 0) {
11596 parser->current.end = breakpoint + 1;
11597 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11598 lex_mode->as.string.nesting--;
11599 continue;
11600 }
11601
11602 // Here we've hit the terminator. If we have already consumed content
11603 // then we need to return that content as string content first.
11604 if (breakpoint > parser->current.start) {
11605 parser->current.end = breakpoint;
11606 pm_token_buffer_flush(parser, &token_buffer);
11607 LEX(PM_TOKEN_STRING_CONTENT);
11608 }
11609
11610 // Otherwise we need to switch back to the parent lex mode and
11611 // return the end of the string.
11612 size_t eol_length = match_eol_at(parser, breakpoint);
11613 if (eol_length) {
11614 parser->current.end = breakpoint + eol_length;
11615
11616 // Track the newline if we're not in a heredoc that
11617 // would have already have added the newline to the
11618 // list.
11619 if (parser->heredoc_end == NULL) {
11620 pm_newline_list_append(&parser->newline_list, parser->current.end - 1);
11621 }
11622 } else {
11623 parser->current.end = breakpoint + 1;
11624 }
11625
11626 if (lex_mode->as.string.label_allowed && (peek(parser) == ':') && (peek_offset(parser, 1) != ':')) {
11627 parser->current.end++;
11628 lex_state_set(parser, PM_LEX_STATE_ARG | PM_LEX_STATE_LABELED);
11629 lex_mode_pop(parser);
11630 LEX(PM_TOKEN_LABEL_END);
11631 }
11632
11633 // When the delimiter itself is a newline, we won't
11634 // get a chance to flush heredocs in the usual places since
11635 // the newline is already consumed.
11636 if (term == '\n' && parser->heredoc_end) {
11637 parser_flush_heredoc_end(parser);
11638 }
11639
11640 lex_state_set(parser, PM_LEX_STATE_END);
11641 lex_mode_pop(parser);
11642 LEX(PM_TOKEN_STRING_END);
11643 }
11644
11645 switch (*breakpoint) {
11646 case '\0':
11647 // Skip directly past the null character.
11648 parser->current.end = breakpoint + 1;
11649 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11650 break;
11651 case '\r':
11652 if (peek_at(parser, breakpoint + 1) != '\n') {
11653 parser->current.end = breakpoint + 1;
11654 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11655 break;
11656 }
11657
11658 // If we hit a \r\n sequence, then we need to treat it
11659 // as a newline.
11660 breakpoint++;
11661 parser->current.end = breakpoint;
11662 pm_token_buffer_escape(parser, &token_buffer);
11663 token_buffer.cursor = breakpoint;
11664
11665 PRISM_FALLTHROUGH
11666 case '\n':
11667 // When we hit a newline, we need to flush any potential
11668 // heredocs. Note that this has to happen after we check
11669 // for the terminator in case the terminator is a
11670 // newline character.
11671 if (parser->heredoc_end == NULL) {
11672 pm_newline_list_append(&parser->newline_list, breakpoint);
11673 parser->current.end = breakpoint + 1;
11674 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11675 break;
11676 }
11677
11678 parser->current.end = breakpoint + 1;
11679 parser_flush_heredoc_end(parser);
11680 pm_token_buffer_flush(parser, &token_buffer);
11681 LEX(PM_TOKEN_STRING_CONTENT);
11682 case '\\': {
11683 // Here we hit escapes.
11684 parser->current.end = breakpoint + 1;
11685
11686 // If we've hit the end of the file, then break out of
11687 // the loop by setting the breakpoint to NULL.
11688 if (parser->current.end == parser->end) {
11689 breakpoint = NULL;
11690 continue;
11691 }
11692
11693 pm_token_buffer_escape(parser, &token_buffer);
11694 uint8_t peeked = peek(parser);
11695
11696 switch (peeked) {
11697 case '\\':
11698 pm_token_buffer_push_byte(&token_buffer, '\\');
11699 parser->current.end++;
11700 break;
11701 case '\r':
11702 parser->current.end++;
11703 if (peek(parser) != '\n') {
11704 if (!lex_mode->as.string.interpolation) {
11705 pm_token_buffer_push_byte(&token_buffer, '\\');
11706 }
11707 pm_token_buffer_push_byte(&token_buffer, '\r');
11708 break;
11709 }
11710 PRISM_FALLTHROUGH
11711 case '\n':
11712 if (!lex_mode->as.string.interpolation) {
11713 pm_token_buffer_push_byte(&token_buffer, '\\');
11714 pm_token_buffer_push_byte(&token_buffer, '\n');
11715 }
11716
11717 if (parser->heredoc_end) {
11718 // ... if we are on the same line as a heredoc,
11719 // flush the heredoc and continue parsing after
11720 // heredoc_end.
11721 parser_flush_heredoc_end(parser);
11722 pm_token_buffer_copy(parser, &token_buffer);
11723 LEX(PM_TOKEN_STRING_CONTENT);
11724 } else {
11725 // ... else track the newline.
11726 pm_newline_list_append(&parser->newline_list, parser->current.end);
11727 }
11728
11729 parser->current.end++;
11730 break;
11731 default:
11732 if (lex_mode->as.string.incrementor != '\0' && peeked == lex_mode->as.string.incrementor) {
11733 pm_token_buffer_push_byte(&token_buffer, peeked);
11734 parser->current.end++;
11735 } else if (lex_mode->as.string.terminator != '\0' && peeked == lex_mode->as.string.terminator) {
11736 pm_token_buffer_push_byte(&token_buffer, peeked);
11737 parser->current.end++;
11738 } else if (lex_mode->as.string.interpolation) {
11739 escape_read(parser, &token_buffer.buffer, NULL, PM_ESCAPE_FLAG_NONE);
11740 } else {
11741 pm_token_buffer_push_byte(&token_buffer, '\\');
11742 pm_token_buffer_push_escaped(&token_buffer, parser);
11743 }
11744
11745 break;
11746 }
11747
11748 token_buffer.cursor = parser->current.end;
11749 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11750 break;
11751 }
11752 case '#': {
11753 pm_token_type_t type = lex_interpolation(parser, breakpoint);
11754
11755 if (type == PM_TOKEN_NOT_PROVIDED) {
11756 // If we haven't returned at this point then we had something that
11757 // looked like an interpolated class or instance variable like "#@"
11758 // but wasn't actually. In this case we'll just skip to the next
11759 // breakpoint.
11760 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11761 break;
11762 }
11763
11764 if (type == PM_TOKEN_STRING_CONTENT) {
11765 pm_token_buffer_flush(parser, &token_buffer);
11766 }
11767
11768 LEX(type);
11769 }
11770 default:
11771 assert(false && "unreachable");
11772 }
11773 }
11774
11775 if (parser->current.end > parser->current.start) {
11776 pm_token_buffer_flush(parser, &token_buffer);
11777 LEX(PM_TOKEN_STRING_CONTENT);
11778 }
11779
11780 // If we've hit the end of the string, then this is an unterminated
11781 // string. In that case we'll return a string content token.
11782 parser->current.end = parser->end;
11783 pm_token_buffer_flush(parser, &token_buffer);
11784 LEX(PM_TOKEN_STRING_CONTENT);
11785 }
11786 case PM_LEX_HEREDOC: {
11787 // First, we'll set to start of this token.
11788 if (parser->next_start == NULL) {
11789 parser->current.start = parser->current.end;
11790 } else {
11791 parser->current.start = parser->next_start;
11792 parser->current.end = parser->next_start;
11793 parser->heredoc_end = NULL;
11794 parser->next_start = NULL;
11795 }
11796
11797 // Now let's grab the information about the identifier off of the
11798 // current lex mode.
11799 pm_lex_mode_t *lex_mode = parser->lex_modes.current;
11800 pm_heredoc_lex_mode_t *heredoc_lex_mode = &lex_mode->as.heredoc.base;
11801
11802 bool line_continuation = lex_mode->as.heredoc.line_continuation;
11803 lex_mode->as.heredoc.line_continuation = false;
11804
11805 // We'll check if we're at the end of the file. If we are, then we
11806 // will add an error (because we weren't able to find the
11807 // terminator) but still continue parsing so that content after the
11808 // declaration of the heredoc can be parsed.
11809 if (parser->current.end >= parser->end) {
11810 pm_parser_err_heredoc_term(parser, heredoc_lex_mode->ident_start, heredoc_lex_mode->ident_length);
11811 parser->next_start = lex_mode->as.heredoc.next_start;
11812 parser->heredoc_end = parser->current.end;
11813 lex_state_set(parser, PM_LEX_STATE_END);
11814 lex_mode_pop(parser);
11815 LEX(PM_TOKEN_HEREDOC_END);
11816 }
11817
11818 const uint8_t *ident_start = heredoc_lex_mode->ident_start;
11819 size_t ident_length = heredoc_lex_mode->ident_length;
11820
11821 // If we are immediately following a newline and we have hit the
11822 // terminator, then we need to return the ending of the heredoc.
11823 if (current_token_starts_line(parser)) {
11824 const uint8_t *start = parser->current.start;
11825
11826 if (!line_continuation && (start + ident_length <= parser->end)) {
11827 const uint8_t *newline = next_newline(start, parser->end - start);
11828 const uint8_t *ident_end = newline;
11829 const uint8_t *terminator_end = newline;
11830
11831 if (newline == NULL) {
11832 terminator_end = parser->end;
11833 ident_end = parser->end;
11834 } else {
11835 terminator_end++;
11836 if (newline[-1] == '\r') {
11837 ident_end--; // Remove \r
11838 }
11839 }
11840
11841 const uint8_t *terminator_start = ident_end - ident_length;
11842 const uint8_t *cursor = start;
11843
11844 if (heredoc_lex_mode->indent == PM_HEREDOC_INDENT_DASH || heredoc_lex_mode->indent == PM_HEREDOC_INDENT_TILDE) {
11845 while (cursor < terminator_start && pm_char_is_inline_whitespace(*cursor)) {
11846 cursor++;
11847 }
11848 }
11849
11850 if (
11851 (cursor == terminator_start) &&
11852 (memcmp(terminator_start, ident_start, ident_length) == 0)
11853 ) {
11854 if (newline != NULL) {
11855 pm_newline_list_append(&parser->newline_list, newline);
11856 }
11857
11858 parser->current.end = terminator_end;
11859 if (*lex_mode->as.heredoc.next_start == '\\') {
11860 parser->next_start = NULL;
11861 } else {
11862 parser->next_start = lex_mode->as.heredoc.next_start;
11863 parser->heredoc_end = parser->current.end;
11864 }
11865
11866 lex_state_set(parser, PM_LEX_STATE_END);
11867 lex_mode_pop(parser);
11868 LEX(PM_TOKEN_HEREDOC_END);
11869 }
11870 }
11871
11872 size_t whitespace = pm_heredoc_strspn_inline_whitespace(parser, &start, heredoc_lex_mode->indent);
11873 if (
11874 heredoc_lex_mode->indent == PM_HEREDOC_INDENT_TILDE &&
11875 lex_mode->as.heredoc.common_whitespace != NULL &&
11876 (*lex_mode->as.heredoc.common_whitespace > whitespace) &&
11877 peek_at(parser, start) != '\n'
11878 ) {
11879 *lex_mode->as.heredoc.common_whitespace = whitespace;
11880 }
11881 }
11882
11883 // Otherwise we'll be parsing string content. These are the places
11884 // where we need to split up the content of the heredoc. We'll use
11885 // strpbrk to find the first of these characters.
11886 uint8_t breakpoints[] = "\r\n\\#";
11887
11888 pm_heredoc_quote_t quote = heredoc_lex_mode->quote;
11889 if (quote == PM_HEREDOC_QUOTE_SINGLE) {
11890 breakpoints[3] = '\0';
11891 }
11892
11893 const uint8_t *breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11894 pm_token_buffer_t token_buffer = { 0 };
11895 bool was_line_continuation = false;
11896
11897 while (breakpoint != NULL) {
11898 switch (*breakpoint) {
11899 case '\0':
11900 // Skip directly past the null character.
11901 parser->current.end = breakpoint + 1;
11902 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11903 break;
11904 case '\r':
11905 parser->current.end = breakpoint + 1;
11906
11907 if (peek_at(parser, breakpoint + 1) != '\n') {
11908 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11909 break;
11910 }
11911
11912 // If we hit a \r\n sequence, then we want to replace it
11913 // with a single \n character in the final string.
11914 breakpoint++;
11915 pm_token_buffer_escape(parser, &token_buffer);
11916 token_buffer.cursor = breakpoint;
11917
11918 PRISM_FALLTHROUGH
11919 case '\n': {
11920 if (parser->heredoc_end != NULL && (parser->heredoc_end > breakpoint)) {
11921 parser_flush_heredoc_end(parser);
11922 parser->current.end = breakpoint + 1;
11923 pm_token_buffer_flush(parser, &token_buffer);
11924 LEX(PM_TOKEN_STRING_CONTENT);
11925 }
11926
11927 pm_newline_list_append(&parser->newline_list, breakpoint);
11928
11929 // If we have a - or ~ heredoc, then we can match after
11930 // some leading whitespace.
11931 const uint8_t *start = breakpoint + 1;
11932
11933 if (!was_line_continuation && (start + ident_length <= parser->end)) {
11934 // We want to match the terminator starting from the end of the line in case
11935 // there is whitespace in the ident such as <<-' DOC' or <<~' DOC'.
11936 const uint8_t *newline = next_newline(start, parser->end - start);
11937
11938 if (newline == NULL) {
11939 newline = parser->end;
11940 } else if (newline[-1] == '\r') {
11941 newline--; // Remove \r
11942 }
11943
11944 // Start of a possible terminator.
11945 const uint8_t *terminator_start = newline - ident_length;
11946
11947 // Cursor to check for the leading whitespace. We skip the
11948 // leading whitespace if we have a - or ~ heredoc.
11949 const uint8_t *cursor = start;
11950
11951 if (heredoc_lex_mode->indent == PM_HEREDOC_INDENT_DASH || heredoc_lex_mode->indent == PM_HEREDOC_INDENT_TILDE) {
11952 while (cursor < terminator_start && pm_char_is_inline_whitespace(*cursor)) {
11953 cursor++;
11954 }
11955 }
11956
11957 if (
11958 cursor == terminator_start &&
11959 (memcmp(terminator_start, ident_start, ident_length) == 0)
11960 ) {
11961 parser->current.end = breakpoint + 1;
11962 pm_token_buffer_flush(parser, &token_buffer);
11963 LEX(PM_TOKEN_STRING_CONTENT);
11964 }
11965 }
11966
11967 size_t whitespace = pm_heredoc_strspn_inline_whitespace(parser, &start, lex_mode->as.heredoc.base.indent);
11968
11969 // If we have hit a newline that is followed by a valid
11970 // terminator, then we need to return the content of the
11971 // heredoc here as string content. Then, the next time a
11972 // token is lexed, it will match again and return the
11973 // end of the heredoc.
11974 if (lex_mode->as.heredoc.base.indent == PM_HEREDOC_INDENT_TILDE) {
11975 if ((lex_mode->as.heredoc.common_whitespace != NULL) && (*lex_mode->as.heredoc.common_whitespace > whitespace) && peek_at(parser, start) != '\n') {
11976 *lex_mode->as.heredoc.common_whitespace = whitespace;
11977 }
11978
11979 parser->current.end = breakpoint + 1;
11980 pm_token_buffer_flush(parser, &token_buffer);
11981 LEX(PM_TOKEN_STRING_CONTENT);
11982 }
11983
11984 // Otherwise we hit a newline and it wasn't followed by
11985 // a terminator, so we can continue parsing.
11986 parser->current.end = breakpoint + 1;
11987 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
11988 break;
11989 }
11990 case '\\': {
11991 // If we hit an escape, then we need to skip past
11992 // however many characters the escape takes up. However
11993 // it's important that if \n or \r\n are escaped, we
11994 // stop looping before the newline and not after the
11995 // newline so that we can still potentially find the
11996 // terminator of the heredoc.
11997 parser->current.end = breakpoint + 1;
11998
11999 // If we've hit the end of the file, then break out of
12000 // the loop by setting the breakpoint to NULL.
12001 if (parser->current.end == parser->end) {
12002 breakpoint = NULL;
12003 continue;
12004 }
12005
12006 pm_token_buffer_escape(parser, &token_buffer);
12007 uint8_t peeked = peek(parser);
12008
12009 if (quote == PM_HEREDOC_QUOTE_SINGLE) {
12010 switch (peeked) {
12011 case '\r':
12012 parser->current.end++;
12013 if (peek(parser) != '\n') {
12014 pm_token_buffer_push_byte(&token_buffer, '\\');
12015 pm_token_buffer_push_byte(&token_buffer, '\r');
12016 break;
12017 }
12018 PRISM_FALLTHROUGH
12019 case '\n':
12020 pm_token_buffer_push_byte(&token_buffer, '\\');
12021 pm_token_buffer_push_byte(&token_buffer, '\n');
12022 token_buffer.cursor = parser->current.end + 1;
12023 breakpoint = parser->current.end;
12024 continue;
12025 default:
12026 pm_token_buffer_push_byte(&token_buffer, '\\');
12027 pm_token_buffer_push_escaped(&token_buffer, parser);
12028 break;
12029 }
12030 } else {
12031 switch (peeked) {
12032 case '\r':
12033 parser->current.end++;
12034 if (peek(parser) != '\n') {
12035 pm_token_buffer_push_byte(&token_buffer, '\r');
12036 break;
12037 }
12038 PRISM_FALLTHROUGH
12039 case '\n':
12040 // If we are in a tilde here, we should
12041 // break out of the loop and return the
12042 // string content.
12043 if (heredoc_lex_mode->indent == PM_HEREDOC_INDENT_TILDE) {
12044 const uint8_t *end = parser->current.end;
12045
12046 if (parser->heredoc_end == NULL) {
12047 pm_newline_list_append(&parser->newline_list, end);
12048 }
12049
12050 // Here we want the buffer to only
12051 // include up to the backslash.
12052 parser->current.end = breakpoint;
12053 pm_token_buffer_flush(parser, &token_buffer);
12054
12055 // Now we can advance the end of the
12056 // token past the newline.
12057 parser->current.end = end + 1;
12058 lex_mode->as.heredoc.line_continuation = true;
12059 LEX(PM_TOKEN_STRING_CONTENT);
12060 }
12061
12062 was_line_continuation = true;
12063 token_buffer.cursor = parser->current.end + 1;
12064 breakpoint = parser->current.end;
12065 continue;
12066 default:
12067 escape_read(parser, &token_buffer.buffer, NULL, PM_ESCAPE_FLAG_NONE);
12068 break;
12069 }
12070 }
12071
12072 token_buffer.cursor = parser->current.end;
12073 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
12074 break;
12075 }
12076 case '#': {
12077 pm_token_type_t type = lex_interpolation(parser, breakpoint);
12078
12079 if (type == PM_TOKEN_NOT_PROVIDED) {
12080 // If we haven't returned at this point then we had
12081 // something that looked like an interpolated class
12082 // or instance variable like "#@" but wasn't
12083 // actually. In this case we'll just skip to the
12084 // next breakpoint.
12085 breakpoint = pm_strpbrk(parser, parser->current.end, breakpoints, parser->end - parser->current.end, true);
12086 break;
12087 }
12088
12089 if (type == PM_TOKEN_STRING_CONTENT) {
12090 pm_token_buffer_flush(parser, &token_buffer);
12091 }
12092
12093 LEX(type);
12094 }
12095 default:
12096 assert(false && "unreachable");
12097 }
12098
12099 was_line_continuation = false;
12100 }
12101
12102 if (parser->current.end > parser->current.start) {
12103 parser->current.end = parser->end;
12104 pm_token_buffer_flush(parser, &token_buffer);
12105 LEX(PM_TOKEN_STRING_CONTENT);
12106 }
12107
12108 // If we've hit the end of the string, then this is an unterminated
12109 // heredoc. In that case we'll return a string content token.
12110 parser->current.end = parser->end;
12111 pm_token_buffer_flush(parser, &token_buffer);
12112 LEX(PM_TOKEN_STRING_CONTENT);
12113 }
12114 }
12115
12116 assert(false && "unreachable");
12117 }
12118
12119 #undef LEX
12120
12121 /******************************************************************************/
12122 /* Parse functions */
12123 /******************************************************************************/
12124
12125 /**
12126 * These are the various precedence rules. Because we are using a Pratt parser,
12127 * they are named binding power to represent the manner in which nodes are bound
12128 * together in the stack.
12129 *
12130 * We increment by 2 because we want to leave room for the infix operators to
12131 * specify their associativity by adding or subtracting one.
12132 */
12133 typedef enum {
12134 PM_BINDING_POWER_UNSET = 0, // used to indicate this token cannot be used as an infix operator
12135 PM_BINDING_POWER_STATEMENT = 2,
12136 PM_BINDING_POWER_MODIFIER_RESCUE = 4, // rescue
12137 PM_BINDING_POWER_MODIFIER = 6, // if unless until while
12138 PM_BINDING_POWER_COMPOSITION = 8, // and or
12139 PM_BINDING_POWER_NOT = 10, // not
12140 PM_BINDING_POWER_MATCH = 12, // => in
12141 PM_BINDING_POWER_DEFINED = 14, // defined?
12142 PM_BINDING_POWER_MULTI_ASSIGNMENT = 16, // =
12143 PM_BINDING_POWER_ASSIGNMENT = 18, // = += -= *= /= %= &= |= ^= &&= ||= <<= >>= **=
12144 PM_BINDING_POWER_TERNARY = 20, // ?:
12145 PM_BINDING_POWER_RANGE = 22, // .. ...
12146 PM_BINDING_POWER_LOGICAL_OR = 24, // ||
12147 PM_BINDING_POWER_LOGICAL_AND = 26, // &&
12148 PM_BINDING_POWER_EQUALITY = 28, // <=> == === != =~ !~
12149 PM_BINDING_POWER_COMPARISON = 30, // > >= < <=
12150 PM_BINDING_POWER_BITWISE_OR = 32, // | ^
12151 PM_BINDING_POWER_BITWISE_AND = 34, // &
12152 PM_BINDING_POWER_SHIFT = 36, // << >>
12153 PM_BINDING_POWER_TERM = 38, // + -
12154 PM_BINDING_POWER_FACTOR = 40, // * / %
12155 PM_BINDING_POWER_UMINUS = 42, // -@
12156 PM_BINDING_POWER_EXPONENT = 44, // **
12157 PM_BINDING_POWER_UNARY = 46, // ! ~ +@
12158 PM_BINDING_POWER_INDEX = 48, // [] []=
12159 PM_BINDING_POWER_CALL = 50, // :: .
12160 PM_BINDING_POWER_MAX = 52
12161 } pm_binding_power_t;
12162
12163 /**
12164 * This struct represents a set of binding powers used for a given token. They
12165 * are combined in this way to make it easier to represent associativity.
12166 */
12167 typedef struct {
12168 /** The left binding power. */
12169 pm_binding_power_t left;
12170
12171 /** The right binding power. */
12172 pm_binding_power_t right;
12173
12174 /** Whether or not this token can be used as a binary operator. */
12175 bool binary;
12176
12177 /**
12178 * Whether or not this token can be used as non-associative binary operator.
12179 * Non-associative operators (e.g. in and =>) need special treatment in parse_expression.
12180 */
12181 bool nonassoc;
12182 } pm_binding_powers_t;
12183
12184 #define BINDING_POWER_ASSIGNMENT { PM_BINDING_POWER_UNARY, PM_BINDING_POWER_ASSIGNMENT, true, false }
12185 #define LEFT_ASSOCIATIVE(precedence) { precedence, precedence + 1, true, false }
12186 #define RIGHT_ASSOCIATIVE(precedence) { precedence, precedence, true, false }
12187 #define NON_ASSOCIATIVE(precedence) { precedence, precedence + 1, true, true }
12188 #define RIGHT_ASSOCIATIVE_UNARY(precedence) { precedence, precedence, false, false }
12189
12190 pm_binding_powers_t pm_binding_powers[PM_TOKEN_MAXIMUM] = {
12191 // rescue
12192 [PM_TOKEN_KEYWORD_RESCUE_MODIFIER] = { PM_BINDING_POWER_MODIFIER_RESCUE, PM_BINDING_POWER_COMPOSITION, true, false },
12193
12194 // if unless until while
12195 [PM_TOKEN_KEYWORD_IF_MODIFIER] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_MODIFIER),
12196 [PM_TOKEN_KEYWORD_UNLESS_MODIFIER] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_MODIFIER),
12197 [PM_TOKEN_KEYWORD_UNTIL_MODIFIER] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_MODIFIER),
12198 [PM_TOKEN_KEYWORD_WHILE_MODIFIER] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_MODIFIER),
12199
12200 // and or
12201 [PM_TOKEN_KEYWORD_AND] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_COMPOSITION),
12202 [PM_TOKEN_KEYWORD_OR] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_COMPOSITION),
12203
12204 // => in
12205 [PM_TOKEN_EQUAL_GREATER] = NON_ASSOCIATIVE(PM_BINDING_POWER_MATCH),
12206 [PM_TOKEN_KEYWORD_IN] = NON_ASSOCIATIVE(PM_BINDING_POWER_MATCH),
12207
12208 // &&= &= ^= = >>= <<= -= %= |= ||= += /= *= **=
12209 [PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL] = BINDING_POWER_ASSIGNMENT,
12210 [PM_TOKEN_AMPERSAND_EQUAL] = BINDING_POWER_ASSIGNMENT,
12211 [PM_TOKEN_CARET_EQUAL] = BINDING_POWER_ASSIGNMENT,
12212 [PM_TOKEN_EQUAL] = BINDING_POWER_ASSIGNMENT,
12213 [PM_TOKEN_GREATER_GREATER_EQUAL] = BINDING_POWER_ASSIGNMENT,
12214 [PM_TOKEN_LESS_LESS_EQUAL] = BINDING_POWER_ASSIGNMENT,
12215 [PM_TOKEN_MINUS_EQUAL] = BINDING_POWER_ASSIGNMENT,
12216 [PM_TOKEN_PERCENT_EQUAL] = BINDING_POWER_ASSIGNMENT,
12217 [PM_TOKEN_PIPE_EQUAL] = BINDING_POWER_ASSIGNMENT,
12218 [PM_TOKEN_PIPE_PIPE_EQUAL] = BINDING_POWER_ASSIGNMENT,
12219 [PM_TOKEN_PLUS_EQUAL] = BINDING_POWER_ASSIGNMENT,
12220 [PM_TOKEN_SLASH_EQUAL] = BINDING_POWER_ASSIGNMENT,
12221 [PM_TOKEN_STAR_EQUAL] = BINDING_POWER_ASSIGNMENT,
12222 [PM_TOKEN_STAR_STAR_EQUAL] = BINDING_POWER_ASSIGNMENT,
12223
12224 // ?:
12225 [PM_TOKEN_QUESTION_MARK] = RIGHT_ASSOCIATIVE(PM_BINDING_POWER_TERNARY),
12226
12227 // .. ...
12228 [PM_TOKEN_DOT_DOT] = NON_ASSOCIATIVE(PM_BINDING_POWER_RANGE),
12229 [PM_TOKEN_DOT_DOT_DOT] = NON_ASSOCIATIVE(PM_BINDING_POWER_RANGE),
12230 [PM_TOKEN_UDOT_DOT] = RIGHT_ASSOCIATIVE_UNARY(PM_BINDING_POWER_LOGICAL_OR),
12231 [PM_TOKEN_UDOT_DOT_DOT] = RIGHT_ASSOCIATIVE_UNARY(PM_BINDING_POWER_LOGICAL_OR),
12232
12233 // ||
12234 [PM_TOKEN_PIPE_PIPE] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_LOGICAL_OR),
12235
12236 // &&
12237 [PM_TOKEN_AMPERSAND_AMPERSAND] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_LOGICAL_AND),
12238
12239 // != !~ == === =~ <=>
12240 [PM_TOKEN_BANG_EQUAL] = NON_ASSOCIATIVE(PM_BINDING_POWER_EQUALITY),
12241 [PM_TOKEN_BANG_TILDE] = NON_ASSOCIATIVE(PM_BINDING_POWER_EQUALITY),
12242 [PM_TOKEN_EQUAL_EQUAL] = NON_ASSOCIATIVE(PM_BINDING_POWER_EQUALITY),
12243 [PM_TOKEN_EQUAL_EQUAL_EQUAL] = NON_ASSOCIATIVE(PM_BINDING_POWER_EQUALITY),
12244 [PM_TOKEN_EQUAL_TILDE] = NON_ASSOCIATIVE(PM_BINDING_POWER_EQUALITY),
12245 [PM_TOKEN_LESS_EQUAL_GREATER] = NON_ASSOCIATIVE(PM_BINDING_POWER_EQUALITY),
12246
12247 // > >= < <=
12248 [PM_TOKEN_GREATER] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_COMPARISON),
12249 [PM_TOKEN_GREATER_EQUAL] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_COMPARISON),
12250 [PM_TOKEN_LESS] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_COMPARISON),
12251 [PM_TOKEN_LESS_EQUAL] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_COMPARISON),
12252
12253 // ^ |
12254 [PM_TOKEN_CARET] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_BITWISE_OR),
12255 [PM_TOKEN_PIPE] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_BITWISE_OR),
12256
12257 // &
12258 [PM_TOKEN_AMPERSAND] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_BITWISE_AND),
12259
12260 // >> <<
12261 [PM_TOKEN_GREATER_GREATER] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_SHIFT),
12262 [PM_TOKEN_LESS_LESS] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_SHIFT),
12263
12264 // - +
12265 [PM_TOKEN_MINUS] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_TERM),
12266 [PM_TOKEN_PLUS] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_TERM),
12267
12268 // % / *
12269 [PM_TOKEN_PERCENT] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_FACTOR),
12270 [PM_TOKEN_SLASH] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_FACTOR),
12271 [PM_TOKEN_STAR] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_FACTOR),
12272 [PM_TOKEN_USTAR] = RIGHT_ASSOCIATIVE_UNARY(PM_BINDING_POWER_FACTOR),
12273
12274 // -@
12275 [PM_TOKEN_UMINUS] = RIGHT_ASSOCIATIVE_UNARY(PM_BINDING_POWER_UMINUS),
12276 [PM_TOKEN_UMINUS_NUM] = { PM_BINDING_POWER_UMINUS, PM_BINDING_POWER_MAX, false, false },
12277
12278 // **
12279 [PM_TOKEN_STAR_STAR] = RIGHT_ASSOCIATIVE(PM_BINDING_POWER_EXPONENT),
12280 [PM_TOKEN_USTAR_STAR] = RIGHT_ASSOCIATIVE_UNARY(PM_BINDING_POWER_UNARY),
12281
12282 // ! ~ +@
12283 [PM_TOKEN_BANG] = RIGHT_ASSOCIATIVE_UNARY(PM_BINDING_POWER_UNARY),
12284 [PM_TOKEN_TILDE] = RIGHT_ASSOCIATIVE_UNARY(PM_BINDING_POWER_UNARY),
12285 [PM_TOKEN_UPLUS] = RIGHT_ASSOCIATIVE_UNARY(PM_BINDING_POWER_UNARY),
12286
12287 // [
12288 [PM_TOKEN_BRACKET_LEFT] = LEFT_ASSOCIATIVE(PM_BINDING_POWER_INDEX),
12289
12290 // :: . &.
12291 [PM_TOKEN_COLON_COLON] = RIGHT_ASSOCIATIVE(PM_BINDING_POWER_CALL),
12292 [PM_TOKEN_DOT] = RIGHT_ASSOCIATIVE(PM_BINDING_POWER_CALL),
12293 [PM_TOKEN_AMPERSAND_DOT] = RIGHT_ASSOCIATIVE(PM_BINDING_POWER_CALL)
12294 };
12295
12296 #undef BINDING_POWER_ASSIGNMENT
12297 #undef LEFT_ASSOCIATIVE
12298 #undef RIGHT_ASSOCIATIVE
12299 #undef RIGHT_ASSOCIATIVE_UNARY
12300
12301 /**
12302 * Returns true if the current token is of the given type.
12303 */
12304 static inline bool
12305 match1(const pm_parser_t *parser, pm_token_type_t type) {
12306 return parser->current.type == type;
12307 }
12308
12309 /**
12310 * Returns true if the current token is of either of the given types.
12311 */
12312 static inline bool
12313 match2(const pm_parser_t *parser, pm_token_type_t type1, pm_token_type_t type2) {
12314 return match1(parser, type1) || match1(parser, type2);
12315 }
12316
12317 /**
12318 * Returns true if the current token is any of the three given types.
12319 */
12320 static inline bool
12321 match3(const pm_parser_t *parser, pm_token_type_t type1, pm_token_type_t type2, pm_token_type_t type3) {
12322 return match1(parser, type1) || match1(parser, type2) || match1(parser, type3);
12323 }
12324
12325 /**
12326 * Returns true if the current token is any of the four given types.
12327 */
12328 static inline bool
12329 match4(const pm_parser_t *parser, pm_token_type_t type1, pm_token_type_t type2, pm_token_type_t type3, pm_token_type_t type4) {
12330 return match1(parser, type1) || match1(parser, type2) || match1(parser, type3) || match1(parser, type4);
12331 }
12332
12333 /**
12334 * Returns true if the current token is any of the seven given types.
12335 */
12336 static inline bool
12337 match7(const pm_parser_t *parser, pm_token_type_t type1, pm_token_type_t type2, pm_token_type_t type3, pm_token_type_t type4, pm_token_type_t type5, pm_token_type_t type6, pm_token_type_t type7) {
12338 return match1(parser, type1) || match1(parser, type2) || match1(parser, type3) || match1(parser, type4) || match1(parser, type5) || match1(parser, type6) || match1(parser, type7);
12339 }
12340
12341 /**
12342 * Returns true if the current token is any of the eight given types.
12343 */
12344 static inline bool
12345 match8(const pm_parser_t *parser, pm_token_type_t type1, pm_token_type_t type2, pm_token_type_t type3, pm_token_type_t type4, pm_token_type_t type5, pm_token_type_t type6, pm_token_type_t type7, pm_token_type_t type8) {
12346 return match1(parser, type1) || match1(parser, type2) || match1(parser, type3) || match1(parser, type4) || match1(parser, type5) || match1(parser, type6) || match1(parser, type7) || match1(parser, type8);
12347 }
12348
12349 /**
12350 * If the current token is of the specified type, lex forward by one token and
12351 * return true. Otherwise, return false. For example:
12352 *
12353 * if (accept1(parser, PM_TOKEN_COLON)) { ... }
12354 */
12355 static bool
12356 accept1(pm_parser_t *parser, pm_token_type_t type) {
12357 if (match1(parser, type)) {
12358 parser_lex(parser);
12359 return true;
12360 }
12361 return false;
12362 }
12363
12364 /**
12365 * If the current token is either of the two given types, lex forward by one
12366 * token and return true. Otherwise return false.
12367 */
12368 static inline bool
12369 accept2(pm_parser_t *parser, pm_token_type_t type1, pm_token_type_t type2) {
12370 if (match2(parser, type1, type2)) {
12371 parser_lex(parser);
12372 return true;
12373 }
12374 return false;
12375 }
12376
12377 /**
12378 * This function indicates that the parser expects a token in a specific
12379 * position. For example, if you're parsing a BEGIN block, you know that a { is
12380 * expected immediately after the keyword. In that case you would call this
12381 * function to indicate that that token should be found.
12382 *
12383 * If we didn't find the token that we were expecting, then we're going to add
12384 * an error to the parser's list of errors (to indicate that the tree is not
12385 * valid) and create an artificial token instead. This allows us to recover from
12386 * the fact that the token isn't present and continue parsing.
12387 */
12388 static void
12389 expect1(pm_parser_t *parser, pm_token_type_t type, pm_diagnostic_id_t diag_id) {
12390 if (accept1(parser, type)) return;
12391
12392 const uint8_t *location = parser->previous.end;
12393 pm_parser_err(parser, location, location, diag_id);
12394
12395 parser->previous.start = location;
12396 parser->previous.type = PM_TOKEN_MISSING;
12397 }
12398
12399 /**
12400 * This function is the same as expect1, but it expects either of two token
12401 * types.
12402 */
12403 static void
12404 expect2(pm_parser_t *parser, pm_token_type_t type1, pm_token_type_t type2, pm_diagnostic_id_t diag_id) {
12405 if (accept2(parser, type1, type2)) return;
12406
12407 const uint8_t *location = parser->previous.end;
12408 pm_parser_err(parser, location, location, diag_id);
12409
12410 parser->previous.start = location;
12411 parser->previous.type = PM_TOKEN_MISSING;
12412 }
12413
12414 /**
12415 * A special expect1 that expects a heredoc terminator and handles popping the
12416 * lex mode accordingly.
12417 */
12418 static void
12419 expect1_heredoc_term(pm_parser_t *parser, const uint8_t *ident_start, size_t ident_length) {
12420 if (match1(parser, PM_TOKEN_HEREDOC_END)) {
12421 parser_lex(parser);
12422 } else {
12423 pm_parser_err_heredoc_term(parser, ident_start, ident_length);
12424 parser->previous.start = parser->previous.end;
12425 parser->previous.type = PM_TOKEN_MISSING;
12426 }
12427 }
12428
12429 /**
12430 * A special expect1 that attaches the error to the opening token location
12431 * rather than the current position. This is useful for errors about missing
12432 * closing tokens, where we want to point to the line with the opening token
12433 * (e.g., `def`, `class`, `if`, `{`) rather than the end of the file.
12434 */
12435 static void
12436 expect1_opening(pm_parser_t *parser, pm_token_type_t type, pm_diagnostic_id_t diag_id, const pm_token_t *opening) {
12437 if (accept1(parser, type)) return;
12438
12439 pm_parser_err(parser, opening->start, opening->end, diag_id);
12440
12441 parser->previous.start = parser->previous.end;
12442 parser->previous.type = PM_TOKEN_MISSING;
12443 }
12444
12445 static pm_node_t *
12446 parse_expression(pm_parser_t *parser, pm_binding_power_t binding_power, bool accepts_command_call, bool accepts_label, pm_diagnostic_id_t diag_id, uint16_t depth);
12447
12448 /**
12449 * This is a wrapper of parse_expression, which also checks whether the
12450 * resulting node is a value expression.
12451 */
12452 static pm_node_t *
12453 parse_value_expression(pm_parser_t *parser, pm_binding_power_t binding_power, bool accepts_command_call, bool accepts_label, pm_diagnostic_id_t diag_id, uint16_t depth) {
12454 pm_node_t *node = parse_expression(parser, binding_power, accepts_command_call, accepts_label, diag_id, depth);
12455 pm_assert_value_expression(parser, node);
12456 return node;
12457 }
12458
12459 /**
12460 * This function controls whether or not we will attempt to parse an expression
12461 * beginning at the subsequent token. It is used when we are in a context where
12462 * an expression is optional.
12463 *
12464 * For example, looking at a range object when we've already lexed the operator,
12465 * we need to know if we should attempt to parse an expression on the right.
12466 *
12467 * For another example, if we've parsed an identifier or a method call and we do
12468 * not have parentheses, then the next token may be the start of an argument or
12469 * it may not.
12470 *
12471 * CRuby parsers that are generated would resolve this by using a lookahead and
12472 * potentially backtracking. We attempt to do this by just looking at the next
12473 * token and making a decision based on that. I am not sure if this is going to
12474 * work in all cases, it may need to be refactored later. But it appears to work
12475 * for now.
12476 */
12477 static inline bool
12478 token_begins_expression_p(pm_token_type_t type) {
12479 switch (type) {
12480 case PM_TOKEN_EQUAL_GREATER:
12481 case PM_TOKEN_KEYWORD_IN:
12482 // We need to special case this because it is a binary operator that
12483 // should not be marked as beginning an expression.
12484 return false;
12485 case PM_TOKEN_BRACE_RIGHT:
12486 case PM_TOKEN_BRACKET_RIGHT:
12487 case PM_TOKEN_COLON:
12488 case PM_TOKEN_COMMA:
12489 case PM_TOKEN_EMBEXPR_END:
12490 case PM_TOKEN_EOF:
12491 case PM_TOKEN_LAMBDA_BEGIN:
12492 case PM_TOKEN_KEYWORD_DO:
12493 case PM_TOKEN_KEYWORD_DO_LOOP:
12494 case PM_TOKEN_KEYWORD_END:
12495 case PM_TOKEN_KEYWORD_ELSE:
12496 case PM_TOKEN_KEYWORD_ELSIF:
12497 case PM_TOKEN_KEYWORD_ENSURE:
12498 case PM_TOKEN_KEYWORD_THEN:
12499 case PM_TOKEN_KEYWORD_RESCUE:
12500 case PM_TOKEN_KEYWORD_WHEN:
12501 case PM_TOKEN_NEWLINE:
12502 case PM_TOKEN_PARENTHESIS_RIGHT:
12503 case PM_TOKEN_SEMICOLON:
12504 // The reason we need this short-circuit is because we're using the
12505 // binding powers table to tell us if the subsequent token could
12506 // potentially be the start of an expression. If there _is_ a binding
12507 // power for one of these tokens, then we should remove it from this list
12508 // and let it be handled by the default case below.
12509 assert(pm_binding_powers[type].left == PM_BINDING_POWER_UNSET);
12510 return false;
12511 case PM_TOKEN_UAMPERSAND:
12512 // This is a special case because this unary operator cannot appear
12513 // as a general operator, it only appears in certain circumstances.
12514 return false;
12515 case PM_TOKEN_UCOLON_COLON:
12516 case PM_TOKEN_UMINUS:
12517 case PM_TOKEN_UMINUS_NUM:
12518 case PM_TOKEN_UPLUS:
12519 case PM_TOKEN_BANG:
12520 case PM_TOKEN_TILDE:
12521 case PM_TOKEN_UDOT_DOT:
12522 case PM_TOKEN_UDOT_DOT_DOT:
12523 // These unary tokens actually do have binding power associated with them
12524 // so that we can correctly place them into the precedence order. But we
12525 // want them to be marked as beginning an expression, so we need to
12526 // special case them here.
12527 return true;
12528 default:
12529 return pm_binding_powers[type].left == PM_BINDING_POWER_UNSET;
12530 }
12531 }
12532
12533 /**
12534 * Parse an expression with the given binding power that may be optionally
12535 * prefixed by the * operator.
12536 */
12537 static pm_node_t *
12538 parse_starred_expression(pm_parser_t *parser, pm_binding_power_t binding_power, bool accepts_command_call, pm_diagnostic_id_t diag_id, uint16_t depth) {
12539 if (accept1(parser, PM_TOKEN_USTAR)) {
12540 pm_token_t operator = parser->previous;
12541 pm_node_t *expression = parse_value_expression(parser, binding_power, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_STAR, (uint16_t) (depth + 1));
12542 return UP(pm_splat_node_create(parser, &operator, expression));
12543 }
12544
12545 return parse_value_expression(parser, binding_power, accepts_command_call, false, diag_id, depth);
12546 }
12547
12548 static bool
12549 pm_node_unreference_each(const pm_node_t *node, void *data) {
12550 switch (PM_NODE_TYPE(node)) {
12551 /* When we are about to destroy a set of nodes that could potentially
12552 * contain block exits for the current scope, we need to check if they
12553 * are contained in the list of block exits and remove them if they are.
12554 */
12555 case PM_BREAK_NODE:
12556 case PM_NEXT_NODE:
12557 case PM_REDO_NODE: {
12558 pm_parser_t *parser = (pm_parser_t *) data;
12559 size_t index = 0;
12560
12561 while (index < parser->current_block_exits->size) {
12562 pm_node_t *block_exit = parser->current_block_exits->nodes[index];
12563
12564 if (block_exit == node) {
12565 if (index + 1 < parser->current_block_exits->size) {
12566 memmove(
12567 &parser->current_block_exits->nodes[index],
12568 &parser->current_block_exits->nodes[index + 1],
12569 (parser->current_block_exits->size - index - 1) * sizeof(pm_node_t *)
12570 );
12571 }
12572 parser->current_block_exits->size--;
12573
12574 /* Note returning true here because these nodes could have
12575 * arguments that are themselves block exits. */
12576 return true;
12577 }
12578
12579 index++;
12580 }
12581
12582 return true;
12583 }
12584 /* When an implicit local variable is written to or targeted, it becomes
12585 * a regular, named local variable. This branch removes it from the list
12586 * of implicit parameters when that happens. */
12587 case PM_LOCAL_VARIABLE_READ_NODE:
12588 case PM_IT_LOCAL_VARIABLE_READ_NODE: {
12589 pm_parser_t *parser = (pm_parser_t *) data;
12590 pm_node_list_t *implicit_parameters = &parser->current_scope->implicit_parameters;
12591
12592 for (size_t index = 0; index < implicit_parameters->size; index++) {
12593 if (implicit_parameters->nodes[index] == node) {
12594 /* If the node is not the last one in the list, we need to
12595 * shift the remaining nodes down to fill the gap. This is
12596 * extremely unlikely to happen. */
12597 if (index != implicit_parameters->size - 1) {
12598 memmove(&implicit_parameters->nodes[index], &implicit_parameters->nodes[index + 1], (implicit_parameters->size - index - 1) * sizeof(pm_node_t *));
12599 }
12600
12601 implicit_parameters->size--;
12602 break;
12603 }
12604 }
12605
12606 return false;
12607 }
12608 default:
12609 return true;
12610 }
12611 }
12612
12613 /**
12614 * When we are about to destroy a set of nodes that could potentially be
12615 * referenced by one or more lists on the parser, then remove them from those
12616 * lists so we don't get a use-after-free.
12617 */
12618 static void
12619 pm_node_unreference(pm_parser_t *parser, const pm_node_t *node) {
12620 pm_visit_node(node, pm_node_unreference_each, parser);
12621 }
12622
12623 /**
12624 * Convert the name of a method into the corresponding write method name. For
12625 * example, foo would be turned into foo=.
12626 */
12627 static void
12628 parse_write_name(pm_parser_t *parser, pm_constant_id_t *name_field) {
12629 // The method name needs to change. If we previously had
12630 // foo, we now need foo=. In this case we'll allocate a new
12631 // owned string, copy the previous method name in, and
12632 // append an =.
12633 pm_constant_t *constant = pm_constant_pool_id_to_constant(&parser->constant_pool, *name_field);
12634 size_t length = constant->length;
12635 uint8_t *name = xcalloc(length + 1, sizeof(uint8_t));
12636 if (name == NULL) return;
12637
12638 memcpy(name, constant->start, length);
12639 name[length] = '=';
12640
12641 // Now switch the name to the new string.
12642 // This silences clang analyzer warning about leak of memory pointed by `name`.
12643 // NOLINTNEXTLINE(clang-analyzer-*)
12644 *name_field = pm_constant_pool_insert_owned(&parser->constant_pool, name, length + 1);
12645 }
12646
12647 /**
12648 * Certain expressions are not targetable, but in order to provide a better
12649 * experience we give a specific error message. In order to maintain as much
12650 * information in the tree as possible, we replace them with local variable
12651 * writes.
12652 */
12653 static pm_node_t *
12654 parse_unwriteable_target(pm_parser_t *parser, pm_node_t *target) {
12655 switch (PM_NODE_TYPE(target)) {
12656 case PM_SOURCE_ENCODING_NODE: pm_parser_err_node(parser, target, PM_ERR_EXPRESSION_NOT_WRITABLE_ENCODING); break;
12657 case PM_FALSE_NODE: pm_parser_err_node(parser, target, PM_ERR_EXPRESSION_NOT_WRITABLE_FALSE); break;
12658 case PM_SOURCE_FILE_NODE: pm_parser_err_node(parser, target, PM_ERR_EXPRESSION_NOT_WRITABLE_FILE); break;
12659 case PM_SOURCE_LINE_NODE: pm_parser_err_node(parser, target, PM_ERR_EXPRESSION_NOT_WRITABLE_LINE); break;
12660 case PM_NIL_NODE: pm_parser_err_node(parser, target, PM_ERR_EXPRESSION_NOT_WRITABLE_NIL); break;
12661 case PM_SELF_NODE: pm_parser_err_node(parser, target, PM_ERR_EXPRESSION_NOT_WRITABLE_SELF); break;
12662 case PM_TRUE_NODE: pm_parser_err_node(parser, target, PM_ERR_EXPRESSION_NOT_WRITABLE_TRUE); break;
12663 default: break;
12664 }
12665
12666 pm_constant_id_t name = pm_parser_constant_id_location(parser, target->location.start, target->location.end);
12667 pm_local_variable_target_node_t *result = pm_local_variable_target_node_create(parser, &target->location, name, 0);
12668
12669 pm_node_destroy(parser, target);
12670 return UP(result);
12671 }
12672
12673 /**
12674 * Convert the given node into a valid target node.
12675 *
12676 * @param multiple Whether or not this target is part of a larger set of
12677 * targets. If it is, then the &. operator is not allowed.
12678 * @param splat Whether or not this target is a child of a splat target. If it
12679 * is, then fewer patterns are allowed.
12680 */
12681 static pm_node_t *
12682 parse_target(pm_parser_t *parser, pm_node_t *target, bool multiple, bool splat_parent) {
12683 switch (PM_NODE_TYPE(target)) {
12684 case PM_MISSING_NODE:
12685 return target;
12686 case PM_SOURCE_ENCODING_NODE:
12687 case PM_FALSE_NODE:
12688 case PM_SOURCE_FILE_NODE:
12689 case PM_SOURCE_LINE_NODE:
12690 case PM_NIL_NODE:
12691 case PM_SELF_NODE:
12692 case PM_TRUE_NODE: {
12693 // In these special cases, we have specific error messages and we
12694 // will replace them with local variable writes.
12695 return parse_unwriteable_target(parser, target);
12696 }
12697 case PM_CLASS_VARIABLE_READ_NODE:
12698 assert(sizeof(pm_class_variable_target_node_t) == sizeof(pm_class_variable_read_node_t));
12699 target->type = PM_CLASS_VARIABLE_TARGET_NODE;
12700 return target;
12701 case PM_CONSTANT_PATH_NODE:
12702 if (context_def_p(parser)) {
12703 pm_parser_err_node(parser, target, PM_ERR_WRITE_TARGET_IN_METHOD);
12704 }
12705
12706 assert(sizeof(pm_constant_path_target_node_t) == sizeof(pm_constant_path_node_t));
12707 target->type = PM_CONSTANT_PATH_TARGET_NODE;
12708
12709 return target;
12710 case PM_CONSTANT_READ_NODE:
12711 if (context_def_p(parser)) {
12712 pm_parser_err_node(parser, target, PM_ERR_WRITE_TARGET_IN_METHOD);
12713 }
12714
12715 assert(sizeof(pm_constant_target_node_t) == sizeof(pm_constant_read_node_t));
12716 target->type = PM_CONSTANT_TARGET_NODE;
12717
12718 return target;
12719 case PM_BACK_REFERENCE_READ_NODE:
12720 case PM_NUMBERED_REFERENCE_READ_NODE:
12721 PM_PARSER_ERR_NODE_FORMAT_CONTENT(parser, target, PM_ERR_WRITE_TARGET_READONLY);
12722 return target;
12723 case PM_GLOBAL_VARIABLE_READ_NODE:
12724 assert(sizeof(pm_global_variable_target_node_t) == sizeof(pm_global_variable_read_node_t));
12725 target->type = PM_GLOBAL_VARIABLE_TARGET_NODE;
12726 return target;
12727 case PM_LOCAL_VARIABLE_READ_NODE: {
12728 if (pm_token_is_numbered_parameter(target->location.start, target->location.end)) {
12729 PM_PARSER_ERR_FORMAT(parser, target->location.start, target->location.end, PM_ERR_PARAMETER_NUMBERED_RESERVED, target->location.start);
12730 pm_node_unreference(parser, target);
12731 }
12732
12733 const pm_local_variable_read_node_t *cast = (const pm_local_variable_read_node_t *) target;
12734 uint32_t name = cast->name;
12735 uint32_t depth = cast->depth;
12736 pm_locals_unread(&pm_parser_scope_find(parser, depth)->locals, name);
12737
12738 assert(sizeof(pm_local_variable_target_node_t) == sizeof(pm_local_variable_read_node_t));
12739 target->type = PM_LOCAL_VARIABLE_TARGET_NODE;
12740
12741 return target;
12742 }
12743 case PM_IT_LOCAL_VARIABLE_READ_NODE: {
12744 pm_constant_id_t name = pm_parser_local_add_constant(parser, "it", 2);
12745 pm_node_t *node = UP(pm_local_variable_target_node_create(parser, &target->location, name, 0));
12746
12747 pm_node_unreference(parser, target);
12748 pm_node_destroy(parser, target);
12749
12750 return node;
12751 }
12752 case PM_INSTANCE_VARIABLE_READ_NODE:
12753 assert(sizeof(pm_instance_variable_target_node_t) == sizeof(pm_instance_variable_read_node_t));
12754 target->type = PM_INSTANCE_VARIABLE_TARGET_NODE;
12755 return target;
12756 case PM_MULTI_TARGET_NODE:
12757 if (splat_parent) {
12758 // Multi target is not accepted in all positions. If this is one
12759 // of them, then we need to add an error.
12760 pm_parser_err_node(parser, target, PM_ERR_WRITE_TARGET_UNEXPECTED);
12761 }
12762
12763 return target;
12764 case PM_SPLAT_NODE: {
12765 pm_splat_node_t *splat = (pm_splat_node_t *) target;
12766
12767 if (splat->expression != NULL) {
12768 splat->expression = parse_target(parser, splat->expression, multiple, true);
12769 }
12770
12771 return UP(splat);
12772 }
12773 case PM_CALL_NODE: {
12774 pm_call_node_t *call = (pm_call_node_t *) target;
12775
12776 // If we have no arguments to the call node and we need this to be a
12777 // target then this is either a method call or a local variable
12778 // write.
12779 if (
12780 (call->message_loc.start != NULL) &&
12781 (call->message_loc.end[-1] != '!') &&
12782 (call->message_loc.end[-1] != '?') &&
12783 (call->opening_loc.start == NULL) &&
12784 (call->arguments == NULL) &&
12785 (call->block == NULL)
12786 ) {
12787 if (call->receiver == NULL) {
12788 // When we get here, we have a local variable write, because it
12789 // was previously marked as a method call but now we have an =.
12790 // This looks like:
12791 //
12792 // foo = 1
12793 //
12794 // When it was parsed in the prefix position, foo was seen as a
12795 // method call with no receiver and no arguments. Now we have an
12796 // =, so we know it's a local variable write.
12797 const pm_location_t message_loc = call->message_loc;
12798
12799 pm_constant_id_t name = pm_parser_local_add_location(parser, message_loc.start, message_loc.end, 0);
12800 pm_node_destroy(parser, target);
12801
12802 return UP(pm_local_variable_target_node_create(parser, &message_loc, name, 0));
12803 }
12804
12805 if (peek_at(parser, call->message_loc.start) == '_' || parser->encoding->alnum_char(call->message_loc.start, call->message_loc.end - call->message_loc.start)) {
12806 if (multiple && PM_NODE_FLAG_P(call, PM_CALL_NODE_FLAGS_SAFE_NAVIGATION)) {
12807 pm_parser_err_node(parser, (const pm_node_t *) call, PM_ERR_UNEXPECTED_SAFE_NAVIGATION);
12808 }
12809
12810 parse_write_name(parser, &call->name);
12811 return UP(pm_call_target_node_create(parser, call));
12812 }
12813 }
12814
12815 // If there is no call operator and the message is "[]" then this is
12816 // an aref expression, and we can transform it into an aset
12817 // expression.
12818 if (PM_NODE_FLAG_P(call, PM_CALL_NODE_FLAGS_INDEX)) {
12819 return UP(pm_index_target_node_create(parser, call));
12820 }
12821 }
12822 PRISM_FALLTHROUGH
12823 default:
12824 // In this case we have a node that we don't know how to convert
12825 // into a target. We need to treat it as an error. For now, we'll
12826 // mark it as an error and just skip right past it.
12827 pm_parser_err_node(parser, target, PM_ERR_WRITE_TARGET_UNEXPECTED);
12828 return target;
12829 }
12830 }
12831
12832 /**
12833 * Parse a write target and validate that it is in a valid position for
12834 * assignment.
12835 */
12836 static pm_node_t *
12837 parse_target_validate(pm_parser_t *parser, pm_node_t *target, bool multiple) {
12838 pm_node_t *result = parse_target(parser, target, multiple, false);
12839
12840 // Ensure that we have one of an =, an 'in' in for indexes, and a ')' in
12841 // parens after the targets.
12842 if (
12843 !match1(parser, PM_TOKEN_EQUAL) &&
12844 !(context_p(parser, PM_CONTEXT_FOR_INDEX) && match1(parser, PM_TOKEN_KEYWORD_IN)) &&
12845 !(context_p(parser, PM_CONTEXT_PARENS) && match1(parser, PM_TOKEN_PARENTHESIS_RIGHT))
12846 ) {
12847 pm_parser_err_node(parser, result, PM_ERR_WRITE_TARGET_UNEXPECTED);
12848 }
12849
12850 return result;
12851 }
12852
12853 /**
12854 * Potentially wrap a constant write node in a shareable constant node depending
12855 * on the current state.
12856 */
12857 static pm_node_t *
12858 parse_shareable_constant_write(pm_parser_t *parser, pm_node_t *write) {
12859 pm_shareable_constant_value_t shareable_constant = pm_parser_scope_shareable_constant_get(parser);
12860
12861 if (shareable_constant != PM_SCOPE_SHAREABLE_CONSTANT_NONE) {
12862 return UP(pm_shareable_constant_node_create(parser, write, shareable_constant));
12863 }
12864
12865 return write;
12866 }
12867
12868 /**
12869 * Convert the given node into a valid write node.
12870 */
12871 static pm_node_t *
12872 parse_write(pm_parser_t *parser, pm_node_t *target, pm_token_t *operator, pm_node_t *value) {
12873 switch (PM_NODE_TYPE(target)) {
12874 case PM_MISSING_NODE:
12875 pm_node_destroy(parser, value);
12876 return target;
12877 case PM_CLASS_VARIABLE_READ_NODE: {
12878 pm_class_variable_write_node_t *node = pm_class_variable_write_node_create(parser, (pm_class_variable_read_node_t *) target, operator, value);
12879 pm_node_destroy(parser, target);
12880 return UP(node);
12881 }
12882 case PM_CONSTANT_PATH_NODE: {
12883 pm_node_t *node = UP(pm_constant_path_write_node_create(parser, (pm_constant_path_node_t *) target, operator, value));
12884
12885 if (context_def_p(parser)) {
12886 pm_parser_err_node(parser, node, PM_ERR_WRITE_TARGET_IN_METHOD);
12887 }
12888
12889 return parse_shareable_constant_write(parser, node);
12890 }
12891 case PM_CONSTANT_READ_NODE: {
12892 pm_node_t *node = UP(pm_constant_write_node_create(parser, (pm_constant_read_node_t *) target, operator, value));
12893
12894 if (context_def_p(parser)) {
12895 pm_parser_err_node(parser, node, PM_ERR_WRITE_TARGET_IN_METHOD);
12896 }
12897
12898 pm_node_destroy(parser, target);
12899 return parse_shareable_constant_write(parser, node);
12900 }
12901 case PM_BACK_REFERENCE_READ_NODE:
12902 case PM_NUMBERED_REFERENCE_READ_NODE:
12903 PM_PARSER_ERR_NODE_FORMAT_CONTENT(parser, target, PM_ERR_WRITE_TARGET_READONLY);
12904 PRISM_FALLTHROUGH
12905 case PM_GLOBAL_VARIABLE_READ_NODE: {
12906 pm_global_variable_write_node_t *node = pm_global_variable_write_node_create(parser, target, operator, value);
12907 pm_node_destroy(parser, target);
12908 return UP(node);
12909 }
12910 case PM_LOCAL_VARIABLE_READ_NODE: {
12911 pm_local_variable_read_node_t *local_read = (pm_local_variable_read_node_t *) target;
12912
12913 pm_constant_id_t name = local_read->name;
12914 pm_location_t name_loc = target->location;
12915
12916 uint32_t depth = local_read->depth;
12917 pm_scope_t *scope = pm_parser_scope_find(parser, depth);
12918
12919 if (pm_token_is_numbered_parameter(target->location.start, target->location.end)) {
12920 pm_diagnostic_id_t diag_id = (scope->parameters & PM_SCOPE_PARAMETERS_NUMBERED_FOUND) ? PM_ERR_EXPRESSION_NOT_WRITABLE_NUMBERED : PM_ERR_PARAMETER_NUMBERED_RESERVED;
12921 PM_PARSER_ERR_FORMAT(parser, target->location.start, target->location.end, diag_id, target->location.start);
12922 pm_node_unreference(parser, target);
12923 }
12924
12925 pm_locals_unread(&scope->locals, name);
12926 pm_node_destroy(parser, target);
12927
12928 return UP(pm_local_variable_write_node_create(parser, name, depth, value, &name_loc, operator));
12929 }
12930 case PM_IT_LOCAL_VARIABLE_READ_NODE: {
12931 pm_constant_id_t name = pm_parser_local_add_constant(parser, "it", 2);
12932 pm_node_t *node = UP(pm_local_variable_write_node_create(parser, name, 0, value, &target->location, operator));
12933
12934 pm_node_unreference(parser, target);
12935 pm_node_destroy(parser, target);
12936
12937 return node;
12938 }
12939 case PM_INSTANCE_VARIABLE_READ_NODE: {
12940 pm_node_t *write_node = UP(pm_instance_variable_write_node_create(parser, (pm_instance_variable_read_node_t *) target, operator, value));
12941 pm_node_destroy(parser, target);
12942 return write_node;
12943 }
12944 case PM_MULTI_TARGET_NODE:
12945 return UP(pm_multi_write_node_create(parser, (pm_multi_target_node_t *) target, operator, value));
12946 case PM_SPLAT_NODE: {
12947 pm_splat_node_t *splat = (pm_splat_node_t *) target;
12948
12949 if (splat->expression != NULL) {
12950 splat->expression = parse_write(parser, splat->expression, operator, value);
12951 }
12952
12953 pm_multi_target_node_t *multi_target = pm_multi_target_node_create(parser);
12954 pm_multi_target_node_targets_append(parser, multi_target, UP(splat));
12955
12956 return UP(pm_multi_write_node_create(parser, multi_target, operator, value));
12957 }
12958 case PM_CALL_NODE: {
12959 pm_call_node_t *call = (pm_call_node_t *) target;
12960
12961 // If we have no arguments to the call node and we need this to be a
12962 // target then this is either a method call or a local variable
12963 // write.
12964 if (
12965 (call->message_loc.start != NULL) &&
12966 (call->message_loc.end[-1] != '!') &&
12967 (call->message_loc.end[-1] != '?') &&
12968 (call->opening_loc.start == NULL) &&
12969 (call->arguments == NULL) &&
12970 (call->block == NULL)
12971 ) {
12972 if (call->receiver == NULL) {
12973 // When we get here, we have a local variable write, because it
12974 // was previously marked as a method call but now we have an =.
12975 // This looks like:
12976 //
12977 // foo = 1
12978 //
12979 // When it was parsed in the prefix position, foo was seen as a
12980 // method call with no receiver and no arguments. Now we have an
12981 // =, so we know it's a local variable write.
12982 const pm_location_t message = call->message_loc;
12983
12984 pm_parser_local_add_location(parser, message.start, message.end, 0);
12985 pm_node_destroy(parser, target);
12986
12987 pm_constant_id_t constant_id = pm_parser_constant_id_location(parser, message.start, message.end);
12988 target = UP(pm_local_variable_write_node_create(parser, constant_id, 0, value, &message, operator));
12989
12990 pm_refute_numbered_parameter(parser, message.start, message.end);
12991 return target;
12992 }
12993
12994 if (char_is_identifier_start(parser, call->message_loc.start, parser->end - call->message_loc.start)) {
12995 // When we get here, we have a method call, because it was
12996 // previously marked as a method call but now we have an =. This
12997 // looks like:
12998 //
12999 // foo.bar = 1
13000 //
13001 // When it was parsed in the prefix position, foo.bar was seen as a
13002 // method call with no arguments. Now we have an =, so we know it's
13003 // a method call with an argument. In this case we will create the
13004 // arguments node, parse the argument, and add it to the list.
13005 pm_arguments_node_t *arguments = pm_arguments_node_create(parser);
13006 call->arguments = arguments;
13007
13008 pm_arguments_node_arguments_append(arguments, value);
13009 call->base.location.end = arguments->base.location.end;
13010 call->equal_loc = PM_LOCATION_TOKEN_VALUE(operator);
13011
13012 parse_write_name(parser, &call->name);
13013 pm_node_flag_set(UP(call), PM_CALL_NODE_FLAGS_ATTRIBUTE_WRITE | pm_implicit_array_write_flags(value, PM_CALL_NODE_FLAGS_IMPLICIT_ARRAY));
13014
13015 return UP(call);
13016 }
13017 }
13018
13019 // If there is no call operator and the message is "[]" then this is
13020 // an aref expression, and we can transform it into an aset
13021 // expression.
13022 if (PM_NODE_FLAG_P(call, PM_CALL_NODE_FLAGS_INDEX)) {
13023 if (call->arguments == NULL) {
13024 call->arguments = pm_arguments_node_create(parser);
13025 }
13026
13027 pm_arguments_node_arguments_append(call->arguments, value);
13028 target->location.end = value->location.end;
13029
13030 // Replace the name with "[]=".
13031 call->name = pm_parser_constant_id_constant(parser, "[]=", 3);
13032 call->equal_loc = PM_LOCATION_TOKEN_VALUE(operator);
13033
13034 // Ensure that the arguments for []= don't contain keywords
13035 pm_index_arguments_check(parser, call->arguments, call->block);
13036 pm_node_flag_set(UP(call), PM_CALL_NODE_FLAGS_ATTRIBUTE_WRITE | pm_implicit_array_write_flags(value, PM_CALL_NODE_FLAGS_IMPLICIT_ARRAY));
13037
13038 return target;
13039 }
13040
13041 // If there are arguments on the call node, then it can't be a
13042 // method call ending with = or a local variable write, so it must
13043 // be a syntax error. In this case we'll fall through to our default
13044 // handling. We need to free the value that we parsed because there
13045 // is no way for us to attach it to the tree at this point.
13046 //
13047 // Since it is possible for the value to contain an implicit
13048 // parameter somewhere in its subtree, we need to walk it and remove
13049 // any implicit parameters from the list of implicit parameters for
13050 // the current scope.
13051 pm_node_unreference(parser, value);
13052 pm_node_destroy(parser, value);
13053 }
13054 PRISM_FALLTHROUGH
13055 default:
13056 // In this case we have a node that we don't know how to convert into a
13057 // target. We need to treat it as an error. For now, we'll mark it as an
13058 // error and just skip right past it.
13059 pm_parser_err_token(parser, operator, PM_ERR_WRITE_TARGET_UNEXPECTED);
13060 return target;
13061 }
13062 }
13063
13064 /**
13065 * Certain expressions are not writable, but in order to provide a better
13066 * experience we give a specific error message. In order to maintain as much
13067 * information in the tree as possible, we replace them with local variable
13068 * writes.
13069 */
13070 static pm_node_t *
13071 parse_unwriteable_write(pm_parser_t *parser, pm_node_t *target, const pm_token_t *equals, pm_node_t *value) {
13072 switch (PM_NODE_TYPE(target)) {
13073 case PM_SOURCE_ENCODING_NODE: pm_parser_err_token(parser, equals, PM_ERR_EXPRESSION_NOT_WRITABLE_ENCODING); break;
13074 case PM_FALSE_NODE: pm_parser_err_token(parser, equals, PM_ERR_EXPRESSION_NOT_WRITABLE_FALSE); break;
13075 case PM_SOURCE_FILE_NODE: pm_parser_err_token(parser, equals, PM_ERR_EXPRESSION_NOT_WRITABLE_FILE); break;
13076 case PM_SOURCE_LINE_NODE: pm_parser_err_token(parser, equals, PM_ERR_EXPRESSION_NOT_WRITABLE_LINE); break;
13077 case PM_NIL_NODE: pm_parser_err_token(parser, equals, PM_ERR_EXPRESSION_NOT_WRITABLE_NIL); break;
13078 case PM_SELF_NODE: pm_parser_err_token(parser, equals, PM_ERR_EXPRESSION_NOT_WRITABLE_SELF); break;
13079 case PM_TRUE_NODE: pm_parser_err_token(parser, equals, PM_ERR_EXPRESSION_NOT_WRITABLE_TRUE); break;
13080 default: break;
13081 }
13082
13083 pm_constant_id_t name = pm_parser_local_add_location(parser, target->location.start, target->location.end, 1);
13084 pm_local_variable_write_node_t *result = pm_local_variable_write_node_create(parser, name, 0, value, &target->location, equals);
13085
13086 pm_node_destroy(parser, target);
13087 return UP(result);
13088 }
13089
13090 /**
13091 * Parse a list of targets for assignment. This is used in the case of a for
13092 * loop or a multi-assignment. For example, in the following code:
13093 *
13094 * for foo, bar in baz
13095 * ^^^^^^^^
13096 *
13097 * The targets are `foo` and `bar`. This function will either return a single
13098 * target node or a multi-target node.
13099 */
13100 static pm_node_t *
13101 parse_targets(pm_parser_t *parser, pm_node_t *first_target, pm_binding_power_t binding_power, uint16_t depth) {
13102 bool has_rest = PM_NODE_TYPE_P(first_target, PM_SPLAT_NODE);
13103
13104 pm_multi_target_node_t *result = pm_multi_target_node_create(parser);
13105 pm_multi_target_node_targets_append(parser, result, parse_target(parser, first_target, true, false));
13106
13107 while (accept1(parser, PM_TOKEN_COMMA)) {
13108 if (accept1(parser, PM_TOKEN_USTAR)) {
13109 // Here we have a splat operator. It can have a name or be
13110 // anonymous. It can be the final target or be in the middle if
13111 // there haven't been any others yet.
13112 if (has_rest) {
13113 pm_parser_err_previous(parser, PM_ERR_MULTI_ASSIGN_MULTI_SPLATS);
13114 }
13115
13116 pm_token_t star_operator = parser->previous;
13117 pm_node_t *name = NULL;
13118
13119 if (token_begins_expression_p(parser->current.type)) {
13120 name = parse_expression(parser, binding_power, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_STAR, (uint16_t) (depth + 1));
13121 name = parse_target(parser, name, true, true);
13122 }
13123
13124 pm_node_t *splat = UP(pm_splat_node_create(parser, &star_operator, name));
13125 pm_multi_target_node_targets_append(parser, result, splat);
13126 has_rest = true;
13127 } else if (match1(parser, PM_TOKEN_PARENTHESIS_LEFT)) {
13128 context_push(parser, PM_CONTEXT_MULTI_TARGET);
13129 pm_node_t *target = parse_expression(parser, binding_power, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_COMMA, (uint16_t) (depth + 1));
13130 target = parse_target(parser, target, true, false);
13131
13132 pm_multi_target_node_targets_append(parser, result, target);
13133 context_pop(parser);
13134 } else if (token_begins_expression_p(parser->current.type)) {
13135 pm_node_t *target = parse_expression(parser, binding_power, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_COMMA, (uint16_t) (depth + 1));
13136 target = parse_target(parser, target, true, false);
13137
13138 pm_multi_target_node_targets_append(parser, result, target);
13139 } else if (!match1(parser, PM_TOKEN_EOF)) {
13140 // If we get here, then we have a trailing , in a multi target node.
13141 // We'll add an implicit rest node to represent this.
13142 pm_node_t *rest = UP(pm_implicit_rest_node_create(parser, &parser->previous));
13143 pm_multi_target_node_targets_append(parser, result, rest);
13144 break;
13145 }
13146 }
13147
13148 return UP(result);
13149 }
13150
13151 /**
13152 * Parse a list of targets and validate that it is in a valid position for
13153 * assignment.
13154 */
13155 static pm_node_t *
13156 parse_targets_validate(pm_parser_t *parser, pm_node_t *first_target, pm_binding_power_t binding_power, uint16_t depth) {
13157 pm_node_t *result = parse_targets(parser, first_target, binding_power, depth);
13158 accept1(parser, PM_TOKEN_NEWLINE);
13159
13160 // Ensure that we have either an = or a ) after the targets.
13161 if (!match2(parser, PM_TOKEN_EQUAL, PM_TOKEN_PARENTHESIS_RIGHT)) {
13162 pm_parser_err_node(parser, result, PM_ERR_WRITE_TARGET_UNEXPECTED);
13163 }
13164
13165 return result;
13166 }
13167
13168 /**
13169 * Parse a list of statements separated by newlines or semicolons.
13170 */
13171 static pm_statements_node_t *
13172 parse_statements(pm_parser_t *parser, pm_context_t context, uint16_t depth) {
13173 // First, skip past any optional terminators that might be at the beginning
13174 // of the statements.
13175 while (accept2(parser, PM_TOKEN_SEMICOLON, PM_TOKEN_NEWLINE));
13176
13177 // If we have a terminator, then we can just return NULL.
13178 if (context_terminator(context, &parser->current)) return NULL;
13179
13180 pm_statements_node_t *statements = pm_statements_node_create(parser);
13181
13182 // At this point we know we have at least one statement, and that it
13183 // immediately follows the current token.
13184 context_push(parser, context);
13185
13186 while (true) {
13187 pm_node_t *node = parse_expression(parser, PM_BINDING_POWER_STATEMENT, true, false, PM_ERR_CANNOT_PARSE_EXPRESSION, (uint16_t) (depth + 1));
13188 pm_statements_node_body_append(parser, statements, node, true);
13189
13190 // If we're recovering from a syntax error, then we need to stop parsing
13191 // the statements now.
13192 if (parser->recovering) {
13193 // If this is the level of context where the recovery has happened,
13194 // then we can mark the parser as done recovering.
13195 if (context_terminator(context, &parser->current)) parser->recovering = false;
13196 break;
13197 }
13198
13199 // If we have a terminator, then we will parse all consecutive
13200 // terminators and then continue parsing the statements list.
13201 if (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON)) {
13202 // If we have a terminator, then we will continue parsing the
13203 // statements list.
13204 while (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON));
13205 if (context_terminator(context, &parser->current)) break;
13206
13207 // Now we can continue parsing the list of statements.
13208 continue;
13209 }
13210
13211 // At this point we have a list of statements that are not terminated by
13212 // a newline or semicolon. At this point we need to check if we're at
13213 // the end of the statements list. If we are, then we should break out
13214 // of the loop.
13215 if (context_terminator(context, &parser->current)) break;
13216
13217 // At this point, we have a syntax error, because the statement was not
13218 // terminated by a newline or semicolon, and we're not at the end of the
13219 // statements list. Ideally we should scan forward to determine if we
13220 // should insert a missing terminator or break out of parsing the
13221 // statements list at this point.
13222 //
13223 // We don't have that yet, so instead we'll do a more naive approach. If
13224 // we were unable to parse an expression, then we will skip past this
13225 // token and continue parsing the statements list. Otherwise we'll add
13226 // an error and continue parsing the statements list.
13227 if (PM_NODE_TYPE_P(node, PM_MISSING_NODE)) {
13228 parser_lex(parser);
13229
13230 // If we are at the end of the file, then we need to stop parsing
13231 // the statements entirely at this point. Mark the parser as
13232 // recovering, as we know that EOF closes the top-level context, and
13233 // then break out of the loop.
13234 if (match1(parser, PM_TOKEN_EOF)) {
13235 parser->recovering = true;
13236 break;
13237 }
13238
13239 while (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON));
13240 if (context_terminator(context, &parser->current)) break;
13241 } else if (!accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_EOF)) {
13242 // This is an inlined version of accept1 because the error that we
13243 // want to add has varargs. If this happens again, we should
13244 // probably extract a helper function.
13245 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_EXPECT_EOL_AFTER_STATEMENT, pm_token_type_human(parser->current.type));
13246 parser->previous.start = parser->previous.end;
13247 parser->previous.type = PM_TOKEN_MISSING;
13248 }
13249 }
13250
13251 context_pop(parser);
13252 bool last_value = true;
13253 switch (context) {
13254 case PM_CONTEXT_BEGIN_ENSURE:
13255 case PM_CONTEXT_DEF_ENSURE:
13256 last_value = false;
13257 break;
13258 default:
13259 break;
13260 }
13261 pm_void_statements_check(parser, statements, last_value);
13262
13263 return statements;
13264 }
13265
13266 /**
13267 * Add a node to a set of static literals that holds a set of hash keys. If the
13268 * node is a duplicate, then add an appropriate warning.
13269 */
13270 static void
13271 pm_hash_key_static_literals_add(pm_parser_t *parser, pm_static_literals_t *literals, pm_node_t *node) {
13272 const pm_node_t *duplicated = pm_static_literals_add(&parser->newline_list, parser->start_line, literals, node, true);
13273
13274 if (duplicated != NULL) {
13275 pm_buffer_t buffer = { 0 };
13276 pm_static_literal_inspect(&buffer, &parser->newline_list, parser->start_line, parser->encoding->name, duplicated);
13277
13278 pm_diagnostic_list_append_format(
13279 &parser->warning_list,
13280 duplicated->location.start,
13281 duplicated->location.end,
13282 PM_WARN_DUPLICATED_HASH_KEY,
13283 (int) pm_buffer_length(&buffer),
13284 pm_buffer_value(&buffer),
13285 pm_newline_list_line_column(&parser->newline_list, node->location.start, parser->start_line).line
13286 );
13287
13288 pm_buffer_free(&buffer);
13289 }
13290 }
13291
13292 /**
13293 * Add a node to a set of static literals that holds a set of hash keys. If the
13294 * node is a duplicate, then add an appropriate warning.
13295 */
13296 static void
13297 pm_when_clause_static_literals_add(pm_parser_t *parser, pm_static_literals_t *literals, pm_node_t *node) {
13298 pm_node_t *previous;
13299
13300 if ((previous = pm_static_literals_add(&parser->newline_list, parser->start_line, literals, node, false)) != NULL) {
13301 pm_diagnostic_list_append_format(
13302 &parser->warning_list,
13303 node->location.start,
13304 node->location.end,
13305 PM_WARN_DUPLICATED_WHEN_CLAUSE,
13306 pm_newline_list_line_column(&parser->newline_list, node->location.start, parser->start_line).line,
13307 pm_newline_list_line_column(&parser->newline_list, previous->location.start, parser->start_line).line
13308 );
13309 }
13310 }
13311
13312 /**
13313 * Parse all of the elements of a hash. Return true if a double splat was found.
13314 */
13315 static bool
13316 parse_assocs(pm_parser_t *parser, pm_static_literals_t *literals, pm_node_t *node, uint16_t depth) {
13317 assert(PM_NODE_TYPE_P(node, PM_HASH_NODE) || PM_NODE_TYPE_P(node, PM_KEYWORD_HASH_NODE));
13318 bool contains_keyword_splat = false;
13319
13320 while (true) {
13321 pm_node_t *element;
13322
13323 switch (parser->current.type) {
13324 case PM_TOKEN_USTAR_STAR: {
13325 parser_lex(parser);
13326 pm_token_t operator = parser->previous;
13327 pm_node_t *value = NULL;
13328
13329 if (match1(parser, PM_TOKEN_BRACE_LEFT)) {
13330 // If we're about to parse a nested hash that is being
13331 // pushed into this hash directly with **, then we want the
13332 // inner hash to share the static literals with the outer
13333 // hash.
13334 parser->current_hash_keys = literals;
13335 value = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_SPLAT_HASH, (uint16_t) (depth + 1));
13336 } else if (token_begins_expression_p(parser->current.type)) {
13337 value = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_SPLAT_HASH, (uint16_t) (depth + 1));
13338 } else {
13339 pm_parser_scope_forwarding_keywords_check(parser, &operator);
13340 }
13341
13342 element = UP(pm_assoc_splat_node_create(parser, value, &operator));
13343 contains_keyword_splat = true;
13344 break;
13345 }
13346 case PM_TOKEN_LABEL: {
13347 pm_token_t label = parser->current;
13348 parser_lex(parser);
13349
13350 pm_node_t *key = UP(pm_symbol_node_label_create(parser, &label));
13351 pm_hash_key_static_literals_add(parser, literals, key);
13352
13353 pm_token_t operator = not_provided(parser);
13354 pm_node_t *value = NULL;
13355
13356 if (token_begins_expression_p(parser->current.type)) {
13357 value = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_HASH_EXPRESSION_AFTER_LABEL, (uint16_t) (depth + 1));
13358 } else {
13359 if (parser->encoding->isupper_char(label.start, (label.end - 1) - label.start)) {
13360 pm_token_t constant = { .type = PM_TOKEN_CONSTANT, .start = label.start, .end = label.end - 1 };
13361 value = UP(pm_constant_read_node_create(parser, &constant));
13362 } else {
13363 int depth = -1;
13364 pm_token_t identifier = { .type = PM_TOKEN_IDENTIFIER, .start = label.start, .end = label.end - 1 };
13365
13366 if (identifier.end[-1] == '!' || identifier.end[-1] == '?') {
13367 PM_PARSER_ERR_TOKEN_FORMAT_CONTENT(parser, identifier, PM_ERR_INVALID_LOCAL_VARIABLE_READ);
13368 } else {
13369 depth = pm_parser_local_depth(parser, &identifier);
13370 }
13371
13372 if (depth == -1) {
13373 value = UP(pm_call_node_variable_call_create(parser, &identifier));
13374 } else {
13375 value = UP(pm_local_variable_read_node_create(parser, &identifier, (uint32_t) depth));
13376 }
13377 }
13378
13379 value->location.end++;
13380 value = UP(pm_implicit_node_create(parser, value));
13381 }
13382
13383 element = UP(pm_assoc_node_create(parser, key, &operator, value));
13384 break;
13385 }
13386 default: {
13387 pm_node_t *key = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, true, PM_ERR_HASH_KEY, (uint16_t) (depth + 1));
13388
13389 // Hash keys that are strings are automatically frozen. We will
13390 // mark that here.
13391 if (PM_NODE_TYPE_P(key, PM_STRING_NODE)) {
13392 pm_node_flag_set(key, PM_STRING_FLAGS_FROZEN | PM_NODE_FLAG_STATIC_LITERAL);
13393 }
13394
13395 pm_hash_key_static_literals_add(parser, literals, key);
13396
13397 pm_token_t operator;
13398 if (pm_symbol_node_label_p(key)) {
13399 operator = not_provided(parser);
13400 } else {
13401 expect1(parser, PM_TOKEN_EQUAL_GREATER, PM_ERR_HASH_ROCKET);
13402 operator = parser->previous;
13403 }
13404
13405 pm_node_t *value = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_HASH_VALUE, (uint16_t) (depth + 1));
13406 element = UP(pm_assoc_node_create(parser, key, &operator, value));
13407 break;
13408 }
13409 }
13410
13411 if (PM_NODE_TYPE_P(node, PM_HASH_NODE)) {
13412 pm_hash_node_elements_append((pm_hash_node_t *) node, element);
13413 } else {
13414 pm_keyword_hash_node_elements_append((pm_keyword_hash_node_t *) node, element);
13415 }
13416
13417 // If there's no comma after the element, then we're done.
13418 if (!accept1(parser, PM_TOKEN_COMMA)) break;
13419
13420 // If the next element starts with a label or a **, then we know we have
13421 // another element in the hash, so we'll continue parsing.
13422 if (match2(parser, PM_TOKEN_USTAR_STAR, PM_TOKEN_LABEL)) continue;
13423
13424 // Otherwise we need to check if the subsequent token begins an expression.
13425 // If it does, then we'll continue parsing.
13426 if (token_begins_expression_p(parser->current.type)) continue;
13427
13428 // Otherwise by default we will exit out of this loop.
13429 break;
13430 }
13431
13432 return contains_keyword_splat;
13433 }
13434
13435 static inline bool
13436 argument_allowed_for_bare_hash(pm_parser_t *parser, pm_node_t *argument) {
13437 if (pm_symbol_node_label_p(argument)) {
13438 return true;
13439 }
13440
13441 switch (PM_NODE_TYPE(argument)) {
13442 case PM_CALL_NODE: {
13443 pm_call_node_t *cast = (pm_call_node_t *) argument;
13444 if (cast->opening_loc.start == NULL && cast->arguments != NULL) {
13445 if (PM_NODE_FLAG_P(cast->arguments, PM_ARGUMENTS_NODE_FLAGS_CONTAINS_KEYWORDS | PM_ARGUMENTS_NODE_FLAGS_CONTAINS_SPLAT)) {
13446 return false;
13447 }
13448 if (cast->block != NULL) {
13449 return false;
13450 }
13451 }
13452 break;
13453 }
13454 default: break;
13455 }
13456 return accept1(parser, PM_TOKEN_EQUAL_GREATER);
13457 }
13458
13459 /**
13460 * Append an argument to a list of arguments.
13461 */
13462 static inline void
13463 parse_arguments_append(pm_parser_t *parser, pm_arguments_t *arguments, pm_node_t *argument) {
13464 if (arguments->arguments == NULL) {
13465 arguments->arguments = pm_arguments_node_create(parser);
13466 }
13467
13468 pm_arguments_node_arguments_append(arguments->arguments, argument);
13469 }
13470
13471 /**
13472 * Parse a list of arguments.
13473 */
13474 static void
13475 parse_arguments(pm_parser_t *parser, pm_arguments_t *arguments, bool accepts_forwarding, pm_token_type_t terminator, uint16_t depth) {
13476 pm_binding_power_t binding_power = pm_binding_powers[parser->current.type].left;
13477
13478 // First we need to check if the next token is one that could be the start
13479 // of an argument. If it's not, then we can just return.
13480 if (
13481 match2(parser, terminator, PM_TOKEN_EOF) ||
13482 (binding_power != PM_BINDING_POWER_UNSET && binding_power < PM_BINDING_POWER_RANGE) ||
13483 context_terminator(parser->current_context->context, &parser->current)
13484 ) {
13485 return;
13486 }
13487
13488 bool parsed_first_argument = false;
13489 bool parsed_bare_hash = false;
13490 bool parsed_block_argument = false;
13491 bool parsed_forwarding_arguments = false;
13492
13493 while (!match1(parser, PM_TOKEN_EOF)) {
13494 if (parsed_forwarding_arguments) {
13495 pm_parser_err_current(parser, PM_ERR_ARGUMENT_AFTER_FORWARDING_ELLIPSES);
13496 }
13497
13498 pm_node_t *argument = NULL;
13499
13500 switch (parser->current.type) {
13501 case PM_TOKEN_USTAR_STAR:
13502 case PM_TOKEN_LABEL: {
13503 if (parsed_bare_hash) {
13504 pm_parser_err_current(parser, PM_ERR_ARGUMENT_BARE_HASH);
13505 }
13506
13507 pm_keyword_hash_node_t *hash = pm_keyword_hash_node_create(parser);
13508 argument = UP(hash);
13509
13510 pm_static_literals_t hash_keys = { 0 };
13511 bool contains_keyword_splat = parse_assocs(parser, &hash_keys, UP(hash), (uint16_t) (depth + 1));
13512
13513 parse_arguments_append(parser, arguments, argument);
13514
13515 pm_node_flags_t flags = PM_ARGUMENTS_NODE_FLAGS_CONTAINS_KEYWORDS;
13516 if (contains_keyword_splat) flags |= PM_ARGUMENTS_NODE_FLAGS_CONTAINS_KEYWORD_SPLAT;
13517 pm_node_flag_set(UP(arguments->arguments), flags);
13518
13519 pm_static_literals_free(&hash_keys);
13520 parsed_bare_hash = true;
13521
13522 break;
13523 }
13524 case PM_TOKEN_UAMPERSAND: {
13525 parser_lex(parser);
13526 pm_token_t operator = parser->previous;
13527 pm_node_t *expression = NULL;
13528
13529 if (token_begins_expression_p(parser->current.type)) {
13530 expression = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_EXPECT_ARGUMENT, (uint16_t) (depth + 1));
13531 } else {
13532 pm_parser_scope_forwarding_block_check(parser, &operator);
13533 }
13534
13535 argument = UP(pm_block_argument_node_create(parser, &operator, expression));
13536 if (parsed_block_argument) {
13537 parse_arguments_append(parser, arguments, argument);
13538 } else {
13539 arguments->block = argument;
13540 }
13541
13542 if (match1(parser, PM_TOKEN_COMMA)) {
13543 pm_parser_err_current(parser, PM_ERR_ARGUMENT_AFTER_BLOCK);
13544 }
13545
13546 parsed_block_argument = true;
13547 break;
13548 }
13549 case PM_TOKEN_USTAR: {
13550 parser_lex(parser);
13551 pm_token_t operator = parser->previous;
13552
13553 if (match4(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_TOKEN_COMMA, PM_TOKEN_SEMICOLON, PM_TOKEN_BRACKET_RIGHT)) {
13554 pm_parser_scope_forwarding_positionals_check(parser, &operator);
13555 argument = UP(pm_splat_node_create(parser, &operator, NULL));
13556 if (parsed_bare_hash) {
13557 pm_parser_err_previous(parser, PM_ERR_ARGUMENT_SPLAT_AFTER_ASSOC_SPLAT);
13558 }
13559 } else {
13560 pm_node_t *expression = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_SPLAT, (uint16_t) (depth + 1));
13561
13562 if (parsed_bare_hash) {
13563 pm_parser_err(parser, operator.start, expression->location.end, PM_ERR_ARGUMENT_SPLAT_AFTER_ASSOC_SPLAT);
13564 }
13565
13566 argument = UP(pm_splat_node_create(parser, &operator, expression));
13567 }
13568
13569 parse_arguments_append(parser, arguments, argument);
13570 break;
13571 }
13572 case PM_TOKEN_UDOT_DOT_DOT: {
13573 if (accepts_forwarding) {
13574 parser_lex(parser);
13575
13576 if (token_begins_expression_p(parser->current.type)) {
13577 // If the token begins an expression then this ... was
13578 // not actually argument forwarding but was instead a
13579 // range.
13580 pm_token_t operator = parser->previous;
13581 pm_node_t *right = parse_expression(parser, PM_BINDING_POWER_RANGE, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
13582
13583 // If we parse a range, we need to validate that we
13584 // didn't accidentally violate the nonassoc rules of the
13585 // ... operator.
13586 if (PM_NODE_TYPE_P(right, PM_RANGE_NODE)) {
13587 pm_range_node_t *range = (pm_range_node_t *) right;
13588 pm_parser_err(parser, range->operator_loc.start, range->operator_loc.end, PM_ERR_UNEXPECTED_RANGE_OPERATOR);
13589 }
13590
13591 argument = UP(pm_range_node_create(parser, NULL, &operator, right));
13592 } else {
13593 pm_parser_scope_forwarding_all_check(parser, &parser->previous);
13594 if (parsed_first_argument && terminator == PM_TOKEN_EOF) {
13595 pm_parser_err_previous(parser, PM_ERR_ARGUMENT_FORWARDING_UNBOUND);
13596 }
13597
13598 argument = UP(pm_forwarding_arguments_node_create(parser, &parser->previous));
13599 parse_arguments_append(parser, arguments, argument);
13600 pm_node_flag_set(UP(arguments->arguments), PM_ARGUMENTS_NODE_FLAGS_CONTAINS_FORWARDING);
13601 arguments->has_forwarding = true;
13602 parsed_forwarding_arguments = true;
13603 break;
13604 }
13605 }
13606 }
13607 PRISM_FALLTHROUGH
13608 default: {
13609 if (argument == NULL) {
13610 argument = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, !parsed_first_argument, true, PM_ERR_EXPECT_ARGUMENT, (uint16_t) (depth + 1));
13611 }
13612
13613 bool contains_keywords = false;
13614 bool contains_keyword_splat = false;
13615
13616 if (argument_allowed_for_bare_hash(parser, argument)){
13617 if (parsed_bare_hash) {
13618 pm_parser_err_previous(parser, PM_ERR_ARGUMENT_BARE_HASH);
13619 }
13620
13621 pm_token_t operator;
13622 if (parser->previous.type == PM_TOKEN_EQUAL_GREATER) {
13623 operator = parser->previous;
13624 } else {
13625 operator = not_provided(parser);
13626 }
13627
13628 pm_keyword_hash_node_t *bare_hash = pm_keyword_hash_node_create(parser);
13629 contains_keywords = true;
13630
13631 // Create the set of static literals for this hash.
13632 pm_static_literals_t hash_keys = { 0 };
13633 pm_hash_key_static_literals_add(parser, &hash_keys, argument);
13634
13635 // Finish parsing the one we are part way through.
13636 pm_node_t *value = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_HASH_VALUE, (uint16_t) (depth + 1));
13637 argument = UP(pm_assoc_node_create(parser, argument, &operator, value));
13638
13639 pm_keyword_hash_node_elements_append(bare_hash, argument);
13640 argument = UP(bare_hash);
13641
13642 // Then parse more if we have a comma
13643 if (accept1(parser, PM_TOKEN_COMMA) && (
13644 token_begins_expression_p(parser->current.type) ||
13645 match2(parser, PM_TOKEN_USTAR_STAR, PM_TOKEN_LABEL)
13646 )) {
13647 contains_keyword_splat = parse_assocs(parser, &hash_keys, UP(bare_hash), (uint16_t) (depth + 1));
13648 }
13649
13650 pm_static_literals_free(&hash_keys);
13651 parsed_bare_hash = true;
13652 }
13653
13654 parse_arguments_append(parser, arguments, argument);
13655
13656 pm_node_flags_t flags = 0;
13657 if (contains_keywords) flags |= PM_ARGUMENTS_NODE_FLAGS_CONTAINS_KEYWORDS;
13658 if (contains_keyword_splat) flags |= PM_ARGUMENTS_NODE_FLAGS_CONTAINS_KEYWORD_SPLAT;
13659 pm_node_flag_set(UP(arguments->arguments), flags);
13660
13661 break;
13662 }
13663 }
13664
13665 parsed_first_argument = true;
13666
13667 // If parsing the argument failed, we need to stop parsing arguments.
13668 if (PM_NODE_TYPE_P(argument, PM_MISSING_NODE) || parser->recovering) break;
13669
13670 // If the terminator of these arguments is not EOF, then we have a
13671 // specific token we're looking for. In that case we can accept a
13672 // newline here because it is not functioning as a statement terminator.
13673 bool accepted_newline = false;
13674 if (terminator != PM_TOKEN_EOF) {
13675 accepted_newline = accept1(parser, PM_TOKEN_NEWLINE);
13676 }
13677
13678 if (parser->previous.type == PM_TOKEN_COMMA && parsed_bare_hash) {
13679 // If we previously were on a comma and we just parsed a bare hash,
13680 // then we want to continue parsing arguments. This is because the
13681 // comma was grabbed up by the hash parser.
13682 } else if (accept1(parser, PM_TOKEN_COMMA)) {
13683 // If there was a comma, then we need to check if we also accepted a
13684 // newline. If we did, then this is a syntax error.
13685 if (accepted_newline) {
13686 pm_parser_err_previous(parser, PM_ERR_INVALID_COMMA);
13687 }
13688
13689 // If this is a command call and an argument takes a block,
13690 // there can be no further arguments. For example,
13691 // `foo(bar 1 do end, 2)` should be rejected.
13692 if (PM_NODE_TYPE_P(argument, PM_CALL_NODE)) {
13693 pm_call_node_t *call = (pm_call_node_t *) argument;
13694 if (call->opening_loc.start == NULL && call->arguments != NULL && call->block != NULL) {
13695 pm_parser_err_previous(parser, PM_ERR_INVALID_COMMA);
13696 break;
13697 }
13698 }
13699 } else {
13700 // If there is no comma at the end of the argument list then we're
13701 // done parsing arguments and can break out of this loop.
13702 break;
13703 }
13704
13705 // If we hit the terminator, then that means we have a trailing comma so
13706 // we can accept that output as well.
13707 if (match1(parser, terminator)) break;
13708 }
13709 }
13710
13711 /**
13712 * Required parameters on method, block, and lambda declarations can be
13713 * destructured using parentheses. This looks like:
13714 *
13715 * def foo((bar, baz))
13716 * end
13717 *
13718 *
13719 * It can recurse infinitely down, and splats are allowed to group arguments.
13720 */
13721 static pm_multi_target_node_t *
13722 parse_required_destructured_parameter(pm_parser_t *parser) {
13723 expect1(parser, PM_TOKEN_PARENTHESIS_LEFT, PM_ERR_EXPECT_LPAREN_REQ_PARAMETER);
13724
13725 pm_multi_target_node_t *node = pm_multi_target_node_create(parser);
13726 pm_multi_target_node_opening_set(node, &parser->previous);
13727
13728 do {
13729 pm_node_t *param;
13730
13731 // If we get here then we have a trailing comma, which isn't allowed in
13732 // the grammar. In other places, multi targets _do_ allow trailing
13733 // commas, so here we'll assume this is a mistake of the user not
13734 // knowing it's not allowed here.
13735 if (node->lefts.size > 0 && match1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
13736 param = UP(pm_implicit_rest_node_create(parser, &parser->previous));
13737 pm_multi_target_node_targets_append(parser, node, param);
13738 pm_parser_err_current(parser, PM_ERR_PARAMETER_WILD_LOOSE_COMMA);
13739 break;
13740 }
13741
13742 if (match1(parser, PM_TOKEN_PARENTHESIS_LEFT)) {
13743 param = UP(parse_required_destructured_parameter(parser));
13744 } else if (accept1(parser, PM_TOKEN_USTAR)) {
13745 pm_token_t star = parser->previous;
13746 pm_node_t *value = NULL;
13747
13748 if (accept1(parser, PM_TOKEN_IDENTIFIER)) {
13749 pm_token_t name = parser->previous;
13750 value = UP(pm_required_parameter_node_create(parser, &name));
13751 if (pm_parser_parameter_name_check(parser, &name)) {
13752 pm_node_flag_set_repeated_parameter(value);
13753 }
13754 pm_parser_local_add_token(parser, &name, 1);
13755 }
13756
13757 param = UP(pm_splat_node_create(parser, &star, value));
13758 } else {
13759 expect1(parser, PM_TOKEN_IDENTIFIER, PM_ERR_EXPECT_IDENT_REQ_PARAMETER);
13760 pm_token_t name = parser->previous;
13761
13762 param = UP(pm_required_parameter_node_create(parser, &name));
13763 if (pm_parser_parameter_name_check(parser, &name)) {
13764 pm_node_flag_set_repeated_parameter(param);
13765 }
13766 pm_parser_local_add_token(parser, &name, 1);
13767 }
13768
13769 pm_multi_target_node_targets_append(parser, node, param);
13770 } while (accept1(parser, PM_TOKEN_COMMA));
13771
13772 accept1(parser, PM_TOKEN_NEWLINE);
13773 expect1(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_EXPECT_RPAREN_REQ_PARAMETER);
13774 pm_multi_target_node_closing_set(node, &parser->previous);
13775
13776 return node;
13777 }
13778
13779 /**
13780 * This represents the different order states we can be in when parsing
13781 * method parameters.
13782 */
13783 typedef enum {
13784 PM_PARAMETERS_NO_CHANGE = 0, // Extra state for tokens that should not change the state
13785 PM_PARAMETERS_ORDER_NOTHING_AFTER = 1,
13786 PM_PARAMETERS_ORDER_KEYWORDS_REST,
13787 PM_PARAMETERS_ORDER_KEYWORDS,
13788 PM_PARAMETERS_ORDER_REST,
13789 PM_PARAMETERS_ORDER_AFTER_OPTIONAL,
13790 PM_PARAMETERS_ORDER_OPTIONAL,
13791 PM_PARAMETERS_ORDER_NAMED,
13792 PM_PARAMETERS_ORDER_NONE,
13793 } pm_parameters_order_t;
13794
13795 /**
13796 * This matches parameters tokens with parameters state.
13797 */
13798 static pm_parameters_order_t parameters_ordering[PM_TOKEN_MAXIMUM] = {
13799 [0] = PM_PARAMETERS_NO_CHANGE,
13800 [PM_TOKEN_UAMPERSAND] = PM_PARAMETERS_ORDER_NOTHING_AFTER,
13801 [PM_TOKEN_AMPERSAND] = PM_PARAMETERS_ORDER_NOTHING_AFTER,
13802 [PM_TOKEN_UDOT_DOT_DOT] = PM_PARAMETERS_ORDER_NOTHING_AFTER,
13803 [PM_TOKEN_IDENTIFIER] = PM_PARAMETERS_ORDER_NAMED,
13804 [PM_TOKEN_PARENTHESIS_LEFT] = PM_PARAMETERS_ORDER_NAMED,
13805 [PM_TOKEN_EQUAL] = PM_PARAMETERS_ORDER_OPTIONAL,
13806 [PM_TOKEN_LABEL] = PM_PARAMETERS_ORDER_KEYWORDS,
13807 [PM_TOKEN_USTAR] = PM_PARAMETERS_ORDER_AFTER_OPTIONAL,
13808 [PM_TOKEN_STAR] = PM_PARAMETERS_ORDER_AFTER_OPTIONAL,
13809 [PM_TOKEN_USTAR_STAR] = PM_PARAMETERS_ORDER_KEYWORDS_REST,
13810 [PM_TOKEN_STAR_STAR] = PM_PARAMETERS_ORDER_KEYWORDS_REST
13811 };
13812
13813 /**
13814 * Check if current parameter follows valid parameters ordering. If not it adds
13815 * an error to the list without stopping the parsing, otherwise sets the
13816 * parameters state to the one corresponding to the current parameter.
13817 *
13818 * It returns true if it was successful, and false otherwise.
13819 */
13820 static bool
13821 update_parameter_state(pm_parser_t *parser, pm_token_t *token, pm_parameters_order_t *current) {
13822 pm_parameters_order_t state = parameters_ordering[token->type];
13823 if (state == PM_PARAMETERS_NO_CHANGE) return true;
13824
13825 // If we see another ordered argument after a optional argument
13826 // we only continue parsing ordered arguments until we stop seeing ordered arguments.
13827 if (*current == PM_PARAMETERS_ORDER_OPTIONAL && state == PM_PARAMETERS_ORDER_NAMED) {
13828 *current = PM_PARAMETERS_ORDER_AFTER_OPTIONAL;
13829 return true;
13830 } else if (*current == PM_PARAMETERS_ORDER_AFTER_OPTIONAL && state == PM_PARAMETERS_ORDER_NAMED) {
13831 return true;
13832 }
13833
13834 if (token->type == PM_TOKEN_USTAR && *current == PM_PARAMETERS_ORDER_AFTER_OPTIONAL) {
13835 pm_parser_err_token(parser, token, PM_ERR_PARAMETER_STAR);
13836 return false;
13837 } else if (token->type == PM_TOKEN_UDOT_DOT_DOT && (*current >= PM_PARAMETERS_ORDER_KEYWORDS_REST && *current <= PM_PARAMETERS_ORDER_AFTER_OPTIONAL)) {
13838 pm_parser_err_token(parser, token, *current == PM_PARAMETERS_ORDER_AFTER_OPTIONAL ? PM_ERR_PARAMETER_FORWARDING_AFTER_REST : PM_ERR_PARAMETER_ORDER);
13839 return false;
13840 } else if (*current == PM_PARAMETERS_ORDER_NOTHING_AFTER || state > *current) {
13841 // We know what transition we failed on, so we can provide a better error here.
13842 pm_parser_err_token(parser, token, PM_ERR_PARAMETER_ORDER);
13843 return false;
13844 }
13845
13846 if (state < *current) *current = state;
13847 return true;
13848 }
13849
13850 /**
13851 * Parse a list of parameters on a method definition.
13852 */
13853 static pm_parameters_node_t *
13854 parse_parameters(
13855 pm_parser_t *parser,
13856 pm_binding_power_t binding_power,
13857 bool uses_parentheses,
13858 bool allows_trailing_comma,
13859 bool allows_forwarding_parameters,
13860 bool accepts_blocks_in_defaults,
13861 bool in_block,
13862 uint16_t depth
13863 ) {
13864 pm_do_loop_stack_push(parser, false);
13865
13866 pm_parameters_node_t *params = pm_parameters_node_create(parser);
13867 pm_parameters_order_t order = PM_PARAMETERS_ORDER_NONE;
13868
13869 while (true) {
13870 bool parsing = true;
13871
13872 switch (parser->current.type) {
13873 case PM_TOKEN_PARENTHESIS_LEFT: {
13874 update_parameter_state(parser, &parser->current, &order);
13875 pm_node_t *param = UP(parse_required_destructured_parameter(parser));
13876
13877 if (order > PM_PARAMETERS_ORDER_AFTER_OPTIONAL) {
13878 pm_parameters_node_requireds_append(params, param);
13879 } else {
13880 pm_parameters_node_posts_append(params, param);
13881 }
13882 break;
13883 }
13884 case PM_TOKEN_UAMPERSAND:
13885 case PM_TOKEN_AMPERSAND: {
13886 update_parameter_state(parser, &parser->current, &order);
13887 parser_lex(parser);
13888
13889 pm_token_t operator = parser->previous;
13890 pm_token_t name;
13891
13892 bool repeated = false;
13893 if (accept1(parser, PM_TOKEN_IDENTIFIER)) {
13894 name = parser->previous;
13895 repeated = pm_parser_parameter_name_check(parser, &name);
13896 pm_parser_local_add_token(parser, &name, 1);
13897 } else {
13898 name = not_provided(parser);
13899 parser->current_scope->parameters |= PM_SCOPE_PARAMETERS_FORWARDING_BLOCK;
13900 }
13901
13902 pm_block_parameter_node_t *param = pm_block_parameter_node_create(parser, &name, &operator);
13903 if (repeated) {
13904 pm_node_flag_set_repeated_parameter(UP(param));
13905 }
13906 if (params->block == NULL) {
13907 pm_parameters_node_block_set(params, param);
13908 } else {
13909 pm_parser_err_node(parser, UP(param), PM_ERR_PARAMETER_BLOCK_MULTI);
13910 pm_parameters_node_posts_append(params, UP(param));
13911 }
13912
13913 break;
13914 }
13915 case PM_TOKEN_UDOT_DOT_DOT: {
13916 if (!allows_forwarding_parameters) {
13917 pm_parser_err_current(parser, PM_ERR_ARGUMENT_NO_FORWARDING_ELLIPSES);
13918 }
13919
13920 bool succeeded = update_parameter_state(parser, &parser->current, &order);
13921 parser_lex(parser);
13922
13923 parser->current_scope->parameters |= PM_SCOPE_PARAMETERS_FORWARDING_ALL;
13924 pm_forwarding_parameter_node_t *param = pm_forwarding_parameter_node_create(parser, &parser->previous);
13925
13926 if (params->keyword_rest != NULL) {
13927 // If we already have a keyword rest parameter, then we replace it with the
13928 // forwarding parameter and move the keyword rest parameter to the posts list.
13929 pm_node_t *keyword_rest = params->keyword_rest;
13930 pm_parameters_node_posts_append(params, keyword_rest);
13931 if (succeeded) pm_parser_err_previous(parser, PM_ERR_PARAMETER_UNEXPECTED_FWD);
13932 params->keyword_rest = NULL;
13933 }
13934
13935 pm_parameters_node_keyword_rest_set(params, UP(param));
13936 break;
13937 }
13938 case PM_TOKEN_CLASS_VARIABLE:
13939 case PM_TOKEN_IDENTIFIER:
13940 case PM_TOKEN_CONSTANT:
13941 case PM_TOKEN_INSTANCE_VARIABLE:
13942 case PM_TOKEN_GLOBAL_VARIABLE:
13943 case PM_TOKEN_METHOD_NAME: {
13944 parser_lex(parser);
13945 switch (parser->previous.type) {
13946 case PM_TOKEN_CONSTANT:
13947 pm_parser_err_previous(parser, PM_ERR_ARGUMENT_FORMAL_CONSTANT);
13948 break;
13949 case PM_TOKEN_INSTANCE_VARIABLE:
13950 pm_parser_err_previous(parser, PM_ERR_ARGUMENT_FORMAL_IVAR);
13951 break;
13952 case PM_TOKEN_GLOBAL_VARIABLE:
13953 pm_parser_err_previous(parser, PM_ERR_ARGUMENT_FORMAL_GLOBAL);
13954 break;
13955 case PM_TOKEN_CLASS_VARIABLE:
13956 pm_parser_err_previous(parser, PM_ERR_ARGUMENT_FORMAL_CLASS);
13957 break;
13958 case PM_TOKEN_METHOD_NAME:
13959 pm_parser_err_previous(parser, PM_ERR_PARAMETER_METHOD_NAME);
13960 break;
13961 default: break;
13962 }
13963
13964 if (parser->current.type == PM_TOKEN_EQUAL) {
13965 update_parameter_state(parser, &parser->current, &order);
13966 } else {
13967 update_parameter_state(parser, &parser->previous, &order);
13968 }
13969
13970 pm_token_t name = parser->previous;
13971 bool repeated = pm_parser_parameter_name_check(parser, &name);
13972 pm_parser_local_add_token(parser, &name, 1);
13973
13974 if (match1(parser, PM_TOKEN_EQUAL)) {
13975 pm_token_t operator = parser->current;
13976 context_push(parser, PM_CONTEXT_DEFAULT_PARAMS);
13977 parser_lex(parser);
13978
13979 pm_constant_id_t name_id = pm_parser_constant_id_token(parser, &name);
13980 uint32_t reads = parser->version <= PM_OPTIONS_VERSION_CRUBY_3_3 ? pm_locals_reads(&parser->current_scope->locals, name_id) : 0;
13981
13982 if (accepts_blocks_in_defaults) pm_accepts_block_stack_push(parser, true);
13983 pm_node_t *value = parse_value_expression(parser, binding_power, false, false, PM_ERR_PARAMETER_NO_DEFAULT, (uint16_t) (depth + 1));
13984 if (accepts_blocks_in_defaults) pm_accepts_block_stack_pop(parser);
13985
13986 pm_optional_parameter_node_t *param = pm_optional_parameter_node_create(parser, &name, &operator, value);
13987
13988 if (repeated) {
13989 pm_node_flag_set_repeated_parameter(UP(param));
13990 }
13991 pm_parameters_node_optionals_append(params, param);
13992
13993 // If the value of the parameter increased the number of
13994 // reads of that parameter, then we need to warn that we
13995 // have a circular definition.
13996 if ((parser->version <= PM_OPTIONS_VERSION_CRUBY_3_3) && (pm_locals_reads(&parser->current_scope->locals, name_id) != reads)) {
13997 PM_PARSER_ERR_TOKEN_FORMAT_CONTENT(parser, name, PM_ERR_PARAMETER_CIRCULAR);
13998 }
13999
14000 context_pop(parser);
14001
14002 // If parsing the value of the parameter resulted in error recovery,
14003 // then we can put a missing node in its place and stop parsing the
14004 // parameters entirely now.
14005 if (parser->recovering) {
14006 parsing = false;
14007 break;
14008 }
14009 } else if (order > PM_PARAMETERS_ORDER_AFTER_OPTIONAL) {
14010 pm_required_parameter_node_t *param = pm_required_parameter_node_create(parser, &name);
14011 if (repeated) {
14012 pm_node_flag_set_repeated_parameter(UP(param));
14013 }
14014 pm_parameters_node_requireds_append(params, UP(param));
14015 } else {
14016 pm_required_parameter_node_t *param = pm_required_parameter_node_create(parser, &name);
14017 if (repeated) {
14018 pm_node_flag_set_repeated_parameter(UP(param));
14019 }
14020 pm_parameters_node_posts_append(params, UP(param));
14021 }
14022
14023 break;
14024 }
14025 case PM_TOKEN_LABEL: {
14026 if (!uses_parentheses && !in_block) parser->in_keyword_arg = true;
14027 update_parameter_state(parser, &parser->current, &order);
14028
14029 context_push(parser, PM_CONTEXT_DEFAULT_PARAMS);
14030 parser_lex(parser);
14031
14032 pm_token_t name = parser->previous;
14033 pm_token_t local = name;
14034 local.end -= 1;
14035
14036 if (parser->encoding_changed ? parser->encoding->isupper_char(local.start, local.end - local.start) : pm_encoding_utf_8_isupper_char(local.start, local.end - local.start)) {
14037 pm_parser_err(parser, local.start, local.end, PM_ERR_ARGUMENT_FORMAL_CONSTANT);
14038 } else if (local.end[-1] == '!' || local.end[-1] == '?') {
14039 PM_PARSER_ERR_TOKEN_FORMAT_CONTENT(parser, local, PM_ERR_INVALID_LOCAL_VARIABLE_WRITE);
14040 }
14041
14042 bool repeated = pm_parser_parameter_name_check(parser, &local);
14043 pm_parser_local_add_token(parser, &local, 1);
14044
14045 switch (parser->current.type) {
14046 case PM_TOKEN_COMMA:
14047 case PM_TOKEN_PARENTHESIS_RIGHT:
14048 case PM_TOKEN_PIPE: {
14049 context_pop(parser);
14050
14051 pm_node_t *param = UP(pm_required_keyword_parameter_node_create(parser, &name));
14052 if (repeated) {
14053 pm_node_flag_set_repeated_parameter(param);
14054 }
14055
14056 pm_parameters_node_keywords_append(params, param);
14057 break;
14058 }
14059 case PM_TOKEN_SEMICOLON:
14060 case PM_TOKEN_NEWLINE: {
14061 context_pop(parser);
14062
14063 if (uses_parentheses) {
14064 parsing = false;
14065 break;
14066 }
14067
14068 pm_node_t *param = UP(pm_required_keyword_parameter_node_create(parser, &name));
14069 if (repeated) {
14070 pm_node_flag_set_repeated_parameter(param);
14071 }
14072
14073 pm_parameters_node_keywords_append(params, param);
14074 break;
14075 }
14076 default: {
14077 pm_node_t *param;
14078
14079 if (token_begins_expression_p(parser->current.type)) {
14080 pm_constant_id_t name_id = pm_parser_constant_id_token(parser, &local);
14081 uint32_t reads = parser->version <= PM_OPTIONS_VERSION_CRUBY_3_3 ? pm_locals_reads(&parser->current_scope->locals, name_id) : 0;
14082
14083 if (accepts_blocks_in_defaults) pm_accepts_block_stack_push(parser, true);
14084 pm_node_t *value = parse_value_expression(parser, binding_power, false, false, PM_ERR_PARAMETER_NO_DEFAULT_KW, (uint16_t) (depth + 1));
14085 if (accepts_blocks_in_defaults) pm_accepts_block_stack_pop(parser);
14086
14087 if (parser->version <= PM_OPTIONS_VERSION_CRUBY_3_3 && (pm_locals_reads(&parser->current_scope->locals, name_id) != reads)) {
14088 PM_PARSER_ERR_TOKEN_FORMAT_CONTENT(parser, local, PM_ERR_PARAMETER_CIRCULAR);
14089 }
14090
14091 param = UP(pm_optional_keyword_parameter_node_create(parser, &name, value));
14092 }
14093 else {
14094 param = UP(pm_required_keyword_parameter_node_create(parser, &name));
14095 }
14096
14097 if (repeated) {
14098 pm_node_flag_set_repeated_parameter(param);
14099 }
14100
14101 context_pop(parser);
14102 pm_parameters_node_keywords_append(params, param);
14103
14104 // If parsing the value of the parameter resulted in error recovery,
14105 // then we can put a missing node in its place and stop parsing the
14106 // parameters entirely now.
14107 if (parser->recovering) {
14108 parsing = false;
14109 break;
14110 }
14111 }
14112 }
14113
14114 parser->in_keyword_arg = false;
14115 break;
14116 }
14117 case PM_TOKEN_USTAR:
14118 case PM_TOKEN_STAR: {
14119 update_parameter_state(parser, &parser->current, &order);
14120 parser_lex(parser);
14121
14122 pm_token_t operator = parser->previous;
14123 pm_token_t name;
14124 bool repeated = false;
14125
14126 if (accept1(parser, PM_TOKEN_IDENTIFIER)) {
14127 name = parser->previous;
14128 repeated = pm_parser_parameter_name_check(parser, &name);
14129 pm_parser_local_add_token(parser, &name, 1);
14130 } else {
14131 name = not_provided(parser);
14132 parser->current_scope->parameters |= PM_SCOPE_PARAMETERS_FORWARDING_POSITIONALS;
14133 }
14134
14135 pm_node_t *param = UP(pm_rest_parameter_node_create(parser, &operator, &name));
14136 if (repeated) {
14137 pm_node_flag_set_repeated_parameter(param);
14138 }
14139
14140 if (params->rest == NULL) {
14141 pm_parameters_node_rest_set(params, param);
14142 } else {
14143 pm_parser_err_node(parser, param, PM_ERR_PARAMETER_SPLAT_MULTI);
14144 pm_parameters_node_posts_append(params, param);
14145 }
14146
14147 break;
14148 }
14149 case PM_TOKEN_STAR_STAR:
14150 case PM_TOKEN_USTAR_STAR: {
14151 pm_parameters_order_t previous_order = order;
14152 update_parameter_state(parser, &parser->current, &order);
14153 parser_lex(parser);
14154
14155 pm_token_t operator = parser->previous;
14156 pm_node_t *param;
14157
14158 if (accept1(parser, PM_TOKEN_KEYWORD_NIL)) {
14159 if (previous_order <= PM_PARAMETERS_ORDER_KEYWORDS) {
14160 pm_parser_err_previous(parser, PM_ERR_PARAMETER_UNEXPECTED_NO_KW);
14161 }
14162
14163 param = UP(pm_no_keywords_parameter_node_create(parser, &operator, &parser->previous));
14164 } else {
14165 pm_token_t name;
14166
14167 bool repeated = false;
14168 if (accept1(parser, PM_TOKEN_IDENTIFIER)) {
14169 name = parser->previous;
14170 repeated = pm_parser_parameter_name_check(parser, &name);
14171 pm_parser_local_add_token(parser, &name, 1);
14172 } else {
14173 name = not_provided(parser);
14174 parser->current_scope->parameters |= PM_SCOPE_PARAMETERS_FORWARDING_KEYWORDS;
14175 }
14176
14177 param = UP(pm_keyword_rest_parameter_node_create(parser, &operator, &name));
14178 if (repeated) {
14179 pm_node_flag_set_repeated_parameter(param);
14180 }
14181 }
14182
14183 if (params->keyword_rest == NULL) {
14184 pm_parameters_node_keyword_rest_set(params, param);
14185 } else {
14186 pm_parser_err_node(parser, param, PM_ERR_PARAMETER_ASSOC_SPLAT_MULTI);
14187 pm_parameters_node_posts_append(params, param);
14188 }
14189
14190 break;
14191 }
14192 default:
14193 if (parser->previous.type == PM_TOKEN_COMMA) {
14194 if (allows_trailing_comma && order >= PM_PARAMETERS_ORDER_NAMED) {
14195 // If we get here, then we have a trailing comma in a
14196 // block parameter list.
14197 pm_node_t *param = UP(pm_implicit_rest_node_create(parser, &parser->previous));
14198
14199 if (params->rest == NULL) {
14200 pm_parameters_node_rest_set(params, param);
14201 } else {
14202 pm_parser_err_node(parser, UP(param), PM_ERR_PARAMETER_SPLAT_MULTI);
14203 pm_parameters_node_posts_append(params, UP(param));
14204 }
14205 } else {
14206 pm_parser_err_previous(parser, PM_ERR_PARAMETER_WILD_LOOSE_COMMA);
14207 }
14208 }
14209
14210 parsing = false;
14211 break;
14212 }
14213
14214 // If we hit some kind of issue while parsing the parameter, this would
14215 // have been set to false. In that case, we need to break out of the
14216 // loop.
14217 if (!parsing) break;
14218
14219 bool accepted_newline = false;
14220 if (uses_parentheses) {
14221 accepted_newline = accept1(parser, PM_TOKEN_NEWLINE);
14222 }
14223
14224 if (accept1(parser, PM_TOKEN_COMMA)) {
14225 // If there was a comma, but we also accepted a newline, then this
14226 // is a syntax error.
14227 if (accepted_newline) {
14228 pm_parser_err_previous(parser, PM_ERR_INVALID_COMMA);
14229 }
14230 } else {
14231 // If there was no comma, then we're done parsing parameters.
14232 break;
14233 }
14234 }
14235
14236 pm_do_loop_stack_pop(parser);
14237
14238 // If we don't have any parameters, return `NULL` instead of an empty `ParametersNode`.
14239 if (params->base.location.start == params->base.location.end) {
14240 pm_node_destroy(parser, UP(params));
14241 return NULL;
14242 }
14243
14244 return params;
14245 }
14246
14247 /**
14248 * Accepts a parser returns the index of the last newline in the file that was
14249 * ecorded before the current token within the newline list.
14250 */
14251 static size_t
14252 token_newline_index(const pm_parser_t *parser) {
14253 if (parser->heredoc_end == NULL) {
14254 // This is the common case. In this case we can look at the previously
14255 // recorded newline in the newline list and subtract from the current
14256 // offset.
14257 return parser->newline_list.size - 1;
14258 } else {
14259 // This is unlikely. This is the case that we have already parsed the
14260 // start of a heredoc, so we cannot rely on looking at the previous
14261 // offset of the newline list, and instead must go through the whole
14262 // process of a binary search for the line number.
14263 return (size_t) pm_newline_list_line(&parser->newline_list, parser->current.start, 0);
14264 }
14265 }
14266
14267 /**
14268 * Accepts a parser, a newline index, and a token and returns the column. The
14269 * important piece of this is that it expands tabs out to the next tab stop.
14270 */
14271 static int64_t
14272 token_column(const pm_parser_t *parser, size_t newline_index, const pm_token_t *token, bool break_on_non_space) {
14273 const uint8_t *cursor = parser->start + parser->newline_list.offsets[newline_index];
14274 const uint8_t *end = token->start;
14275
14276 // Skip over the BOM if it is present.
14277 if (
14278 newline_index == 0 &&
14279 parser->start[0] == 0xef &&
14280 parser->start[1] == 0xbb &&
14281 parser->start[2] == 0xbf
14282 ) cursor += 3;
14283
14284 int64_t column = 0;
14285 for (; cursor < end; cursor++) {
14286 switch (*cursor) {
14287 case '\t':
14288 column = ((column / PM_TAB_WHITESPACE_SIZE) + 1) * PM_TAB_WHITESPACE_SIZE;
14289 break;
14290 case ' ':
14291 column++;
14292 break;
14293 default:
14294 column++;
14295 if (break_on_non_space) return -1;
14296 break;
14297 }
14298 }
14299
14300 return column;
14301 }
14302
14303 /**
14304 * Accepts a parser, two newline indices, and pointers to two tokens. This
14305 * function warns if the indentation of the two tokens does not match.
14306 */
14307 static void
14308 parser_warn_indentation_mismatch(pm_parser_t *parser, size_t opening_newline_index, const pm_token_t *opening_token, bool if_after_else, bool allow_indent) {
14309 // If these warnings are disabled (unlikely), then we can just return.
14310 if (!parser->warn_mismatched_indentation) return;
14311
14312 // If the tokens are on the same line, we do not warn.
14313 size_t closing_newline_index = token_newline_index(parser);
14314 if (opening_newline_index == closing_newline_index) return;
14315
14316 // If the opening token has anything other than spaces or tabs before it,
14317 // then we do not warn. This is unless we are matching up an `if`/`end` pair
14318 // and the `if` immediately follows an `else` keyword.
14319 int64_t opening_column = token_column(parser, opening_newline_index, opening_token, !if_after_else);
14320 if (!if_after_else && (opening_column == -1)) return;
14321
14322 // Get a reference to the closing token off the current parser. This assumes
14323 // that the caller has placed this in the correct position.
14324 pm_token_t *closing_token = &parser->current;
14325
14326 // If the tokens are at the same indentation, we do not warn.
14327 int64_t closing_column = token_column(parser, closing_newline_index, closing_token, true);
14328 if ((closing_column == -1) || (opening_column == closing_column)) return;
14329
14330 // If the closing column is greater than the opening column and we are
14331 // allowing indentation, then we do not warn.
14332 if (allow_indent && (closing_column > opening_column)) return;
14333
14334 // Otherwise, add a warning.
14335 PM_PARSER_WARN_FORMAT(
14336 parser,
14337 closing_token->start,
14338 closing_token->end,
14339 PM_WARN_INDENTATION_MISMATCH,
14340 (int) (closing_token->end - closing_token->start),
14341 (const char *) closing_token->start,
14342 (int) (opening_token->end - opening_token->start),
14343 (const char *) opening_token->start,
14344 ((int32_t) opening_newline_index) + parser->start_line
14345 );
14346 }
14347
14348 typedef enum {
14349 PM_RESCUES_BEGIN = 1,
14350 PM_RESCUES_BLOCK,
14351 PM_RESCUES_CLASS,
14352 PM_RESCUES_DEF,
14353 PM_RESCUES_LAMBDA,
14354 PM_RESCUES_MODULE,
14355 PM_RESCUES_SCLASS
14356 } pm_rescues_type_t;
14357
14358 /**
14359 * Parse any number of rescue clauses. This will form a linked list of if
14360 * nodes pointing to each other from the top.
14361 */
14362 static inline void
14363 parse_rescues(pm_parser_t *parser, size_t opening_newline_index, const pm_token_t *opening, pm_begin_node_t *parent_node, pm_rescues_type_t type, uint16_t depth) {
14364 pm_rescue_node_t *current = NULL;
14365
14366 while (match1(parser, PM_TOKEN_KEYWORD_RESCUE)) {
14367 if (opening != NULL) parser_warn_indentation_mismatch(parser, opening_newline_index, opening, false, false);
14368 parser_lex(parser);
14369
14370 pm_rescue_node_t *rescue = pm_rescue_node_create(parser, &parser->previous);
14371
14372 switch (parser->current.type) {
14373 case PM_TOKEN_EQUAL_GREATER: {
14374 // Here we have an immediate => after the rescue keyword, in which case
14375 // we're going to have an empty list of exceptions to rescue (which
14376 // implies StandardError).
14377 parser_lex(parser);
14378 pm_rescue_node_operator_set(rescue, &parser->previous);
14379
14380 pm_node_t *reference = parse_expression(parser, PM_BINDING_POWER_INDEX, false, false, PM_ERR_RESCUE_VARIABLE, (uint16_t) (depth + 1));
14381 reference = parse_target(parser, reference, false, false);
14382
14383 pm_rescue_node_reference_set(rescue, reference);
14384 break;
14385 }
14386 case PM_TOKEN_NEWLINE:
14387 case PM_TOKEN_SEMICOLON:
14388 case PM_TOKEN_KEYWORD_THEN:
14389 // Here we have a terminator for the rescue keyword, in which
14390 // case we're going to just continue on.
14391 break;
14392 default: {
14393 if (token_begins_expression_p(parser->current.type) || match1(parser, PM_TOKEN_USTAR)) {
14394 // Here we have something that could be an exception expression, so
14395 // we'll attempt to parse it here and any others delimited by commas.
14396
14397 do {
14398 pm_node_t *expression = parse_starred_expression(parser, PM_BINDING_POWER_DEFINED, false, PM_ERR_RESCUE_EXPRESSION, (uint16_t) (depth + 1));
14399 pm_rescue_node_exceptions_append(rescue, expression);
14400
14401 // If we hit a newline, then this is the end of the rescue expression. We
14402 // can continue on to parse the statements.
14403 if (match3(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON, PM_TOKEN_KEYWORD_THEN)) break;
14404
14405 // If we hit a `=>` then we're going to parse the exception variable. Once
14406 // we've done that, we'll break out of the loop and parse the statements.
14407 if (accept1(parser, PM_TOKEN_EQUAL_GREATER)) {
14408 pm_rescue_node_operator_set(rescue, &parser->previous);
14409
14410 pm_node_t *reference = parse_expression(parser, PM_BINDING_POWER_INDEX, false, false, PM_ERR_RESCUE_VARIABLE, (uint16_t) (depth + 1));
14411 reference = parse_target(parser, reference, false, false);
14412
14413 pm_rescue_node_reference_set(rescue, reference);
14414 break;
14415 }
14416 } while (accept1(parser, PM_TOKEN_COMMA));
14417 }
14418 }
14419 }
14420
14421 if (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON)) {
14422 if (accept1(parser, PM_TOKEN_KEYWORD_THEN)) {
14423 rescue->then_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(&parser->previous);
14424 }
14425 } else {
14426 expect1(parser, PM_TOKEN_KEYWORD_THEN, PM_ERR_RESCUE_TERM);
14427 rescue->then_keyword_loc = PM_OPTIONAL_LOCATION_TOKEN_VALUE(&parser->previous);
14428 }
14429
14430 if (!match3(parser, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_KEYWORD_ENSURE, PM_TOKEN_KEYWORD_END)) {
14431 pm_accepts_block_stack_push(parser, true);
14432 pm_context_t context;
14433
14434 switch (type) {
14435 case PM_RESCUES_BEGIN: context = PM_CONTEXT_BEGIN_RESCUE; break;
14436 case PM_RESCUES_BLOCK: context = PM_CONTEXT_BLOCK_RESCUE; break;
14437 case PM_RESCUES_CLASS: context = PM_CONTEXT_CLASS_RESCUE; break;
14438 case PM_RESCUES_DEF: context = PM_CONTEXT_DEF_RESCUE; break;
14439 case PM_RESCUES_LAMBDA: context = PM_CONTEXT_LAMBDA_RESCUE; break;
14440 case PM_RESCUES_MODULE: context = PM_CONTEXT_MODULE_RESCUE; break;
14441 case PM_RESCUES_SCLASS: context = PM_CONTEXT_SCLASS_RESCUE; break;
14442 default: assert(false && "unreachable"); context = PM_CONTEXT_BEGIN_RESCUE; break;
14443 }
14444
14445 pm_statements_node_t *statements = parse_statements(parser, context, (uint16_t) (depth + 1));
14446 if (statements != NULL) pm_rescue_node_statements_set(rescue, statements);
14447
14448 pm_accepts_block_stack_pop(parser);
14449 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
14450 }
14451
14452 if (current == NULL) {
14453 pm_begin_node_rescue_clause_set(parent_node, rescue);
14454 } else {
14455 pm_rescue_node_subsequent_set(current, rescue);
14456 }
14457
14458 current = rescue;
14459 }
14460
14461 // The end node locations on rescue nodes will not be set correctly
14462 // since we won't know the end until we've found all subsequent
14463 // clauses. This sets the end location on all rescues once we know it.
14464 if (current != NULL) {
14465 const uint8_t *end_to_set = current->base.location.end;
14466 pm_rescue_node_t *clause = parent_node->rescue_clause;
14467
14468 while (clause != NULL) {
14469 clause->base.location.end = end_to_set;
14470 clause = clause->subsequent;
14471 }
14472 }
14473
14474 pm_token_t else_keyword;
14475 if (match1(parser, PM_TOKEN_KEYWORD_ELSE)) {
14476 if (opening != NULL) parser_warn_indentation_mismatch(parser, opening_newline_index, opening, false, false);
14477 opening_newline_index = token_newline_index(parser);
14478
14479 else_keyword = parser->current;
14480 opening = &else_keyword;
14481
14482 parser_lex(parser);
14483 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
14484
14485 pm_statements_node_t *else_statements = NULL;
14486 if (!match2(parser, PM_TOKEN_KEYWORD_END, PM_TOKEN_KEYWORD_ENSURE)) {
14487 pm_accepts_block_stack_push(parser, true);
14488 pm_context_t context;
14489
14490 switch (type) {
14491 case PM_RESCUES_BEGIN: context = PM_CONTEXT_BEGIN_ELSE; break;
14492 case PM_RESCUES_BLOCK: context = PM_CONTEXT_BLOCK_ELSE; break;
14493 case PM_RESCUES_CLASS: context = PM_CONTEXT_CLASS_ELSE; break;
14494 case PM_RESCUES_DEF: context = PM_CONTEXT_DEF_ELSE; break;
14495 case PM_RESCUES_LAMBDA: context = PM_CONTEXT_LAMBDA_ELSE; break;
14496 case PM_RESCUES_MODULE: context = PM_CONTEXT_MODULE_ELSE; break;
14497 case PM_RESCUES_SCLASS: context = PM_CONTEXT_SCLASS_ELSE; break;
14498 default: assert(false && "unreachable"); context = PM_CONTEXT_BEGIN_ELSE; break;
14499 }
14500
14501 else_statements = parse_statements(parser, context, (uint16_t) (depth + 1));
14502 pm_accepts_block_stack_pop(parser);
14503
14504 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
14505 }
14506
14507 pm_else_node_t *else_clause = pm_else_node_create(parser, &else_keyword, else_statements, &parser->current);
14508 pm_begin_node_else_clause_set(parent_node, else_clause);
14509
14510 // If we don't have a `current` rescue node, then this is a dangling
14511 // else, and it's an error.
14512 if (current == NULL) pm_parser_err_node(parser, UP(else_clause), PM_ERR_BEGIN_LONELY_ELSE);
14513 }
14514
14515 if (match1(parser, PM_TOKEN_KEYWORD_ENSURE)) {
14516 if (opening != NULL) parser_warn_indentation_mismatch(parser, opening_newline_index, opening, false, false);
14517 pm_token_t ensure_keyword = parser->current;
14518
14519 parser_lex(parser);
14520 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
14521
14522 pm_statements_node_t *ensure_statements = NULL;
14523 if (!match1(parser, PM_TOKEN_KEYWORD_END)) {
14524 pm_accepts_block_stack_push(parser, true);
14525 pm_context_t context;
14526
14527 switch (type) {
14528 case PM_RESCUES_BEGIN: context = PM_CONTEXT_BEGIN_ENSURE; break;
14529 case PM_RESCUES_BLOCK: context = PM_CONTEXT_BLOCK_ENSURE; break;
14530 case PM_RESCUES_CLASS: context = PM_CONTEXT_CLASS_ENSURE; break;
14531 case PM_RESCUES_DEF: context = PM_CONTEXT_DEF_ENSURE; break;
14532 case PM_RESCUES_LAMBDA: context = PM_CONTEXT_LAMBDA_ENSURE; break;
14533 case PM_RESCUES_MODULE: context = PM_CONTEXT_MODULE_ENSURE; break;
14534 case PM_RESCUES_SCLASS: context = PM_CONTEXT_SCLASS_ENSURE; break;
14535 default: assert(false && "unreachable"); context = PM_CONTEXT_BEGIN_RESCUE; break;
14536 }
14537
14538 ensure_statements = parse_statements(parser, context, (uint16_t) (depth + 1));
14539 pm_accepts_block_stack_pop(parser);
14540
14541 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
14542 }
14543
14544 pm_ensure_node_t *ensure_clause = pm_ensure_node_create(parser, &ensure_keyword, ensure_statements, &parser->current);
14545 pm_begin_node_ensure_clause_set(parent_node, ensure_clause);
14546 }
14547
14548 if (match1(parser, PM_TOKEN_KEYWORD_END)) {
14549 if (opening != NULL) parser_warn_indentation_mismatch(parser, opening_newline_index, opening, false, false);
14550 pm_begin_node_end_keyword_set(parent_node, &parser->current);
14551 } else {
14552 pm_token_t end_keyword = (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->previous.end, .end = parser->previous.end };
14553 pm_begin_node_end_keyword_set(parent_node, &end_keyword);
14554 }
14555 }
14556
14557 /**
14558 * Parse a set of rescue clauses with an implicit begin (for example when on a
14559 * class, module, def, etc.).
14560 */
14561 static pm_begin_node_t *
14562 parse_rescues_implicit_begin(pm_parser_t *parser, size_t opening_newline_index, const pm_token_t *opening, const uint8_t *start, pm_statements_node_t *statements, pm_rescues_type_t type, uint16_t depth) {
14563 pm_token_t begin_keyword = not_provided(parser);
14564 pm_begin_node_t *node = pm_begin_node_create(parser, &begin_keyword, statements);
14565
14566 parse_rescues(parser, opening_newline_index, opening, node, type, (uint16_t) (depth + 1));
14567 node->base.location.start = start;
14568
14569 return node;
14570 }
14571
14572 /**
14573 * Parse a list of parameters and local on a block definition.
14574 */
14575 static pm_block_parameters_node_t *
14576 parse_block_parameters(
14577 pm_parser_t *parser,
14578 bool allows_trailing_comma,
14579 const pm_token_t *opening,
14580 bool is_lambda_literal,
14581 bool accepts_blocks_in_defaults,
14582 uint16_t depth
14583 ) {
14584 pm_parameters_node_t *parameters = NULL;
14585 if (!match1(parser, PM_TOKEN_SEMICOLON)) {
14586 if (!is_lambda_literal) {
14587 context_push(parser, PM_CONTEXT_BLOCK_PARAMETERS);
14588 }
14589 parameters = parse_parameters(
14590 parser,
14591 is_lambda_literal ? PM_BINDING_POWER_DEFINED : PM_BINDING_POWER_INDEX,
14592 false,
14593 allows_trailing_comma,
14594 false,
14595 accepts_blocks_in_defaults,
14596 true,
14597 (uint16_t) (depth + 1)
14598 );
14599 if (!is_lambda_literal) {
14600 context_pop(parser);
14601 }
14602 }
14603
14604 pm_block_parameters_node_t *block_parameters = pm_block_parameters_node_create(parser, parameters, opening);
14605 if ((opening->type != PM_TOKEN_NOT_PROVIDED)) {
14606 accept1(parser, PM_TOKEN_NEWLINE);
14607
14608 if (accept1(parser, PM_TOKEN_SEMICOLON)) {
14609 do {
14610 switch (parser->current.type) {
14611 case PM_TOKEN_CONSTANT:
14612 pm_parser_err_current(parser, PM_ERR_ARGUMENT_FORMAL_CONSTANT);
14613 parser_lex(parser);
14614 break;
14615 case PM_TOKEN_INSTANCE_VARIABLE:
14616 pm_parser_err_current(parser, PM_ERR_ARGUMENT_FORMAL_IVAR);
14617 parser_lex(parser);
14618 break;
14619 case PM_TOKEN_GLOBAL_VARIABLE:
14620 pm_parser_err_current(parser, PM_ERR_ARGUMENT_FORMAL_GLOBAL);
14621 parser_lex(parser);
14622 break;
14623 case PM_TOKEN_CLASS_VARIABLE:
14624 pm_parser_err_current(parser, PM_ERR_ARGUMENT_FORMAL_CLASS);
14625 parser_lex(parser);
14626 break;
14627 default:
14628 expect1(parser, PM_TOKEN_IDENTIFIER, PM_ERR_BLOCK_PARAM_LOCAL_VARIABLE);
14629 break;
14630 }
14631
14632 bool repeated = pm_parser_parameter_name_check(parser, &parser->previous);
14633 pm_parser_local_add_token(parser, &parser->previous, 1);
14634
14635 pm_block_local_variable_node_t *local = pm_block_local_variable_node_create(parser, &parser->previous);
14636 if (repeated) pm_node_flag_set_repeated_parameter(UP(local));
14637
14638 pm_block_parameters_node_append_local(block_parameters, local);
14639 } while (accept1(parser, PM_TOKEN_COMMA));
14640 }
14641 }
14642
14643 return block_parameters;
14644 }
14645
14646 /**
14647 * Return true if any of the visible scopes to the current context are using
14648 * numbered parameters.
14649 */
14650 static bool
14651 outer_scope_using_numbered_parameters_p(pm_parser_t *parser) {
14652 for (pm_scope_t *scope = parser->current_scope->previous; scope != NULL && !scope->closed; scope = scope->previous) {
14653 if (scope->parameters & PM_SCOPE_PARAMETERS_NUMBERED_FOUND) return true;
14654 }
14655
14656 return false;
14657 }
14658
14659 /**
14660 * These are the names of the various numbered parameters. We have them here so
14661 * that when we insert them into the constant pool we can use a constant string
14662 * and not have to allocate.
14663 */
14664 static const char * const pm_numbered_parameter_names[] = {
14665 "_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9"
14666 };
14667
14668 /**
14669 * Return the node that should be used in the parameters field of a block-like
14670 * (block or lambda) node, depending on the kind of parameters that were
14671 * declared in the current scope.
14672 */
14673 static pm_node_t *
14674 parse_blocklike_parameters(pm_parser_t *parser, pm_node_t *parameters, const pm_token_t *opening, const pm_token_t *closing) {
14675 pm_node_list_t *implicit_parameters = &parser->current_scope->implicit_parameters;
14676
14677 // If we have ordinary parameters, then we will return them as the set of
14678 // parameters.
14679 if (parameters != NULL) {
14680 // If we also have implicit parameters, then this is an error.
14681 if (implicit_parameters->size > 0) {
14682 pm_node_t *node = implicit_parameters->nodes[0];
14683
14684 if (PM_NODE_TYPE_P(node, PM_LOCAL_VARIABLE_READ_NODE)) {
14685 pm_parser_err_node(parser, node, PM_ERR_NUMBERED_PARAMETER_ORDINARY);
14686 } else if (PM_NODE_TYPE_P(node, PM_IT_LOCAL_VARIABLE_READ_NODE)) {
14687 pm_parser_err_node(parser, node, PM_ERR_IT_NOT_ALLOWED_ORDINARY);
14688 } else {
14689 assert(false && "unreachable");
14690 }
14691 }
14692
14693 return parameters;
14694 }
14695
14696 // If we don't have any implicit parameters, then the set of parameters is
14697 // NULL.
14698 if (implicit_parameters->size == 0) {
14699 return NULL;
14700 }
14701
14702 // If we don't have ordinary parameters, then we now must validate our set
14703 // of implicit parameters. We can only have numbered parameters or it, but
14704 // they cannot be mixed.
14705 uint8_t numbered_parameter = 0;
14706 bool it_parameter = false;
14707
14708 for (size_t index = 0; index < implicit_parameters->size; index++) {
14709 pm_node_t *node = implicit_parameters->nodes[index];
14710
14711 if (PM_NODE_TYPE_P(node, PM_LOCAL_VARIABLE_READ_NODE)) {
14712 if (it_parameter) {
14713 pm_parser_err_node(parser, node, PM_ERR_NUMBERED_PARAMETER_IT);
14714 } else if (outer_scope_using_numbered_parameters_p(parser)) {
14715 pm_parser_err_node(parser, node, PM_ERR_NUMBERED_PARAMETER_OUTER_BLOCK);
14716 } else if (parser->current_scope->parameters & PM_SCOPE_PARAMETERS_NUMBERED_INNER) {
14717 pm_parser_err_node(parser, node, PM_ERR_NUMBERED_PARAMETER_INNER_BLOCK);
14718 } else if (pm_token_is_numbered_parameter(node->location.start, node->location.end)) {
14719 numbered_parameter = MAX(numbered_parameter, (uint8_t) (node->location.start[1] - '0'));
14720 } else {
14721 assert(false && "unreachable");
14722 }
14723 } else if (PM_NODE_TYPE_P(node, PM_IT_LOCAL_VARIABLE_READ_NODE)) {
14724 if (numbered_parameter > 0) {
14725 pm_parser_err_node(parser, node, PM_ERR_IT_NOT_ALLOWED_NUMBERED);
14726 } else {
14727 it_parameter = true;
14728 }
14729 }
14730 }
14731
14732 if (numbered_parameter > 0) {
14733 // Go through the parent scopes and mark them as being disallowed from
14734 // using numbered parameters because this inner scope is using them.
14735 for (pm_scope_t *scope = parser->current_scope->previous; scope != NULL && !scope->closed; scope = scope->previous) {
14736 scope->parameters |= PM_SCOPE_PARAMETERS_NUMBERED_INNER;
14737 }
14738
14739 const pm_location_t location = { .start = opening->start, .end = closing->end };
14740 return UP(pm_numbered_parameters_node_create(parser, &location, numbered_parameter));
14741 }
14742
14743 if (it_parameter) {
14744 return UP(pm_it_parameters_node_create(parser, opening, closing));
14745 }
14746
14747 return NULL;
14748 }
14749
14750 /**
14751 * Parse a block.
14752 */
14753 static pm_block_node_t *
14754 parse_block(pm_parser_t *parser, uint16_t depth) {
14755 pm_token_t opening = parser->previous;
14756 accept1(parser, PM_TOKEN_NEWLINE);
14757
14758 pm_accepts_block_stack_push(parser, true);
14759 pm_parser_scope_push(parser, false);
14760
14761 pm_block_parameters_node_t *block_parameters = NULL;
14762
14763 if (accept1(parser, PM_TOKEN_PIPE)) {
14764 pm_token_t block_parameters_opening = parser->previous;
14765 if (match1(parser, PM_TOKEN_PIPE)) {
14766 block_parameters = pm_block_parameters_node_create(parser, NULL, &block_parameters_opening);
14767 parser->command_start = true;
14768 parser_lex(parser);
14769 } else {
14770 block_parameters = parse_block_parameters(parser, true, &block_parameters_opening, false, true, (uint16_t) (depth + 1));
14771 accept1(parser, PM_TOKEN_NEWLINE);
14772 parser->command_start = true;
14773 expect1(parser, PM_TOKEN_PIPE, PM_ERR_BLOCK_PARAM_PIPE_TERM);
14774 }
14775
14776 pm_block_parameters_node_closing_set(block_parameters, &parser->previous);
14777 }
14778
14779 accept1(parser, PM_TOKEN_NEWLINE);
14780 pm_node_t *statements = NULL;
14781
14782 if (opening.type == PM_TOKEN_BRACE_LEFT) {
14783 if (!match1(parser, PM_TOKEN_BRACE_RIGHT)) {
14784 statements = UP(parse_statements(parser, PM_CONTEXT_BLOCK_BRACES, (uint16_t) (depth + 1)));
14785 }
14786
14787 expect1_opening(parser, PM_TOKEN_BRACE_RIGHT, PM_ERR_BLOCK_TERM_BRACE, &opening);
14788 } else {
14789 if (!match1(parser, PM_TOKEN_KEYWORD_END)) {
14790 if (!match3(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_KEYWORD_ENSURE)) {
14791 pm_accepts_block_stack_push(parser, true);
14792 statements = UP(parse_statements(parser, PM_CONTEXT_BLOCK_KEYWORDS, (uint16_t) (depth + 1)));
14793 pm_accepts_block_stack_pop(parser);
14794 }
14795
14796 if (match2(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE)) {
14797 assert(statements == NULL || PM_NODE_TYPE_P(statements, PM_STATEMENTS_NODE));
14798 statements = UP(parse_rescues_implicit_begin(parser, 0, NULL, opening.start, (pm_statements_node_t *) statements, PM_RESCUES_BLOCK, (uint16_t) (depth + 1)));
14799 }
14800 }
14801
14802 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_BLOCK_TERM_END, &opening);
14803 }
14804
14805 pm_constant_id_list_t locals;
14806 pm_locals_order(parser, &parser->current_scope->locals, &locals, pm_parser_scope_toplevel_p(parser));
14807 pm_node_t *parameters = parse_blocklike_parameters(parser, UP(block_parameters), &opening, &parser->previous);
14808
14809 pm_parser_scope_pop(parser);
14810 pm_accepts_block_stack_pop(parser);
14811
14812 return pm_block_node_create(parser, &locals, &opening, parameters, statements, &parser->previous);
14813 }
14814
14815 /**
14816 * Parse a list of arguments and their surrounding parentheses if they are
14817 * present. It returns true if it found any pieces of arguments (parentheses,
14818 * arguments, or blocks).
14819 */
14820 static bool
14821 parse_arguments_list(pm_parser_t *parser, pm_arguments_t *arguments, bool accepts_block, bool accepts_command_call, uint16_t depth) {
14822 bool found = false;
14823
14824 if (accept1(parser, PM_TOKEN_PARENTHESIS_LEFT)) {
14825 found |= true;
14826 arguments->opening_loc = PM_LOCATION_TOKEN_VALUE(&parser->previous);
14827
14828 if (accept1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
14829 arguments->closing_loc = PM_LOCATION_TOKEN_VALUE(&parser->previous);
14830 } else {
14831 pm_accepts_block_stack_push(parser, true);
14832 parse_arguments(parser, arguments, accepts_block, PM_TOKEN_PARENTHESIS_RIGHT, (uint16_t) (depth + 1));
14833
14834 if (!accept1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
14835 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_ARGUMENT_TERM_PAREN, pm_token_type_human(parser->current.type));
14836 parser->previous.start = parser->previous.end;
14837 parser->previous.type = PM_TOKEN_MISSING;
14838 }
14839
14840 pm_accepts_block_stack_pop(parser);
14841 arguments->closing_loc = PM_LOCATION_TOKEN_VALUE(&parser->previous);
14842 }
14843 } else if (accepts_command_call && (token_begins_expression_p(parser->current.type) || match3(parser, PM_TOKEN_USTAR, PM_TOKEN_USTAR_STAR, PM_TOKEN_UAMPERSAND)) && !match1(parser, PM_TOKEN_BRACE_LEFT)) {
14844 found |= true;
14845 pm_accepts_block_stack_push(parser, false);
14846
14847 // If we get here, then the subsequent token cannot be used as an infix
14848 // operator. In this case we assume the subsequent token is part of an
14849 // argument to this method call.
14850 parse_arguments(parser, arguments, accepts_block, PM_TOKEN_EOF, (uint16_t) (depth + 1));
14851
14852 // If we have done with the arguments and still not consumed the comma,
14853 // then we have a trailing comma where we need to check whether it is
14854 // allowed or not.
14855 if (parser->previous.type == PM_TOKEN_COMMA && !match1(parser, PM_TOKEN_SEMICOLON)) {
14856 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->previous, PM_ERR_EXPECT_ARGUMENT, pm_token_type_human(parser->current.type));
14857 }
14858
14859 pm_accepts_block_stack_pop(parser);
14860 }
14861
14862 // If we're at the end of the arguments, we can now check if there is a block
14863 // node that starts with a {. If there is, then we can parse it and add it to
14864 // the arguments.
14865 if (accepts_block) {
14866 pm_block_node_t *block = NULL;
14867
14868 if (accept1(parser, PM_TOKEN_BRACE_LEFT)) {
14869 found |= true;
14870 block = parse_block(parser, (uint16_t) (depth + 1));
14871 pm_arguments_validate_block(parser, arguments, block);
14872 } else if (pm_accepts_block_stack_p(parser) && accept1(parser, PM_TOKEN_KEYWORD_DO)) {
14873 found |= true;
14874 block = parse_block(parser, (uint16_t) (depth + 1));
14875 }
14876
14877 if (block != NULL) {
14878 if (arguments->block == NULL && !arguments->has_forwarding) {
14879 arguments->block = UP(block);
14880 } else {
14881 pm_parser_err_node(parser, UP(block), PM_ERR_ARGUMENT_BLOCK_MULTI);
14882
14883 if (arguments->block != NULL) {
14884 if (arguments->arguments == NULL) {
14885 arguments->arguments = pm_arguments_node_create(parser);
14886 }
14887 pm_arguments_node_arguments_append(arguments->arguments, arguments->block);
14888 }
14889 arguments->block = UP(block);
14890 }
14891 }
14892 }
14893
14894 return found;
14895 }
14896
14897 /**
14898 * Check that the return is allowed in the current context. If it isn't, add an
14899 * error to the parser.
14900 */
14901 static void
14902 parse_return(pm_parser_t *parser, pm_node_t *node) {
14903 bool in_sclass = false;
14904 for (pm_context_node_t *context_node = parser->current_context; context_node != NULL; context_node = context_node->prev) {
14905 switch (context_node->context) {
14906 case PM_CONTEXT_BEGIN_ELSE:
14907 case PM_CONTEXT_BEGIN_ENSURE:
14908 case PM_CONTEXT_BEGIN_RESCUE:
14909 case PM_CONTEXT_BEGIN:
14910 case PM_CONTEXT_CASE_IN:
14911 case PM_CONTEXT_CASE_WHEN:
14912 case PM_CONTEXT_DEFAULT_PARAMS:
14913 case PM_CONTEXT_DEFINED:
14914 case PM_CONTEXT_ELSE:
14915 case PM_CONTEXT_ELSIF:
14916 case PM_CONTEXT_EMBEXPR:
14917 case PM_CONTEXT_FOR_INDEX:
14918 case PM_CONTEXT_FOR:
14919 case PM_CONTEXT_IF:
14920 case PM_CONTEXT_LOOP_PREDICATE:
14921 case PM_CONTEXT_MAIN:
14922 case PM_CONTEXT_MULTI_TARGET:
14923 case PM_CONTEXT_PARENS:
14924 case PM_CONTEXT_POSTEXE:
14925 case PM_CONTEXT_PREDICATE:
14926 case PM_CONTEXT_PREEXE:
14927 case PM_CONTEXT_RESCUE_MODIFIER:
14928 case PM_CONTEXT_TERNARY:
14929 case PM_CONTEXT_UNLESS:
14930 case PM_CONTEXT_UNTIL:
14931 case PM_CONTEXT_WHILE:
14932 // Keep iterating up the lists of contexts, because returns can
14933 // see through these.
14934 continue;
14935 case PM_CONTEXT_SCLASS_ELSE:
14936 case PM_CONTEXT_SCLASS_ENSURE:
14937 case PM_CONTEXT_SCLASS_RESCUE:
14938 case PM_CONTEXT_SCLASS:
14939 in_sclass = true;
14940 continue;
14941 case PM_CONTEXT_CLASS_ELSE:
14942 case PM_CONTEXT_CLASS_ENSURE:
14943 case PM_CONTEXT_CLASS_RESCUE:
14944 case PM_CONTEXT_CLASS:
14945 case PM_CONTEXT_MODULE_ELSE:
14946 case PM_CONTEXT_MODULE_ENSURE:
14947 case PM_CONTEXT_MODULE_RESCUE:
14948 case PM_CONTEXT_MODULE:
14949 // These contexts are invalid for a return.
14950 pm_parser_err_node(parser, node, PM_ERR_RETURN_INVALID);
14951 return;
14952 case PM_CONTEXT_BLOCK_BRACES:
14953 case PM_CONTEXT_BLOCK_ELSE:
14954 case PM_CONTEXT_BLOCK_ENSURE:
14955 case PM_CONTEXT_BLOCK_KEYWORDS:
14956 case PM_CONTEXT_BLOCK_RESCUE:
14957 case PM_CONTEXT_BLOCK_PARAMETERS:
14958 case PM_CONTEXT_DEF_ELSE:
14959 case PM_CONTEXT_DEF_ENSURE:
14960 case PM_CONTEXT_DEF_PARAMS:
14961 case PM_CONTEXT_DEF_RESCUE:
14962 case PM_CONTEXT_DEF:
14963 case PM_CONTEXT_LAMBDA_BRACES:
14964 case PM_CONTEXT_LAMBDA_DO_END:
14965 case PM_CONTEXT_LAMBDA_ELSE:
14966 case PM_CONTEXT_LAMBDA_ENSURE:
14967 case PM_CONTEXT_LAMBDA_RESCUE:
14968 // These contexts are valid for a return, and we should not
14969 // continue to loop.
14970 return;
14971 case PM_CONTEXT_NONE:
14972 // This case should never happen.
14973 assert(false && "unreachable");
14974 break;
14975 }
14976 }
14977 if (in_sclass && parser->version >= PM_OPTIONS_VERSION_CRUBY_3_4) {
14978 pm_parser_err_node(parser, node, PM_ERR_RETURN_INVALID);
14979 }
14980 }
14981
14982 /**
14983 * Check that the block exit (next, break, redo) is allowed in the current
14984 * context. If it isn't, add an error to the parser.
14985 */
14986 static void
14987 parse_block_exit(pm_parser_t *parser, pm_node_t *node) {
14988 for (pm_context_node_t *context_node = parser->current_context; context_node != NULL; context_node = context_node->prev) {
14989 switch (context_node->context) {
14990 case PM_CONTEXT_BLOCK_BRACES:
14991 case PM_CONTEXT_BLOCK_KEYWORDS:
14992 case PM_CONTEXT_BLOCK_ELSE:
14993 case PM_CONTEXT_BLOCK_ENSURE:
14994 case PM_CONTEXT_BLOCK_PARAMETERS:
14995 case PM_CONTEXT_BLOCK_RESCUE:
14996 case PM_CONTEXT_DEFINED:
14997 case PM_CONTEXT_FOR:
14998 case PM_CONTEXT_LAMBDA_BRACES:
14999 case PM_CONTEXT_LAMBDA_DO_END:
15000 case PM_CONTEXT_LAMBDA_ELSE:
15001 case PM_CONTEXT_LAMBDA_ENSURE:
15002 case PM_CONTEXT_LAMBDA_RESCUE:
15003 case PM_CONTEXT_LOOP_PREDICATE:
15004 case PM_CONTEXT_POSTEXE:
15005 case PM_CONTEXT_UNTIL:
15006 case PM_CONTEXT_WHILE:
15007 // These are the good cases. We're allowed to have a block exit
15008 // in these contexts.
15009 return;
15010 case PM_CONTEXT_DEF:
15011 case PM_CONTEXT_DEF_PARAMS:
15012 case PM_CONTEXT_DEF_ELSE:
15013 case PM_CONTEXT_DEF_ENSURE:
15014 case PM_CONTEXT_DEF_RESCUE:
15015 case PM_CONTEXT_MAIN:
15016 case PM_CONTEXT_PREEXE:
15017 case PM_CONTEXT_SCLASS:
15018 case PM_CONTEXT_SCLASS_ELSE:
15019 case PM_CONTEXT_SCLASS_ENSURE:
15020 case PM_CONTEXT_SCLASS_RESCUE:
15021 // These are the bad cases. We're not allowed to have a block
15022 // exit in these contexts.
15023 //
15024 // If we get here, then we're about to mark this block exit
15025 // as invalid. However, it could later _become_ valid if we
15026 // find a trailing while/until on the expression. In this
15027 // case instead of adding the error here, we'll add the
15028 // block exit to the list of exits for the expression, and
15029 // the node parsing will handle validating it instead.
15030 assert(parser->current_block_exits != NULL);
15031 pm_node_list_append(parser->current_block_exits, node);
15032 return;
15033 case PM_CONTEXT_BEGIN_ELSE:
15034 case PM_CONTEXT_BEGIN_ENSURE:
15035 case PM_CONTEXT_BEGIN_RESCUE:
15036 case PM_CONTEXT_BEGIN:
15037 case PM_CONTEXT_CASE_IN:
15038 case PM_CONTEXT_CASE_WHEN:
15039 case PM_CONTEXT_CLASS_ELSE:
15040 case PM_CONTEXT_CLASS_ENSURE:
15041 case PM_CONTEXT_CLASS_RESCUE:
15042 case PM_CONTEXT_CLASS:
15043 case PM_CONTEXT_DEFAULT_PARAMS:
15044 case PM_CONTEXT_ELSE:
15045 case PM_CONTEXT_ELSIF:
15046 case PM_CONTEXT_EMBEXPR:
15047 case PM_CONTEXT_FOR_INDEX:
15048 case PM_CONTEXT_IF:
15049 case PM_CONTEXT_MODULE_ELSE:
15050 case PM_CONTEXT_MODULE_ENSURE:
15051 case PM_CONTEXT_MODULE_RESCUE:
15052 case PM_CONTEXT_MODULE:
15053 case PM_CONTEXT_MULTI_TARGET:
15054 case PM_CONTEXT_PARENS:
15055 case PM_CONTEXT_PREDICATE:
15056 case PM_CONTEXT_RESCUE_MODIFIER:
15057 case PM_CONTEXT_TERNARY:
15058 case PM_CONTEXT_UNLESS:
15059 // In these contexts we should continue walking up the list of
15060 // contexts.
15061 break;
15062 case PM_CONTEXT_NONE:
15063 // This case should never happen.
15064 assert(false && "unreachable");
15065 break;
15066 }
15067 }
15068 }
15069
15070 /**
15071 * When we hit an expression that could contain block exits, we need to stash
15072 * the previous set and create a new one.
15073 */
15074 static pm_node_list_t *
15075 push_block_exits(pm_parser_t *parser, pm_node_list_t *current_block_exits) {
15076 pm_node_list_t *previous_block_exits = parser->current_block_exits;
15077 parser->current_block_exits = current_block_exits;
15078 return previous_block_exits;
15079 }
15080
15081 /**
15082 * If we did not match a trailing while/until and this was the last chance to do
15083 * so, then all of the block exits in the list are invalid and we need to add an
15084 * error for each of them.
15085 */
15086 static void
15087 flush_block_exits(pm_parser_t *parser, pm_node_list_t *previous_block_exits) {
15088 pm_node_t *block_exit;
15089 PM_NODE_LIST_FOREACH(parser->current_block_exits, index, block_exit) {
15090 const char *type;
15091
15092 switch (PM_NODE_TYPE(block_exit)) {
15093 case PM_BREAK_NODE: type = "break"; break;
15094 case PM_NEXT_NODE: type = "next"; break;
15095 case PM_REDO_NODE: type = "redo"; break;
15096 default: assert(false && "unreachable"); type = ""; break;
15097 }
15098
15099 PM_PARSER_ERR_NODE_FORMAT(parser, block_exit, PM_ERR_INVALID_BLOCK_EXIT, type);
15100 }
15101
15102 parser->current_block_exits = previous_block_exits;
15103 }
15104
15105 /**
15106 * Pop the current level of block exits from the parser, and add errors to the
15107 * parser if any of them are deemed to be invalid.
15108 */
15109 static void
15110 pop_block_exits(pm_parser_t *parser, pm_node_list_t *previous_block_exits) {
15111 if (match2(parser, PM_TOKEN_KEYWORD_WHILE_MODIFIER, PM_TOKEN_KEYWORD_UNTIL_MODIFIER)) {
15112 // If we matched a trailing while/until, then all of the block exits in
15113 // the contained list are valid. In this case we do not need to do
15114 // anything.
15115 parser->current_block_exits = previous_block_exits;
15116 } else if (previous_block_exits != NULL) {
15117 // If we did not matching a trailing while/until, then all of the block
15118 // exits contained in the list are invalid for this specific context.
15119 // However, they could still become valid in a higher level context if
15120 // there is another list above this one. In this case we'll push all of
15121 // the block exits up to the previous list.
15122 pm_node_list_concat(previous_block_exits, parser->current_block_exits);
15123 parser->current_block_exits = previous_block_exits;
15124 } else {
15125 // If we did not match a trailing while/until and this was the last
15126 // chance to do so, then all of the block exits in the list are invalid
15127 // and we need to add an error for each of them.
15128 flush_block_exits(parser, previous_block_exits);
15129 }
15130 }
15131
15132 static inline pm_node_t *
15133 parse_predicate(pm_parser_t *parser, pm_binding_power_t binding_power, pm_context_t context, pm_token_t *then_keyword, uint16_t depth) {
15134 context_push(parser, PM_CONTEXT_PREDICATE);
15135 pm_diagnostic_id_t error_id = context == PM_CONTEXT_IF ? PM_ERR_CONDITIONAL_IF_PREDICATE : PM_ERR_CONDITIONAL_UNLESS_PREDICATE;
15136 pm_node_t *predicate = parse_value_expression(parser, binding_power, true, false, error_id, (uint16_t) (depth + 1));
15137
15138 // Predicates are closed by a term, a "then", or a term and then a "then".
15139 bool predicate_closed = accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
15140
15141 if (accept1(parser, PM_TOKEN_KEYWORD_THEN)) {
15142 predicate_closed = true;
15143 *then_keyword = parser->previous;
15144 }
15145
15146 if (!predicate_closed) {
15147 pm_parser_err_current(parser, PM_ERR_CONDITIONAL_PREDICATE_TERM);
15148 }
15149
15150 context_pop(parser);
15151 return predicate;
15152 }
15153
15154 static inline pm_node_t *
15155 parse_conditional(pm_parser_t *parser, pm_context_t context, size_t opening_newline_index, bool if_after_else, uint16_t depth) {
15156 pm_node_list_t current_block_exits = { 0 };
15157 pm_node_list_t *previous_block_exits = push_block_exits(parser, &current_block_exits);
15158
15159 pm_token_t keyword = parser->previous;
15160 pm_token_t then_keyword = not_provided(parser);
15161
15162 pm_node_t *predicate = parse_predicate(parser, PM_BINDING_POWER_MODIFIER, context, &then_keyword, (uint16_t) (depth + 1));
15163 pm_statements_node_t *statements = NULL;
15164
15165 if (!match3(parser, PM_TOKEN_KEYWORD_ELSIF, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_KEYWORD_END)) {
15166 pm_accepts_block_stack_push(parser, true);
15167 statements = parse_statements(parser, context, (uint16_t) (depth + 1));
15168 pm_accepts_block_stack_pop(parser);
15169 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
15170 }
15171
15172 pm_token_t end_keyword = not_provided(parser);
15173 pm_node_t *parent = NULL;
15174
15175 switch (context) {
15176 case PM_CONTEXT_IF:
15177 parent = UP(pm_if_node_create(parser, &keyword, predicate, &then_keyword, statements, NULL, &end_keyword));
15178 break;
15179 case PM_CONTEXT_UNLESS:
15180 parent = UP(pm_unless_node_create(parser, &keyword, predicate, &then_keyword, statements));
15181 break;
15182 default:
15183 assert(false && "unreachable");
15184 break;
15185 }
15186
15187 pm_node_t *current = parent;
15188
15189 // Parse any number of elsif clauses. This will form a linked list of if
15190 // nodes pointing to each other from the top.
15191 if (context == PM_CONTEXT_IF) {
15192 while (match1(parser, PM_TOKEN_KEYWORD_ELSIF)) {
15193 if (parser_end_of_line_p(parser)) {
15194 PM_PARSER_WARN_TOKEN_FORMAT_CONTENT(parser, parser->current, PM_WARN_KEYWORD_EOL);
15195 }
15196
15197 parser_warn_indentation_mismatch(parser, opening_newline_index, &keyword, false, false);
15198 pm_token_t elsif_keyword = parser->current;
15199 parser_lex(parser);
15200
15201 pm_node_t *predicate = parse_predicate(parser, PM_BINDING_POWER_MODIFIER, PM_CONTEXT_ELSIF, &then_keyword, (uint16_t) (depth + 1));
15202 pm_accepts_block_stack_push(parser, true);
15203
15204 pm_statements_node_t *statements = parse_statements(parser, PM_CONTEXT_ELSIF, (uint16_t) (depth + 1));
15205 pm_accepts_block_stack_pop(parser);
15206 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
15207
15208 pm_node_t *elsif = UP(pm_if_node_create(parser, &elsif_keyword, predicate, &then_keyword, statements, NULL, &end_keyword));
15209 ((pm_if_node_t *) current)->subsequent = elsif;
15210 current = elsif;
15211 }
15212 }
15213
15214 if (match1(parser, PM_TOKEN_KEYWORD_ELSE)) {
15215 parser_warn_indentation_mismatch(parser, opening_newline_index, &keyword, false, false);
15216 opening_newline_index = token_newline_index(parser);
15217
15218 parser_lex(parser);
15219 pm_token_t else_keyword = parser->previous;
15220
15221 pm_accepts_block_stack_push(parser, true);
15222 pm_statements_node_t *else_statements = parse_statements(parser, PM_CONTEXT_ELSE, (uint16_t) (depth + 1));
15223 pm_accepts_block_stack_pop(parser);
15224
15225 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
15226 parser_warn_indentation_mismatch(parser, opening_newline_index, &else_keyword, false, false);
15227 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_CONDITIONAL_TERM_ELSE, &keyword);
15228
15229 pm_else_node_t *else_node = pm_else_node_create(parser, &else_keyword, else_statements, &parser->previous);
15230
15231 switch (context) {
15232 case PM_CONTEXT_IF:
15233 ((pm_if_node_t *) current)->subsequent = UP(else_node);
15234 break;
15235 case PM_CONTEXT_UNLESS:
15236 ((pm_unless_node_t *) parent)->else_clause = else_node;
15237 break;
15238 default:
15239 assert(false && "unreachable");
15240 break;
15241 }
15242 } else {
15243 parser_warn_indentation_mismatch(parser, opening_newline_index, &keyword, if_after_else, false);
15244 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_CONDITIONAL_TERM, &keyword);
15245 }
15246
15247 // Set the appropriate end location for all of the nodes in the subtree.
15248 switch (context) {
15249 case PM_CONTEXT_IF: {
15250 pm_node_t *current = parent;
15251 bool recursing = true;
15252
15253 while (recursing) {
15254 switch (PM_NODE_TYPE(current)) {
15255 case PM_IF_NODE:
15256 pm_if_node_end_keyword_loc_set((pm_if_node_t *) current, &parser->previous);
15257 current = ((pm_if_node_t *) current)->subsequent;
15258 recursing = current != NULL;
15259 break;
15260 case PM_ELSE_NODE:
15261 pm_else_node_end_keyword_loc_set((pm_else_node_t *) current, &parser->previous);
15262 recursing = false;
15263 break;
15264 default: {
15265 recursing = false;
15266 break;
15267 }
15268 }
15269 }
15270 break;
15271 }
15272 case PM_CONTEXT_UNLESS:
15273 pm_unless_node_end_keyword_loc_set((pm_unless_node_t *) parent, &parser->previous);
15274 break;
15275 default:
15276 assert(false && "unreachable");
15277 break;
15278 }
15279
15280 pop_block_exits(parser, previous_block_exits);
15281 pm_node_list_free(&current_block_exits);
15282
15283 return parent;
15284 }
15285
15286 /**
15287 * This macro allows you to define a case statement for all of the keywords.
15288 * It's meant to be used in a switch statement.
15289 */
15290 #define PM_CASE_KEYWORD PM_TOKEN_KEYWORD___ENCODING__: case PM_TOKEN_KEYWORD___FILE__: case PM_TOKEN_KEYWORD___LINE__: \
15291 case PM_TOKEN_KEYWORD_ALIAS: case PM_TOKEN_KEYWORD_AND: case PM_TOKEN_KEYWORD_BEGIN: case PM_TOKEN_KEYWORD_BEGIN_UPCASE: \
15292 case PM_TOKEN_KEYWORD_BREAK: case PM_TOKEN_KEYWORD_CASE: case PM_TOKEN_KEYWORD_CLASS: case PM_TOKEN_KEYWORD_DEF: \
15293 case PM_TOKEN_KEYWORD_DEFINED: case PM_TOKEN_KEYWORD_DO: case PM_TOKEN_KEYWORD_DO_LOOP: case PM_TOKEN_KEYWORD_ELSE: \
15294 case PM_TOKEN_KEYWORD_ELSIF: case PM_TOKEN_KEYWORD_END: case PM_TOKEN_KEYWORD_END_UPCASE: case PM_TOKEN_KEYWORD_ENSURE: \
15295 case PM_TOKEN_KEYWORD_FALSE: case PM_TOKEN_KEYWORD_FOR: case PM_TOKEN_KEYWORD_IF: case PM_TOKEN_KEYWORD_IN: \
15296 case PM_TOKEN_KEYWORD_MODULE: case PM_TOKEN_KEYWORD_NEXT: case PM_TOKEN_KEYWORD_NIL: case PM_TOKEN_KEYWORD_NOT: \
15297 case PM_TOKEN_KEYWORD_OR: case PM_TOKEN_KEYWORD_REDO: case PM_TOKEN_KEYWORD_RESCUE: case PM_TOKEN_KEYWORD_RETRY: \
15298 case PM_TOKEN_KEYWORD_RETURN: case PM_TOKEN_KEYWORD_SELF: case PM_TOKEN_KEYWORD_SUPER: case PM_TOKEN_KEYWORD_THEN: \
15299 case PM_TOKEN_KEYWORD_TRUE: case PM_TOKEN_KEYWORD_UNDEF: case PM_TOKEN_KEYWORD_UNLESS: case PM_TOKEN_KEYWORD_UNTIL: \
15300 case PM_TOKEN_KEYWORD_WHEN: case PM_TOKEN_KEYWORD_WHILE: case PM_TOKEN_KEYWORD_YIELD
15301
15302 /**
15303 * This macro allows you to define a case statement for all of the operators.
15304 * It's meant to be used in a switch statement.
15305 */
15306 #define PM_CASE_OPERATOR PM_TOKEN_AMPERSAND: case PM_TOKEN_BACKTICK: case PM_TOKEN_BANG_EQUAL: \
15307 case PM_TOKEN_BANG_TILDE: case PM_TOKEN_BANG: case PM_TOKEN_BRACKET_LEFT_RIGHT_EQUAL: \
15308 case PM_TOKEN_BRACKET_LEFT_RIGHT: case PM_TOKEN_CARET: case PM_TOKEN_EQUAL_EQUAL_EQUAL: case PM_TOKEN_EQUAL_EQUAL: \
15309 case PM_TOKEN_EQUAL_TILDE: case PM_TOKEN_GREATER_EQUAL: case PM_TOKEN_GREATER_GREATER: case PM_TOKEN_GREATER: \
15310 case PM_TOKEN_LESS_EQUAL_GREATER: case PM_TOKEN_LESS_EQUAL: case PM_TOKEN_LESS_LESS: case PM_TOKEN_LESS: \
15311 case PM_TOKEN_MINUS: case PM_TOKEN_PERCENT: case PM_TOKEN_PIPE: case PM_TOKEN_PLUS: case PM_TOKEN_SLASH: \
15312 case PM_TOKEN_STAR_STAR: case PM_TOKEN_STAR: case PM_TOKEN_TILDE: case PM_TOKEN_UAMPERSAND: case PM_TOKEN_UMINUS: \
15313 case PM_TOKEN_UMINUS_NUM: case PM_TOKEN_UPLUS: case PM_TOKEN_USTAR: case PM_TOKEN_USTAR_STAR
15314
15315 /**
15316 * This macro allows you to define a case statement for all of the token types
15317 * that represent the beginning of nodes that are "primitives" in a pattern
15318 * matching expression.
15319 */
15320 #define PM_CASE_PRIMITIVE PM_TOKEN_INTEGER: case PM_TOKEN_INTEGER_IMAGINARY: case PM_TOKEN_INTEGER_RATIONAL: \
15321 case PM_TOKEN_INTEGER_RATIONAL_IMAGINARY: case PM_TOKEN_FLOAT: case PM_TOKEN_FLOAT_IMAGINARY: \
15322 case PM_TOKEN_FLOAT_RATIONAL: case PM_TOKEN_FLOAT_RATIONAL_IMAGINARY: case PM_TOKEN_SYMBOL_BEGIN: \
15323 case PM_TOKEN_REGEXP_BEGIN: case PM_TOKEN_BACKTICK: case PM_TOKEN_PERCENT_LOWER_X: case PM_TOKEN_PERCENT_LOWER_I: \
15324 case PM_TOKEN_PERCENT_LOWER_W: case PM_TOKEN_PERCENT_UPPER_I: case PM_TOKEN_PERCENT_UPPER_W: \
15325 case PM_TOKEN_STRING_BEGIN: case PM_TOKEN_KEYWORD_NIL: case PM_TOKEN_KEYWORD_SELF: case PM_TOKEN_KEYWORD_TRUE: \
15326 case PM_TOKEN_KEYWORD_FALSE: case PM_TOKEN_KEYWORD___FILE__: case PM_TOKEN_KEYWORD___LINE__: \
15327 case PM_TOKEN_KEYWORD___ENCODING__: case PM_TOKEN_MINUS_GREATER: case PM_TOKEN_HEREDOC_START: \
15328 case PM_TOKEN_UMINUS_NUM: case PM_TOKEN_CHARACTER_LITERAL
15329
15330 /**
15331 * This macro allows you to define a case statement for all of the token types
15332 * that could begin a parameter.
15333 */
15334 #define PM_CASE_PARAMETER PM_TOKEN_UAMPERSAND: case PM_TOKEN_AMPERSAND: case PM_TOKEN_UDOT_DOT_DOT: \
15335 case PM_TOKEN_IDENTIFIER: case PM_TOKEN_LABEL: case PM_TOKEN_USTAR: case PM_TOKEN_STAR: case PM_TOKEN_STAR_STAR: \
15336 case PM_TOKEN_USTAR_STAR: case PM_TOKEN_CONSTANT: case PM_TOKEN_INSTANCE_VARIABLE: case PM_TOKEN_GLOBAL_VARIABLE: \
15337 case PM_TOKEN_CLASS_VARIABLE
15338
15339 /**
15340 * This macro allows you to define a case statement for all of the nodes that
15341 * can be transformed into write targets.
15342 */
15343 #define PM_CASE_WRITABLE PM_CLASS_VARIABLE_READ_NODE: case PM_CONSTANT_PATH_NODE: \
15344 case PM_CONSTANT_READ_NODE: case PM_GLOBAL_VARIABLE_READ_NODE: case PM_LOCAL_VARIABLE_READ_NODE: \
15345 case PM_INSTANCE_VARIABLE_READ_NODE: case PM_MULTI_TARGET_NODE: case PM_BACK_REFERENCE_READ_NODE: \
15346 case PM_NUMBERED_REFERENCE_READ_NODE: case PM_IT_LOCAL_VARIABLE_READ_NODE
15347
15348 // Assert here that the flags are the same so that we can safely switch the type
15349 // of the node without having to move the flags.
15350 PM_STATIC_ASSERT(__LINE__, ((int) PM_STRING_FLAGS_FORCED_UTF8_ENCODING) == ((int) PM_ENCODING_FLAGS_FORCED_UTF8_ENCODING), "Expected the flags to match.");
15351
15352 /**
15353 * If the encoding was explicitly set through the lexing process, then we need
15354 * to potentially mark the string's flags to indicate how to encode it.
15355 */
15356 static inline pm_node_flags_t
15357 parse_unescaped_encoding(const pm_parser_t *parser) {
15358 if (parser->explicit_encoding != NULL) {
15359 if (parser->explicit_encoding == PM_ENCODING_UTF_8_ENTRY) {
15360 // If the there's an explicit encoding and it's using a UTF-8 escape
15361 // sequence, then mark the string as UTF-8.
15362 return PM_STRING_FLAGS_FORCED_UTF8_ENCODING;
15363 } else if (parser->encoding == PM_ENCODING_US_ASCII_ENTRY) {
15364 // If there's a non-UTF-8 escape sequence being used, then the
15365 // string uses the source encoding, unless the source is marked as
15366 // US-ASCII. In that case the string is forced as ASCII-8BIT in
15367 // order to keep the string valid.
15368 return PM_STRING_FLAGS_FORCED_BINARY_ENCODING;
15369 }
15370 }
15371 return 0;
15372 }
15373
15374 /**
15375 * Parse a node that is part of a string. If the subsequent tokens cannot be
15376 * parsed as a string part, then NULL is returned.
15377 */
15378 static pm_node_t *
15379 parse_string_part(pm_parser_t *parser, uint16_t depth) {
15380 switch (parser->current.type) {
15381 // Here the lexer has returned to us plain string content. In this case
15382 // we'll create a string node that has no opening or closing and return that
15383 // as the part. These kinds of parts look like:
15384 //
15385 // "aaa #{bbb} #@ccc ddd"
15386 // ^^^^ ^ ^^^^
15387 case PM_TOKEN_STRING_CONTENT: {
15388 pm_token_t opening = not_provided(parser);
15389 pm_token_t closing = not_provided(parser);
15390
15391 pm_node_t *node = UP(pm_string_node_create_current_string(parser, &opening, &parser->current, &closing));
15392 pm_node_flag_set(node, parse_unescaped_encoding(parser));
15393
15394 parser_lex(parser);
15395 return node;
15396 }
15397 // Here the lexer has returned the beginning of an embedded expression. In
15398 // that case we'll parse the inner statements and return that as the part.
15399 // These kinds of parts look like:
15400 //
15401 // "aaa #{bbb} #@ccc ddd"
15402 // ^^^^^^
15403 case PM_TOKEN_EMBEXPR_BEGIN: {
15404 // Ruby disallows seeing encoding around interpolation in strings,
15405 // even though it is known at parse time.
15406 parser->explicit_encoding = NULL;
15407
15408 pm_lex_state_t state = parser->lex_state;
15409 int brace_nesting = parser->brace_nesting;
15410
15411 parser->brace_nesting = 0;
15412 lex_state_set(parser, PM_LEX_STATE_BEG);
15413 parser_lex(parser);
15414
15415 pm_token_t opening = parser->previous;
15416 pm_statements_node_t *statements = NULL;
15417
15418 if (!match1(parser, PM_TOKEN_EMBEXPR_END)) {
15419 pm_accepts_block_stack_push(parser, true);
15420 statements = parse_statements(parser, PM_CONTEXT_EMBEXPR, (uint16_t) (depth + 1));
15421 pm_accepts_block_stack_pop(parser);
15422 }
15423
15424 parser->brace_nesting = brace_nesting;
15425 lex_state_set(parser, state);
15426
15427 expect1(parser, PM_TOKEN_EMBEXPR_END, PM_ERR_EMBEXPR_END);
15428 pm_token_t closing = parser->previous;
15429
15430 // If this set of embedded statements only contains a single
15431 // statement, then Ruby does not consider it as a possible statement
15432 // that could emit a line event.
15433 if (statements != NULL && statements->body.size == 1) {
15434 pm_node_flag_unset(statements->body.nodes[0], PM_NODE_FLAG_NEWLINE);
15435 }
15436
15437 return UP(pm_embedded_statements_node_create(parser, &opening, statements, &closing));
15438 }
15439
15440 // Here the lexer has returned the beginning of an embedded variable.
15441 // In that case we'll parse the variable and create an appropriate node
15442 // for it and then return that node. These kinds of parts look like:
15443 //
15444 // "aaa #{bbb} #@ccc ddd"
15445 // ^^^^^
15446 case PM_TOKEN_EMBVAR: {
15447 // Ruby disallows seeing encoding around interpolation in strings,
15448 // even though it is known at parse time.
15449 parser->explicit_encoding = NULL;
15450
15451 lex_state_set(parser, PM_LEX_STATE_BEG);
15452 parser_lex(parser);
15453
15454 pm_token_t operator = parser->previous;
15455 pm_node_t *variable;
15456
15457 switch (parser->current.type) {
15458 // In this case a back reference is being interpolated. We'll
15459 // create a global variable read node.
15460 case PM_TOKEN_BACK_REFERENCE:
15461 parser_lex(parser);
15462 variable = UP(pm_back_reference_read_node_create(parser, &parser->previous));
15463 break;
15464 // In this case an nth reference is being interpolated. We'll
15465 // create a global variable read node.
15466 case PM_TOKEN_NUMBERED_REFERENCE:
15467 parser_lex(parser);
15468 variable = UP(pm_numbered_reference_read_node_create(parser, &parser->previous));
15469 break;
15470 // In this case a global variable is being interpolated. We'll
15471 // create a global variable read node.
15472 case PM_TOKEN_GLOBAL_VARIABLE:
15473 parser_lex(parser);
15474 variable = UP(pm_global_variable_read_node_create(parser, &parser->previous));
15475 break;
15476 // In this case an instance variable is being interpolated.
15477 // We'll create an instance variable read node.
15478 case PM_TOKEN_INSTANCE_VARIABLE:
15479 parser_lex(parser);
15480 variable = UP(pm_instance_variable_read_node_create(parser, &parser->previous));
15481 break;
15482 // In this case a class variable is being interpolated. We'll
15483 // create a class variable read node.
15484 case PM_TOKEN_CLASS_VARIABLE:
15485 parser_lex(parser);
15486 variable = UP(pm_class_variable_read_node_create(parser, &parser->previous));
15487 break;
15488 // We can hit here if we got an invalid token. In that case
15489 // we'll not attempt to lex this token and instead just return a
15490 // missing node.
15491 default:
15492 expect1(parser, PM_TOKEN_IDENTIFIER, PM_ERR_EMBVAR_INVALID);
15493 variable = UP(pm_missing_node_create(parser, parser->current.start, parser->current.end));
15494 break;
15495 }
15496
15497 return UP(pm_embedded_variable_node_create(parser, &operator, variable));
15498 }
15499 default:
15500 parser_lex(parser);
15501 pm_parser_err_previous(parser, PM_ERR_CANNOT_PARSE_STRING_PART);
15502 return NULL;
15503 }
15504 }
15505
15506 /**
15507 * When creating a symbol, unary operators that cannot be binary operators
15508 * automatically drop trailing `@` characters. This happens at the parser level,
15509 * such that `~@` is parsed as `~` and `!@` is parsed as `!`. We do that here.
15510 */
15511 static const uint8_t *
15512 parse_operator_symbol_name(const pm_token_t *name) {
15513 switch (name->type) {
15514 case PM_TOKEN_TILDE:
15515 case PM_TOKEN_BANG:
15516 if (name->end[-1] == '@') return name->end - 1;
15517 PRISM_FALLTHROUGH
15518 default:
15519 return name->end;
15520 }
15521 }
15522
15523 static pm_node_t *
15524 parse_operator_symbol(pm_parser_t *parser, const pm_token_t *opening, pm_lex_state_t next_state) {
15525 pm_token_t closing = not_provided(parser);
15526 pm_symbol_node_t *symbol = pm_symbol_node_create(parser, opening, &parser->current, &closing);
15527
15528 const uint8_t *end = parse_operator_symbol_name(&parser->current);
15529
15530 if (next_state != PM_LEX_STATE_NONE) lex_state_set(parser, next_state);
15531 parser_lex(parser);
15532
15533 pm_string_shared_init(&symbol->unescaped, parser->previous.start, end);
15534 pm_node_flag_set(UP(symbol), PM_SYMBOL_FLAGS_FORCED_US_ASCII_ENCODING);
15535
15536 return UP(symbol);
15537 }
15538
15539 /**
15540 * Parse a symbol node. This function will get called immediately after finding
15541 * a symbol opening token. This handles parsing bare symbols and interpolated
15542 * symbols.
15543 */
15544 static pm_node_t *
15545 parse_symbol(pm_parser_t *parser, pm_lex_mode_t *lex_mode, pm_lex_state_t next_state, uint16_t depth) {
15546 const pm_token_t opening = parser->previous;
15547
15548 if (lex_mode->mode != PM_LEX_STRING) {
15549 if (next_state != PM_LEX_STATE_NONE) lex_state_set(parser, next_state);
15550
15551 switch (parser->current.type) {
15552 case PM_CASE_OPERATOR:
15553 return parse_operator_symbol(parser, &opening, next_state == PM_LEX_STATE_NONE ? PM_LEX_STATE_ENDFN : next_state);
15554 case PM_TOKEN_IDENTIFIER:
15555 case PM_TOKEN_CONSTANT:
15556 case PM_TOKEN_INSTANCE_VARIABLE:
15557 case PM_TOKEN_METHOD_NAME:
15558 case PM_TOKEN_CLASS_VARIABLE:
15559 case PM_TOKEN_GLOBAL_VARIABLE:
15560 case PM_TOKEN_NUMBERED_REFERENCE:
15561 case PM_TOKEN_BACK_REFERENCE:
15562 case PM_CASE_KEYWORD:
15563 parser_lex(parser);
15564 break;
15565 default:
15566 expect2(parser, PM_TOKEN_IDENTIFIER, PM_TOKEN_METHOD_NAME, PM_ERR_SYMBOL_INVALID);
15567 break;
15568 }
15569
15570 pm_token_t closing = not_provided(parser);
15571 pm_symbol_node_t *symbol = pm_symbol_node_create(parser, &opening, &parser->previous, &closing);
15572
15573 pm_string_shared_init(&symbol->unescaped, parser->previous.start, parser->previous.end);
15574 pm_node_flag_set(UP(symbol), parse_symbol_encoding(parser, &parser->previous, &symbol->unescaped, false));
15575
15576 return UP(symbol);
15577 }
15578
15579 if (lex_mode->as.string.interpolation) {
15580 // If we have the end of the symbol, then we can return an empty symbol.
15581 if (match1(parser, PM_TOKEN_STRING_END)) {
15582 if (next_state != PM_LEX_STATE_NONE) lex_state_set(parser, next_state);
15583 parser_lex(parser);
15584
15585 pm_token_t content = not_provided(parser);
15586 pm_token_t closing = parser->previous;
15587 return UP(pm_symbol_node_create(parser, &opening, &content, &closing));
15588 }
15589
15590 // Now we can parse the first part of the symbol.
15591 pm_node_t *part = parse_string_part(parser, (uint16_t) (depth + 1));
15592
15593 // If we got a string part, then it's possible that we could transform
15594 // what looks like an interpolated symbol into a regular symbol.
15595 if (part && PM_NODE_TYPE_P(part, PM_STRING_NODE) && match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) {
15596 if (next_state != PM_LEX_STATE_NONE) lex_state_set(parser, next_state);
15597 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_SYMBOL_TERM_INTERPOLATED);
15598
15599 return UP(pm_string_node_to_symbol_node(parser, (pm_string_node_t *) part, &opening, &parser->previous));
15600 }
15601
15602 pm_interpolated_symbol_node_t *symbol = pm_interpolated_symbol_node_create(parser, &opening, NULL, &opening);
15603 if (part) pm_interpolated_symbol_node_append(symbol, part);
15604
15605 while (!match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) {
15606 if ((part = parse_string_part(parser, (uint16_t) (depth + 1))) != NULL) {
15607 pm_interpolated_symbol_node_append(symbol, part);
15608 }
15609 }
15610
15611 if (next_state != PM_LEX_STATE_NONE) lex_state_set(parser, next_state);
15612 if (match1(parser, PM_TOKEN_EOF)) {
15613 pm_parser_err_token(parser, &opening, PM_ERR_SYMBOL_TERM_INTERPOLATED);
15614 } else {
15615 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_SYMBOL_TERM_INTERPOLATED);
15616 }
15617
15618 pm_interpolated_symbol_node_closing_loc_set(symbol, &parser->previous);
15619 return UP(symbol);
15620 }
15621
15622 pm_token_t content;
15623 pm_string_t unescaped;
15624
15625 if (match1(parser, PM_TOKEN_STRING_CONTENT)) {
15626 content = parser->current;
15627 unescaped = parser->current_string;
15628 parser_lex(parser);
15629
15630 // If we have two string contents in a row, then the content of this
15631 // symbol is split because of heredoc contents. This looks like:
15632 //
15633 // <<A; :'a
15634 // A
15635 // b'
15636 //
15637 // In this case, the best way we have to represent this is as an
15638 // interpolated string node, so that's what we'll do here.
15639 if (match1(parser, PM_TOKEN_STRING_CONTENT)) {
15640 pm_interpolated_symbol_node_t *symbol = pm_interpolated_symbol_node_create(parser, &opening, NULL, &opening);
15641 pm_token_t bounds = not_provided(parser);
15642
15643 pm_node_t *part = UP(pm_string_node_create_unescaped(parser, &bounds, &content, &bounds, &unescaped));
15644 pm_interpolated_symbol_node_append(symbol, part);
15645
15646 part = UP(pm_string_node_create_unescaped(parser, &bounds, &parser->current, &bounds, &parser->current_string));
15647 pm_interpolated_symbol_node_append(symbol, part);
15648
15649 if (next_state != PM_LEX_STATE_NONE) {
15650 lex_state_set(parser, next_state);
15651 }
15652
15653 parser_lex(parser);
15654 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_SYMBOL_TERM_DYNAMIC);
15655
15656 pm_interpolated_symbol_node_closing_loc_set(symbol, &parser->previous);
15657 return UP(symbol);
15658 }
15659 } else {
15660 content = (pm_token_t) { .type = PM_TOKEN_STRING_CONTENT, .start = parser->previous.end, .end = parser->previous.end };
15661 pm_string_shared_init(&unescaped, content.start, content.end);
15662 }
15663
15664 if (next_state != PM_LEX_STATE_NONE) {
15665 lex_state_set(parser, next_state);
15666 }
15667
15668 if (match1(parser, PM_TOKEN_EOF)) {
15669 pm_parser_err_token(parser, &opening, PM_ERR_SYMBOL_TERM_DYNAMIC);
15670 } else {
15671 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_SYMBOL_TERM_DYNAMIC);
15672 }
15673
15674 return UP(pm_symbol_node_create_unescaped(parser, &opening, &content, &parser->previous, &unescaped, parse_symbol_encoding(parser, &content, &unescaped, false)));
15675 }
15676
15677 /**
15678 * Parse an argument to undef which can either be a bare word, a symbol, a
15679 * constant, or an interpolated symbol.
15680 */
15681 static inline pm_node_t *
15682 parse_undef_argument(pm_parser_t *parser, uint16_t depth) {
15683 switch (parser->current.type) {
15684 case PM_CASE_OPERATOR: {
15685 const pm_token_t opening = not_provided(parser);
15686 return parse_operator_symbol(parser, &opening, PM_LEX_STATE_NONE);
15687 }
15688 case PM_CASE_KEYWORD:
15689 case PM_TOKEN_CONSTANT:
15690 case PM_TOKEN_IDENTIFIER:
15691 case PM_TOKEN_METHOD_NAME: {
15692 parser_lex(parser);
15693
15694 pm_token_t opening = not_provided(parser);
15695 pm_token_t closing = not_provided(parser);
15696 pm_symbol_node_t *symbol = pm_symbol_node_create(parser, &opening, &parser->previous, &closing);
15697
15698 pm_string_shared_init(&symbol->unescaped, parser->previous.start, parser->previous.end);
15699 pm_node_flag_set(UP(symbol), parse_symbol_encoding(parser, &parser->previous, &symbol->unescaped, false));
15700
15701 return UP(symbol);
15702 }
15703 case PM_TOKEN_SYMBOL_BEGIN: {
15704 pm_lex_mode_t lex_mode = *parser->lex_modes.current;
15705 parser_lex(parser);
15706
15707 return parse_symbol(parser, &lex_mode, PM_LEX_STATE_NONE, (uint16_t) (depth + 1));
15708 }
15709 default:
15710 pm_parser_err_current(parser, PM_ERR_UNDEF_ARGUMENT);
15711 return UP(pm_missing_node_create(parser, parser->current.start, parser->current.end));
15712 }
15713 }
15714
15715 /**
15716 * Parse an argument to alias which can either be a bare word, a symbol, an
15717 * interpolated symbol or a global variable. If this is the first argument, then
15718 * we need to set the lex state to PM_LEX_STATE_FNAME | PM_LEX_STATE_FITEM
15719 * between the first and second arguments.
15720 */
15721 static inline pm_node_t *
15722 parse_alias_argument(pm_parser_t *parser, bool first, uint16_t depth) {
15723 switch (parser->current.type) {
15724 case PM_CASE_OPERATOR: {
15725 const pm_token_t opening = not_provided(parser);
15726 return parse_operator_symbol(parser, &opening, first ? PM_LEX_STATE_FNAME | PM_LEX_STATE_FITEM : PM_LEX_STATE_NONE);
15727 }
15728 case PM_CASE_KEYWORD:
15729 case PM_TOKEN_CONSTANT:
15730 case PM_TOKEN_IDENTIFIER:
15731 case PM_TOKEN_METHOD_NAME: {
15732 if (first) lex_state_set(parser, PM_LEX_STATE_FNAME | PM_LEX_STATE_FITEM);
15733 parser_lex(parser);
15734
15735 pm_token_t opening = not_provided(parser);
15736 pm_token_t closing = not_provided(parser);
15737 pm_symbol_node_t *symbol = pm_symbol_node_create(parser, &opening, &parser->previous, &closing);
15738
15739 pm_string_shared_init(&symbol->unescaped, parser->previous.start, parser->previous.end);
15740 pm_node_flag_set(UP(symbol), parse_symbol_encoding(parser, &parser->previous, &symbol->unescaped, false));
15741
15742 return UP(symbol);
15743 }
15744 case PM_TOKEN_SYMBOL_BEGIN: {
15745 pm_lex_mode_t lex_mode = *parser->lex_modes.current;
15746 parser_lex(parser);
15747
15748 return parse_symbol(parser, &lex_mode, first ? PM_LEX_STATE_FNAME | PM_LEX_STATE_FITEM : PM_LEX_STATE_NONE, (uint16_t) (depth + 1));
15749 }
15750 case PM_TOKEN_BACK_REFERENCE:
15751 parser_lex(parser);
15752 return UP(pm_back_reference_read_node_create(parser, &parser->previous));
15753 case PM_TOKEN_NUMBERED_REFERENCE:
15754 parser_lex(parser);
15755 return UP(pm_numbered_reference_read_node_create(parser, &parser->previous));
15756 case PM_TOKEN_GLOBAL_VARIABLE:
15757 parser_lex(parser);
15758 return UP(pm_global_variable_read_node_create(parser, &parser->previous));
15759 default:
15760 pm_parser_err_current(parser, PM_ERR_ALIAS_ARGUMENT);
15761 return UP(pm_missing_node_create(parser, parser->current.start, parser->current.end));
15762 }
15763 }
15764
15765 /**
15766 * Parse an identifier into either a local variable read. If the local variable
15767 * is not found, it returns NULL instead.
15768 */
15769 static pm_node_t *
15770 parse_variable(pm_parser_t *parser) {
15771 pm_constant_id_t name_id = pm_parser_constant_id_token(parser, &parser->previous);
15772 int depth;
15773 bool is_numbered_param = pm_token_is_numbered_parameter(parser->previous.start, parser->previous.end);
15774
15775 if (!is_numbered_param && ((depth = pm_parser_local_depth_constant_id(parser, name_id)) != -1)) {
15776 return UP(pm_local_variable_read_node_create_constant_id(parser, &parser->previous, name_id, (uint32_t) depth, false));
15777 }
15778
15779 pm_scope_t *current_scope = parser->current_scope;
15780 if (!current_scope->closed && !(current_scope->parameters & PM_SCOPE_PARAMETERS_IMPLICIT_DISALLOWED)) {
15781 if (is_numbered_param) {
15782 // When you use a numbered parameter, it implies the existence of
15783 // all of the locals that exist before it. For example, referencing
15784 // _2 means that _1 must exist. Therefore here we loop through all
15785 // of the possibilities and add them into the constant pool.
15786 uint8_t maximum = (uint8_t) (parser->previous.start[1] - '0');
15787 for (uint8_t number = 1; number <= maximum; number++) {
15788 pm_parser_local_add_constant(parser, pm_numbered_parameter_names[number - 1], 2);
15789 }
15790
15791 if (!match1(parser, PM_TOKEN_EQUAL)) {
15792 parser->current_scope->parameters |= PM_SCOPE_PARAMETERS_NUMBERED_FOUND;
15793 }
15794
15795 pm_node_t *node = UP(pm_local_variable_read_node_create_constant_id(parser, &parser->previous, name_id, 0, false));
15796 pm_node_list_append(&current_scope->implicit_parameters, node);
15797
15798 return node;
15799 } else if ((parser->version >= PM_OPTIONS_VERSION_CRUBY_3_4) && pm_token_is_it(parser->previous.start, parser->previous.end)) {
15800 pm_node_t *node = UP(pm_it_local_variable_read_node_create(parser, &parser->previous));
15801 pm_node_list_append(&current_scope->implicit_parameters, node);
15802
15803 return node;
15804 }
15805 }
15806
15807 return NULL;
15808 }
15809
15810 /**
15811 * Parse an identifier into either a local variable read or a call.
15812 */
15813 static pm_node_t *
15814 parse_variable_call(pm_parser_t *parser) {
15815 pm_node_flags_t flags = 0;
15816
15817 if (!match1(parser, PM_TOKEN_PARENTHESIS_LEFT) && (parser->previous.end[-1] != '!') && (parser->previous.end[-1] != '?')) {
15818 pm_node_t *node = parse_variable(parser);
15819 if (node != NULL) return node;
15820 flags |= PM_CALL_NODE_FLAGS_VARIABLE_CALL;
15821 }
15822
15823 pm_call_node_t *node = pm_call_node_variable_call_create(parser, &parser->previous);
15824 pm_node_flag_set(UP(node), flags);
15825
15826 return UP(node);
15827 }
15828
15829 /**
15830 * Parse the method definition name based on the current token available on the
15831 * parser. If it does not match a valid method definition name, then a missing
15832 * token is returned.
15833 */
15834 static inline pm_token_t
15835 parse_method_definition_name(pm_parser_t *parser) {
15836 switch (parser->current.type) {
15837 case PM_CASE_KEYWORD:
15838 case PM_TOKEN_CONSTANT:
15839 case PM_TOKEN_METHOD_NAME:
15840 parser_lex(parser);
15841 return parser->previous;
15842 case PM_TOKEN_IDENTIFIER:
15843 pm_refute_numbered_parameter(parser, parser->current.start, parser->current.end);
15844 parser_lex(parser);
15845 return parser->previous;
15846 case PM_CASE_OPERATOR:
15847 lex_state_set(parser, PM_LEX_STATE_ENDFN);
15848 parser_lex(parser);
15849 return parser->previous;
15850 default:
15851 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_DEF_NAME, pm_token_type_human(parser->current.type));
15852 return (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->current.start, .end = parser->current.end };
15853 }
15854 }
15855
15856 static void
15857 parse_heredoc_dedent_string(pm_string_t *string, size_t common_whitespace) {
15858 // Get a reference to the string struct that is being held by the string
15859 // node. This is the value we're going to actually manipulate.
15860 pm_string_ensure_owned(string);
15861
15862 // Now get the bounds of the existing string. We'll use this as a
15863 // destination to move bytes into. We'll also use it for bounds checking
15864 // since we don't require that these strings be null terminated.
15865 size_t dest_length = pm_string_length(string);
15866 const uint8_t *source_cursor = (uint8_t *) string->source;
15867 const uint8_t *source_end = source_cursor + dest_length;
15868
15869 // We're going to move bytes backward in the string when we get leading
15870 // whitespace, so we'll maintain a pointer to the current position in the
15871 // string that we're writing to.
15872 size_t trimmed_whitespace = 0;
15873
15874 // While we haven't reached the amount of common whitespace that we need to
15875 // trim and we haven't reached the end of the string, we'll keep trimming
15876 // whitespace. Trimming in this context means skipping over these bytes such
15877 // that they aren't copied into the new string.
15878 while ((source_cursor < source_end) && pm_char_is_inline_whitespace(*source_cursor) && trimmed_whitespace < common_whitespace) {
15879 if (*source_cursor == '\t') {
15880 trimmed_whitespace = (trimmed_whitespace / PM_TAB_WHITESPACE_SIZE + 1) * PM_TAB_WHITESPACE_SIZE;
15881 if (trimmed_whitespace > common_whitespace) break;
15882 } else {
15883 trimmed_whitespace++;
15884 }
15885
15886 source_cursor++;
15887 dest_length--;
15888 }
15889
15890 memmove((uint8_t *) string->source, source_cursor, (size_t) (source_end - source_cursor));
15891 string->length = dest_length;
15892 }
15893
15894 /**
15895 * Take a heredoc node that is indented by a ~ and trim the leading whitespace.
15896 */
15897 static void
15898 parse_heredoc_dedent(pm_parser_t *parser, pm_node_list_t *nodes, size_t common_whitespace) {
15899 // The next node should be dedented if it's the first node in the list or if
15900 // it follows a string node.
15901 bool dedent_next = true;
15902
15903 // Iterate over all nodes, and trim whitespace accordingly. We're going to
15904 // keep around two indices: a read and a write. If we end up trimming all of
15905 // the whitespace from a node, then we'll drop it from the list entirely.
15906 size_t write_index = 0;
15907
15908 pm_node_t *node;
15909 PM_NODE_LIST_FOREACH(nodes, read_index, node) {
15910 // We're not manipulating child nodes that aren't strings. In this case
15911 // we'll skip past it and indicate that the subsequent node should not
15912 // be dedented.
15913 if (!PM_NODE_TYPE_P(node, PM_STRING_NODE)) {
15914 nodes->nodes[write_index++] = node;
15915 dedent_next = false;
15916 continue;
15917 }
15918
15919 pm_string_node_t *string_node = ((pm_string_node_t *) node);
15920 if (dedent_next) {
15921 parse_heredoc_dedent_string(&string_node->unescaped, common_whitespace);
15922 }
15923
15924 if (string_node->unescaped.length == 0) {
15925 pm_node_destroy(parser, node);
15926 } else {
15927 nodes->nodes[write_index++] = node;
15928 }
15929
15930 // We always dedent the next node if it follows a string node.
15931 dedent_next = true;
15932 }
15933
15934 nodes->size = write_index;
15935 }
15936
15937 /**
15938 * Return a string content token at a particular location that is empty.
15939 */
15940 static pm_token_t
15941 parse_strings_empty_content(const uint8_t *location) {
15942 return (pm_token_t) { .type = PM_TOKEN_STRING_CONTENT, .start = location, .end = location };
15943 }
15944
15945 /**
15946 * Parse a set of strings that could be concatenated together.
15947 */
15948 static inline pm_node_t *
15949 parse_strings(pm_parser_t *parser, pm_node_t *current, bool accepts_label, uint16_t depth) {
15950 assert(parser->current.type == PM_TOKEN_STRING_BEGIN);
15951 bool concating = false;
15952
15953 while (match1(parser, PM_TOKEN_STRING_BEGIN)) {
15954 pm_node_t *node = NULL;
15955
15956 // Here we have found a string literal. We'll parse it and add it to
15957 // the list of strings.
15958 const pm_lex_mode_t *lex_mode = parser->lex_modes.current;
15959 assert(lex_mode->mode == PM_LEX_STRING);
15960 bool lex_interpolation = lex_mode->as.string.interpolation;
15961 bool label_allowed = lex_mode->as.string.label_allowed && accepts_label;
15962
15963 pm_token_t opening = parser->current;
15964 parser_lex(parser);
15965
15966 if (match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) {
15967 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_STRING_LITERAL_EOF);
15968 // If we get here, then we have an end immediately after a
15969 // start. In that case we'll create an empty content token and
15970 // return an uninterpolated string.
15971 pm_token_t content = parse_strings_empty_content(parser->previous.start);
15972 pm_string_node_t *string = pm_string_node_create(parser, &opening, &content, &parser->previous);
15973
15974 pm_string_shared_init(&string->unescaped, content.start, content.end);
15975 node = UP(string);
15976 } else if (accept1(parser, PM_TOKEN_LABEL_END)) {
15977 // If we get here, then we have an end of a label immediately
15978 // after a start. In that case we'll create an empty symbol
15979 // node.
15980 pm_token_t content = parse_strings_empty_content(parser->previous.start);
15981 pm_symbol_node_t *symbol = pm_symbol_node_create(parser, &opening, &content, &parser->previous);
15982
15983 pm_string_shared_init(&symbol->unescaped, content.start, content.end);
15984 node = UP(symbol);
15985
15986 if (!label_allowed) pm_parser_err_node(parser, node, PM_ERR_UNEXPECTED_LABEL);
15987 } else if (!lex_interpolation) {
15988 // If we don't accept interpolation then we expect the string to
15989 // start with a single string content node.
15990 pm_string_t unescaped;
15991 pm_token_t content;
15992
15993 if (match1(parser, PM_TOKEN_EOF)) {
15994 unescaped = PM_STRING_EMPTY;
15995 content = not_provided(parser);
15996 } else {
15997 unescaped = parser->current_string;
15998 expect1(parser, PM_TOKEN_STRING_CONTENT, PM_ERR_EXPECT_STRING_CONTENT);
15999 content = parser->previous;
16000 }
16001
16002 // It is unfortunately possible to have multiple string content
16003 // nodes in a row in the case that there's heredoc content in
16004 // the middle of the string, like this cursed example:
16005 //
16006 // <<-END+'b
16007 // a
16008 // END
16009 // c'+'d'
16010 //
16011 // In that case we need to switch to an interpolated string to
16012 // be able to contain all of the parts.
16013 if (match1(parser, PM_TOKEN_STRING_CONTENT)) {
16014 pm_node_list_t parts = { 0 };
16015
16016 pm_token_t delimiters = not_provided(parser);
16017 pm_node_t *part = UP(pm_string_node_create_unescaped(parser, &delimiters, &content, &delimiters, &unescaped));
16018 pm_node_list_append(&parts, part);
16019
16020 do {
16021 part = UP(pm_string_node_create_current_string(parser, &delimiters, &parser->current, &delimiters));
16022 pm_node_list_append(&parts, part);
16023 parser_lex(parser);
16024 } while (match1(parser, PM_TOKEN_STRING_CONTENT));
16025
16026 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_STRING_LITERAL_EOF);
16027 node = UP(pm_interpolated_string_node_create(parser, &opening, &parts, &parser->previous));
16028
16029 pm_node_list_free(&parts);
16030 } else if (accept1(parser, PM_TOKEN_LABEL_END)) {
16031 node = UP(pm_symbol_node_create_unescaped(parser, &opening, &content, &parser->previous, &unescaped, parse_symbol_encoding(parser, &content, &unescaped, true)));
16032 if (!label_allowed) pm_parser_err_node(parser, node, PM_ERR_UNEXPECTED_LABEL);
16033 } else if (match1(parser, PM_TOKEN_EOF)) {
16034 pm_parser_err_token(parser, &opening, PM_ERR_STRING_LITERAL_EOF);
16035 node = UP(pm_string_node_create_unescaped(parser, &opening, &content, &parser->current, &unescaped));
16036 } else if (accept1(parser, PM_TOKEN_STRING_END)) {
16037 node = UP(pm_string_node_create_unescaped(parser, &opening, &content, &parser->previous, &unescaped));
16038 } else {
16039 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->previous, PM_ERR_STRING_LITERAL_TERM, pm_token_type_human(parser->previous.type));
16040 parser->previous.start = parser->previous.end;
16041 parser->previous.type = PM_TOKEN_MISSING;
16042 node = UP(pm_string_node_create_unescaped(parser, &opening, &content, &parser->previous, &unescaped));
16043 }
16044 } else if (match1(parser, PM_TOKEN_STRING_CONTENT)) {
16045 // In this case we've hit string content so we know the string
16046 // at least has something in it. We'll need to check if the
16047 // following token is the end (in which case we can return a
16048 // plain string) or if it's not then it has interpolation.
16049 pm_token_t content = parser->current;
16050 pm_string_t unescaped = parser->current_string;
16051 parser_lex(parser);
16052
16053 if (match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) {
16054 node = UP(pm_string_node_create_unescaped(parser, &opening, &content, &parser->current, &unescaped));
16055 pm_node_flag_set(node, parse_unescaped_encoding(parser));
16056
16057 // Kind of odd behavior, but basically if we have an
16058 // unterminated string and it ends in a newline, we back up one
16059 // character so that the error message is on the last line of
16060 // content in the string.
16061 if (!accept1(parser, PM_TOKEN_STRING_END)) {
16062 const uint8_t *location = parser->previous.end;
16063 if (location > parser->start && location[-1] == '\n') location--;
16064 pm_parser_err(parser, location, location, PM_ERR_STRING_LITERAL_EOF);
16065
16066 parser->previous.start = parser->previous.end;
16067 parser->previous.type = PM_TOKEN_MISSING;
16068 }
16069 } else if (accept1(parser, PM_TOKEN_LABEL_END)) {
16070 node = UP(pm_symbol_node_create_unescaped(parser, &opening, &content, &parser->previous, &unescaped, parse_symbol_encoding(parser, &content, &unescaped, true)));
16071 if (!label_allowed) pm_parser_err_node(parser, node, PM_ERR_UNEXPECTED_LABEL);
16072 } else {
16073 // If we get here, then we have interpolation so we'll need
16074 // to create a string or symbol node with interpolation.
16075 pm_node_list_t parts = { 0 };
16076 pm_token_t string_opening = not_provided(parser);
16077 pm_token_t string_closing = not_provided(parser);
16078
16079 pm_node_t *part = UP(pm_string_node_create_unescaped(parser, &string_opening, &parser->previous, &string_closing, &unescaped));
16080 pm_node_flag_set(part, parse_unescaped_encoding(parser));
16081 pm_node_list_append(&parts, part);
16082
16083 while (!match3(parser, PM_TOKEN_STRING_END, PM_TOKEN_LABEL_END, PM_TOKEN_EOF)) {
16084 if ((part = parse_string_part(parser, (uint16_t) (depth + 1))) != NULL) {
16085 pm_node_list_append(&parts, part);
16086 }
16087 }
16088
16089 if (accept1(parser, PM_TOKEN_LABEL_END)) {
16090 node = UP(pm_interpolated_symbol_node_create(parser, &opening, &parts, &parser->previous));
16091 if (!label_allowed) pm_parser_err_node(parser, node, PM_ERR_UNEXPECTED_LABEL);
16092 } else if (match1(parser, PM_TOKEN_EOF)) {
16093 pm_parser_err_token(parser, &opening, PM_ERR_STRING_INTERPOLATED_TERM);
16094 node = UP(pm_interpolated_string_node_create(parser, &opening, &parts, &parser->current));
16095 } else {
16096 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_STRING_INTERPOLATED_TERM);
16097 node = UP(pm_interpolated_string_node_create(parser, &opening, &parts, &parser->previous));
16098 }
16099
16100 pm_node_list_free(&parts);
16101 }
16102 } else {
16103 // If we get here, then the first part of the string is not plain
16104 // string content, in which case we need to parse the string as an
16105 // interpolated string.
16106 pm_node_list_t parts = { 0 };
16107 pm_node_t *part;
16108
16109 while (!match3(parser, PM_TOKEN_STRING_END, PM_TOKEN_LABEL_END, PM_TOKEN_EOF)) {
16110 if ((part = parse_string_part(parser, (uint16_t) (depth + 1))) != NULL) {
16111 pm_node_list_append(&parts, part);
16112 }
16113 }
16114
16115 if (accept1(parser, PM_TOKEN_LABEL_END)) {
16116 node = UP(pm_interpolated_symbol_node_create(parser, &opening, &parts, &parser->previous));
16117 if (!label_allowed) pm_parser_err_node(parser, node, PM_ERR_UNEXPECTED_LABEL);
16118 } else if (match1(parser, PM_TOKEN_EOF)) {
16119 pm_parser_err_token(parser, &opening, PM_ERR_STRING_INTERPOLATED_TERM);
16120 node = UP(pm_interpolated_string_node_create(parser, &opening, &parts, &parser->current));
16121 } else {
16122 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_STRING_INTERPOLATED_TERM);
16123 node = UP(pm_interpolated_string_node_create(parser, &opening, &parts, &parser->previous));
16124 }
16125
16126 pm_node_list_free(&parts);
16127 }
16128
16129 if (current == NULL) {
16130 // If the node we just parsed is a symbol node, then we can't
16131 // concatenate it with anything else, so we can now return that
16132 // node.
16133 if (PM_NODE_TYPE_P(node, PM_SYMBOL_NODE) || PM_NODE_TYPE_P(node, PM_INTERPOLATED_SYMBOL_NODE)) {
16134 return node;
16135 }
16136
16137 // If we don't already have a node, then it's fine and we can just
16138 // set the result to be the node we just parsed.
16139 current = node;
16140 } else {
16141 // Otherwise we need to check the type of the node we just parsed.
16142 // If it cannot be concatenated with the previous node, then we'll
16143 // need to add a syntax error.
16144 if (!PM_NODE_TYPE_P(node, PM_STRING_NODE) && !PM_NODE_TYPE_P(node, PM_INTERPOLATED_STRING_NODE)) {
16145 pm_parser_err_node(parser, node, PM_ERR_STRING_CONCATENATION);
16146 }
16147
16148 // If we haven't already created our container for concatenation,
16149 // we'll do that now.
16150 if (!concating) {
16151 if (!PM_NODE_TYPE_P(current, PM_STRING_NODE) && !PM_NODE_TYPE_P(current, PM_INTERPOLATED_STRING_NODE)) {
16152 pm_parser_err_node(parser, current, PM_ERR_STRING_CONCATENATION);
16153 }
16154
16155 concating = true;
16156 pm_token_t bounds = not_provided(parser);
16157
16158 pm_interpolated_string_node_t *container = pm_interpolated_string_node_create(parser, &bounds, NULL, &bounds);
16159 pm_interpolated_string_node_append(container, current);
16160 current = UP(container);
16161 }
16162
16163 pm_interpolated_string_node_append((pm_interpolated_string_node_t *) current, node);
16164 }
16165 }
16166
16167 return current;
16168 }
16169
16170 #define PM_PARSE_PATTERN_SINGLE 0
16171 #define PM_PARSE_PATTERN_TOP 1
16172 #define PM_PARSE_PATTERN_MULTI 2
16173
16174 static pm_node_t *
16175 parse_pattern(pm_parser_t *parser, pm_constant_id_list_t *captures, uint8_t flags, pm_diagnostic_id_t diag_id, uint16_t depth);
16176
16177 /**
16178 * Add the newly created local to the list of captures for this pattern matching
16179 * expression. If it is duplicated from a previous local, then we'll need to add
16180 * an error to the parser.
16181 */
16182 static void
16183 parse_pattern_capture(pm_parser_t *parser, pm_constant_id_list_t *captures, pm_constant_id_t capture, const pm_location_t *location) {
16184 // Skip this capture if it starts with an underscore.
16185 if (peek_at(parser, location->start) == '_') return;
16186
16187 if (pm_constant_id_list_includes(captures, capture)) {
16188 pm_parser_err(parser, location->start, location->end, PM_ERR_PATTERN_CAPTURE_DUPLICATE);
16189 } else {
16190 pm_constant_id_list_append(captures, capture);
16191 }
16192 }
16193
16194 /**
16195 * Accept any number of constants joined by :: delimiters.
16196 */
16197 static pm_node_t *
16198 parse_pattern_constant_path(pm_parser_t *parser, pm_constant_id_list_t *captures, pm_node_t *node, uint16_t depth) {
16199 // Now, if there are any :: operators that follow, parse them as constant
16200 // path nodes.
16201 while (accept1(parser, PM_TOKEN_COLON_COLON)) {
16202 pm_token_t delimiter = parser->previous;
16203 expect1(parser, PM_TOKEN_CONSTANT, PM_ERR_CONSTANT_PATH_COLON_COLON_CONSTANT);
16204 node = UP(pm_constant_path_node_create(parser, node, &delimiter, &parser->previous));
16205 }
16206
16207 // If there is a [ or ( that follows, then this is part of a larger pattern
16208 // expression. We'll parse the inner pattern here, then modify the returned
16209 // inner pattern with our constant path attached.
16210 if (!match2(parser, PM_TOKEN_BRACKET_LEFT, PM_TOKEN_PARENTHESIS_LEFT)) {
16211 return node;
16212 }
16213
16214 pm_token_t opening;
16215 pm_token_t closing;
16216 pm_node_t *inner = NULL;
16217
16218 if (accept1(parser, PM_TOKEN_BRACKET_LEFT)) {
16219 opening = parser->previous;
16220 accept1(parser, PM_TOKEN_NEWLINE);
16221
16222 if (!accept1(parser, PM_TOKEN_BRACKET_RIGHT)) {
16223 inner = parse_pattern(parser, captures, PM_PARSE_PATTERN_TOP | PM_PARSE_PATTERN_MULTI, PM_ERR_PATTERN_EXPRESSION_AFTER_BRACKET, (uint16_t) (depth + 1));
16224 accept1(parser, PM_TOKEN_NEWLINE);
16225 expect1_opening(parser, PM_TOKEN_BRACKET_RIGHT, PM_ERR_PATTERN_TERM_BRACKET, &opening);
16226 }
16227
16228 closing = parser->previous;
16229 } else {
16230 parser_lex(parser);
16231 opening = parser->previous;
16232 accept1(parser, PM_TOKEN_NEWLINE);
16233
16234 if (!accept1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
16235 inner = parse_pattern(parser, captures, PM_PARSE_PATTERN_TOP | PM_PARSE_PATTERN_MULTI, PM_ERR_PATTERN_EXPRESSION_AFTER_PAREN, (uint16_t) (depth + 1));
16236 accept1(parser, PM_TOKEN_NEWLINE);
16237 expect1_opening(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_PATTERN_TERM_PAREN, &opening);
16238 }
16239
16240 closing = parser->previous;
16241 }
16242
16243 if (!inner) {
16244 // If there was no inner pattern, then we have something like Foo() or
16245 // Foo[]. In that case we'll create an array pattern with no requireds.
16246 return UP(pm_array_pattern_node_constant_create(parser, node, &opening, &closing));
16247 }
16248
16249 // Now that we have the inner pattern, check to see if it's an array, find,
16250 // or hash pattern. If it is, then we'll attach our constant path to it if
16251 // it doesn't already have a constant. If it's not one of those node types
16252 // or it does have a constant, then we'll create an array pattern.
16253 switch (PM_NODE_TYPE(inner)) {
16254 case PM_ARRAY_PATTERN_NODE: {
16255 pm_array_pattern_node_t *pattern_node = (pm_array_pattern_node_t *) inner;
16256
16257 if (pattern_node->constant == NULL && pattern_node->opening_loc.start == NULL) {
16258 pattern_node->base.location.start = node->location.start;
16259 pattern_node->base.location.end = closing.end;
16260
16261 pattern_node->constant = node;
16262 pattern_node->opening_loc = PM_LOCATION_TOKEN_VALUE(&opening);
16263 pattern_node->closing_loc = PM_LOCATION_TOKEN_VALUE(&closing);
16264
16265 return UP(pattern_node);
16266 }
16267
16268 break;
16269 }
16270 case PM_FIND_PATTERN_NODE: {
16271 pm_find_pattern_node_t *pattern_node = (pm_find_pattern_node_t *) inner;
16272
16273 if (pattern_node->constant == NULL && pattern_node->opening_loc.start == NULL) {
16274 pattern_node->base.location.start = node->location.start;
16275 pattern_node->base.location.end = closing.end;
16276
16277 pattern_node->constant = node;
16278 pattern_node->opening_loc = PM_LOCATION_TOKEN_VALUE(&opening);
16279 pattern_node->closing_loc = PM_LOCATION_TOKEN_VALUE(&closing);
16280
16281 return UP(pattern_node);
16282 }
16283
16284 break;
16285 }
16286 case PM_HASH_PATTERN_NODE: {
16287 pm_hash_pattern_node_t *pattern_node = (pm_hash_pattern_node_t *) inner;
16288
16289 if (pattern_node->constant == NULL && pattern_node->opening_loc.start == NULL) {
16290 pattern_node->base.location.start = node->location.start;
16291 pattern_node->base.location.end = closing.end;
16292
16293 pattern_node->constant = node;
16294 pattern_node->opening_loc = PM_LOCATION_TOKEN_VALUE(&opening);
16295 pattern_node->closing_loc = PM_LOCATION_TOKEN_VALUE(&closing);
16296
16297 return UP(pattern_node);
16298 }
16299
16300 break;
16301 }
16302 default:
16303 break;
16304 }
16305
16306 // If we got here, then we didn't return one of the inner patterns by
16307 // attaching its constant. In this case we'll create an array pattern and
16308 // attach our constant to it.
16309 pm_array_pattern_node_t *pattern_node = pm_array_pattern_node_constant_create(parser, node, &opening, &closing);
16310 pm_array_pattern_node_requireds_append(pattern_node, inner);
16311 return UP(pattern_node);
16312 }
16313
16314 /**
16315 * Parse a rest pattern.
16316 */
16317 static pm_splat_node_t *
16318 parse_pattern_rest(pm_parser_t *parser, pm_constant_id_list_t *captures) {
16319 assert(parser->previous.type == PM_TOKEN_USTAR);
16320 pm_token_t operator = parser->previous;
16321 pm_node_t *name = NULL;
16322
16323 // Rest patterns don't necessarily have a name associated with them. So we
16324 // will check for that here. If they do, then we'll add it to the local
16325 // table since this pattern will cause it to become a local variable.
16326 if (accept1(parser, PM_TOKEN_IDENTIFIER)) {
16327 pm_token_t identifier = parser->previous;
16328 pm_constant_id_t constant_id = pm_parser_constant_id_token(parser, &identifier);
16329
16330 int depth;
16331 if ((depth = pm_parser_local_depth_constant_id(parser, constant_id)) == -1) {
16332 pm_parser_local_add(parser, constant_id, identifier.start, identifier.end, 0);
16333 }
16334
16335 parse_pattern_capture(parser, captures, constant_id, &PM_LOCATION_TOKEN_VALUE(&identifier));
16336 name = UP(pm_local_variable_target_node_create(
16337 parser,
16338 &PM_LOCATION_TOKEN_VALUE(&identifier),
16339 constant_id,
16340 (uint32_t) (depth == -1 ? 0 : depth)
16341 ));
16342 }
16343
16344 // Finally we can return the created node.
16345 return pm_splat_node_create(parser, &operator, name);
16346 }
16347
16348 /**
16349 * Parse a keyword rest node.
16350 */
16351 static pm_node_t *
16352 parse_pattern_keyword_rest(pm_parser_t *parser, pm_constant_id_list_t *captures) {
16353 assert(parser->current.type == PM_TOKEN_USTAR_STAR);
16354 parser_lex(parser);
16355
16356 pm_token_t operator = parser->previous;
16357 pm_node_t *value = NULL;
16358
16359 if (accept1(parser, PM_TOKEN_KEYWORD_NIL)) {
16360 return UP(pm_no_keywords_parameter_node_create(parser, &operator, &parser->previous));
16361 }
16362
16363 if (accept1(parser, PM_TOKEN_IDENTIFIER)) {
16364 pm_constant_id_t constant_id = pm_parser_constant_id_token(parser, &parser->previous);
16365
16366 int depth;
16367 if ((depth = pm_parser_local_depth_constant_id(parser, constant_id)) == -1) {
16368 pm_parser_local_add(parser, constant_id, parser->previous.start, parser->previous.end, 0);
16369 }
16370
16371 parse_pattern_capture(parser, captures, constant_id, &PM_LOCATION_TOKEN_VALUE(&parser->previous));
16372 value = UP(pm_local_variable_target_node_create(
16373 parser,
16374 &PM_LOCATION_TOKEN_VALUE(&parser->previous),
16375 constant_id,
16376 (uint32_t) (depth == -1 ? 0 : depth)
16377 ));
16378 }
16379
16380 return UP(pm_assoc_splat_node_create(parser, value, &operator));
16381 }
16382
16383 /**
16384 * Check that the slice of the source given by the bounds parameters constitutes
16385 * a valid local variable name.
16386 */
16387 static bool
16388 pm_slice_is_valid_local(const pm_parser_t *parser, const uint8_t *start, const uint8_t *end) {
16389 ptrdiff_t length = end - start;
16390 if (length == 0) return false;
16391
16392 // First ensure that it starts with a valid identifier starting character.
16393 size_t width = char_is_identifier_start(parser, start, end - start);
16394 if (width == 0) return false;
16395
16396 // Next, ensure that it's not an uppercase character.
16397 if (parser->encoding_changed) {
16398 if (parser->encoding->isupper_char(start, length)) return false;
16399 } else {
16400 if (pm_encoding_utf_8_isupper_char(start, length)) return false;
16401 }
16402
16403 // Next, iterate through all of the bytes of the string to ensure that they
16404 // are all valid identifier characters.
16405 const uint8_t *cursor = start + width;
16406 while ((width = char_is_identifier(parser, cursor, end - cursor))) cursor += width;
16407 return cursor == end;
16408 }
16409
16410 /**
16411 * Create an implicit node for the value of a hash pattern that has omitted the
16412 * value. This will use an implicit local variable target.
16413 */
16414 static pm_node_t *
16415 parse_pattern_hash_implicit_value(pm_parser_t *parser, pm_constant_id_list_t *captures, pm_symbol_node_t *key) {
16416 const pm_location_t *value_loc = &((pm_symbol_node_t *) key)->value_loc;
16417
16418 pm_constant_id_t constant_id = pm_parser_constant_id_location(parser, value_loc->start, value_loc->end);
16419 int depth = -1;
16420
16421 if (pm_slice_is_valid_local(parser, value_loc->start, value_loc->end)) {
16422 depth = pm_parser_local_depth_constant_id(parser, constant_id);
16423 } else {
16424 pm_parser_err(parser, key->base.location.start, key->base.location.end, PM_ERR_PATTERN_HASH_KEY_LOCALS);
16425
16426 if ((value_loc->end > value_loc->start) && ((value_loc->end[-1] == '!') || (value_loc->end[-1] == '?'))) {
16427 PM_PARSER_ERR_LOCATION_FORMAT(parser, value_loc, PM_ERR_INVALID_LOCAL_VARIABLE_WRITE, (int) (value_loc->end - value_loc->start), (const char *) value_loc->start);
16428 }
16429 }
16430
16431 if (depth == -1) {
16432 pm_parser_local_add(parser, constant_id, value_loc->start, value_loc->end, 0);
16433 }
16434
16435 parse_pattern_capture(parser, captures, constant_id, value_loc);
16436 pm_local_variable_target_node_t *target = pm_local_variable_target_node_create(
16437 parser,
16438 value_loc,
16439 constant_id,
16440 (uint32_t) (depth == -1 ? 0 : depth)
16441 );
16442
16443 return UP(pm_implicit_node_create(parser, UP(target)));
16444 }
16445
16446 /**
16447 * Add a node to the list of keys for a hash pattern, and if it is a duplicate
16448 * then add an error to the parser.
16449 */
16450 static void
16451 parse_pattern_hash_key(pm_parser_t *parser, pm_static_literals_t *keys, pm_node_t *node) {
16452 if (pm_static_literals_add(&parser->newline_list, parser->start_line, keys, node, true) != NULL) {
16453 pm_parser_err_node(parser, node, PM_ERR_PATTERN_HASH_KEY_DUPLICATE);
16454 }
16455 }
16456
16457 /**
16458 * Parse a hash pattern.
16459 */
16460 static pm_hash_pattern_node_t *
16461 parse_pattern_hash(pm_parser_t *parser, pm_constant_id_list_t *captures, pm_node_t *first_node, uint16_t depth) {
16462 pm_node_list_t assocs = { 0 };
16463 pm_static_literals_t keys = { 0 };
16464 pm_node_t *rest = NULL;
16465
16466 switch (PM_NODE_TYPE(first_node)) {
16467 case PM_ASSOC_SPLAT_NODE:
16468 case PM_NO_KEYWORDS_PARAMETER_NODE:
16469 rest = first_node;
16470 break;
16471 case PM_SYMBOL_NODE: {
16472 if (pm_symbol_node_label_p(first_node)) {
16473 parse_pattern_hash_key(parser, &keys, first_node);
16474 pm_node_t *value;
16475
16476 if (match8(parser, PM_TOKEN_COMMA, PM_TOKEN_KEYWORD_THEN, PM_TOKEN_BRACE_RIGHT, PM_TOKEN_BRACKET_RIGHT, PM_TOKEN_PARENTHESIS_RIGHT, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON, PM_TOKEN_EOF)) {
16477 // Otherwise, we will create an implicit local variable
16478 // target for the value.
16479 value = parse_pattern_hash_implicit_value(parser, captures, (pm_symbol_node_t *) first_node);
16480 } else {
16481 // Here we have a value for the first assoc in the list, so
16482 // we will parse it now.
16483 value = parse_pattern(parser, captures, PM_PARSE_PATTERN_SINGLE, PM_ERR_PATTERN_EXPRESSION_AFTER_KEY, (uint16_t) (depth + 1));
16484 }
16485
16486 pm_token_t operator = not_provided(parser);
16487 pm_node_t *assoc = UP(pm_assoc_node_create(parser, first_node, &operator, value));
16488
16489 pm_node_list_append(&assocs, assoc);
16490 break;
16491 }
16492 }
16493 PRISM_FALLTHROUGH
16494 default: {
16495 // If we get anything else, then this is an error. For this we'll
16496 // create a missing node for the value and create an assoc node for
16497 // the first node in the list.
16498 pm_diagnostic_id_t diag_id = PM_NODE_TYPE_P(first_node, PM_INTERPOLATED_SYMBOL_NODE) ? PM_ERR_PATTERN_HASH_KEY_INTERPOLATED : PM_ERR_PATTERN_HASH_KEY_LABEL;
16499 pm_parser_err_node(parser, first_node, diag_id);
16500
16501 pm_token_t operator = not_provided(parser);
16502 pm_node_t *value = UP(pm_missing_node_create(parser, first_node->location.start, first_node->location.end));
16503 pm_node_t *assoc = UP(pm_assoc_node_create(parser, first_node, &operator, value));
16504
16505 pm_node_list_append(&assocs, assoc);
16506 break;
16507 }
16508 }
16509
16510 // If there are any other assocs, then we'll parse them now.
16511 while (accept1(parser, PM_TOKEN_COMMA)) {
16512 // Here we need to break to support trailing commas.
16513 if (match7(parser, PM_TOKEN_KEYWORD_THEN, PM_TOKEN_BRACE_RIGHT, PM_TOKEN_BRACKET_RIGHT, PM_TOKEN_PARENTHESIS_RIGHT, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON, PM_TOKEN_EOF)) {
16514 // Trailing commas are not allowed to follow a rest pattern.
16515 if (rest != NULL) {
16516 pm_parser_err_token(parser, &parser->current, PM_ERR_PATTERN_EXPRESSION_AFTER_REST);
16517 }
16518
16519 break;
16520 }
16521
16522 if (match1(parser, PM_TOKEN_USTAR_STAR)) {
16523 pm_node_t *assoc = parse_pattern_keyword_rest(parser, captures);
16524
16525 if (rest == NULL) {
16526 rest = assoc;
16527 } else {
16528 pm_parser_err_node(parser, assoc, PM_ERR_PATTERN_EXPRESSION_AFTER_REST);
16529 pm_node_list_append(&assocs, assoc);
16530 }
16531 } else {
16532 pm_node_t *key;
16533
16534 if (match1(parser, PM_TOKEN_STRING_BEGIN)) {
16535 key = parse_strings(parser, NULL, true, (uint16_t) (depth + 1));
16536
16537 if (PM_NODE_TYPE_P(key, PM_INTERPOLATED_SYMBOL_NODE)) {
16538 pm_parser_err_node(parser, key, PM_ERR_PATTERN_HASH_KEY_INTERPOLATED);
16539 } else if (!pm_symbol_node_label_p(key)) {
16540 pm_parser_err_node(parser, key, PM_ERR_PATTERN_LABEL_AFTER_COMMA);
16541 }
16542 } else {
16543 expect1(parser, PM_TOKEN_LABEL, PM_ERR_PATTERN_LABEL_AFTER_COMMA);
16544 key = UP(pm_symbol_node_label_create(parser, &parser->previous));
16545 }
16546
16547 parse_pattern_hash_key(parser, &keys, key);
16548 pm_node_t *value = NULL;
16549
16550 if (match7(parser, PM_TOKEN_COMMA, PM_TOKEN_KEYWORD_THEN, PM_TOKEN_BRACE_RIGHT, PM_TOKEN_BRACKET_RIGHT, PM_TOKEN_PARENTHESIS_RIGHT, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON)) {
16551 if (PM_NODE_TYPE_P(key, PM_SYMBOL_NODE)) {
16552 value = parse_pattern_hash_implicit_value(parser, captures, (pm_symbol_node_t *) key);
16553 } else {
16554 value = UP(pm_missing_node_create(parser, key->location.end, key->location.end));
16555 }
16556 } else {
16557 value = parse_pattern(parser, captures, PM_PARSE_PATTERN_SINGLE, PM_ERR_PATTERN_EXPRESSION_AFTER_KEY, (uint16_t) (depth + 1));
16558 }
16559
16560 pm_token_t operator = not_provided(parser);
16561 pm_node_t *assoc = UP(pm_assoc_node_create(parser, key, &operator, value));
16562
16563 if (rest != NULL) {
16564 pm_parser_err_node(parser, assoc, PM_ERR_PATTERN_EXPRESSION_AFTER_REST);
16565 }
16566
16567 pm_node_list_append(&assocs, assoc);
16568 }
16569 }
16570
16571 pm_hash_pattern_node_t *node = pm_hash_pattern_node_node_list_create(parser, &assocs, rest);
16572 xfree(assocs.nodes);
16573
16574 pm_static_literals_free(&keys);
16575 return node;
16576 }
16577
16578 /**
16579 * Parse a pattern expression primitive.
16580 */
16581 static pm_node_t *
16582 parse_pattern_primitive(pm_parser_t *parser, pm_constant_id_list_t *captures, pm_diagnostic_id_t diag_id, uint16_t depth) {
16583 switch (parser->current.type) {
16584 case PM_TOKEN_IDENTIFIER:
16585 case PM_TOKEN_METHOD_NAME: {
16586 parser_lex(parser);
16587 pm_constant_id_t constant_id = pm_parser_constant_id_token(parser, &parser->previous);
16588
16589 int depth;
16590 if ((depth = pm_parser_local_depth_constant_id(parser, constant_id)) == -1) {
16591 pm_parser_local_add(parser, constant_id, parser->previous.start, parser->previous.end, 0);
16592 }
16593
16594 parse_pattern_capture(parser, captures, constant_id, &PM_LOCATION_TOKEN_VALUE(&parser->previous));
16595 return UP(pm_local_variable_target_node_create(
16596 parser,
16597 &PM_LOCATION_TOKEN_VALUE(&parser->previous),
16598 constant_id,
16599 (uint32_t) (depth == -1 ? 0 : depth)
16600 ));
16601 }
16602 case PM_TOKEN_BRACKET_LEFT_ARRAY: {
16603 pm_token_t opening = parser->current;
16604 parser_lex(parser);
16605
16606 if (accept1(parser, PM_TOKEN_BRACKET_RIGHT)) {
16607 // If we have an empty array pattern, then we'll just return a new
16608 // array pattern node.
16609 return UP(pm_array_pattern_node_empty_create(parser, &opening, &parser->previous));
16610 }
16611
16612 // Otherwise, we'll parse the inner pattern, then deal with it depending
16613 // on the type it returns.
16614 pm_node_t *inner = parse_pattern(parser, captures, PM_PARSE_PATTERN_MULTI, PM_ERR_PATTERN_EXPRESSION_AFTER_BRACKET, (uint16_t) (depth + 1));
16615
16616 accept1(parser, PM_TOKEN_NEWLINE);
16617 expect1_opening(parser, PM_TOKEN_BRACKET_RIGHT, PM_ERR_PATTERN_TERM_BRACKET, &opening);
16618 pm_token_t closing = parser->previous;
16619
16620 switch (PM_NODE_TYPE(inner)) {
16621 case PM_ARRAY_PATTERN_NODE: {
16622 pm_array_pattern_node_t *pattern_node = (pm_array_pattern_node_t *) inner;
16623 if (pattern_node->opening_loc.start == NULL) {
16624 pattern_node->base.location.start = opening.start;
16625 pattern_node->base.location.end = closing.end;
16626
16627 pattern_node->opening_loc = PM_LOCATION_TOKEN_VALUE(&opening);
16628 pattern_node->closing_loc = PM_LOCATION_TOKEN_VALUE(&closing);
16629
16630 return UP(pattern_node);
16631 }
16632
16633 break;
16634 }
16635 case PM_FIND_PATTERN_NODE: {
16636 pm_find_pattern_node_t *pattern_node = (pm_find_pattern_node_t *) inner;
16637 if (pattern_node->opening_loc.start == NULL) {
16638 pattern_node->base.location.start = opening.start;
16639 pattern_node->base.location.end = closing.end;
16640
16641 pattern_node->opening_loc = PM_LOCATION_TOKEN_VALUE(&opening);
16642 pattern_node->closing_loc = PM_LOCATION_TOKEN_VALUE(&closing);
16643
16644 return UP(pattern_node);
16645 }
16646
16647 break;
16648 }
16649 default:
16650 break;
16651 }
16652
16653 pm_array_pattern_node_t *node = pm_array_pattern_node_empty_create(parser, &opening, &closing);
16654 pm_array_pattern_node_requireds_append(node, inner);
16655 return UP(node);
16656 }
16657 case PM_TOKEN_BRACE_LEFT: {
16658 bool previous_pattern_matching_newlines = parser->pattern_matching_newlines;
16659 parser->pattern_matching_newlines = false;
16660
16661 pm_hash_pattern_node_t *node;
16662 pm_token_t opening = parser->current;
16663 parser_lex(parser);
16664
16665 if (accept1(parser, PM_TOKEN_BRACE_RIGHT)) {
16666 // If we have an empty hash pattern, then we'll just return a new hash
16667 // pattern node.
16668 node = pm_hash_pattern_node_empty_create(parser, &opening, &parser->previous);
16669 } else {
16670 pm_node_t *first_node;
16671
16672 switch (parser->current.type) {
16673 case PM_TOKEN_LABEL:
16674 parser_lex(parser);
16675 first_node = UP(pm_symbol_node_label_create(parser, &parser->previous));
16676 break;
16677 case PM_TOKEN_USTAR_STAR:
16678 first_node = parse_pattern_keyword_rest(parser, captures);
16679 break;
16680 case PM_TOKEN_STRING_BEGIN:
16681 first_node = parse_expression(parser, PM_BINDING_POWER_MAX, false, true, PM_ERR_PATTERN_HASH_KEY_LABEL, (uint16_t) (depth + 1));
16682 break;
16683 default: {
16684 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_PATTERN_HASH_KEY, pm_token_type_human(parser->current.type));
16685 parser_lex(parser);
16686
16687 first_node = UP(pm_missing_node_create(parser, parser->previous.start, parser->previous.end));
16688 break;
16689 }
16690 }
16691
16692 node = parse_pattern_hash(parser, captures, first_node, (uint16_t) (depth + 1));
16693
16694 accept1(parser, PM_TOKEN_NEWLINE);
16695 expect1_opening(parser, PM_TOKEN_BRACE_RIGHT, PM_ERR_PATTERN_TERM_BRACE, &opening);
16696 pm_token_t closing = parser->previous;
16697
16698 node->base.location.start = opening.start;
16699 node->base.location.end = closing.end;
16700
16701 node->opening_loc = PM_LOCATION_TOKEN_VALUE(&opening);
16702 node->closing_loc = PM_LOCATION_TOKEN_VALUE(&closing);
16703 }
16704
16705 parser->pattern_matching_newlines = previous_pattern_matching_newlines;
16706 return UP(node);
16707 }
16708 case PM_TOKEN_UDOT_DOT:
16709 case PM_TOKEN_UDOT_DOT_DOT: {
16710 pm_token_t operator = parser->current;
16711 parser_lex(parser);
16712
16713 // Since we have a unary range operator, we need to parse the subsequent
16714 // expression as the right side of the range.
16715 switch (parser->current.type) {
16716 case PM_CASE_PRIMITIVE: {
16717 pm_node_t *right = parse_expression(parser, PM_BINDING_POWER_MAX, false, false, PM_ERR_PATTERN_EXPRESSION_AFTER_RANGE, (uint16_t) (depth + 1));
16718 return UP(pm_range_node_create(parser, NULL, &operator, right));
16719 }
16720 default: {
16721 pm_parser_err_token(parser, &operator, PM_ERR_PATTERN_EXPRESSION_AFTER_RANGE);
16722 pm_node_t *right = UP(pm_missing_node_create(parser, operator.start, operator.end));
16723 return UP(pm_range_node_create(parser, NULL, &operator, right));
16724 }
16725 }
16726 }
16727 case PM_CASE_PRIMITIVE: {
16728 pm_node_t *node = parse_expression(parser, PM_BINDING_POWER_MAX, false, true, diag_id, (uint16_t) (depth + 1));
16729
16730 // If we found a label, we need to immediately return to the caller.
16731 if (pm_symbol_node_label_p(node)) return node;
16732
16733 // Call nodes (arithmetic operations) are not allowed in patterns
16734 if (PM_NODE_TYPE(node) == PM_CALL_NODE) {
16735 pm_parser_err_node(parser, node, diag_id);
16736 pm_missing_node_t *missing_node = pm_missing_node_create(parser, node->location.start, node->location.end);
16737
16738 pm_node_unreference(parser, node);
16739 pm_node_destroy(parser, node);
16740 return UP(missing_node);
16741 }
16742
16743 // Now that we have a primitive, we need to check if it's part of a range.
16744 if (accept2(parser, PM_TOKEN_DOT_DOT, PM_TOKEN_DOT_DOT_DOT)) {
16745 pm_token_t operator = parser->previous;
16746
16747 // Now that we have the operator, we need to check if this is followed
16748 // by another expression. If it is, then we will create a full range
16749 // node. Otherwise, we'll create an endless range.
16750 switch (parser->current.type) {
16751 case PM_CASE_PRIMITIVE: {
16752 pm_node_t *right = parse_expression(parser, PM_BINDING_POWER_MAX, false, false, PM_ERR_PATTERN_EXPRESSION_AFTER_RANGE, (uint16_t) (depth + 1));
16753 return UP(pm_range_node_create(parser, node, &operator, right));
16754 }
16755 default:
16756 return UP(pm_range_node_create(parser, node, &operator, NULL));
16757 }
16758 }
16759
16760 return node;
16761 }
16762 case PM_TOKEN_CARET: {
16763 parser_lex(parser);
16764 pm_token_t operator = parser->previous;
16765
16766 // At this point we have a pin operator. We need to check the subsequent
16767 // expression to determine if it's a variable or an expression.
16768 switch (parser->current.type) {
16769 case PM_TOKEN_IDENTIFIER: {
16770 parser_lex(parser);
16771 pm_node_t *variable = UP(parse_variable(parser));
16772
16773 if (variable == NULL) {
16774 PM_PARSER_ERR_TOKEN_FORMAT_CONTENT(parser, parser->previous, PM_ERR_NO_LOCAL_VARIABLE);
16775 variable = UP(pm_local_variable_read_node_missing_create(parser, &parser->previous, 0));
16776 }
16777
16778 return UP(pm_pinned_variable_node_create(parser, &operator, variable));
16779 }
16780 case PM_TOKEN_INSTANCE_VARIABLE: {
16781 parser_lex(parser);
16782 pm_node_t *variable = UP(pm_instance_variable_read_node_create(parser, &parser->previous));
16783
16784 return UP(pm_pinned_variable_node_create(parser, &operator, variable));
16785 }
16786 case PM_TOKEN_CLASS_VARIABLE: {
16787 parser_lex(parser);
16788 pm_node_t *variable = UP(pm_class_variable_read_node_create(parser, &parser->previous));
16789
16790 return UP(pm_pinned_variable_node_create(parser, &operator, variable));
16791 }
16792 case PM_TOKEN_GLOBAL_VARIABLE: {
16793 parser_lex(parser);
16794 pm_node_t *variable = UP(pm_global_variable_read_node_create(parser, &parser->previous));
16795
16796 return UP(pm_pinned_variable_node_create(parser, &operator, variable));
16797 }
16798 case PM_TOKEN_NUMBERED_REFERENCE: {
16799 parser_lex(parser);
16800 pm_node_t *variable = UP(pm_numbered_reference_read_node_create(parser, &parser->previous));
16801
16802 return UP(pm_pinned_variable_node_create(parser, &operator, variable));
16803 }
16804 case PM_TOKEN_BACK_REFERENCE: {
16805 parser_lex(parser);
16806 pm_node_t *variable = UP(pm_back_reference_read_node_create(parser, &parser->previous));
16807
16808 return UP(pm_pinned_variable_node_create(parser, &operator, variable));
16809 }
16810 case PM_TOKEN_PARENTHESIS_LEFT: {
16811 bool previous_pattern_matching_newlines = parser->pattern_matching_newlines;
16812 parser->pattern_matching_newlines = false;
16813
16814 pm_token_t lparen = parser->current;
16815 parser_lex(parser);
16816
16817 pm_node_t *expression = parse_value_expression(parser, PM_BINDING_POWER_STATEMENT, true, false, PM_ERR_PATTERN_EXPRESSION_AFTER_PIN, (uint16_t) (depth + 1));
16818 parser->pattern_matching_newlines = previous_pattern_matching_newlines;
16819
16820 accept1(parser, PM_TOKEN_NEWLINE);
16821 expect1_opening(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_PATTERN_TERM_PAREN, &lparen);
16822 return UP(pm_pinned_expression_node_create(parser, expression, &operator, &lparen, &parser->previous));
16823 }
16824 default: {
16825 // If we get here, then we have a pin operator followed by something
16826 // not understood. We'll create a missing node and return that.
16827 pm_parser_err_token(parser, &operator, PM_ERR_PATTERN_EXPRESSION_AFTER_PIN);
16828 pm_node_t *variable = UP(pm_missing_node_create(parser, operator.start, operator.end));
16829 return UP(pm_pinned_variable_node_create(parser, &operator, variable));
16830 }
16831 }
16832 }
16833 case PM_TOKEN_UCOLON_COLON: {
16834 pm_token_t delimiter = parser->current;
16835 parser_lex(parser);
16836
16837 expect1(parser, PM_TOKEN_CONSTANT, PM_ERR_CONSTANT_PATH_COLON_COLON_CONSTANT);
16838 pm_constant_path_node_t *node = pm_constant_path_node_create(parser, NULL, &delimiter, &parser->previous);
16839
16840 return parse_pattern_constant_path(parser, captures, UP(node), (uint16_t) (depth + 1));
16841 }
16842 case PM_TOKEN_CONSTANT: {
16843 pm_token_t constant = parser->current;
16844 parser_lex(parser);
16845
16846 pm_node_t *node = UP(pm_constant_read_node_create(parser, &constant));
16847 return parse_pattern_constant_path(parser, captures, node, (uint16_t) (depth + 1));
16848 }
16849 default:
16850 pm_parser_err_current(parser, diag_id);
16851 return UP(pm_missing_node_create(parser, parser->current.start, parser->current.end));
16852 }
16853 }
16854
16855 static bool
16856 parse_pattern_alternation_error_each(const pm_node_t *node, void *data) {
16857 switch (PM_NODE_TYPE(node)) {
16858 case PM_LOCAL_VARIABLE_TARGET_NODE:
16859 pm_parser_err((pm_parser_t *) data, node->location.start, node->location.end, PM_ERR_PATTERN_CAPTURE_IN_ALTERNATIVE);
16860 return false;
16861 default:
16862 return true;
16863 }
16864 }
16865
16866 /**
16867 * When we get here, we know that we already have a syntax error, because we
16868 * know we have captured a variable and that we are in an alternation.
16869 */
16870 static void
16871 parse_pattern_alternation_error(pm_parser_t *parser, const pm_node_t *node) {
16872 pm_visit_node(node, parse_pattern_alternation_error_each, parser);
16873 }
16874
16875 /**
16876 * Parse any number of primitives joined by alternation and ended optionally by
16877 * assignment.
16878 */
16879 static pm_node_t *
16880 parse_pattern_primitives(pm_parser_t *parser, pm_constant_id_list_t *captures, pm_node_t *first_node, pm_diagnostic_id_t diag_id, uint16_t depth) {
16881 pm_node_t *node = first_node;
16882 bool alternation = false;
16883
16884 while ((node == NULL) || (alternation = accept1(parser, PM_TOKEN_PIPE))) {
16885 if (alternation && !PM_NODE_TYPE_P(node, PM_ALTERNATION_PATTERN_NODE) && captures->size) {
16886 parse_pattern_alternation_error(parser, node);
16887 }
16888
16889 switch (parser->current.type) {
16890 case PM_TOKEN_IDENTIFIER:
16891 case PM_TOKEN_BRACKET_LEFT_ARRAY:
16892 case PM_TOKEN_BRACE_LEFT:
16893 case PM_TOKEN_CARET:
16894 case PM_TOKEN_CONSTANT:
16895 case PM_TOKEN_UCOLON_COLON:
16896 case PM_TOKEN_UDOT_DOT:
16897 case PM_TOKEN_UDOT_DOT_DOT:
16898 case PM_CASE_PRIMITIVE: {
16899 if (!alternation) {
16900 node = parse_pattern_primitive(parser, captures, diag_id, (uint16_t) (depth + 1));
16901 } else {
16902 pm_token_t operator = parser->previous;
16903 pm_node_t *right = parse_pattern_primitive(parser, captures, PM_ERR_PATTERN_EXPRESSION_AFTER_PIPE, (uint16_t) (depth + 1));
16904
16905 if (captures->size) parse_pattern_alternation_error(parser, right);
16906 node = UP(pm_alternation_pattern_node_create(parser, node, right, &operator));
16907 }
16908
16909 break;
16910 }
16911 case PM_TOKEN_PARENTHESIS_LEFT:
16912 case PM_TOKEN_PARENTHESIS_LEFT_PARENTHESES: {
16913 pm_token_t operator = parser->previous;
16914 pm_token_t opening = parser->current;
16915 parser_lex(parser);
16916
16917 pm_node_t *body = parse_pattern(parser, captures, PM_PARSE_PATTERN_SINGLE, PM_ERR_PATTERN_EXPRESSION_AFTER_PAREN, (uint16_t) (depth + 1));
16918 accept1(parser, PM_TOKEN_NEWLINE);
16919 expect1_opening(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_PATTERN_TERM_PAREN, &opening);
16920 pm_node_t *right = UP(pm_parentheses_node_create(parser, &opening, body, &parser->previous, 0));
16921
16922 if (!alternation) {
16923 node = right;
16924 } else {
16925 if (captures->size) parse_pattern_alternation_error(parser, right);
16926 node = UP(pm_alternation_pattern_node_create(parser, node, right, &operator));
16927 }
16928
16929 break;
16930 }
16931 default: {
16932 pm_parser_err_current(parser, diag_id);
16933 pm_node_t *right = UP(pm_missing_node_create(parser, parser->current.start, parser->current.end));
16934
16935 if (!alternation) {
16936 node = right;
16937 } else {
16938 if (captures->size) parse_pattern_alternation_error(parser, right);
16939 node = UP(pm_alternation_pattern_node_create(parser, node, right, &parser->previous));
16940 }
16941
16942 break;
16943 }
16944 }
16945 }
16946
16947 // If we have an =>, then we are assigning this pattern to a variable.
16948 // In this case we should create an assignment node.
16949 while (accept1(parser, PM_TOKEN_EQUAL_GREATER)) {
16950 pm_token_t operator = parser->previous;
16951 expect1(parser, PM_TOKEN_IDENTIFIER, PM_ERR_PATTERN_IDENT_AFTER_HROCKET);
16952
16953 pm_constant_id_t constant_id = pm_parser_constant_id_token(parser, &parser->previous);
16954 int depth;
16955
16956 if ((depth = pm_parser_local_depth_constant_id(parser, constant_id)) == -1) {
16957 pm_parser_local_add(parser, constant_id, parser->previous.start, parser->previous.end, 0);
16958 }
16959
16960 parse_pattern_capture(parser, captures, constant_id, &PM_LOCATION_TOKEN_VALUE(&parser->previous));
16961 pm_local_variable_target_node_t *target = pm_local_variable_target_node_create(
16962 parser,
16963 &PM_LOCATION_TOKEN_VALUE(&parser->previous),
16964 constant_id,
16965 (uint32_t) (depth == -1 ? 0 : depth)
16966 );
16967
16968 node = UP(pm_capture_pattern_node_create(parser, node, target, &operator));
16969 }
16970
16971 return node;
16972 }
16973
16974 /**
16975 * Parse a pattern matching expression.
16976 */
16977 static pm_node_t *
16978 parse_pattern(pm_parser_t *parser, pm_constant_id_list_t *captures, uint8_t flags, pm_diagnostic_id_t diag_id, uint16_t depth) {
16979 pm_node_t *node = NULL;
16980
16981 bool leading_rest = false;
16982 bool trailing_rest = false;
16983
16984 switch (parser->current.type) {
16985 case PM_TOKEN_LABEL: {
16986 parser_lex(parser);
16987 pm_node_t *key = UP(pm_symbol_node_label_create(parser, &parser->previous));
16988 node = UP(parse_pattern_hash(parser, captures, key, (uint16_t) (depth + 1)));
16989
16990 if (!(flags & PM_PARSE_PATTERN_TOP)) {
16991 pm_parser_err_node(parser, node, PM_ERR_PATTERN_HASH_IMPLICIT);
16992 }
16993
16994 return node;
16995 }
16996 case PM_TOKEN_USTAR_STAR: {
16997 node = parse_pattern_keyword_rest(parser, captures);
16998 node = UP(parse_pattern_hash(parser, captures, node, (uint16_t) (depth + 1)));
16999
17000 if (!(flags & PM_PARSE_PATTERN_TOP)) {
17001 pm_parser_err_node(parser, node, PM_ERR_PATTERN_HASH_IMPLICIT);
17002 }
17003
17004 return node;
17005 }
17006 case PM_TOKEN_STRING_BEGIN: {
17007 // We need special handling for string beginnings because they could
17008 // be dynamic symbols leading to hash patterns.
17009 node = parse_pattern_primitive(parser, captures, diag_id, (uint16_t) (depth + 1));
17010
17011 if (pm_symbol_node_label_p(node)) {
17012 node = UP(parse_pattern_hash(parser, captures, node, (uint16_t) (depth + 1)));
17013
17014 if (!(flags & PM_PARSE_PATTERN_TOP)) {
17015 pm_parser_err_node(parser, node, PM_ERR_PATTERN_HASH_IMPLICIT);
17016 }
17017
17018 return node;
17019 }
17020
17021 node = parse_pattern_primitives(parser, captures, node, diag_id, (uint16_t) (depth + 1));
17022 break;
17023 }
17024 case PM_TOKEN_USTAR: {
17025 if (flags & (PM_PARSE_PATTERN_TOP | PM_PARSE_PATTERN_MULTI)) {
17026 parser_lex(parser);
17027 node = UP(parse_pattern_rest(parser, captures));
17028 leading_rest = true;
17029 break;
17030 }
17031 }
17032 PRISM_FALLTHROUGH
17033 default:
17034 node = parse_pattern_primitives(parser, captures, NULL, diag_id, (uint16_t) (depth + 1));
17035 break;
17036 }
17037
17038 // If we got a dynamic label symbol, then we need to treat it like the
17039 // beginning of a hash pattern.
17040 if (pm_symbol_node_label_p(node)) {
17041 return UP(parse_pattern_hash(parser, captures, node, (uint16_t) (depth + 1)));
17042 }
17043
17044 if ((flags & PM_PARSE_PATTERN_MULTI) && match1(parser, PM_TOKEN_COMMA)) {
17045 // If we have a comma, then we are now parsing either an array pattern
17046 // or a find pattern. We need to parse all of the patterns, put them
17047 // into a big list, and then determine which type of node we have.
17048 pm_node_list_t nodes = { 0 };
17049 pm_node_list_append(&nodes, node);
17050
17051 // Gather up all of the patterns into the list.
17052 while (accept1(parser, PM_TOKEN_COMMA)) {
17053 // Break early here in case we have a trailing comma.
17054 if (match7(parser, PM_TOKEN_KEYWORD_THEN, PM_TOKEN_BRACE_RIGHT, PM_TOKEN_BRACKET_RIGHT, PM_TOKEN_PARENTHESIS_RIGHT, PM_TOKEN_SEMICOLON, PM_TOKEN_KEYWORD_AND, PM_TOKEN_KEYWORD_OR)) {
17055 node = UP(pm_implicit_rest_node_create(parser, &parser->previous));
17056 pm_node_list_append(&nodes, node);
17057 trailing_rest = true;
17058 break;
17059 }
17060
17061 if (accept1(parser, PM_TOKEN_USTAR)) {
17062 node = UP(parse_pattern_rest(parser, captures));
17063
17064 // If we have already parsed a splat pattern, then this is an
17065 // error. We will continue to parse the rest of the patterns,
17066 // but we will indicate it as an error.
17067 if (trailing_rest) {
17068 pm_parser_err_previous(parser, PM_ERR_PATTERN_REST);
17069 }
17070
17071 trailing_rest = true;
17072 } else {
17073 node = parse_pattern_primitives(parser, captures, NULL, PM_ERR_PATTERN_EXPRESSION_AFTER_COMMA, (uint16_t) (depth + 1));
17074 }
17075
17076 pm_node_list_append(&nodes, node);
17077 }
17078
17079 // If the first pattern and the last pattern are rest patterns, then we
17080 // will call this a find pattern, regardless of how many rest patterns
17081 // are in between because we know we already added the appropriate
17082 // errors. Otherwise we will create an array pattern.
17083 if (leading_rest && PM_NODE_TYPE_P(nodes.nodes[nodes.size - 1], PM_SPLAT_NODE)) {
17084 node = UP(pm_find_pattern_node_create(parser, &nodes));
17085
17086 if (nodes.size == 2) {
17087 pm_parser_err_node(parser, node, PM_ERR_PATTERN_FIND_MISSING_INNER);
17088 }
17089 } else {
17090 node = UP(pm_array_pattern_node_node_list_create(parser, &nodes));
17091
17092 if (leading_rest && trailing_rest) {
17093 pm_parser_err_node(parser, node, PM_ERR_PATTERN_ARRAY_MULTIPLE_RESTS);
17094 }
17095 }
17096
17097 xfree(nodes.nodes);
17098 } else if (leading_rest) {
17099 // Otherwise, if we parsed a single splat pattern, then we know we have
17100 // an array pattern, so we can go ahead and create that node.
17101 node = UP(pm_array_pattern_node_rest_create(parser, node));
17102 }
17103
17104 return node;
17105 }
17106
17107 /**
17108 * Incorporate a negative sign into a numeric node by subtracting 1 character
17109 * from its start bounds. If it's a compound node, then we will recursively
17110 * apply this function to its value.
17111 */
17112 static inline void
17113 parse_negative_numeric(pm_node_t *node) {
17114 switch (PM_NODE_TYPE(node)) {
17115 case PM_INTEGER_NODE: {
17116 pm_integer_node_t *cast = (pm_integer_node_t *) node;
17117 cast->base.location.start--;
17118 cast->value.negative = true;
17119 break;
17120 }
17121 case PM_FLOAT_NODE: {
17122 pm_float_node_t *cast = (pm_float_node_t *) node;
17123 cast->base.location.start--;
17124 cast->value = -cast->value;
17125 break;
17126 }
17127 case PM_RATIONAL_NODE: {
17128 pm_rational_node_t *cast = (pm_rational_node_t *) node;
17129 cast->base.location.start--;
17130 cast->numerator.negative = true;
17131 break;
17132 }
17133 case PM_IMAGINARY_NODE:
17134 node->location.start--;
17135 parse_negative_numeric(((pm_imaginary_node_t *) node)->numeric);
17136 break;
17137 default:
17138 assert(false && "unreachable");
17139 break;
17140 }
17141 }
17142
17143 /**
17144 * Append an error to the error list on the parser using the given diagnostic
17145 * ID. This function is a specialization that handles formatting the specific
17146 * kind of error that is being appended.
17147 */
17148 static void
17149 pm_parser_err_prefix(pm_parser_t *parser, pm_diagnostic_id_t diag_id) {
17150 switch (diag_id) {
17151 case PM_ERR_HASH_KEY: {
17152 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->previous, diag_id, pm_token_type_human(parser->previous.type));
17153 break;
17154 }
17155 case PM_ERR_HASH_VALUE:
17156 case PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR: {
17157 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, diag_id, pm_token_type_human(parser->current.type));
17158 break;
17159 }
17160 case PM_ERR_UNARY_RECEIVER: {
17161 const char *human = (parser->current.type == PM_TOKEN_EOF ? "end-of-input" : pm_token_type_human(parser->current.type));
17162 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->previous, diag_id, human, parser->previous.start[0]);
17163 break;
17164 }
17165 case PM_ERR_UNARY_DISALLOWED:
17166 case PM_ERR_EXPECT_ARGUMENT: {
17167 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, diag_id, pm_token_type_human(parser->current.type));
17168 break;
17169 }
17170 default:
17171 pm_parser_err_previous(parser, diag_id);
17172 break;
17173 }
17174 }
17175
17176 /**
17177 * Ensures that the current retry token is valid in the current context.
17178 */
17179 static void
17180 parse_retry(pm_parser_t *parser, const pm_node_t *node) {
17181 #define CONTEXT_NONE 0
17182 #define CONTEXT_THROUGH_ENSURE 1
17183 #define CONTEXT_THROUGH_ELSE 2
17184
17185 pm_context_node_t *context_node = parser->current_context;
17186 int context = CONTEXT_NONE;
17187
17188 while (context_node != NULL) {
17189 switch (context_node->context) {
17190 case PM_CONTEXT_BEGIN_RESCUE:
17191 case PM_CONTEXT_BLOCK_RESCUE:
17192 case PM_CONTEXT_CLASS_RESCUE:
17193 case PM_CONTEXT_DEF_RESCUE:
17194 case PM_CONTEXT_LAMBDA_RESCUE:
17195 case PM_CONTEXT_MODULE_RESCUE:
17196 case PM_CONTEXT_SCLASS_RESCUE:
17197 case PM_CONTEXT_DEFINED:
17198 case PM_CONTEXT_RESCUE_MODIFIER:
17199 // These are the good cases. We're allowed to have a retry here.
17200 return;
17201 case PM_CONTEXT_CLASS:
17202 case PM_CONTEXT_DEF:
17203 case PM_CONTEXT_DEF_PARAMS:
17204 case PM_CONTEXT_MAIN:
17205 case PM_CONTEXT_MODULE:
17206 case PM_CONTEXT_PREEXE:
17207 case PM_CONTEXT_SCLASS:
17208 // These are the bad cases. We're not allowed to have a retry in
17209 // these contexts.
17210 if (context == CONTEXT_NONE) {
17211 pm_parser_err_node(parser, node, PM_ERR_INVALID_RETRY_WITHOUT_RESCUE);
17212 } else if (context == CONTEXT_THROUGH_ENSURE) {
17213 pm_parser_err_node(parser, node, PM_ERR_INVALID_RETRY_AFTER_ENSURE);
17214 } else if (context == CONTEXT_THROUGH_ELSE) {
17215 pm_parser_err_node(parser, node, PM_ERR_INVALID_RETRY_AFTER_ELSE);
17216 }
17217 return;
17218 case PM_CONTEXT_BEGIN_ELSE:
17219 case PM_CONTEXT_BLOCK_ELSE:
17220 case PM_CONTEXT_CLASS_ELSE:
17221 case PM_CONTEXT_DEF_ELSE:
17222 case PM_CONTEXT_LAMBDA_ELSE:
17223 case PM_CONTEXT_MODULE_ELSE:
17224 case PM_CONTEXT_SCLASS_ELSE:
17225 // These are also bad cases, but with a more specific error
17226 // message indicating the else.
17227 context = CONTEXT_THROUGH_ELSE;
17228 break;
17229 case PM_CONTEXT_BEGIN_ENSURE:
17230 case PM_CONTEXT_BLOCK_ENSURE:
17231 case PM_CONTEXT_CLASS_ENSURE:
17232 case PM_CONTEXT_DEF_ENSURE:
17233 case PM_CONTEXT_LAMBDA_ENSURE:
17234 case PM_CONTEXT_MODULE_ENSURE:
17235 case PM_CONTEXT_SCLASS_ENSURE:
17236 // These are also bad cases, but with a more specific error
17237 // message indicating the ensure.
17238 context = CONTEXT_THROUGH_ENSURE;
17239 break;
17240 case PM_CONTEXT_NONE:
17241 // This case should never happen.
17242 assert(false && "unreachable");
17243 break;
17244 case PM_CONTEXT_BEGIN:
17245 case PM_CONTEXT_BLOCK_BRACES:
17246 case PM_CONTEXT_BLOCK_KEYWORDS:
17247 case PM_CONTEXT_BLOCK_PARAMETERS:
17248 case PM_CONTEXT_CASE_IN:
17249 case PM_CONTEXT_CASE_WHEN:
17250 case PM_CONTEXT_DEFAULT_PARAMS:
17251 case PM_CONTEXT_ELSE:
17252 case PM_CONTEXT_ELSIF:
17253 case PM_CONTEXT_EMBEXPR:
17254 case PM_CONTEXT_FOR_INDEX:
17255 case PM_CONTEXT_FOR:
17256 case PM_CONTEXT_IF:
17257 case PM_CONTEXT_LAMBDA_BRACES:
17258 case PM_CONTEXT_LAMBDA_DO_END:
17259 case PM_CONTEXT_LOOP_PREDICATE:
17260 case PM_CONTEXT_MULTI_TARGET:
17261 case PM_CONTEXT_PARENS:
17262 case PM_CONTEXT_POSTEXE:
17263 case PM_CONTEXT_PREDICATE:
17264 case PM_CONTEXT_TERNARY:
17265 case PM_CONTEXT_UNLESS:
17266 case PM_CONTEXT_UNTIL:
17267 case PM_CONTEXT_WHILE:
17268 // In these contexts we should continue walking up the list of
17269 // contexts.
17270 break;
17271 }
17272
17273 context_node = context_node->prev;
17274 }
17275
17276 #undef CONTEXT_NONE
17277 #undef CONTEXT_ENSURE
17278 #undef CONTEXT_ELSE
17279 }
17280
17281 /**
17282 * Ensures that the current yield token is valid in the current context.
17283 */
17284 static void
17285 parse_yield(pm_parser_t *parser, const pm_node_t *node) {
17286 pm_context_node_t *context_node = parser->current_context;
17287
17288 while (context_node != NULL) {
17289 switch (context_node->context) {
17290 case PM_CONTEXT_DEF:
17291 case PM_CONTEXT_DEF_PARAMS:
17292 case PM_CONTEXT_DEFINED:
17293 case PM_CONTEXT_DEF_ENSURE:
17294 case PM_CONTEXT_DEF_RESCUE:
17295 case PM_CONTEXT_DEF_ELSE:
17296 // These are the good cases. We're allowed to have a block exit
17297 // in these contexts.
17298 return;
17299 case PM_CONTEXT_CLASS:
17300 case PM_CONTEXT_CLASS_ENSURE:
17301 case PM_CONTEXT_CLASS_RESCUE:
17302 case PM_CONTEXT_CLASS_ELSE:
17303 case PM_CONTEXT_MAIN:
17304 case PM_CONTEXT_MODULE:
17305 case PM_CONTEXT_MODULE_ENSURE:
17306 case PM_CONTEXT_MODULE_RESCUE:
17307 case PM_CONTEXT_MODULE_ELSE:
17308 case PM_CONTEXT_SCLASS:
17309 case PM_CONTEXT_SCLASS_RESCUE:
17310 case PM_CONTEXT_SCLASS_ENSURE:
17311 case PM_CONTEXT_SCLASS_ELSE:
17312 // These are the bad cases. We're not allowed to have a retry in
17313 // these contexts.
17314 pm_parser_err_node(parser, node, PM_ERR_INVALID_YIELD);
17315 return;
17316 case PM_CONTEXT_NONE:
17317 // This case should never happen.
17318 assert(false && "unreachable");
17319 break;
17320 case PM_CONTEXT_BEGIN:
17321 case PM_CONTEXT_BEGIN_ELSE:
17322 case PM_CONTEXT_BEGIN_ENSURE:
17323 case PM_CONTEXT_BEGIN_RESCUE:
17324 case PM_CONTEXT_BLOCK_BRACES:
17325 case PM_CONTEXT_BLOCK_KEYWORDS:
17326 case PM_CONTEXT_BLOCK_ELSE:
17327 case PM_CONTEXT_BLOCK_ENSURE:
17328 case PM_CONTEXT_BLOCK_PARAMETERS:
17329 case PM_CONTEXT_BLOCK_RESCUE:
17330 case PM_CONTEXT_CASE_IN:
17331 case PM_CONTEXT_CASE_WHEN:
17332 case PM_CONTEXT_DEFAULT_PARAMS:
17333 case PM_CONTEXT_ELSE:
17334 case PM_CONTEXT_ELSIF:
17335 case PM_CONTEXT_EMBEXPR:
17336 case PM_CONTEXT_FOR_INDEX:
17337 case PM_CONTEXT_FOR:
17338 case PM_CONTEXT_IF:
17339 case PM_CONTEXT_LAMBDA_BRACES:
17340 case PM_CONTEXT_LAMBDA_DO_END:
17341 case PM_CONTEXT_LAMBDA_ELSE:
17342 case PM_CONTEXT_LAMBDA_ENSURE:
17343 case PM_CONTEXT_LAMBDA_RESCUE:
17344 case PM_CONTEXT_LOOP_PREDICATE:
17345 case PM_CONTEXT_MULTI_TARGET:
17346 case PM_CONTEXT_PARENS:
17347 case PM_CONTEXT_POSTEXE:
17348 case PM_CONTEXT_PREDICATE:
17349 case PM_CONTEXT_PREEXE:
17350 case PM_CONTEXT_RESCUE_MODIFIER:
17351 case PM_CONTEXT_TERNARY:
17352 case PM_CONTEXT_UNLESS:
17353 case PM_CONTEXT_UNTIL:
17354 case PM_CONTEXT_WHILE:
17355 // In these contexts we should continue walking up the list of
17356 // contexts.
17357 break;
17358 }
17359
17360 context_node = context_node->prev;
17361 }
17362 }
17363
17364 /**
17365 * This struct is used to pass information between the regular expression parser
17366 * and the error callback.
17367 */
17368 typedef struct {
17369 /** The parser that we are parsing the regular expression for. */
17370 pm_parser_t *parser;
17371
17372 /** The start of the regular expression. */
17373 const uint8_t *start;
17374
17375 /** The end of the regular expression. */
17376 const uint8_t *end;
17377
17378 /**
17379 * Whether or not the source of the regular expression is shared. This
17380 * impacts the location of error messages, because if it is shared then we
17381 * can use the location directly and if it is not, then we use the bounds of
17382 * the regular expression itself.
17383 */
17384 bool shared;
17385 } parse_regular_expression_error_data_t;
17386
17387 /**
17388 * This callback is called when the regular expression parser encounters a
17389 * syntax error.
17390 */
17391 static void
17392 parse_regular_expression_error(const uint8_t *start, const uint8_t *end, const char *message, void *data) {
17393 parse_regular_expression_error_data_t *callback_data = (parse_regular_expression_error_data_t *) data;
17394 pm_location_t location;
17395
17396 if (callback_data->shared) {
17397 location = (pm_location_t) { .start = start, .end = end };
17398 } else {
17399 location = (pm_location_t) { .start = callback_data->start, .end = callback_data->end };
17400 }
17401
17402 PM_PARSER_ERR_FORMAT(callback_data->parser, location.start, location.end, PM_ERR_REGEXP_PARSE_ERROR, message);
17403 }
17404
17405 /**
17406 * Parse the errors for the regular expression and add them to the parser.
17407 */
17408 static void
17409 parse_regular_expression_errors(pm_parser_t *parser, pm_regular_expression_node_t *node) {
17410 const pm_string_t *unescaped = &node->unescaped;
17411 parse_regular_expression_error_data_t error_data = {
17412 .parser = parser,
17413 .start = node->base.location.start,
17414 .end = node->base.location.end,
17415 .shared = unescaped->type == PM_STRING_SHARED
17416 };
17417
17418 pm_regexp_parse(parser, pm_string_source(unescaped), pm_string_length(unescaped), PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_EXTENDED), NULL, NULL, parse_regular_expression_error, &error_data);
17419 }
17420
17421 /**
17422 * Parse an expression that begins with the previous node that we just lexed.
17423 */
17424 static inline pm_node_t *
17425 parse_expression_prefix(pm_parser_t *parser, pm_binding_power_t binding_power, bool accepts_command_call, bool accepts_label, pm_diagnostic_id_t diag_id, uint16_t depth) {
17426 switch (parser->current.type) {
17427 case PM_TOKEN_BRACKET_LEFT_ARRAY: {
17428 parser_lex(parser);
17429
17430 pm_array_node_t *array = pm_array_node_create(parser, &parser->previous);
17431 pm_accepts_block_stack_push(parser, true);
17432 bool parsed_bare_hash = false;
17433
17434 while (!match2(parser, PM_TOKEN_BRACKET_RIGHT, PM_TOKEN_EOF)) {
17435 bool accepted_newline = accept1(parser, PM_TOKEN_NEWLINE);
17436
17437 // Handle the case where we don't have a comma and we have a
17438 // newline followed by a right bracket.
17439 if (accepted_newline && match1(parser, PM_TOKEN_BRACKET_RIGHT)) {
17440 break;
17441 }
17442
17443 // Ensure that we have a comma between elements in the array.
17444 if (array->elements.size > 0) {
17445 if (accept1(parser, PM_TOKEN_COMMA)) {
17446 // If there was a comma but we also accepts a newline,
17447 // then this is a syntax error.
17448 if (accepted_newline) {
17449 pm_parser_err_previous(parser, PM_ERR_INVALID_COMMA);
17450 }
17451 } else {
17452 // If there was no comma, then we need to add a syntax
17453 // error.
17454 const uint8_t *location = parser->previous.end;
17455 PM_PARSER_ERR_FORMAT(parser, location, location, PM_ERR_ARRAY_SEPARATOR, pm_token_type_human(parser->current.type));
17456
17457 parser->previous.start = location;
17458 parser->previous.type = PM_TOKEN_MISSING;
17459 }
17460 }
17461
17462 // If we have a right bracket immediately following a comma,
17463 // this is allowed since it's a trailing comma. In this case we
17464 // can break out of the loop.
17465 if (match1(parser, PM_TOKEN_BRACKET_RIGHT)) break;
17466
17467 pm_node_t *element;
17468
17469 if (accept1(parser, PM_TOKEN_USTAR)) {
17470 pm_token_t operator = parser->previous;
17471 pm_node_t *expression = NULL;
17472
17473 if (match3(parser, PM_TOKEN_BRACKET_RIGHT, PM_TOKEN_COMMA, PM_TOKEN_EOF)) {
17474 pm_parser_scope_forwarding_positionals_check(parser, &operator);
17475 } else {
17476 expression = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_ARRAY_EXPRESSION_AFTER_STAR, (uint16_t) (depth + 1));
17477 }
17478
17479 element = UP(pm_splat_node_create(parser, &operator, expression));
17480 } else if (match2(parser, PM_TOKEN_LABEL, PM_TOKEN_USTAR_STAR)) {
17481 if (parsed_bare_hash) {
17482 pm_parser_err_current(parser, PM_ERR_EXPRESSION_BARE_HASH);
17483 }
17484
17485 element = UP(pm_keyword_hash_node_create(parser));
17486 pm_static_literals_t hash_keys = { 0 };
17487
17488 if (!match8(parser, PM_TOKEN_EOF, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON, PM_TOKEN_EOF, PM_TOKEN_BRACE_RIGHT, PM_TOKEN_BRACKET_RIGHT, PM_TOKEN_KEYWORD_DO, PM_TOKEN_PARENTHESIS_RIGHT)) {
17489 parse_assocs(parser, &hash_keys, element, (uint16_t) (depth + 1));
17490 }
17491
17492 pm_static_literals_free(&hash_keys);
17493 parsed_bare_hash = true;
17494 } else {
17495 element = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, true, PM_ERR_ARRAY_EXPRESSION, (uint16_t) (depth + 1));
17496
17497 if (pm_symbol_node_label_p(element) || accept1(parser, PM_TOKEN_EQUAL_GREATER)) {
17498 if (parsed_bare_hash) {
17499 pm_parser_err_previous(parser, PM_ERR_EXPRESSION_BARE_HASH);
17500 }
17501
17502 pm_keyword_hash_node_t *hash = pm_keyword_hash_node_create(parser);
17503 pm_static_literals_t hash_keys = { 0 };
17504 pm_hash_key_static_literals_add(parser, &hash_keys, element);
17505
17506 pm_token_t operator;
17507 if (parser->previous.type == PM_TOKEN_EQUAL_GREATER) {
17508 operator = parser->previous;
17509 } else {
17510 operator = not_provided(parser);
17511 }
17512
17513 pm_node_t *value = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_HASH_VALUE, (uint16_t) (depth + 1));
17514 pm_node_t *assoc = UP(pm_assoc_node_create(parser, element, &operator, value));
17515 pm_keyword_hash_node_elements_append(hash, assoc);
17516
17517 element = UP(hash);
17518 if (accept1(parser, PM_TOKEN_COMMA) && !match1(parser, PM_TOKEN_BRACKET_RIGHT)) {
17519 parse_assocs(parser, &hash_keys, element, (uint16_t) (depth + 1));
17520 }
17521
17522 pm_static_literals_free(&hash_keys);
17523 parsed_bare_hash = true;
17524 }
17525 }
17526
17527 pm_array_node_elements_append(array, element);
17528 if (PM_NODE_TYPE_P(element, PM_MISSING_NODE)) break;
17529 }
17530
17531 accept1(parser, PM_TOKEN_NEWLINE);
17532
17533 if (!accept1(parser, PM_TOKEN_BRACKET_RIGHT)) {
17534 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_ARRAY_TERM, pm_token_type_human(parser->current.type));
17535 parser->previous.start = parser->previous.end;
17536 parser->previous.type = PM_TOKEN_MISSING;
17537 }
17538
17539 pm_array_node_close_set(array, &parser->previous);
17540 pm_accepts_block_stack_pop(parser);
17541
17542 return UP(array);
17543 }
17544 case PM_TOKEN_PARENTHESIS_LEFT:
17545 case PM_TOKEN_PARENTHESIS_LEFT_PARENTHESES: {
17546 pm_token_t opening = parser->current;
17547 pm_node_flags_t flags = 0;
17548
17549 pm_node_list_t current_block_exits = { 0 };
17550 pm_node_list_t *previous_block_exits = push_block_exits(parser, &current_block_exits);
17551
17552 parser_lex(parser);
17553 while (true) {
17554 if (accept1(parser, PM_TOKEN_SEMICOLON)) {
17555 flags |= PM_PARENTHESES_NODE_FLAGS_MULTIPLE_STATEMENTS;
17556 } else if (!accept1(parser, PM_TOKEN_NEWLINE)) {
17557 break;
17558 }
17559 }
17560
17561 // If this is the end of the file or we match a right parenthesis, then
17562 // we have an empty parentheses node, and we can immediately return.
17563 if (match2(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_TOKEN_EOF)) {
17564 expect1(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_EXPECT_RPAREN);
17565
17566 pop_block_exits(parser, previous_block_exits);
17567 pm_node_list_free(&current_block_exits);
17568
17569 return UP(pm_parentheses_node_create(parser, &opening, NULL, &parser->previous, flags));
17570 }
17571
17572 // Otherwise, we're going to parse the first statement in the list
17573 // of statements within the parentheses.
17574 pm_accepts_block_stack_push(parser, true);
17575 context_push(parser, PM_CONTEXT_PARENS);
17576 pm_node_t *statement = parse_expression(parser, PM_BINDING_POWER_STATEMENT, true, false, PM_ERR_CANNOT_PARSE_EXPRESSION, (uint16_t) (depth + 1));
17577 context_pop(parser);
17578
17579 // Determine if this statement is followed by a terminator. In the
17580 // case of a single statement, this is fine. But in the case of
17581 // multiple statements it's required.
17582 bool terminator_found = false;
17583
17584 if (accept1(parser, PM_TOKEN_SEMICOLON)) {
17585 terminator_found = true;
17586 flags |= PM_PARENTHESES_NODE_FLAGS_MULTIPLE_STATEMENTS;
17587 } else if (accept1(parser, PM_TOKEN_NEWLINE)) {
17588 terminator_found = true;
17589 }
17590
17591 if (terminator_found) {
17592 while (true) {
17593 if (accept1(parser, PM_TOKEN_SEMICOLON)) {
17594 flags |= PM_PARENTHESES_NODE_FLAGS_MULTIPLE_STATEMENTS;
17595 } else if (!accept1(parser, PM_TOKEN_NEWLINE)) {
17596 break;
17597 }
17598 }
17599 }
17600
17601 // If we hit a right parenthesis, then we're done parsing the
17602 // parentheses node, and we can check which kind of node we should
17603 // return.
17604 if (match1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
17605 if (opening.type == PM_TOKEN_PARENTHESIS_LEFT_PARENTHESES) {
17606 lex_state_set(parser, PM_LEX_STATE_ENDARG);
17607 }
17608
17609 parser_lex(parser);
17610 pm_accepts_block_stack_pop(parser);
17611
17612 pop_block_exits(parser, previous_block_exits);
17613 pm_node_list_free(&current_block_exits);
17614
17615 if (PM_NODE_TYPE_P(statement, PM_MULTI_TARGET_NODE) || PM_NODE_TYPE_P(statement, PM_SPLAT_NODE)) {
17616 // If we have a single statement and are ending on a right
17617 // parenthesis, then we need to check if this is possibly a
17618 // multiple target node.
17619 pm_multi_target_node_t *multi_target;
17620
17621 if (PM_NODE_TYPE_P(statement, PM_MULTI_TARGET_NODE) && ((pm_multi_target_node_t *) statement)->lparen_loc.start == NULL) {
17622 multi_target = (pm_multi_target_node_t *) statement;
17623 } else {
17624 multi_target = pm_multi_target_node_create(parser);
17625 pm_multi_target_node_targets_append(parser, multi_target, statement);
17626 }
17627
17628 pm_location_t lparen_loc = PM_LOCATION_TOKEN_VALUE(&opening);
17629 pm_location_t rparen_loc = PM_LOCATION_TOKEN_VALUE(&parser->previous);
17630
17631 multi_target->lparen_loc = lparen_loc;
17632 multi_target->rparen_loc = rparen_loc;
17633 multi_target->base.location.start = lparen_loc.start;
17634 multi_target->base.location.end = rparen_loc.end;
17635
17636 pm_node_t *result;
17637 if (match1(parser, PM_TOKEN_COMMA) && (binding_power == PM_BINDING_POWER_STATEMENT)) {
17638 result = parse_targets(parser, UP(multi_target), PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
17639 accept1(parser, PM_TOKEN_NEWLINE);
17640 } else {
17641 result = UP(multi_target);
17642 }
17643
17644 if (context_p(parser, PM_CONTEXT_MULTI_TARGET)) {
17645 // All set, this is explicitly allowed by the parent
17646 // context.
17647 } else if (context_p(parser, PM_CONTEXT_FOR_INDEX) && match1(parser, PM_TOKEN_KEYWORD_IN)) {
17648 // All set, we're inside a for loop and we're parsing
17649 // multiple targets.
17650 } else if (binding_power != PM_BINDING_POWER_STATEMENT) {
17651 // Multi targets are not allowed when it's not a
17652 // statement level.
17653 pm_parser_err_node(parser, result, PM_ERR_WRITE_TARGET_UNEXPECTED);
17654 } else if (!match2(parser, PM_TOKEN_EQUAL, PM_TOKEN_PARENTHESIS_RIGHT)) {
17655 // Multi targets must be followed by an equal sign in
17656 // order to be valid (or a right parenthesis if they are
17657 // nested).
17658 pm_parser_err_node(parser, result, PM_ERR_WRITE_TARGET_UNEXPECTED);
17659 }
17660
17661 return result;
17662 }
17663
17664 // If we have a single statement and are ending on a right parenthesis
17665 // and we didn't return a multiple assignment node, then we can return a
17666 // regular parentheses node now.
17667 pm_statements_node_t *statements = pm_statements_node_create(parser);
17668 pm_statements_node_body_append(parser, statements, statement, true);
17669
17670 return UP(pm_parentheses_node_create(parser, &opening, UP(statements), &parser->previous, flags));
17671 }
17672
17673 // If we have more than one statement in the set of parentheses,
17674 // then we are going to parse all of them as a list of statements.
17675 // We'll do that here.
17676 context_push(parser, PM_CONTEXT_PARENS);
17677 flags |= PM_PARENTHESES_NODE_FLAGS_MULTIPLE_STATEMENTS;
17678
17679 pm_statements_node_t *statements = pm_statements_node_create(parser);
17680 pm_statements_node_body_append(parser, statements, statement, true);
17681
17682 // If we didn't find a terminator and we didn't find a right
17683 // parenthesis, then this is a syntax error.
17684 if (!terminator_found && !match1(parser, PM_TOKEN_EOF)) {
17685 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_EXPECT_EOL_AFTER_STATEMENT, pm_token_type_human(parser->current.type));
17686 }
17687
17688 // Parse each statement within the parentheses.
17689 while (true) {
17690 pm_node_t *node = parse_expression(parser, PM_BINDING_POWER_STATEMENT, true, false, PM_ERR_CANNOT_PARSE_EXPRESSION, (uint16_t) (depth + 1));
17691 pm_statements_node_body_append(parser, statements, node, true);
17692
17693 // If we're recovering from a syntax error, then we need to stop
17694 // parsing the statements now.
17695 if (parser->recovering) {
17696 // If this is the level of context where the recovery has
17697 // happened, then we can mark the parser as done recovering.
17698 if (match1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) parser->recovering = false;
17699 break;
17700 }
17701
17702 // If we couldn't parse an expression at all, then we need to
17703 // bail out of the loop.
17704 if (PM_NODE_TYPE_P(node, PM_MISSING_NODE)) break;
17705
17706 // If we successfully parsed a statement, then we are going to
17707 // need terminator to delimit them.
17708 if (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON)) {
17709 while (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON));
17710 if (match1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) break;
17711 } else if (match1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
17712 break;
17713 } else if (!match1(parser, PM_TOKEN_EOF)) {
17714 // If we're at the end of the file, then we're going to add
17715 // an error after this for the ) anyway.
17716 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_EXPECT_EOL_AFTER_STATEMENT, pm_token_type_human(parser->current.type));
17717 }
17718 }
17719
17720 context_pop(parser);
17721 pm_accepts_block_stack_pop(parser);
17722 expect1(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_EXPECT_RPAREN);
17723
17724 // When we're parsing multi targets, we allow them to be followed by
17725 // a right parenthesis if they are at the statement level. This is
17726 // only possible if they are the final statement in a parentheses.
17727 // We need to explicitly reject that here.
17728 {
17729 pm_node_t *statement = statements->body.nodes[statements->body.size - 1];
17730
17731 if (PM_NODE_TYPE_P(statement, PM_SPLAT_NODE)) {
17732 pm_multi_target_node_t *multi_target = pm_multi_target_node_create(parser);
17733 pm_multi_target_node_targets_append(parser, multi_target, statement);
17734
17735 statement = UP(multi_target);
17736 statements->body.nodes[statements->body.size - 1] = statement;
17737 }
17738
17739 if (PM_NODE_TYPE_P(statement, PM_MULTI_TARGET_NODE)) {
17740 const uint8_t *offset = statement->location.end;
17741 pm_token_t operator = { .type = PM_TOKEN_EQUAL, .start = offset, .end = offset };
17742 pm_node_t *value = UP(pm_missing_node_create(parser, offset, offset));
17743
17744 statement = UP(pm_multi_write_node_create(parser, (pm_multi_target_node_t *) statement, &operator, value));
17745 statements->body.nodes[statements->body.size - 1] = statement;
17746
17747 pm_parser_err_node(parser, statement, PM_ERR_WRITE_TARGET_UNEXPECTED);
17748 }
17749 }
17750
17751 pop_block_exits(parser, previous_block_exits);
17752 pm_node_list_free(&current_block_exits);
17753
17754 pm_void_statements_check(parser, statements, true);
17755 return UP(pm_parentheses_node_create(parser, &opening, UP(statements), &parser->previous, flags));
17756 }
17757 case PM_TOKEN_BRACE_LEFT: {
17758 // If we were passed a current_hash_keys via the parser, then that
17759 // means we're already parsing a hash and we want to share the set
17760 // of hash keys with this inner hash we're about to parse for the
17761 // sake of warnings. We'll set it to NULL after we grab it to make
17762 // sure subsequent expressions don't use it. Effectively this is a
17763 // way of getting around passing it to every call to
17764 // parse_expression.
17765 pm_static_literals_t *current_hash_keys = parser->current_hash_keys;
17766 parser->current_hash_keys = NULL;
17767
17768 pm_accepts_block_stack_push(parser, true);
17769 parser_lex(parser);
17770
17771 pm_token_t opening = parser->previous;
17772 pm_hash_node_t *node = pm_hash_node_create(parser, &opening);
17773
17774 if (!match2(parser, PM_TOKEN_BRACE_RIGHT, PM_TOKEN_EOF)) {
17775 if (current_hash_keys != NULL) {
17776 parse_assocs(parser, current_hash_keys, UP(node), (uint16_t) (depth + 1));
17777 } else {
17778 pm_static_literals_t hash_keys = { 0 };
17779 parse_assocs(parser, &hash_keys, UP(node), (uint16_t) (depth + 1));
17780 pm_static_literals_free(&hash_keys);
17781 }
17782
17783 accept1(parser, PM_TOKEN_NEWLINE);
17784 }
17785
17786 pm_accepts_block_stack_pop(parser);
17787 expect1_opening(parser, PM_TOKEN_BRACE_RIGHT, PM_ERR_HASH_TERM, &opening);
17788 pm_hash_node_closing_loc_set(node, &parser->previous);
17789
17790 return UP(node);
17791 }
17792 case PM_TOKEN_CHARACTER_LITERAL: {
17793 pm_token_t closing = not_provided(parser);
17794 pm_node_t *node = UP(pm_string_node_create_current_string(
17795 parser,
17796 &(pm_token_t) {
17797 .type = PM_TOKEN_STRING_BEGIN,
17798 .start = parser->current.start,
17799 .end = parser->current.start + 1
17800 },
17801 &(pm_token_t) {
17802 .type = PM_TOKEN_STRING_CONTENT,
17803 .start = parser->current.start + 1,
17804 .end = parser->current.end
17805 },
17806 &closing
17807 ));
17808
17809 pm_node_flag_set(node, parse_unescaped_encoding(parser));
17810
17811 // Skip past the character literal here, since now we have handled
17812 // parser->explicit_encoding correctly.
17813 parser_lex(parser);
17814
17815 // Characters can be followed by strings in which case they are
17816 // automatically concatenated.
17817 if (match1(parser, PM_TOKEN_STRING_BEGIN)) {
17818 return parse_strings(parser, node, false, (uint16_t) (depth + 1));
17819 }
17820
17821 return node;
17822 }
17823 case PM_TOKEN_CLASS_VARIABLE: {
17824 parser_lex(parser);
17825 pm_node_t *node = UP(pm_class_variable_read_node_create(parser, &parser->previous));
17826
17827 if (binding_power == PM_BINDING_POWER_STATEMENT && match1(parser, PM_TOKEN_COMMA)) {
17828 node = parse_targets_validate(parser, node, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
17829 }
17830
17831 return node;
17832 }
17833 case PM_TOKEN_CONSTANT: {
17834 parser_lex(parser);
17835 pm_token_t constant = parser->previous;
17836
17837 // If a constant is immediately followed by parentheses, then this is in
17838 // fact a method call, not a constant read.
17839 if (
17840 match1(parser, PM_TOKEN_PARENTHESIS_LEFT) ||
17841 (accepts_command_call && (token_begins_expression_p(parser->current.type) || match3(parser, PM_TOKEN_UAMPERSAND, PM_TOKEN_USTAR, PM_TOKEN_USTAR_STAR))) ||
17842 (pm_accepts_block_stack_p(parser) && match1(parser, PM_TOKEN_KEYWORD_DO)) ||
17843 match1(parser, PM_TOKEN_BRACE_LEFT)
17844 ) {
17845 pm_arguments_t arguments = { 0 };
17846 parse_arguments_list(parser, &arguments, true, accepts_command_call, (uint16_t) (depth + 1));
17847 return UP(pm_call_node_fcall_create(parser, &constant, &arguments));
17848 }
17849
17850 pm_node_t *node = UP(pm_constant_read_node_create(parser, &parser->previous));
17851
17852 if ((binding_power == PM_BINDING_POWER_STATEMENT) && match1(parser, PM_TOKEN_COMMA)) {
17853 // If we get here, then we have a comma immediately following a
17854 // constant, so we're going to parse this as a multiple assignment.
17855 node = parse_targets_validate(parser, node, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
17856 }
17857
17858 return node;
17859 }
17860 case PM_TOKEN_UCOLON_COLON: {
17861 parser_lex(parser);
17862 pm_token_t delimiter = parser->previous;
17863
17864 expect1(parser, PM_TOKEN_CONSTANT, PM_ERR_CONSTANT_PATH_COLON_COLON_CONSTANT);
17865 pm_node_t *node = UP(pm_constant_path_node_create(parser, NULL, &delimiter, &parser->previous));
17866
17867 if ((binding_power == PM_BINDING_POWER_STATEMENT) && match1(parser, PM_TOKEN_COMMA)) {
17868 node = parse_targets_validate(parser, node, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
17869 }
17870
17871 return node;
17872 }
17873 case PM_TOKEN_UDOT_DOT:
17874 case PM_TOKEN_UDOT_DOT_DOT: {
17875 pm_token_t operator = parser->current;
17876 parser_lex(parser);
17877
17878 pm_node_t *right = parse_expression(parser, pm_binding_powers[operator.type].left, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
17879
17880 // Unary .. and ... are special because these are non-associative
17881 // operators that can also be unary operators. In this case we need
17882 // to explicitly reject code that has a .. or ... that follows this
17883 // expression.
17884 if (match2(parser, PM_TOKEN_DOT_DOT, PM_TOKEN_DOT_DOT_DOT)) {
17885 pm_parser_err_current(parser, PM_ERR_UNEXPECTED_RANGE_OPERATOR);
17886 }
17887
17888 return UP(pm_range_node_create(parser, NULL, &operator, right));
17889 }
17890 case PM_TOKEN_FLOAT:
17891 parser_lex(parser);
17892 return UP(pm_float_node_create(parser, &parser->previous));
17893 case PM_TOKEN_FLOAT_IMAGINARY:
17894 parser_lex(parser);
17895 return UP(pm_float_node_imaginary_create(parser, &parser->previous));
17896 case PM_TOKEN_FLOAT_RATIONAL:
17897 parser_lex(parser);
17898 return UP(pm_float_node_rational_create(parser, &parser->previous));
17899 case PM_TOKEN_FLOAT_RATIONAL_IMAGINARY:
17900 parser_lex(parser);
17901 return UP(pm_float_node_rational_imaginary_create(parser, &parser->previous));
17902 case PM_TOKEN_NUMBERED_REFERENCE: {
17903 parser_lex(parser);
17904 pm_node_t *node = UP(pm_numbered_reference_read_node_create(parser, &parser->previous));
17905
17906 if (binding_power == PM_BINDING_POWER_STATEMENT && match1(parser, PM_TOKEN_COMMA)) {
17907 node = parse_targets_validate(parser, node, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
17908 }
17909
17910 return node;
17911 }
17912 case PM_TOKEN_GLOBAL_VARIABLE: {
17913 parser_lex(parser);
17914 pm_node_t *node = UP(pm_global_variable_read_node_create(parser, &parser->previous));
17915
17916 if (binding_power == PM_BINDING_POWER_STATEMENT && match1(parser, PM_TOKEN_COMMA)) {
17917 node = parse_targets_validate(parser, node, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
17918 }
17919
17920 return node;
17921 }
17922 case PM_TOKEN_BACK_REFERENCE: {
17923 parser_lex(parser);
17924 pm_node_t *node = UP(pm_back_reference_read_node_create(parser, &parser->previous));
17925
17926 if (binding_power == PM_BINDING_POWER_STATEMENT && match1(parser, PM_TOKEN_COMMA)) {
17927 node = parse_targets_validate(parser, node, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
17928 }
17929
17930 return node;
17931 }
17932 case PM_TOKEN_IDENTIFIER:
17933 case PM_TOKEN_METHOD_NAME: {
17934 parser_lex(parser);
17935 pm_token_t identifier = parser->previous;
17936 pm_node_t *node = parse_variable_call(parser);
17937
17938 if (PM_NODE_TYPE_P(node, PM_CALL_NODE)) {
17939 // If parse_variable_call returned with a call node, then we
17940 // know the identifier is not in the local table. In that case
17941 // we need to check if there are arguments following the
17942 // identifier.
17943 pm_call_node_t *call = (pm_call_node_t *) node;
17944 pm_arguments_t arguments = { 0 };
17945
17946 if (parse_arguments_list(parser, &arguments, true, accepts_command_call, (uint16_t) (depth + 1))) {
17947 // Since we found arguments, we need to turn off the
17948 // variable call bit in the flags.
17949 pm_node_flag_unset(UP(call), PM_CALL_NODE_FLAGS_VARIABLE_CALL);
17950
17951 call->opening_loc = arguments.opening_loc;
17952 call->arguments = arguments.arguments;
17953 call->closing_loc = arguments.closing_loc;
17954 call->block = arguments.block;
17955
17956 const uint8_t *end = pm_arguments_end(&arguments);
17957 if (!end) {
17958 end = call->message_loc.end;
17959 }
17960 call->base.location.end = end;
17961 }
17962 } else {
17963 // Otherwise, we know the identifier is in the local table. This
17964 // can still be a method call if it is followed by arguments or
17965 // a block, so we need to check for that here.
17966 if (
17967 (accepts_command_call && (token_begins_expression_p(parser->current.type) || match3(parser, PM_TOKEN_UAMPERSAND, PM_TOKEN_USTAR, PM_TOKEN_USTAR_STAR))) ||
17968 (pm_accepts_block_stack_p(parser) && match1(parser, PM_TOKEN_KEYWORD_DO)) ||
17969 match1(parser, PM_TOKEN_BRACE_LEFT)
17970 ) {
17971 pm_arguments_t arguments = { 0 };
17972 parse_arguments_list(parser, &arguments, true, accepts_command_call, (uint16_t) (depth + 1));
17973 pm_call_node_t *fcall = pm_call_node_fcall_create(parser, &identifier, &arguments);
17974
17975 if (PM_NODE_TYPE_P(node, PM_IT_LOCAL_VARIABLE_READ_NODE)) {
17976 // If we're about to convert an 'it' implicit local
17977 // variable read into a method call, we need to remove
17978 // it from the list of implicit local variables.
17979 pm_node_unreference(parser, node);
17980 } else {
17981 // Otherwise, we're about to convert a regular local
17982 // variable read into a method call, in which case we
17983 // need to indicate that this was not a read for the
17984 // purposes of warnings.
17985 assert(PM_NODE_TYPE_P(node, PM_LOCAL_VARIABLE_READ_NODE));
17986
17987 if (pm_token_is_numbered_parameter(identifier.start, identifier.end)) {
17988 pm_node_unreference(parser, node);
17989 } else {
17990 pm_local_variable_read_node_t *cast = (pm_local_variable_read_node_t *) node;
17991 pm_locals_unread(&pm_parser_scope_find(parser, cast->depth)->locals, cast->name);
17992 }
17993 }
17994
17995 pm_node_destroy(parser, node);
17996 return UP(fcall);
17997 }
17998 }
17999
18000 if ((binding_power == PM_BINDING_POWER_STATEMENT) && match1(parser, PM_TOKEN_COMMA)) {
18001 node = parse_targets_validate(parser, node, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
18002 }
18003
18004 return node;
18005 }
18006 case PM_TOKEN_HEREDOC_START: {
18007 // Here we have found a heredoc. We'll parse it and add it to the
18008 // list of strings.
18009 assert(parser->lex_modes.current->mode == PM_LEX_HEREDOC);
18010 pm_heredoc_lex_mode_t lex_mode = parser->lex_modes.current->as.heredoc.base;
18011
18012 size_t common_whitespace = (size_t) -1;
18013 parser->lex_modes.current->as.heredoc.common_whitespace = &common_whitespace;
18014
18015 parser_lex(parser);
18016 pm_token_t opening = parser->previous;
18017
18018 pm_node_t *node;
18019 pm_node_t *part;
18020
18021 if (match2(parser, PM_TOKEN_HEREDOC_END, PM_TOKEN_EOF)) {
18022 // If we get here, then we have an empty heredoc. We'll create
18023 // an empty content token and return an empty string node.
18024 expect1_heredoc_term(parser, lex_mode.ident_start, lex_mode.ident_length);
18025 pm_token_t content = parse_strings_empty_content(parser->previous.start);
18026
18027 if (lex_mode.quote == PM_HEREDOC_QUOTE_BACKTICK) {
18028 node = UP(pm_xstring_node_create_unescaped(parser, &opening, &content, &parser->previous, &PM_STRING_EMPTY));
18029 } else {
18030 node = UP(pm_string_node_create_unescaped(parser, &opening, &content, &parser->previous, &PM_STRING_EMPTY));
18031 }
18032
18033 node->location.end = opening.end;
18034 } else if ((part = parse_string_part(parser, (uint16_t) (depth + 1))) == NULL) {
18035 // If we get here, then we tried to find something in the
18036 // heredoc but couldn't actually parse anything, so we'll just
18037 // return a missing node.
18038 //
18039 // parse_string_part handles its own errors, so there is no need
18040 // for us to add one here.
18041 node = UP(pm_missing_node_create(parser, parser->previous.start, parser->previous.end));
18042 } else if (PM_NODE_TYPE_P(part, PM_STRING_NODE) && match2(parser, PM_TOKEN_HEREDOC_END, PM_TOKEN_EOF)) {
18043 // If we get here, then the part that we parsed was plain string
18044 // content and we're at the end of the heredoc, so we can return
18045 // just a string node with the heredoc opening and closing as
18046 // its opening and closing.
18047 pm_node_flag_set(part, parse_unescaped_encoding(parser));
18048 pm_string_node_t *cast = (pm_string_node_t *) part;
18049
18050 cast->opening_loc = PM_LOCATION_TOKEN_VALUE(&opening);
18051 cast->closing_loc = PM_LOCATION_TOKEN_VALUE(&parser->current);
18052 cast->base.location = cast->opening_loc;
18053
18054 if (lex_mode.quote == PM_HEREDOC_QUOTE_BACKTICK) {
18055 assert(sizeof(pm_string_node_t) == sizeof(pm_x_string_node_t));
18056 cast->base.type = PM_X_STRING_NODE;
18057 }
18058
18059 if (lex_mode.indent == PM_HEREDOC_INDENT_TILDE && (common_whitespace != (size_t) -1) && (common_whitespace != 0)) {
18060 parse_heredoc_dedent_string(&cast->unescaped, common_whitespace);
18061 }
18062
18063 node = UP(cast);
18064 expect1_heredoc_term(parser, lex_mode.ident_start, lex_mode.ident_length);
18065 } else {
18066 // If we get here, then we have multiple parts in the heredoc,
18067 // so we'll need to create an interpolated string node to hold
18068 // them all.
18069 pm_node_list_t parts = { 0 };
18070 pm_node_list_append(&parts, part);
18071
18072 while (!match2(parser, PM_TOKEN_HEREDOC_END, PM_TOKEN_EOF)) {
18073 if ((part = parse_string_part(parser, (uint16_t) (depth + 1))) != NULL) {
18074 pm_node_list_append(&parts, part);
18075 }
18076 }
18077
18078 // Now that we have all of the parts, create the correct type of
18079 // interpolated node.
18080 if (lex_mode.quote == PM_HEREDOC_QUOTE_BACKTICK) {
18081 pm_interpolated_x_string_node_t *cast = pm_interpolated_xstring_node_create(parser, &opening, &opening);
18082 cast->parts = parts;
18083
18084 expect1_heredoc_term(parser, lex_mode.ident_start, lex_mode.ident_length);
18085 pm_interpolated_xstring_node_closing_set(cast, &parser->previous);
18086
18087 cast->base.location = cast->opening_loc;
18088 node = UP(cast);
18089 } else {
18090 pm_interpolated_string_node_t *cast = pm_interpolated_string_node_create(parser, &opening, &parts, &opening);
18091 pm_node_list_free(&parts);
18092
18093 expect1_heredoc_term(parser, lex_mode.ident_start, lex_mode.ident_length);
18094 pm_interpolated_string_node_closing_set(cast, &parser->previous);
18095
18096 cast->base.location = cast->opening_loc;
18097 node = UP(cast);
18098 }
18099
18100 // If this is a heredoc that is indented with a ~, then we need
18101 // to dedent each line by the common leading whitespace.
18102 if (lex_mode.indent == PM_HEREDOC_INDENT_TILDE && (common_whitespace != (size_t) -1) && (common_whitespace != 0)) {
18103 pm_node_list_t *nodes;
18104 if (lex_mode.quote == PM_HEREDOC_QUOTE_BACKTICK) {
18105 nodes = &((pm_interpolated_x_string_node_t *) node)->parts;
18106 } else {
18107 nodes = &((pm_interpolated_string_node_t *) node)->parts;
18108 }
18109
18110 parse_heredoc_dedent(parser, nodes, common_whitespace);
18111 }
18112 }
18113
18114 if (match1(parser, PM_TOKEN_STRING_BEGIN)) {
18115 return parse_strings(parser, node, false, (uint16_t) (depth + 1));
18116 }
18117
18118 return node;
18119 }
18120 case PM_TOKEN_INSTANCE_VARIABLE: {
18121 parser_lex(parser);
18122 pm_node_t *node = UP(pm_instance_variable_read_node_create(parser, &parser->previous));
18123
18124 if (binding_power == PM_BINDING_POWER_STATEMENT && match1(parser, PM_TOKEN_COMMA)) {
18125 node = parse_targets_validate(parser, node, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
18126 }
18127
18128 return node;
18129 }
18130 case PM_TOKEN_INTEGER: {
18131 pm_node_flags_t base = parser->integer_base;
18132 parser_lex(parser);
18133 return UP(pm_integer_node_create(parser, base, &parser->previous));
18134 }
18135 case PM_TOKEN_INTEGER_IMAGINARY: {
18136 pm_node_flags_t base = parser->integer_base;
18137 parser_lex(parser);
18138 return UP(pm_integer_node_imaginary_create(parser, base, &parser->previous));
18139 }
18140 case PM_TOKEN_INTEGER_RATIONAL: {
18141 pm_node_flags_t base = parser->integer_base;
18142 parser_lex(parser);
18143 return UP(pm_integer_node_rational_create(parser, base, &parser->previous));
18144 }
18145 case PM_TOKEN_INTEGER_RATIONAL_IMAGINARY: {
18146 pm_node_flags_t base = parser->integer_base;
18147 parser_lex(parser);
18148 return UP(pm_integer_node_rational_imaginary_create(parser, base, &parser->previous));
18149 }
18150 case PM_TOKEN_KEYWORD___ENCODING__:
18151 parser_lex(parser);
18152 return UP(pm_source_encoding_node_create(parser, &parser->previous));
18153 case PM_TOKEN_KEYWORD___FILE__:
18154 parser_lex(parser);
18155 return UP(pm_source_file_node_create(parser, &parser->previous));
18156 case PM_TOKEN_KEYWORD___LINE__:
18157 parser_lex(parser);
18158 return UP(pm_source_line_node_create(parser, &parser->previous));
18159 case PM_TOKEN_KEYWORD_ALIAS: {
18160 if (binding_power != PM_BINDING_POWER_STATEMENT) {
18161 pm_parser_err_current(parser, PM_ERR_STATEMENT_ALIAS);
18162 }
18163
18164 parser_lex(parser);
18165 pm_token_t keyword = parser->previous;
18166
18167 pm_node_t *new_name = parse_alias_argument(parser, true, (uint16_t) (depth + 1));
18168 pm_node_t *old_name = parse_alias_argument(parser, false, (uint16_t) (depth + 1));
18169
18170 switch (PM_NODE_TYPE(new_name)) {
18171 case PM_BACK_REFERENCE_READ_NODE:
18172 case PM_NUMBERED_REFERENCE_READ_NODE:
18173 case PM_GLOBAL_VARIABLE_READ_NODE: {
18174 if (PM_NODE_TYPE_P(old_name, PM_BACK_REFERENCE_READ_NODE) || PM_NODE_TYPE_P(old_name, PM_NUMBERED_REFERENCE_READ_NODE) || PM_NODE_TYPE_P(old_name, PM_GLOBAL_VARIABLE_READ_NODE)) {
18175 if (PM_NODE_TYPE_P(old_name, PM_NUMBERED_REFERENCE_READ_NODE)) {
18176 pm_parser_err_node(parser, old_name, PM_ERR_ALIAS_ARGUMENT_NUMBERED_REFERENCE);
18177 }
18178 } else {
18179 pm_parser_err_node(parser, old_name, PM_ERR_ALIAS_ARGUMENT);
18180 }
18181
18182 return UP(pm_alias_global_variable_node_create(parser, &keyword, new_name, old_name));
18183 }
18184 case PM_SYMBOL_NODE:
18185 case PM_INTERPOLATED_SYMBOL_NODE: {
18186 if (!PM_NODE_TYPE_P(old_name, PM_SYMBOL_NODE) && !PM_NODE_TYPE_P(old_name, PM_INTERPOLATED_SYMBOL_NODE)) {
18187 pm_parser_err_node(parser, old_name, PM_ERR_ALIAS_ARGUMENT);
18188 }
18189 }
18190 PRISM_FALLTHROUGH
18191 default:
18192 return UP(pm_alias_method_node_create(parser, &keyword, new_name, old_name));
18193 }
18194 }
18195 case PM_TOKEN_KEYWORD_CASE: {
18196 size_t opening_newline_index = token_newline_index(parser);
18197 parser_lex(parser);
18198
18199 pm_token_t case_keyword = parser->previous;
18200 pm_node_t *predicate = NULL;
18201
18202 pm_node_list_t current_block_exits = { 0 };
18203 pm_node_list_t *previous_block_exits = push_block_exits(parser, &current_block_exits);
18204
18205 if (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON)) {
18206 while (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON));
18207 predicate = NULL;
18208 } else if (match3(parser, PM_TOKEN_KEYWORD_WHEN, PM_TOKEN_KEYWORD_IN, PM_TOKEN_KEYWORD_END)) {
18209 predicate = NULL;
18210 } else if (!token_begins_expression_p(parser->current.type)) {
18211 predicate = NULL;
18212 } else {
18213 predicate = parse_value_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_CASE_EXPRESSION_AFTER_CASE, (uint16_t) (depth + 1));
18214 while (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON));
18215 }
18216
18217 if (match1(parser, PM_TOKEN_KEYWORD_END)) {
18218 parser_warn_indentation_mismatch(parser, opening_newline_index, &case_keyword, false, false);
18219 parser_lex(parser);
18220
18221 pop_block_exits(parser, previous_block_exits);
18222 pm_node_list_free(&current_block_exits);
18223
18224 pm_parser_err_token(parser, &case_keyword, PM_ERR_CASE_MISSING_CONDITIONS);
18225 return UP(pm_case_node_create(parser, &case_keyword, predicate, &parser->previous));
18226 }
18227
18228 // At this point we can create a case node, though we don't yet know
18229 // if it is a case-in or case-when node.
18230 pm_token_t end_keyword = not_provided(parser);
18231 pm_node_t *node;
18232
18233 if (match1(parser, PM_TOKEN_KEYWORD_WHEN)) {
18234 pm_case_node_t *case_node = pm_case_node_create(parser, &case_keyword, predicate, &end_keyword);
18235 pm_static_literals_t literals = { 0 };
18236
18237 // At this point we've seen a when keyword, so we know this is a
18238 // case-when node. We will continue to parse the when nodes
18239 // until we hit the end of the list.
18240 while (match1(parser, PM_TOKEN_KEYWORD_WHEN)) {
18241 parser_warn_indentation_mismatch(parser, opening_newline_index, &case_keyword, false, true);
18242 parser_lex(parser);
18243
18244 pm_token_t when_keyword = parser->previous;
18245 pm_when_node_t *when_node = pm_when_node_create(parser, &when_keyword);
18246
18247 do {
18248 if (accept1(parser, PM_TOKEN_USTAR)) {
18249 pm_token_t operator = parser->previous;
18250 pm_node_t *expression = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_STAR, (uint16_t) (depth + 1));
18251
18252 pm_splat_node_t *splat_node = pm_splat_node_create(parser, &operator, expression);
18253 pm_when_node_conditions_append(when_node, UP(splat_node));
18254
18255 if (PM_NODE_TYPE_P(expression, PM_MISSING_NODE)) break;
18256 } else {
18257 pm_node_t *condition = parse_value_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_CASE_EXPRESSION_AFTER_WHEN, (uint16_t) (depth + 1));
18258 pm_when_node_conditions_append(when_node, condition);
18259
18260 // If we found a missing node, then this is a syntax
18261 // error and we should stop looping.
18262 if (PM_NODE_TYPE_P(condition, PM_MISSING_NODE)) break;
18263
18264 // If this is a string node, then we need to mark it
18265 // as frozen because when clause strings are frozen.
18266 if (PM_NODE_TYPE_P(condition, PM_STRING_NODE)) {
18267 pm_node_flag_set(condition, PM_STRING_FLAGS_FROZEN | PM_NODE_FLAG_STATIC_LITERAL);
18268 } else if (PM_NODE_TYPE_P(condition, PM_SOURCE_FILE_NODE)) {
18269 pm_node_flag_set(condition, PM_NODE_FLAG_STATIC_LITERAL);
18270 }
18271
18272 pm_when_clause_static_literals_add(parser, &literals, condition);
18273 }
18274 } while (accept1(parser, PM_TOKEN_COMMA));
18275
18276 if (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON)) {
18277 if (accept1(parser, PM_TOKEN_KEYWORD_THEN)) {
18278 pm_when_node_then_keyword_loc_set(when_node, &parser->previous);
18279 }
18280 } else {
18281 expect1(parser, PM_TOKEN_KEYWORD_THEN, PM_ERR_EXPECT_WHEN_DELIMITER);
18282 pm_when_node_then_keyword_loc_set(when_node, &parser->previous);
18283 }
18284
18285 if (!match3(parser, PM_TOKEN_KEYWORD_WHEN, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_KEYWORD_END)) {
18286 pm_statements_node_t *statements = parse_statements(parser, PM_CONTEXT_CASE_WHEN, (uint16_t) (depth + 1));
18287 if (statements != NULL) {
18288 pm_when_node_statements_set(when_node, statements);
18289 }
18290 }
18291
18292 pm_case_node_condition_append(case_node, UP(when_node));
18293 }
18294
18295 // If we didn't parse any conditions (in or when) then we need
18296 // to indicate that we have an error.
18297 if (case_node->conditions.size == 0) {
18298 pm_parser_err_token(parser, &case_keyword, PM_ERR_CASE_MISSING_CONDITIONS);
18299 }
18300
18301 pm_static_literals_free(&literals);
18302 node = UP(case_node);
18303 } else {
18304 pm_case_match_node_t *case_node = pm_case_match_node_create(parser, &case_keyword, predicate, &end_keyword);
18305
18306 // If this is a case-match node (i.e., it is a pattern matching
18307 // case statement) then we must have a predicate.
18308 if (predicate == NULL) {
18309 pm_parser_err_token(parser, &case_keyword, PM_ERR_CASE_MATCH_MISSING_PREDICATE);
18310 }
18311
18312 // At this point we expect that we're parsing a case-in node. We
18313 // will continue to parse the in nodes until we hit the end of
18314 // the list.
18315 while (match1(parser, PM_TOKEN_KEYWORD_IN)) {
18316 parser_warn_indentation_mismatch(parser, opening_newline_index, &case_keyword, false, true);
18317
18318 bool previous_pattern_matching_newlines = parser->pattern_matching_newlines;
18319 parser->pattern_matching_newlines = true;
18320
18321 lex_state_set(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_LABEL);
18322 parser->command_start = false;
18323 parser_lex(parser);
18324
18325 pm_token_t in_keyword = parser->previous;
18326
18327 pm_constant_id_list_t captures = { 0 };
18328 pm_node_t *pattern = parse_pattern(parser, &captures, PM_PARSE_PATTERN_TOP | PM_PARSE_PATTERN_MULTI, PM_ERR_PATTERN_EXPRESSION_AFTER_IN, (uint16_t) (depth + 1));
18329
18330 parser->pattern_matching_newlines = previous_pattern_matching_newlines;
18331 pm_constant_id_list_free(&captures);
18332
18333 // Since we're in the top-level of the case-in node we need
18334 // to check for guard clauses in the form of `if` or
18335 // `unless` statements.
18336 if (accept1(parser, PM_TOKEN_KEYWORD_IF_MODIFIER)) {
18337 pm_token_t keyword = parser->previous;
18338 pm_node_t *predicate = parse_value_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_CONDITIONAL_IF_PREDICATE, (uint16_t) (depth + 1));
18339 pattern = UP(pm_if_node_modifier_create(parser, pattern, &keyword, predicate));
18340 } else if (accept1(parser, PM_TOKEN_KEYWORD_UNLESS_MODIFIER)) {
18341 pm_token_t keyword = parser->previous;
18342 pm_node_t *predicate = parse_value_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_CONDITIONAL_UNLESS_PREDICATE, (uint16_t) (depth + 1));
18343 pattern = UP(pm_unless_node_modifier_create(parser, pattern, &keyword, predicate));
18344 }
18345
18346 // Now we need to check for the terminator of the in node's
18347 // pattern. It can be a newline or semicolon optionally
18348 // followed by a `then` keyword.
18349 pm_token_t then_keyword;
18350 if (accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON)) {
18351 if (accept1(parser, PM_TOKEN_KEYWORD_THEN)) {
18352 then_keyword = parser->previous;
18353 } else {
18354 then_keyword = not_provided(parser);
18355 }
18356 } else {
18357 expect1(parser, PM_TOKEN_KEYWORD_THEN, PM_ERR_EXPECT_IN_DELIMITER);
18358 then_keyword = parser->previous;
18359 }
18360
18361 // Now we can actually parse the statements associated with
18362 // the in node.
18363 pm_statements_node_t *statements;
18364 if (match3(parser, PM_TOKEN_KEYWORD_IN, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_KEYWORD_END)) {
18365 statements = NULL;
18366 } else {
18367 statements = parse_statements(parser, PM_CONTEXT_CASE_IN, (uint16_t) (depth + 1));
18368 }
18369
18370 // Now that we have the full pattern and statements, we can
18371 // create the node and attach it to the case node.
18372 pm_node_t *condition = UP(pm_in_node_create(parser, pattern, statements, &in_keyword, &then_keyword));
18373 pm_case_match_node_condition_append(case_node, condition);
18374 }
18375
18376 // If we didn't parse any conditions (in or when) then we need
18377 // to indicate that we have an error.
18378 if (case_node->conditions.size == 0) {
18379 pm_parser_err_token(parser, &case_keyword, PM_ERR_CASE_MISSING_CONDITIONS);
18380 }
18381
18382 node = UP(case_node);
18383 }
18384
18385 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
18386 if (accept1(parser, PM_TOKEN_KEYWORD_ELSE)) {
18387 pm_token_t else_keyword = parser->previous;
18388 pm_else_node_t *else_node;
18389
18390 if (!match1(parser, PM_TOKEN_KEYWORD_END)) {
18391 else_node = pm_else_node_create(parser, &else_keyword, parse_statements(parser, PM_CONTEXT_ELSE, (uint16_t) (depth + 1)), &parser->current);
18392 } else {
18393 else_node = pm_else_node_create(parser, &else_keyword, NULL, &parser->current);
18394 }
18395
18396 if (PM_NODE_TYPE_P(node, PM_CASE_NODE)) {
18397 pm_case_node_else_clause_set((pm_case_node_t *) node, else_node);
18398 } else {
18399 pm_case_match_node_else_clause_set((pm_case_match_node_t *) node, else_node);
18400 }
18401 }
18402
18403 parser_warn_indentation_mismatch(parser, opening_newline_index, &case_keyword, false, false);
18404 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_CASE_TERM, &case_keyword);
18405
18406 if (PM_NODE_TYPE_P(node, PM_CASE_NODE)) {
18407 pm_case_node_end_keyword_loc_set((pm_case_node_t *) node, &parser->previous);
18408 } else {
18409 pm_case_match_node_end_keyword_loc_set((pm_case_match_node_t *) node, &parser->previous);
18410 }
18411
18412 pop_block_exits(parser, previous_block_exits);
18413 pm_node_list_free(&current_block_exits);
18414
18415 return node;
18416 }
18417 case PM_TOKEN_KEYWORD_BEGIN: {
18418 size_t opening_newline_index = token_newline_index(parser);
18419 parser_lex(parser);
18420
18421 pm_token_t begin_keyword = parser->previous;
18422 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
18423
18424 pm_node_list_t current_block_exits = { 0 };
18425 pm_node_list_t *previous_block_exits = push_block_exits(parser, &current_block_exits);
18426 pm_statements_node_t *begin_statements = NULL;
18427
18428 if (!match4(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_KEYWORD_END)) {
18429 pm_accepts_block_stack_push(parser, true);
18430 begin_statements = parse_statements(parser, PM_CONTEXT_BEGIN, (uint16_t) (depth + 1));
18431 pm_accepts_block_stack_pop(parser);
18432 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
18433 }
18434
18435 pm_begin_node_t *begin_node = pm_begin_node_create(parser, &begin_keyword, begin_statements);
18436 parse_rescues(parser, opening_newline_index, &begin_keyword, begin_node, PM_RESCUES_BEGIN, (uint16_t) (depth + 1));
18437 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_BEGIN_TERM, &begin_keyword);
18438
18439 begin_node->base.location.end = parser->previous.end;
18440 pm_begin_node_end_keyword_set(begin_node, &parser->previous);
18441
18442 pop_block_exits(parser, previous_block_exits);
18443 pm_node_list_free(&current_block_exits);
18444
18445 return UP(begin_node);
18446 }
18447 case PM_TOKEN_KEYWORD_BEGIN_UPCASE: {
18448 pm_node_list_t current_block_exits = { 0 };
18449 pm_node_list_t *previous_block_exits = push_block_exits(parser, &current_block_exits);
18450
18451 if (binding_power != PM_BINDING_POWER_STATEMENT) {
18452 pm_parser_err_current(parser, PM_ERR_STATEMENT_PREEXE_BEGIN);
18453 }
18454
18455 parser_lex(parser);
18456 pm_token_t keyword = parser->previous;
18457
18458 expect1(parser, PM_TOKEN_BRACE_LEFT, PM_ERR_BEGIN_UPCASE_BRACE);
18459 pm_token_t opening = parser->previous;
18460 pm_statements_node_t *statements = parse_statements(parser, PM_CONTEXT_PREEXE, (uint16_t) (depth + 1));
18461
18462 expect1_opening(parser, PM_TOKEN_BRACE_RIGHT, PM_ERR_BEGIN_UPCASE_TERM, &opening);
18463 pm_context_t context = parser->current_context->context;
18464 if ((context != PM_CONTEXT_MAIN) && (context != PM_CONTEXT_PREEXE)) {
18465 pm_parser_err_token(parser, &keyword, PM_ERR_BEGIN_UPCASE_TOPLEVEL);
18466 }
18467
18468 flush_block_exits(parser, previous_block_exits);
18469 pm_node_list_free(&current_block_exits);
18470
18471 return UP(pm_pre_execution_node_create(parser, &keyword, &opening, statements, &parser->previous));
18472 }
18473 case PM_TOKEN_KEYWORD_BREAK:
18474 case PM_TOKEN_KEYWORD_NEXT:
18475 case PM_TOKEN_KEYWORD_RETURN: {
18476 parser_lex(parser);
18477
18478 pm_token_t keyword = parser->previous;
18479 pm_arguments_t arguments = { 0 };
18480
18481 if (
18482 token_begins_expression_p(parser->current.type) ||
18483 match2(parser, PM_TOKEN_USTAR, PM_TOKEN_USTAR_STAR)
18484 ) {
18485 pm_binding_power_t binding_power = pm_binding_powers[parser->current.type].left;
18486
18487 if (binding_power == PM_BINDING_POWER_UNSET || binding_power >= PM_BINDING_POWER_RANGE) {
18488 pm_token_t next = parser->current;
18489 parse_arguments(parser, &arguments, false, PM_TOKEN_EOF, (uint16_t) (depth + 1));
18490
18491 // Reject `foo && return bar`.
18492 if (!accepts_command_call && arguments.arguments != NULL) {
18493 PM_PARSER_ERR_TOKEN_FORMAT(parser, next, PM_ERR_EXPECT_EOL_AFTER_STATEMENT, pm_token_type_human(next.type));
18494 }
18495 }
18496 }
18497
18498 switch (keyword.type) {
18499 case PM_TOKEN_KEYWORD_BREAK: {
18500 pm_node_t *node = UP(pm_break_node_create(parser, &keyword, arguments.arguments));
18501 if (!parser->partial_script) parse_block_exit(parser, node);
18502 return node;
18503 }
18504 case PM_TOKEN_KEYWORD_NEXT: {
18505 pm_node_t *node = UP(pm_next_node_create(parser, &keyword, arguments.arguments));
18506 if (!parser->partial_script) parse_block_exit(parser, node);
18507 return node;
18508 }
18509 case PM_TOKEN_KEYWORD_RETURN: {
18510 pm_node_t *node = UP(pm_return_node_create(parser, &keyword, arguments.arguments));
18511 parse_return(parser, node);
18512 return node;
18513 }
18514 default:
18515 assert(false && "unreachable");
18516 return UP(pm_missing_node_create(parser, parser->previous.start, parser->previous.end));
18517 }
18518 }
18519 case PM_TOKEN_KEYWORD_SUPER: {
18520 parser_lex(parser);
18521
18522 pm_token_t keyword = parser->previous;
18523 pm_arguments_t arguments = { 0 };
18524 parse_arguments_list(parser, &arguments, true, accepts_command_call, (uint16_t) (depth + 1));
18525
18526 if (
18527 arguments.opening_loc.start == NULL &&
18528 arguments.arguments == NULL &&
18529 ((arguments.block == NULL) || PM_NODE_TYPE_P(arguments.block, PM_BLOCK_NODE))
18530 ) {
18531 return UP(pm_forwarding_super_node_create(parser, &keyword, &arguments));
18532 }
18533
18534 return UP(pm_super_node_create(parser, &keyword, &arguments));
18535 }
18536 case PM_TOKEN_KEYWORD_YIELD: {
18537 parser_lex(parser);
18538
18539 pm_token_t keyword = parser->previous;
18540 pm_arguments_t arguments = { 0 };
18541 parse_arguments_list(parser, &arguments, false, accepts_command_call, (uint16_t) (depth + 1));
18542
18543 // It's possible that we've parsed a block argument through our
18544 // call to parse_arguments_list. If we found one, we should mark it
18545 // as invalid and destroy it, as we don't have a place for it on the
18546 // yield node.
18547 if (arguments.block != NULL) {
18548 pm_parser_err_node(parser, arguments.block, PM_ERR_UNEXPECTED_BLOCK_ARGUMENT);
18549 pm_node_unreference(parser, arguments.block);
18550 pm_node_destroy(parser, arguments.block);
18551 arguments.block = NULL;
18552 }
18553
18554 pm_node_t *node = UP(pm_yield_node_create(parser, &keyword, &arguments.opening_loc, arguments.arguments, &arguments.closing_loc));
18555 if (!parser->parsing_eval && !parser->partial_script) parse_yield(parser, node);
18556
18557 return node;
18558 }
18559 case PM_TOKEN_KEYWORD_CLASS: {
18560 size_t opening_newline_index = token_newline_index(parser);
18561 parser_lex(parser);
18562
18563 pm_token_t class_keyword = parser->previous;
18564 pm_do_loop_stack_push(parser, false);
18565
18566 pm_node_list_t current_block_exits = { 0 };
18567 pm_node_list_t *previous_block_exits = push_block_exits(parser, &current_block_exits);
18568
18569 if (accept1(parser, PM_TOKEN_LESS_LESS)) {
18570 pm_token_t operator = parser->previous;
18571 pm_node_t *expression = parse_value_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_EXPECT_EXPRESSION_AFTER_LESS_LESS, (uint16_t) (depth + 1));
18572
18573 pm_parser_scope_push(parser, true);
18574 if (!match2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON)) {
18575 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_EXPECT_SINGLETON_CLASS_DELIMITER, pm_token_type_human(parser->current.type));
18576 }
18577
18578 pm_node_t *statements = NULL;
18579 if (!match4(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_KEYWORD_END)) {
18580 pm_accepts_block_stack_push(parser, true);
18581 statements = UP(parse_statements(parser, PM_CONTEXT_SCLASS, (uint16_t) (depth + 1)));
18582 pm_accepts_block_stack_pop(parser);
18583 }
18584
18585 if (match2(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE)) {
18586 assert(statements == NULL || PM_NODE_TYPE_P(statements, PM_STATEMENTS_NODE));
18587 statements = UP(parse_rescues_implicit_begin(parser, opening_newline_index, &class_keyword, class_keyword.start, (pm_statements_node_t *) statements, PM_RESCUES_SCLASS, (uint16_t) (depth + 1)));
18588 } else {
18589 parser_warn_indentation_mismatch(parser, opening_newline_index, &class_keyword, false, false);
18590 }
18591
18592 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_CLASS_TERM, &class_keyword);
18593
18594 pm_constant_id_list_t locals;
18595 pm_locals_order(parser, &parser->current_scope->locals, &locals, false);
18596
18597 pm_parser_scope_pop(parser);
18598 pm_do_loop_stack_pop(parser);
18599
18600 flush_block_exits(parser, previous_block_exits);
18601 pm_node_list_free(&current_block_exits);
18602
18603 return UP(pm_singleton_class_node_create(parser, &locals, &class_keyword, &operator, expression, statements, &parser->previous));
18604 }
18605
18606 pm_node_t *constant_path = parse_expression(parser, PM_BINDING_POWER_INDEX, false, false, PM_ERR_CLASS_NAME, (uint16_t) (depth + 1));
18607 pm_token_t name = parser->previous;
18608 if (name.type != PM_TOKEN_CONSTANT) {
18609 pm_parser_err_token(parser, &name, PM_ERR_CLASS_NAME);
18610 }
18611
18612 pm_token_t inheritance_operator;
18613 pm_node_t *superclass;
18614
18615 if (match1(parser, PM_TOKEN_LESS)) {
18616 inheritance_operator = parser->current;
18617 lex_state_set(parser, PM_LEX_STATE_BEG);
18618
18619 parser->command_start = true;
18620 parser_lex(parser);
18621
18622 superclass = parse_value_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_CLASS_SUPERCLASS, (uint16_t) (depth + 1));
18623 } else {
18624 inheritance_operator = not_provided(parser);
18625 superclass = NULL;
18626 }
18627
18628 pm_parser_scope_push(parser, true);
18629
18630 if (inheritance_operator.type != PM_TOKEN_NOT_PROVIDED) {
18631 expect2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON, PM_ERR_CLASS_UNEXPECTED_END);
18632 } else {
18633 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
18634 }
18635 pm_node_t *statements = NULL;
18636
18637 if (!match4(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_KEYWORD_END)) {
18638 pm_accepts_block_stack_push(parser, true);
18639 statements = UP(parse_statements(parser, PM_CONTEXT_CLASS, (uint16_t) (depth + 1)));
18640 pm_accepts_block_stack_pop(parser);
18641 }
18642
18643 if (match2(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE)) {
18644 assert(statements == NULL || PM_NODE_TYPE_P(statements, PM_STATEMENTS_NODE));
18645 statements = UP(parse_rescues_implicit_begin(parser, opening_newline_index, &class_keyword, class_keyword.start, (pm_statements_node_t *) statements, PM_RESCUES_CLASS, (uint16_t) (depth + 1)));
18646 } else {
18647 parser_warn_indentation_mismatch(parser, opening_newline_index, &class_keyword, false, false);
18648 }
18649
18650 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_CLASS_TERM, &class_keyword);
18651
18652 if (context_def_p(parser)) {
18653 pm_parser_err_token(parser, &class_keyword, PM_ERR_CLASS_IN_METHOD);
18654 }
18655
18656 pm_constant_id_list_t locals;
18657 pm_locals_order(parser, &parser->current_scope->locals, &locals, false);
18658
18659 pm_parser_scope_pop(parser);
18660 pm_do_loop_stack_pop(parser);
18661
18662 if (!PM_NODE_TYPE_P(constant_path, PM_CONSTANT_PATH_NODE) && !(PM_NODE_TYPE_P(constant_path, PM_CONSTANT_READ_NODE))) {
18663 pm_parser_err_node(parser, constant_path, PM_ERR_CLASS_NAME);
18664 }
18665
18666 pop_block_exits(parser, previous_block_exits);
18667 pm_node_list_free(&current_block_exits);
18668
18669 return UP(pm_class_node_create(parser, &locals, &class_keyword, constant_path, &name, &inheritance_operator, superclass, statements, &parser->previous));
18670 }
18671 case PM_TOKEN_KEYWORD_DEF: {
18672 pm_node_list_t current_block_exits = { 0 };
18673 pm_node_list_t *previous_block_exits = push_block_exits(parser, &current_block_exits);
18674
18675 pm_token_t def_keyword = parser->current;
18676 size_t opening_newline_index = token_newline_index(parser);
18677
18678 pm_node_t *receiver = NULL;
18679 pm_token_t operator = not_provided(parser);
18680 pm_token_t name;
18681
18682 // This context is necessary for lexing `...` in a bare params
18683 // correctly. It must be pushed before lexing the first param, so it
18684 // is here.
18685 context_push(parser, PM_CONTEXT_DEF_PARAMS);
18686 parser_lex(parser);
18687
18688 // This will be false if the method name is not a valid identifier
18689 // but could be followed by an operator.
18690 bool valid_name = true;
18691
18692 switch (parser->current.type) {
18693 case PM_CASE_OPERATOR:
18694 pm_parser_scope_push(parser, true);
18695 lex_state_set(parser, PM_LEX_STATE_ENDFN);
18696 parser_lex(parser);
18697
18698 name = parser->previous;
18699 break;
18700 case PM_TOKEN_IDENTIFIER: {
18701 parser_lex(parser);
18702
18703 if (match2(parser, PM_TOKEN_DOT, PM_TOKEN_COLON_COLON)) {
18704 receiver = parse_variable_call(parser);
18705
18706 pm_parser_scope_push(parser, true);
18707 lex_state_set(parser, PM_LEX_STATE_FNAME);
18708 parser_lex(parser);
18709
18710 operator = parser->previous;
18711 name = parse_method_definition_name(parser);
18712 } else {
18713 pm_refute_numbered_parameter(parser, parser->previous.start, parser->previous.end);
18714 pm_parser_scope_push(parser, true);
18715
18716 name = parser->previous;
18717 }
18718
18719 break;
18720 }
18721 case PM_TOKEN_INSTANCE_VARIABLE:
18722 case PM_TOKEN_CLASS_VARIABLE:
18723 case PM_TOKEN_GLOBAL_VARIABLE:
18724 valid_name = false;
18725 PRISM_FALLTHROUGH
18726 case PM_TOKEN_CONSTANT:
18727 case PM_TOKEN_KEYWORD_NIL:
18728 case PM_TOKEN_KEYWORD_SELF:
18729 case PM_TOKEN_KEYWORD_TRUE:
18730 case PM_TOKEN_KEYWORD_FALSE:
18731 case PM_TOKEN_KEYWORD___FILE__:
18732 case PM_TOKEN_KEYWORD___LINE__:
18733 case PM_TOKEN_KEYWORD___ENCODING__: {
18734 pm_parser_scope_push(parser, true);
18735 parser_lex(parser);
18736
18737 pm_token_t identifier = parser->previous;
18738
18739 if (match2(parser, PM_TOKEN_DOT, PM_TOKEN_COLON_COLON)) {
18740 lex_state_set(parser, PM_LEX_STATE_FNAME);
18741 parser_lex(parser);
18742 operator = parser->previous;
18743
18744 switch (identifier.type) {
18745 case PM_TOKEN_CONSTANT:
18746 receiver = UP(pm_constant_read_node_create(parser, &identifier));
18747 break;
18748 case PM_TOKEN_INSTANCE_VARIABLE:
18749 receiver = UP(pm_instance_variable_read_node_create(parser, &identifier));
18750 break;
18751 case PM_TOKEN_CLASS_VARIABLE:
18752 receiver = UP(pm_class_variable_read_node_create(parser, &identifier));
18753 break;
18754 case PM_TOKEN_GLOBAL_VARIABLE:
18755 receiver = UP(pm_global_variable_read_node_create(parser, &identifier));
18756 break;
18757 case PM_TOKEN_KEYWORD_NIL:
18758 receiver = UP(pm_nil_node_create(parser, &identifier));
18759 break;
18760 case PM_TOKEN_KEYWORD_SELF:
18761 receiver = UP(pm_self_node_create(parser, &identifier));
18762 break;
18763 case PM_TOKEN_KEYWORD_TRUE:
18764 receiver = UP(pm_true_node_create(parser, &identifier));
18765 break;
18766 case PM_TOKEN_KEYWORD_FALSE:
18767 receiver = UP(pm_false_node_create(parser, &identifier));
18768 break;
18769 case PM_TOKEN_KEYWORD___FILE__:
18770 receiver = UP(pm_source_file_node_create(parser, &identifier));
18771 break;
18772 case PM_TOKEN_KEYWORD___LINE__:
18773 receiver = UP(pm_source_line_node_create(parser, &identifier));
18774 break;
18775 case PM_TOKEN_KEYWORD___ENCODING__:
18776 receiver = UP(pm_source_encoding_node_create(parser, &identifier));
18777 break;
18778 default:
18779 break;
18780 }
18781
18782 name = parse_method_definition_name(parser);
18783 } else {
18784 if (!valid_name) {
18785 PM_PARSER_ERR_TOKEN_FORMAT(parser, identifier, PM_ERR_DEF_NAME, pm_token_type_human(identifier.type));
18786 }
18787
18788 name = identifier;
18789 }
18790 break;
18791 }
18792 case PM_TOKEN_PARENTHESIS_LEFT: {
18793 // The current context is `PM_CONTEXT_DEF_PARAMS`, however
18794 // the inner expression of this parenthesis should not be
18795 // processed under this context. Thus, the context is popped
18796 // here.
18797 context_pop(parser);
18798 parser_lex(parser);
18799
18800 pm_token_t lparen = parser->previous;
18801 pm_node_t *expression = parse_value_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_DEF_RECEIVER, (uint16_t) (depth + 1));
18802
18803 accept1(parser, PM_TOKEN_NEWLINE);
18804 expect1(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_EXPECT_RPAREN);
18805 pm_token_t rparen = parser->previous;
18806
18807 lex_state_set(parser, PM_LEX_STATE_FNAME);
18808 expect2(parser, PM_TOKEN_DOT, PM_TOKEN_COLON_COLON, PM_ERR_DEF_RECEIVER_TERM);
18809
18810 operator = parser->previous;
18811 receiver = UP(pm_parentheses_node_create(parser, &lparen, expression, &rparen, 0));
18812
18813 // To push `PM_CONTEXT_DEF_PARAMS` again is for the same
18814 // reason as described the above.
18815 pm_parser_scope_push(parser, true);
18816 context_push(parser, PM_CONTEXT_DEF_PARAMS);
18817 name = parse_method_definition_name(parser);
18818 break;
18819 }
18820 default:
18821 pm_parser_scope_push(parser, true);
18822 name = parse_method_definition_name(parser);
18823 break;
18824 }
18825
18826 pm_token_t lparen;
18827 pm_token_t rparen;
18828 pm_parameters_node_t *params;
18829
18830 bool accept_endless_def = true;
18831 switch (parser->current.type) {
18832 case PM_TOKEN_PARENTHESIS_LEFT: {
18833 parser_lex(parser);
18834 lparen = parser->previous;
18835
18836 if (match1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
18837 params = NULL;
18838 } else {
18839 params = parse_parameters(parser, PM_BINDING_POWER_DEFINED, true, false, true, true, false, (uint16_t) (depth + 1));
18840 }
18841
18842 lex_state_set(parser, PM_LEX_STATE_BEG);
18843 parser->command_start = true;
18844
18845 context_pop(parser);
18846 if (!accept1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
18847 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_DEF_PARAMS_TERM_PAREN, pm_token_type_human(parser->current.type));
18848 parser->previous.start = parser->previous.end;
18849 parser->previous.type = PM_TOKEN_MISSING;
18850 }
18851
18852 rparen = parser->previous;
18853 break;
18854 }
18855 case PM_CASE_PARAMETER: {
18856 // If we're about to lex a label, we need to add the label
18857 // state to make sure the next newline is ignored.
18858 if (parser->current.type == PM_TOKEN_LABEL) {
18859 lex_state_set(parser, parser->lex_state | PM_LEX_STATE_LABEL);
18860 }
18861
18862 lparen = not_provided(parser);
18863 rparen = not_provided(parser);
18864 params = parse_parameters(parser, PM_BINDING_POWER_DEFINED, false, false, true, true, false, (uint16_t) (depth + 1));
18865
18866 // Reject `def * = 1` and similar. We have to specifically check
18867 // for them because they create ambiguity with optional arguments.
18868 accept_endless_def = false;
18869
18870 context_pop(parser);
18871 break;
18872 }
18873 default: {
18874 lparen = not_provided(parser);
18875 rparen = not_provided(parser);
18876 params = NULL;
18877
18878 context_pop(parser);
18879 break;
18880 }
18881 }
18882
18883 pm_node_t *statements = NULL;
18884 pm_token_t equal;
18885 pm_token_t end_keyword;
18886
18887 if (accept1(parser, PM_TOKEN_EQUAL)) {
18888 if (token_is_setter_name(&name)) {
18889 pm_parser_err_token(parser, &name, PM_ERR_DEF_ENDLESS_SETTER);
18890 }
18891 if (!accept_endless_def) {
18892 pm_parser_err_previous(parser, PM_ERR_DEF_ENDLESS_PARAMETERS);
18893 }
18894 if (
18895 parser->current_context->context == PM_CONTEXT_DEFAULT_PARAMS &&
18896 parser->current_context->prev->context == PM_CONTEXT_BLOCK_PARAMETERS
18897 ) {
18898 PM_PARSER_ERR_FORMAT(parser, def_keyword.start, parser->previous.end, PM_ERR_UNEXPECTED_PARAMETER_DEFAULT_VALUE, "endless method definition");
18899 }
18900 equal = parser->previous;
18901
18902 context_push(parser, PM_CONTEXT_DEF);
18903 pm_do_loop_stack_push(parser, false);
18904 statements = UP(pm_statements_node_create(parser));
18905
18906 bool allow_command_call;
18907 if (parser->version >= PM_OPTIONS_VERSION_CRUBY_4_0) {
18908 allow_command_call = accepts_command_call;
18909 } else {
18910 // Allow `def foo = puts "Hello"` but not `private def foo = puts "Hello"`
18911 allow_command_call = binding_power == PM_BINDING_POWER_ASSIGNMENT || binding_power < PM_BINDING_POWER_COMPOSITION;
18912 }
18913
18914 pm_node_t *statement = parse_expression(parser, PM_BINDING_POWER_DEFINED + 1, allow_command_call, false, PM_ERR_DEF_ENDLESS, (uint16_t) (depth + 1));
18915
18916 if (accept1(parser, PM_TOKEN_KEYWORD_RESCUE_MODIFIER)) {
18917 context_push(parser, PM_CONTEXT_RESCUE_MODIFIER);
18918
18919 pm_token_t rescue_keyword = parser->previous;
18920 pm_node_t *value = parse_expression(parser, pm_binding_powers[PM_TOKEN_KEYWORD_RESCUE_MODIFIER].right, false, false, PM_ERR_RESCUE_MODIFIER_VALUE, (uint16_t) (depth + 1));
18921 context_pop(parser);
18922
18923 statement = UP(pm_rescue_modifier_node_create(parser, statement, &rescue_keyword, value));
18924 }
18925
18926 pm_statements_node_body_append(parser, (pm_statements_node_t *) statements, statement, false);
18927 pm_do_loop_stack_pop(parser);
18928 context_pop(parser);
18929 end_keyword = not_provided(parser);
18930 } else {
18931 equal = not_provided(parser);
18932
18933 if (lparen.type == PM_TOKEN_NOT_PROVIDED) {
18934 lex_state_set(parser, PM_LEX_STATE_BEG);
18935 parser->command_start = true;
18936 expect2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON, PM_ERR_DEF_PARAMS_TERM);
18937 } else {
18938 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
18939 }
18940
18941 pm_accepts_block_stack_push(parser, true);
18942 pm_do_loop_stack_push(parser, false);
18943
18944 if (!match4(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_KEYWORD_END)) {
18945 pm_accepts_block_stack_push(parser, true);
18946 statements = UP(parse_statements(parser, PM_CONTEXT_DEF, (uint16_t) (depth + 1)));
18947 pm_accepts_block_stack_pop(parser);
18948 }
18949
18950 if (match3(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE, PM_TOKEN_KEYWORD_ELSE)) {
18951 assert(statements == NULL || PM_NODE_TYPE_P(statements, PM_STATEMENTS_NODE));
18952 statements = UP(parse_rescues_implicit_begin(parser, opening_newline_index, &def_keyword, def_keyword.start, (pm_statements_node_t *) statements, PM_RESCUES_DEF, (uint16_t) (depth + 1)));
18953 } else {
18954 parser_warn_indentation_mismatch(parser, opening_newline_index, &def_keyword, false, false);
18955 }
18956
18957 pm_accepts_block_stack_pop(parser);
18958 pm_do_loop_stack_pop(parser);
18959
18960 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_DEF_TERM, &def_keyword);
18961 end_keyword = parser->previous;
18962 }
18963
18964 pm_constant_id_list_t locals;
18965 pm_locals_order(parser, &parser->current_scope->locals, &locals, false);
18966 pm_parser_scope_pop(parser);
18967
18968 /**
18969 * If the final character is `@` as is the case when defining
18970 * methods to override the unary operators, we should ignore
18971 * the @ in the same way we do for symbols.
18972 */
18973 pm_constant_id_t name_id = pm_parser_constant_id_location(parser, name.start, parse_operator_symbol_name(&name));
18974
18975 flush_block_exits(parser, previous_block_exits);
18976 pm_node_list_free(&current_block_exits);
18977
18978 return UP(pm_def_node_create(
18979 parser,
18980 name_id,
18981 &name,
18982 receiver,
18983 params,
18984 statements,
18985 &locals,
18986 &def_keyword,
18987 &operator,
18988 &lparen,
18989 &rparen,
18990 &equal,
18991 &end_keyword
18992 ));
18993 }
18994 case PM_TOKEN_KEYWORD_DEFINED: {
18995 parser_lex(parser);
18996 pm_token_t keyword = parser->previous;
18997
18998 pm_token_t lparen;
18999 pm_token_t rparen;
19000 pm_node_t *expression;
19001
19002 context_push(parser, PM_CONTEXT_DEFINED);
19003 bool newline = accept1(parser, PM_TOKEN_NEWLINE);
19004
19005 if (accept1(parser, PM_TOKEN_PARENTHESIS_LEFT)) {
19006 lparen = parser->previous;
19007
19008 if (newline && accept1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
19009 expression = UP(pm_parentheses_node_create(parser, &lparen, NULL, &parser->previous, 0));
19010 lparen = not_provided(parser);
19011 rparen = not_provided(parser);
19012 } else {
19013 expression = parse_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_DEFINED_EXPRESSION, (uint16_t) (depth + 1));
19014
19015 if (parser->recovering) {
19016 rparen = not_provided(parser);
19017 } else {
19018 accept1(parser, PM_TOKEN_NEWLINE);
19019 expect1(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_EXPECT_RPAREN);
19020 rparen = parser->previous;
19021 }
19022 }
19023 } else {
19024 lparen = not_provided(parser);
19025 rparen = not_provided(parser);
19026 expression = parse_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_DEFINED_EXPRESSION, (uint16_t) (depth + 1));
19027 }
19028
19029 context_pop(parser);
19030 return UP(pm_defined_node_create(
19031 parser,
19032 &lparen,
19033 expression,
19034 &rparen,
19035 &keyword
19036 ));
19037 }
19038 case PM_TOKEN_KEYWORD_END_UPCASE: {
19039 if (binding_power != PM_BINDING_POWER_STATEMENT) {
19040 pm_parser_err_current(parser, PM_ERR_STATEMENT_POSTEXE_END);
19041 }
19042
19043 parser_lex(parser);
19044 pm_token_t keyword = parser->previous;
19045
19046 if (context_def_p(parser)) {
19047 pm_parser_warn_token(parser, &keyword, PM_WARN_END_IN_METHOD);
19048 }
19049
19050 expect1(parser, PM_TOKEN_BRACE_LEFT, PM_ERR_END_UPCASE_BRACE);
19051 pm_token_t opening = parser->previous;
19052 pm_statements_node_t *statements = parse_statements(parser, PM_CONTEXT_POSTEXE, (uint16_t) (depth + 1));
19053
19054 expect1_opening(parser, PM_TOKEN_BRACE_RIGHT, PM_ERR_END_UPCASE_TERM, &opening);
19055 return UP(pm_post_execution_node_create(parser, &keyword, &opening, statements, &parser->previous));
19056 }
19057 case PM_TOKEN_KEYWORD_FALSE:
19058 parser_lex(parser);
19059 return UP(pm_false_node_create(parser, &parser->previous));
19060 case PM_TOKEN_KEYWORD_FOR: {
19061 size_t opening_newline_index = token_newline_index(parser);
19062 parser_lex(parser);
19063
19064 pm_token_t for_keyword = parser->previous;
19065 pm_node_t *index;
19066
19067 context_push(parser, PM_CONTEXT_FOR_INDEX);
19068
19069 // First, parse out the first index expression.
19070 if (accept1(parser, PM_TOKEN_USTAR)) {
19071 pm_token_t star_operator = parser->previous;
19072 pm_node_t *name = NULL;
19073
19074 if (token_begins_expression_p(parser->current.type)) {
19075 name = parse_expression(parser, PM_BINDING_POWER_INDEX, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_STAR, (uint16_t) (depth + 1));
19076 }
19077
19078 index = UP(pm_splat_node_create(parser, &star_operator, name));
19079 } else if (token_begins_expression_p(parser->current.type)) {
19080 index = parse_expression(parser, PM_BINDING_POWER_INDEX, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_COMMA, (uint16_t) (depth + 1));
19081 } else {
19082 pm_parser_err_token(parser, &for_keyword, PM_ERR_FOR_INDEX);
19083 index = UP(pm_missing_node_create(parser, for_keyword.start, for_keyword.end));
19084 }
19085
19086 // Now, if there are multiple index expressions, parse them out.
19087 if (match1(parser, PM_TOKEN_COMMA)) {
19088 index = parse_targets(parser, index, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
19089 } else {
19090 index = parse_target(parser, index, false, false);
19091 }
19092
19093 context_pop(parser);
19094 pm_do_loop_stack_push(parser, true);
19095
19096 expect1(parser, PM_TOKEN_KEYWORD_IN, PM_ERR_FOR_IN);
19097 pm_token_t in_keyword = parser->previous;
19098
19099 pm_node_t *collection = parse_value_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_FOR_COLLECTION, (uint16_t) (depth + 1));
19100 pm_do_loop_stack_pop(parser);
19101
19102 pm_token_t do_keyword;
19103 if (accept1(parser, PM_TOKEN_KEYWORD_DO_LOOP)) {
19104 do_keyword = parser->previous;
19105 } else {
19106 do_keyword = not_provided(parser);
19107 if (!match2(parser, PM_TOKEN_SEMICOLON, PM_TOKEN_NEWLINE)) {
19108 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_EXPECT_FOR_DELIMITER, pm_token_type_human(parser->current.type));
19109 }
19110 }
19111
19112 pm_statements_node_t *statements = NULL;
19113 if (!match1(parser, PM_TOKEN_KEYWORD_END)) {
19114 statements = parse_statements(parser, PM_CONTEXT_FOR, (uint16_t) (depth + 1));
19115 }
19116
19117 parser_warn_indentation_mismatch(parser, opening_newline_index, &for_keyword, false, false);
19118 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_FOR_TERM, &for_keyword);
19119
19120 return UP(pm_for_node_create(parser, index, collection, statements, &for_keyword, &in_keyword, &do_keyword, &parser->previous));
19121 }
19122 case PM_TOKEN_KEYWORD_IF:
19123 if (parser_end_of_line_p(parser)) {
19124 PM_PARSER_WARN_TOKEN_FORMAT_CONTENT(parser, parser->current, PM_WARN_KEYWORD_EOL);
19125 }
19126
19127 size_t opening_newline_index = token_newline_index(parser);
19128 bool if_after_else = parser->previous.type == PM_TOKEN_KEYWORD_ELSE;
19129 parser_lex(parser);
19130
19131 return parse_conditional(parser, PM_CONTEXT_IF, opening_newline_index, if_after_else, (uint16_t) (depth + 1));
19132 case PM_TOKEN_KEYWORD_UNDEF: {
19133 if (binding_power != PM_BINDING_POWER_STATEMENT) {
19134 pm_parser_err_current(parser, PM_ERR_STATEMENT_UNDEF);
19135 }
19136
19137 parser_lex(parser);
19138 pm_undef_node_t *undef = pm_undef_node_create(parser, &parser->previous);
19139 pm_node_t *name = parse_undef_argument(parser, (uint16_t) (depth + 1));
19140
19141 if (PM_NODE_TYPE_P(name, PM_MISSING_NODE)) {
19142 pm_node_destroy(parser, name);
19143 } else {
19144 pm_undef_node_append(undef, name);
19145
19146 while (match1(parser, PM_TOKEN_COMMA)) {
19147 lex_state_set(parser, PM_LEX_STATE_FNAME | PM_LEX_STATE_FITEM);
19148 parser_lex(parser);
19149 name = parse_undef_argument(parser, (uint16_t) (depth + 1));
19150
19151 if (PM_NODE_TYPE_P(name, PM_MISSING_NODE)) {
19152 pm_node_destroy(parser, name);
19153 break;
19154 }
19155
19156 pm_undef_node_append(undef, name);
19157 }
19158 }
19159
19160 return UP(undef);
19161 }
19162 case PM_TOKEN_KEYWORD_NOT: {
19163 parser_lex(parser);
19164
19165 pm_token_t message = parser->previous;
19166 pm_arguments_t arguments = { 0 };
19167 pm_node_t *receiver = NULL;
19168
19169 // If we do not accept a command call, then we also do not accept a
19170 // not without parentheses. In this case we need to reject this
19171 // syntax.
19172 if (!accepts_command_call && !match1(parser, PM_TOKEN_PARENTHESIS_LEFT)) {
19173 if (match1(parser, PM_TOKEN_PARENTHESIS_LEFT_PARENTHESES)) {
19174 pm_parser_err(parser, parser->previous.end, parser->previous.end + 1, PM_ERR_EXPECT_LPAREN_AFTER_NOT_LPAREN);
19175 } else {
19176 accept1(parser, PM_TOKEN_NEWLINE);
19177 pm_parser_err_current(parser, PM_ERR_EXPECT_LPAREN_AFTER_NOT_OTHER);
19178 }
19179
19180 return UP(pm_missing_node_create(parser, parser->current.start, parser->current.end));
19181 }
19182
19183 accept1(parser, PM_TOKEN_NEWLINE);
19184
19185 if (accept1(parser, PM_TOKEN_PARENTHESIS_LEFT)) {
19186 pm_token_t lparen = parser->previous;
19187
19188 if (accept1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
19189 receiver = UP(pm_parentheses_node_create(parser, &lparen, NULL, &parser->previous, 0));
19190 } else {
19191 arguments.opening_loc = PM_LOCATION_TOKEN_VALUE(&lparen);
19192 receiver = parse_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_NOT_EXPRESSION, (uint16_t) (depth + 1));
19193
19194 if (!parser->recovering) {
19195 accept1(parser, PM_TOKEN_NEWLINE);
19196 expect1(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_EXPECT_RPAREN);
19197 arguments.closing_loc = PM_LOCATION_TOKEN_VALUE(&parser->previous);
19198 }
19199 }
19200 } else {
19201 receiver = parse_expression(parser, PM_BINDING_POWER_NOT, true, false, PM_ERR_NOT_EXPRESSION, (uint16_t) (depth + 1));
19202 }
19203
19204 return UP(pm_call_node_not_create(parser, receiver, &message, &arguments));
19205 }
19206 case PM_TOKEN_KEYWORD_UNLESS: {
19207 size_t opening_newline_index = token_newline_index(parser);
19208 parser_lex(parser);
19209
19210 return parse_conditional(parser, PM_CONTEXT_UNLESS, opening_newline_index, false, (uint16_t) (depth + 1));
19211 }
19212 case PM_TOKEN_KEYWORD_MODULE: {
19213 pm_node_list_t current_block_exits = { 0 };
19214 pm_node_list_t *previous_block_exits = push_block_exits(parser, &current_block_exits);
19215
19216 size_t opening_newline_index = token_newline_index(parser);
19217 parser_lex(parser);
19218 pm_token_t module_keyword = parser->previous;
19219
19220 pm_node_t *constant_path = parse_expression(parser, PM_BINDING_POWER_INDEX, false, false, PM_ERR_MODULE_NAME, (uint16_t) (depth + 1));
19221 pm_token_t name;
19222
19223 // If we can recover from a syntax error that occurred while parsing
19224 // the name of the module, then we'll handle that here.
19225 if (PM_NODE_TYPE_P(constant_path, PM_MISSING_NODE)) {
19226 pop_block_exits(parser, previous_block_exits);
19227 pm_node_list_free(&current_block_exits);
19228
19229 pm_token_t missing = (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->previous.end, .end = parser->previous.end };
19230 return UP(pm_module_node_create(parser, NULL, &module_keyword, constant_path, &missing, NULL, &missing));
19231 }
19232
19233 while (accept1(parser, PM_TOKEN_COLON_COLON)) {
19234 pm_token_t double_colon = parser->previous;
19235
19236 expect1(parser, PM_TOKEN_CONSTANT, PM_ERR_CONSTANT_PATH_COLON_COLON_CONSTANT);
19237 constant_path = UP(pm_constant_path_node_create(parser, constant_path, &double_colon, &parser->previous));
19238 }
19239
19240 // Here we retrieve the name of the module. If it wasn't a constant,
19241 // then it's possible that `module foo` was passed, which is a
19242 // syntax error. We handle that here as well.
19243 name = parser->previous;
19244 if (name.type != PM_TOKEN_CONSTANT) {
19245 pm_parser_err_token(parser, &name, PM_ERR_MODULE_NAME);
19246 }
19247
19248 pm_parser_scope_push(parser, true);
19249 accept2(parser, PM_TOKEN_SEMICOLON, PM_TOKEN_NEWLINE);
19250 pm_node_t *statements = NULL;
19251
19252 if (!match4(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE, PM_TOKEN_KEYWORD_ELSE, PM_TOKEN_KEYWORD_END)) {
19253 pm_accepts_block_stack_push(parser, true);
19254 statements = UP(parse_statements(parser, PM_CONTEXT_MODULE, (uint16_t) (depth + 1)));
19255 pm_accepts_block_stack_pop(parser);
19256 }
19257
19258 if (match3(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE, PM_TOKEN_KEYWORD_ELSE)) {
19259 assert(statements == NULL || PM_NODE_TYPE_P(statements, PM_STATEMENTS_NODE));
19260 statements = UP(parse_rescues_implicit_begin(parser, opening_newline_index, &module_keyword, module_keyword.start, (pm_statements_node_t *) statements, PM_RESCUES_MODULE, (uint16_t) (depth + 1)));
19261 } else {
19262 parser_warn_indentation_mismatch(parser, opening_newline_index, &module_keyword, false, false);
19263 }
19264
19265 pm_constant_id_list_t locals;
19266 pm_locals_order(parser, &parser->current_scope->locals, &locals, false);
19267
19268 pm_parser_scope_pop(parser);
19269 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_MODULE_TERM, &module_keyword);
19270
19271 if (context_def_p(parser)) {
19272 pm_parser_err_token(parser, &module_keyword, PM_ERR_MODULE_IN_METHOD);
19273 }
19274
19275 pop_block_exits(parser, previous_block_exits);
19276 pm_node_list_free(&current_block_exits);
19277
19278 return UP(pm_module_node_create(parser, &locals, &module_keyword, constant_path, &name, statements, &parser->previous));
19279 }
19280 case PM_TOKEN_KEYWORD_NIL:
19281 parser_lex(parser);
19282 return UP(pm_nil_node_create(parser, &parser->previous));
19283 case PM_TOKEN_KEYWORD_REDO: {
19284 parser_lex(parser);
19285
19286 pm_node_t *node = UP(pm_redo_node_create(parser, &parser->previous));
19287 if (!parser->partial_script) parse_block_exit(parser, node);
19288
19289 return node;
19290 }
19291 case PM_TOKEN_KEYWORD_RETRY: {
19292 parser_lex(parser);
19293
19294 pm_node_t *node = UP(pm_retry_node_create(parser, &parser->previous));
19295 parse_retry(parser, node);
19296
19297 return node;
19298 }
19299 case PM_TOKEN_KEYWORD_SELF:
19300 parser_lex(parser);
19301 return UP(pm_self_node_create(parser, &parser->previous));
19302 case PM_TOKEN_KEYWORD_TRUE:
19303 parser_lex(parser);
19304 return UP(pm_true_node_create(parser, &parser->previous));
19305 case PM_TOKEN_KEYWORD_UNTIL: {
19306 size_t opening_newline_index = token_newline_index(parser);
19307
19308 context_push(parser, PM_CONTEXT_LOOP_PREDICATE);
19309 pm_do_loop_stack_push(parser, true);
19310
19311 parser_lex(parser);
19312 pm_token_t keyword = parser->previous;
19313 pm_node_t *predicate = parse_value_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_CONDITIONAL_UNTIL_PREDICATE, (uint16_t) (depth + 1));
19314
19315 pm_do_loop_stack_pop(parser);
19316 context_pop(parser);
19317
19318 pm_token_t do_keyword;
19319 if (accept1(parser, PM_TOKEN_KEYWORD_DO_LOOP)) {
19320 do_keyword = parser->previous;
19321 } else {
19322 do_keyword = not_provided(parser);
19323 expect2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON, PM_ERR_CONDITIONAL_UNTIL_PREDICATE);
19324 }
19325
19326 pm_statements_node_t *statements = NULL;
19327 if (!match1(parser, PM_TOKEN_KEYWORD_END)) {
19328 pm_accepts_block_stack_push(parser, true);
19329 statements = parse_statements(parser, PM_CONTEXT_UNTIL, (uint16_t) (depth + 1));
19330 pm_accepts_block_stack_pop(parser);
19331 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
19332 }
19333
19334 parser_warn_indentation_mismatch(parser, opening_newline_index, &keyword, false, false);
19335 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_UNTIL_TERM, &keyword);
19336
19337 return UP(pm_until_node_create(parser, &keyword, &do_keyword, &parser->previous, predicate, statements, 0));
19338 }
19339 case PM_TOKEN_KEYWORD_WHILE: {
19340 size_t opening_newline_index = token_newline_index(parser);
19341
19342 context_push(parser, PM_CONTEXT_LOOP_PREDICATE);
19343 pm_do_loop_stack_push(parser, true);
19344
19345 parser_lex(parser);
19346 pm_token_t keyword = parser->previous;
19347 pm_node_t *predicate = parse_value_expression(parser, PM_BINDING_POWER_COMPOSITION, true, false, PM_ERR_CONDITIONAL_WHILE_PREDICATE, (uint16_t) (depth + 1));
19348
19349 pm_do_loop_stack_pop(parser);
19350 context_pop(parser);
19351
19352 pm_token_t do_keyword;
19353 if (accept1(parser, PM_TOKEN_KEYWORD_DO_LOOP)) {
19354 do_keyword = parser->previous;
19355 } else {
19356 do_keyword = not_provided(parser);
19357 expect2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON, PM_ERR_CONDITIONAL_WHILE_PREDICATE);
19358 }
19359
19360 pm_statements_node_t *statements = NULL;
19361 if (!match1(parser, PM_TOKEN_KEYWORD_END)) {
19362 pm_accepts_block_stack_push(parser, true);
19363 statements = parse_statements(parser, PM_CONTEXT_WHILE, (uint16_t) (depth + 1));
19364 pm_accepts_block_stack_pop(parser);
19365 accept2(parser, PM_TOKEN_NEWLINE, PM_TOKEN_SEMICOLON);
19366 }
19367
19368 parser_warn_indentation_mismatch(parser, opening_newline_index, &keyword, false, false);
19369 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_WHILE_TERM, &keyword);
19370
19371 return UP(pm_while_node_create(parser, &keyword, &do_keyword, &parser->previous, predicate, statements, 0));
19372 }
19373 case PM_TOKEN_PERCENT_LOWER_I: {
19374 parser_lex(parser);
19375 pm_token_t opening = parser->previous;
19376 pm_array_node_t *array = pm_array_node_create(parser, &opening);
19377 pm_node_t *current = NULL;
19378
19379 while (!match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) {
19380 accept1(parser, PM_TOKEN_WORDS_SEP);
19381 if (match1(parser, PM_TOKEN_STRING_END)) break;
19382
19383 // Interpolation is not possible but nested heredocs can still lead to
19384 // consecutive (disjoint) string tokens when the final newline is escaped.
19385 while (match1(parser, PM_TOKEN_STRING_CONTENT)) {
19386 pm_token_t opening = not_provided(parser);
19387 pm_token_t closing = not_provided(parser);
19388
19389 // Record the string node, moving to interpolation if needed.
19390 if (current == NULL) {
19391 current = UP(pm_symbol_node_create_current_string(parser, &opening, &parser->current, &closing));
19392 parser_lex(parser);
19393 } else if (PM_NODE_TYPE_P(current, PM_INTERPOLATED_SYMBOL_NODE)) {
19394 pm_node_t *string = UP(pm_string_node_create_current_string(parser, &opening, &parser->current, &closing));
19395 parser_lex(parser);
19396 pm_interpolated_symbol_node_append((pm_interpolated_symbol_node_t *) current, string);
19397 } else if (PM_NODE_TYPE_P(current, PM_SYMBOL_NODE)) {
19398 pm_symbol_node_t *cast = (pm_symbol_node_t *) current;
19399 pm_token_t bounds = not_provided(parser);
19400
19401 pm_token_t content = { .type = PM_TOKEN_STRING_CONTENT, .start = cast->value_loc.start, .end = cast->value_loc.end };
19402 pm_node_t *first_string = UP(pm_string_node_create_unescaped(parser, &bounds, &content, &bounds, &cast->unescaped));
19403 pm_node_t *second_string = UP(pm_string_node_create_current_string(parser, &opening, &parser->previous, &closing));
19404 parser_lex(parser);
19405
19406 pm_interpolated_symbol_node_t *interpolated = pm_interpolated_symbol_node_create(parser, &opening, NULL, &closing);
19407 pm_interpolated_symbol_node_append(interpolated, first_string);
19408 pm_interpolated_symbol_node_append(interpolated, second_string);
19409
19410 xfree(current);
19411 current = UP(interpolated);
19412 } else {
19413 assert(false && "unreachable");
19414 }
19415 }
19416
19417 if (current) {
19418 pm_array_node_elements_append(array, current);
19419 current = NULL;
19420 } else {
19421 expect1(parser, PM_TOKEN_STRING_CONTENT, PM_ERR_LIST_I_LOWER_ELEMENT);
19422 }
19423 }
19424
19425 pm_token_t closing = parser->current;
19426 if (match1(parser, PM_TOKEN_EOF)) {
19427 pm_parser_err_token(parser, &opening, PM_ERR_LIST_I_LOWER_TERM);
19428 closing = (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->previous.end, .end = parser->previous.end };
19429 } else {
19430 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_LIST_I_LOWER_TERM);
19431 }
19432 pm_array_node_close_set(array, &closing);
19433
19434 return UP(array);
19435 }
19436 case PM_TOKEN_PERCENT_UPPER_I: {
19437 parser_lex(parser);
19438 pm_token_t opening = parser->previous;
19439 pm_array_node_t *array = pm_array_node_create(parser, &opening);
19440
19441 // This is the current node that we are parsing that will be added to the
19442 // list of elements.
19443 pm_node_t *current = NULL;
19444
19445 while (!match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) {
19446 switch (parser->current.type) {
19447 case PM_TOKEN_WORDS_SEP: {
19448 if (current == NULL) {
19449 // If we hit a separator before we have any content, then we don't
19450 // need to do anything.
19451 } else {
19452 // If we hit a separator after we've hit content, then we need to
19453 // append that content to the list and reset the current node.
19454 pm_array_node_elements_append(array, current);
19455 current = NULL;
19456 }
19457
19458 parser_lex(parser);
19459 break;
19460 }
19461 case PM_TOKEN_STRING_CONTENT: {
19462 pm_token_t opening = not_provided(parser);
19463 pm_token_t closing = not_provided(parser);
19464
19465 if (current == NULL) {
19466 // If we hit content and the current node is NULL, then this is
19467 // the first string content we've seen. In that case we're going
19468 // to create a new string node and set that to the current.
19469 current = UP(pm_symbol_node_create_current_string(parser, &opening, &parser->current, &closing));
19470 parser_lex(parser);
19471 } else if (PM_NODE_TYPE_P(current, PM_INTERPOLATED_SYMBOL_NODE)) {
19472 // If we hit string content and the current node is an
19473 // interpolated string, then we need to append the string content
19474 // to the list of child nodes.
19475 pm_node_t *string = UP(pm_string_node_create_current_string(parser, &opening, &parser->current, &closing));
19476 parser_lex(parser);
19477
19478 pm_interpolated_symbol_node_append((pm_interpolated_symbol_node_t *) current, string);
19479 } else if (PM_NODE_TYPE_P(current, PM_SYMBOL_NODE)) {
19480 // If we hit string content and the current node is a symbol node,
19481 // then we need to convert the current node into an interpolated
19482 // string and add the string content to the list of child nodes.
19483 pm_symbol_node_t *cast = (pm_symbol_node_t *) current;
19484 pm_token_t bounds = not_provided(parser);
19485
19486 pm_token_t content = { .type = PM_TOKEN_STRING_CONTENT, .start = cast->value_loc.start, .end = cast->value_loc.end };
19487 pm_node_t *first_string = UP(pm_string_node_create_unescaped(parser, &bounds, &content, &bounds, &cast->unescaped));
19488 pm_node_t *second_string = UP(pm_string_node_create_current_string(parser, &opening, &parser->previous, &closing));
19489 parser_lex(parser);
19490
19491 pm_interpolated_symbol_node_t *interpolated = pm_interpolated_symbol_node_create(parser, &opening, NULL, &closing);
19492 pm_interpolated_symbol_node_append(interpolated, first_string);
19493 pm_interpolated_symbol_node_append(interpolated, second_string);
19494
19495 xfree(current);
19496 current = UP(interpolated);
19497 } else {
19498 assert(false && "unreachable");
19499 }
19500
19501 break;
19502 }
19503 case PM_TOKEN_EMBVAR: {
19504 bool start_location_set = false;
19505 if (current == NULL) {
19506 // If we hit an embedded variable and the current node is NULL,
19507 // then this is the start of a new string. We'll set the current
19508 // node to a new interpolated string.
19509 pm_token_t opening = not_provided(parser);
19510 pm_token_t closing = not_provided(parser);
19511 current = UP(pm_interpolated_symbol_node_create(parser, &opening, NULL, &closing));
19512 } else if (PM_NODE_TYPE_P(current, PM_SYMBOL_NODE)) {
19513 // If we hit an embedded variable and the current node is a string
19514 // node, then we'll convert the current into an interpolated
19515 // string and add the string node to the list of parts.
19516 pm_token_t opening = not_provided(parser);
19517 pm_token_t closing = not_provided(parser);
19518 pm_interpolated_symbol_node_t *interpolated = pm_interpolated_symbol_node_create(parser, &opening, NULL, &closing);
19519
19520 current = UP(pm_symbol_node_to_string_node(parser, (pm_symbol_node_t *) current));
19521 pm_interpolated_symbol_node_append(interpolated, current);
19522 interpolated->base.location.start = current->location.start;
19523 start_location_set = true;
19524 current = UP(interpolated);
19525 } else {
19526 // If we hit an embedded variable and the current node is an
19527 // interpolated string, then we'll just add the embedded variable.
19528 }
19529
19530 pm_node_t *part = parse_string_part(parser, (uint16_t) (depth + 1));
19531 pm_interpolated_symbol_node_append((pm_interpolated_symbol_node_t *) current, part);
19532 if (!start_location_set) {
19533 current->location.start = part->location.start;
19534 }
19535 break;
19536 }
19537 case PM_TOKEN_EMBEXPR_BEGIN: {
19538 bool start_location_set = false;
19539 if (current == NULL) {
19540 // If we hit an embedded expression and the current node is NULL,
19541 // then this is the start of a new string. We'll set the current
19542 // node to a new interpolated string.
19543 pm_token_t opening = not_provided(parser);
19544 pm_token_t closing = not_provided(parser);
19545 current = UP(pm_interpolated_symbol_node_create(parser, &opening, NULL, &closing));
19546 } else if (PM_NODE_TYPE_P(current, PM_SYMBOL_NODE)) {
19547 // If we hit an embedded expression and the current node is a
19548 // string node, then we'll convert the current into an
19549 // interpolated string and add the string node to the list of
19550 // parts.
19551 pm_token_t opening = not_provided(parser);
19552 pm_token_t closing = not_provided(parser);
19553 pm_interpolated_symbol_node_t *interpolated = pm_interpolated_symbol_node_create(parser, &opening, NULL, &closing);
19554
19555 current = UP(pm_symbol_node_to_string_node(parser, (pm_symbol_node_t *) current));
19556 pm_interpolated_symbol_node_append(interpolated, current);
19557 interpolated->base.location.start = current->location.start;
19558 start_location_set = true;
19559 current = UP(interpolated);
19560 } else if (PM_NODE_TYPE_P(current, PM_INTERPOLATED_SYMBOL_NODE)) {
19561 // If we hit an embedded expression and the current node is an
19562 // interpolated string, then we'll just continue on.
19563 } else {
19564 assert(false && "unreachable");
19565 }
19566
19567 pm_node_t *part = parse_string_part(parser, (uint16_t) (depth + 1));
19568 pm_interpolated_symbol_node_append((pm_interpolated_symbol_node_t *) current, part);
19569 if (!start_location_set) {
19570 current->location.start = part->location.start;
19571 }
19572 break;
19573 }
19574 default:
19575 expect1(parser, PM_TOKEN_STRING_CONTENT, PM_ERR_LIST_I_UPPER_ELEMENT);
19576 parser_lex(parser);
19577 break;
19578 }
19579 }
19580
19581 // If we have a current node, then we need to append it to the list.
19582 if (current) {
19583 pm_array_node_elements_append(array, current);
19584 }
19585
19586 pm_token_t closing = parser->current;
19587 if (match1(parser, PM_TOKEN_EOF)) {
19588 pm_parser_err_token(parser, &opening, PM_ERR_LIST_I_UPPER_TERM);
19589 closing = (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->previous.end, .end = parser->previous.end };
19590 } else {
19591 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_LIST_I_UPPER_TERM);
19592 }
19593 pm_array_node_close_set(array, &closing);
19594
19595 return UP(array);
19596 }
19597 case PM_TOKEN_PERCENT_LOWER_W: {
19598 parser_lex(parser);
19599 pm_token_t opening = parser->previous;
19600 pm_array_node_t *array = pm_array_node_create(parser, &opening);
19601 pm_node_t *current = NULL;
19602
19603 while (!match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) {
19604 accept1(parser, PM_TOKEN_WORDS_SEP);
19605 if (match1(parser, PM_TOKEN_STRING_END)) break;
19606
19607 // Interpolation is not possible but nested heredocs can still lead to
19608 // consecutive (disjoint) string tokens when the final newline is escaped.
19609 while (match1(parser, PM_TOKEN_STRING_CONTENT)) {
19610 pm_token_t opening = not_provided(parser);
19611 pm_token_t closing = not_provided(parser);
19612
19613 pm_node_t *string = UP(pm_string_node_create_current_string(parser, &opening, &parser->current, &closing));
19614
19615 // Record the string node, moving to interpolation if needed.
19616 if (current == NULL) {
19617 current = string;
19618 } else if (PM_NODE_TYPE_P(current, PM_INTERPOLATED_STRING_NODE)) {
19619 pm_interpolated_string_node_append((pm_interpolated_string_node_t *) current, string);
19620 } else if (PM_NODE_TYPE_P(current, PM_STRING_NODE)) {
19621 pm_interpolated_string_node_t *interpolated = pm_interpolated_string_node_create(parser, &opening, NULL, &closing);
19622 pm_interpolated_string_node_append(interpolated, current);
19623 pm_interpolated_string_node_append(interpolated, string);
19624 current = UP(interpolated);
19625 } else {
19626 assert(false && "unreachable");
19627 }
19628 parser_lex(parser);
19629 }
19630
19631 if (current) {
19632 pm_array_node_elements_append(array, current);
19633 current = NULL;
19634 } else {
19635 expect1(parser, PM_TOKEN_STRING_CONTENT, PM_ERR_LIST_W_LOWER_ELEMENT);
19636 }
19637 }
19638
19639 pm_token_t closing = parser->current;
19640 if (match1(parser, PM_TOKEN_EOF)) {
19641 pm_parser_err_token(parser, &opening, PM_ERR_LIST_W_LOWER_TERM);
19642 closing = (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->previous.end, .end = parser->previous.end };
19643 } else {
19644 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_LIST_W_LOWER_TERM);
19645 }
19646
19647 pm_array_node_close_set(array, &closing);
19648 return UP(array);
19649 }
19650 case PM_TOKEN_PERCENT_UPPER_W: {
19651 parser_lex(parser);
19652 pm_token_t opening = parser->previous;
19653 pm_array_node_t *array = pm_array_node_create(parser, &opening);
19654
19655 // This is the current node that we are parsing that will be added
19656 // to the list of elements.
19657 pm_node_t *current = NULL;
19658
19659 while (!match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) {
19660 switch (parser->current.type) {
19661 case PM_TOKEN_WORDS_SEP: {
19662 // Reset the explicit encoding if we hit a separator
19663 // since each element can have its own encoding.
19664 parser->explicit_encoding = NULL;
19665
19666 if (current == NULL) {
19667 // If we hit a separator before we have any content,
19668 // then we don't need to do anything.
19669 } else {
19670 // If we hit a separator after we've hit content,
19671 // then we need to append that content to the list
19672 // and reset the current node.
19673 pm_array_node_elements_append(array, current);
19674 current = NULL;
19675 }
19676
19677 parser_lex(parser);
19678 break;
19679 }
19680 case PM_TOKEN_STRING_CONTENT: {
19681 pm_token_t opening = not_provided(parser);
19682 pm_token_t closing = not_provided(parser);
19683
19684 pm_node_t *string = UP(pm_string_node_create_current_string(parser, &opening, &parser->current, &closing));
19685 pm_node_flag_set(string, parse_unescaped_encoding(parser));
19686 parser_lex(parser);
19687
19688 if (current == NULL) {
19689 // If we hit content and the current node is NULL,
19690 // then this is the first string content we've seen.
19691 // In that case we're going to create a new string
19692 // node and set that to the current.
19693 current = string;
19694 } else if (PM_NODE_TYPE_P(current, PM_INTERPOLATED_STRING_NODE)) {
19695 // If we hit string content and the current node is
19696 // an interpolated string, then we need to append
19697 // the string content to the list of child nodes.
19698 pm_interpolated_string_node_append((pm_interpolated_string_node_t *) current, string);
19699 } else if (PM_NODE_TYPE_P(current, PM_STRING_NODE)) {
19700 // If we hit string content and the current node is
19701 // a string node, then we need to convert the
19702 // current node into an interpolated string and add
19703 // the string content to the list of child nodes.
19704 pm_interpolated_string_node_t *interpolated = pm_interpolated_string_node_create(parser, &opening, NULL, &closing);
19705 pm_interpolated_string_node_append(interpolated, current);
19706 pm_interpolated_string_node_append(interpolated, string);
19707 current = UP(interpolated);
19708 } else {
19709 assert(false && "unreachable");
19710 }
19711
19712 break;
19713 }
19714 case PM_TOKEN_EMBVAR: {
19715 if (current == NULL) {
19716 // If we hit an embedded variable and the current
19717 // node is NULL, then this is the start of a new
19718 // string. We'll set the current node to a new
19719 // interpolated string.
19720 pm_token_t opening = not_provided(parser);
19721 pm_token_t closing = not_provided(parser);
19722 current = UP(pm_interpolated_string_node_create(parser, &opening, NULL, &closing));
19723 } else if (PM_NODE_TYPE_P(current, PM_STRING_NODE)) {
19724 // If we hit an embedded variable and the current
19725 // node is a string node, then we'll convert the
19726 // current into an interpolated string and add the
19727 // string node to the list of parts.
19728 pm_token_t opening = not_provided(parser);
19729 pm_token_t closing = not_provided(parser);
19730 pm_interpolated_string_node_t *interpolated = pm_interpolated_string_node_create(parser, &opening, NULL, &closing);
19731 pm_interpolated_string_node_append(interpolated, current);
19732 current = UP(interpolated);
19733 } else {
19734 // If we hit an embedded variable and the current
19735 // node is an interpolated string, then we'll just
19736 // add the embedded variable.
19737 }
19738
19739 pm_node_t *part = parse_string_part(parser, (uint16_t) (depth + 1));
19740 pm_interpolated_string_node_append((pm_interpolated_string_node_t *) current, part);
19741 break;
19742 }
19743 case PM_TOKEN_EMBEXPR_BEGIN: {
19744 if (current == NULL) {
19745 // If we hit an embedded expression and the current
19746 // node is NULL, then this is the start of a new
19747 // string. We'll set the current node to a new
19748 // interpolated string.
19749 pm_token_t opening = not_provided(parser);
19750 pm_token_t closing = not_provided(parser);
19751 current = UP(pm_interpolated_string_node_create(parser, &opening, NULL, &closing));
19752 } else if (PM_NODE_TYPE_P(current, PM_STRING_NODE)) {
19753 // If we hit an embedded expression and the current
19754 // node is a string node, then we'll convert the
19755 // current into an interpolated string and add the
19756 // string node to the list of parts.
19757 pm_token_t opening = not_provided(parser);
19758 pm_token_t closing = not_provided(parser);
19759 pm_interpolated_string_node_t *interpolated = pm_interpolated_string_node_create(parser, &opening, NULL, &closing);
19760 pm_interpolated_string_node_append(interpolated, current);
19761 current = UP(interpolated);
19762 } else if (PM_NODE_TYPE_P(current, PM_INTERPOLATED_STRING_NODE)) {
19763 // If we hit an embedded expression and the current
19764 // node is an interpolated string, then we'll just
19765 // continue on.
19766 } else {
19767 assert(false && "unreachable");
19768 }
19769
19770 pm_node_t *part = parse_string_part(parser, (uint16_t) (depth + 1));
19771 pm_interpolated_string_node_append((pm_interpolated_string_node_t *) current, part);
19772 break;
19773 }
19774 default:
19775 expect1(parser, PM_TOKEN_STRING_CONTENT, PM_ERR_LIST_W_UPPER_ELEMENT);
19776 parser_lex(parser);
19777 break;
19778 }
19779 }
19780
19781 // If we have a current node, then we need to append it to the list.
19782 if (current) {
19783 pm_array_node_elements_append(array, current);
19784 }
19785
19786 pm_token_t closing = parser->current;
19787 if (match1(parser, PM_TOKEN_EOF)) {
19788 pm_parser_err_token(parser, &opening, PM_ERR_LIST_W_UPPER_TERM);
19789 closing = (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->previous.end, .end = parser->previous.end };
19790 } else {
19791 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_LIST_W_UPPER_TERM);
19792 }
19793
19794 pm_array_node_close_set(array, &closing);
19795 return UP(array);
19796 }
19797 case PM_TOKEN_REGEXP_BEGIN: {
19798 pm_token_t opening = parser->current;
19799 parser_lex(parser);
19800
19801 if (match1(parser, PM_TOKEN_REGEXP_END)) {
19802 // If we get here, then we have an end immediately after a start. In
19803 // that case we'll create an empty content token and return an
19804 // uninterpolated regular expression.
19805 pm_token_t content = (pm_token_t) {
19806 .type = PM_TOKEN_STRING_CONTENT,
19807 .start = parser->previous.end,
19808 .end = parser->previous.end
19809 };
19810
19811 parser_lex(parser);
19812
19813 pm_node_t *node = UP(pm_regular_expression_node_create(parser, &opening, &content, &parser->previous));
19814 pm_node_flag_set(node, PM_REGULAR_EXPRESSION_FLAGS_FORCED_US_ASCII_ENCODING);
19815
19816 return node;
19817 }
19818
19819 pm_interpolated_regular_expression_node_t *interpolated;
19820
19821 if (match1(parser, PM_TOKEN_STRING_CONTENT)) {
19822 // In this case we've hit string content so we know the regular
19823 // expression at least has something in it. We'll need to check if the
19824 // following token is the end (in which case we can return a plain
19825 // regular expression) or if it's not then it has interpolation.
19826 pm_string_t unescaped = parser->current_string;
19827 pm_token_t content = parser->current;
19828 bool ascii_only = parser->current_regular_expression_ascii_only;
19829 parser_lex(parser);
19830
19831 // If we hit an end, then we can create a regular expression
19832 // node without interpolation, which can be represented more
19833 // succinctly and more easily compiled.
19834 if (accept1(parser, PM_TOKEN_REGEXP_END)) {
19835 pm_regular_expression_node_t *node = (pm_regular_expression_node_t *) pm_regular_expression_node_create_unescaped(parser, &opening, &content, &parser->previous, &unescaped);
19836
19837 // If we're not immediately followed by a =~, then we want
19838 // to parse all of the errors at this point. If it is
19839 // followed by a =~, then it will get parsed higher up while
19840 // parsing the named captures as well.
19841 if (!match1(parser, PM_TOKEN_EQUAL_TILDE)) {
19842 parse_regular_expression_errors(parser, node);
19843 }
19844
19845 pm_node_flag_set(UP(node), parse_and_validate_regular_expression_encoding(parser, &unescaped, ascii_only, FL(node)));
19846 return UP(node);
19847 }
19848
19849 // If we get here, then we have interpolation so we'll need to create
19850 // a regular expression node with interpolation.
19851 interpolated = pm_interpolated_regular_expression_node_create(parser, &opening);
19852
19853 pm_token_t opening = not_provided(parser);
19854 pm_token_t closing = not_provided(parser);
19855 pm_node_t *part = UP(pm_string_node_create_unescaped(parser, &opening, &parser->previous, &closing, &unescaped));
19856
19857 if (parser->encoding == PM_ENCODING_US_ASCII_ENTRY) {
19858 // This is extremely strange, but the first string part of a
19859 // regular expression will always be tagged as binary if we
19860 // are in a US-ASCII file, no matter its contents.
19861 pm_node_flag_set(part, PM_STRING_FLAGS_FORCED_BINARY_ENCODING);
19862 }
19863
19864 pm_interpolated_regular_expression_node_append(interpolated, part);
19865 } else {
19866 // If the first part of the body of the regular expression is not a
19867 // string content, then we have interpolation and we need to create an
19868 // interpolated regular expression node.
19869 interpolated = pm_interpolated_regular_expression_node_create(parser, &opening);
19870 }
19871
19872 // Now that we're here and we have interpolation, we'll parse all of the
19873 // parts into the list.
19874 pm_node_t *part;
19875 while (!match2(parser, PM_TOKEN_REGEXP_END, PM_TOKEN_EOF)) {
19876 if ((part = parse_string_part(parser, (uint16_t) (depth + 1))) != NULL) {
19877 pm_interpolated_regular_expression_node_append(interpolated, part);
19878 }
19879 }
19880
19881 pm_token_t closing = parser->current;
19882 if (match1(parser, PM_TOKEN_EOF)) {
19883 pm_parser_err_token(parser, &opening, PM_ERR_REGEXP_TERM);
19884 closing = (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->previous.end, .end = parser->previous.end };
19885 } else {
19886 expect1(parser, PM_TOKEN_REGEXP_END, PM_ERR_REGEXP_TERM);
19887 }
19888
19889 pm_interpolated_regular_expression_node_closing_set(parser, interpolated, &closing);
19890 return UP(interpolated);
19891 }
19892 case PM_TOKEN_BACKTICK:
19893 case PM_TOKEN_PERCENT_LOWER_X: {
19894 parser_lex(parser);
19895 pm_token_t opening = parser->previous;
19896
19897 // When we get here, we don't know if this string is going to have
19898 // interpolation or not, even though it is allowed. Still, we want to be
19899 // able to return a string node without interpolation if we can since
19900 // it'll be faster.
19901 if (match1(parser, PM_TOKEN_STRING_END)) {
19902 // If we get here, then we have an end immediately after a start. In
19903 // that case we'll create an empty content token and return an
19904 // uninterpolated string.
19905 pm_token_t content = (pm_token_t) {
19906 .type = PM_TOKEN_STRING_CONTENT,
19907 .start = parser->previous.end,
19908 .end = parser->previous.end
19909 };
19910
19911 parser_lex(parser);
19912 return UP(pm_xstring_node_create(parser, &opening, &content, &parser->previous));
19913 }
19914
19915 pm_interpolated_x_string_node_t *node;
19916
19917 if (match1(parser, PM_TOKEN_STRING_CONTENT)) {
19918 // In this case we've hit string content so we know the string
19919 // at least has something in it. We'll need to check if the
19920 // following token is the end (in which case we can return a
19921 // plain string) or if it's not then it has interpolation.
19922 pm_string_t unescaped = parser->current_string;
19923 pm_token_t content = parser->current;
19924 parser_lex(parser);
19925
19926 if (match1(parser, PM_TOKEN_STRING_END)) {
19927 pm_node_t *node = UP(pm_xstring_node_create_unescaped(parser, &opening, &content, &parser->current, &unescaped));
19928 pm_node_flag_set(node, parse_unescaped_encoding(parser));
19929 parser_lex(parser);
19930 return node;
19931 }
19932
19933 // If we get here, then we have interpolation so we'll need to
19934 // create a string node with interpolation.
19935 node = pm_interpolated_xstring_node_create(parser, &opening, &opening);
19936
19937 pm_token_t opening = not_provided(parser);
19938 pm_token_t closing = not_provided(parser);
19939
19940 pm_node_t *part = UP(pm_string_node_create_unescaped(parser, &opening, &parser->previous, &closing, &unescaped));
19941 pm_node_flag_set(part, parse_unescaped_encoding(parser));
19942
19943 pm_interpolated_xstring_node_append(node, part);
19944 } else {
19945 // If the first part of the body of the string is not a string
19946 // content, then we have interpolation and we need to create an
19947 // interpolated string node.
19948 node = pm_interpolated_xstring_node_create(parser, &opening, &opening);
19949 }
19950
19951 pm_node_t *part;
19952 while (!match2(parser, PM_TOKEN_STRING_END, PM_TOKEN_EOF)) {
19953 if ((part = parse_string_part(parser, (uint16_t) (depth + 1))) != NULL) {
19954 pm_interpolated_xstring_node_append(node, part);
19955 }
19956 }
19957
19958 pm_token_t closing = parser->current;
19959 if (match1(parser, PM_TOKEN_EOF)) {
19960 pm_parser_err_token(parser, &opening, PM_ERR_XSTRING_TERM);
19961 closing = (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->previous.end, .end = parser->previous.end };
19962 } else {
19963 expect1(parser, PM_TOKEN_STRING_END, PM_ERR_XSTRING_TERM);
19964 }
19965 pm_interpolated_xstring_node_closing_set(node, &closing);
19966
19967 return UP(node);
19968 }
19969 case PM_TOKEN_USTAR: {
19970 parser_lex(parser);
19971
19972 // * operators at the beginning of expressions are only valid in the
19973 // context of a multiple assignment. We enforce that here. We'll
19974 // still lex past it though and create a missing node place.
19975 if (binding_power != PM_BINDING_POWER_STATEMENT) {
19976 pm_parser_err_prefix(parser, diag_id);
19977 return UP(pm_missing_node_create(parser, parser->previous.start, parser->previous.end));
19978 }
19979
19980 pm_token_t operator = parser->previous;
19981 pm_node_t *name = NULL;
19982
19983 if (token_begins_expression_p(parser->current.type)) {
19984 name = parse_expression(parser, PM_BINDING_POWER_INDEX, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_STAR, (uint16_t) (depth + 1));
19985 }
19986
19987 pm_node_t *splat = UP(pm_splat_node_create(parser, &operator, name));
19988
19989 if (match1(parser, PM_TOKEN_COMMA)) {
19990 return parse_targets_validate(parser, splat, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
19991 } else {
19992 return parse_target_validate(parser, splat, true);
19993 }
19994 }
19995 case PM_TOKEN_BANG: {
19996 if (binding_power > PM_BINDING_POWER_UNARY) {
19997 pm_parser_err_prefix(parser, PM_ERR_UNARY_DISALLOWED);
19998 }
19999
20000 parser_lex(parser);
20001
20002 pm_token_t operator = parser->previous;
20003 pm_node_t *receiver = parse_expression(parser, pm_binding_powers[parser->previous.type].right, binding_power < PM_BINDING_POWER_MATCH, false, PM_ERR_UNARY_RECEIVER, (uint16_t) (depth + 1));
20004 pm_call_node_t *node = pm_call_node_unary_create(parser, &operator, receiver, "!");
20005
20006 pm_conditional_predicate(parser, receiver, PM_CONDITIONAL_PREDICATE_TYPE_NOT);
20007 return UP(node);
20008 }
20009 case PM_TOKEN_TILDE: {
20010 if (binding_power > PM_BINDING_POWER_UNARY) {
20011 pm_parser_err_prefix(parser, PM_ERR_UNARY_DISALLOWED);
20012 }
20013 parser_lex(parser);
20014
20015 pm_token_t operator = parser->previous;
20016 pm_node_t *receiver = parse_expression(parser, pm_binding_powers[parser->previous.type].right, false, false, PM_ERR_UNARY_RECEIVER, (uint16_t) (depth + 1));
20017 pm_call_node_t *node = pm_call_node_unary_create(parser, &operator, receiver, "~");
20018
20019 return UP(node);
20020 }
20021 case PM_TOKEN_UMINUS: {
20022 if (binding_power > PM_BINDING_POWER_UNARY) {
20023 pm_parser_err_prefix(parser, PM_ERR_UNARY_DISALLOWED);
20024 }
20025 parser_lex(parser);
20026
20027 pm_token_t operator = parser->previous;
20028 pm_node_t *receiver = parse_expression(parser, pm_binding_powers[parser->previous.type].right, false, false, PM_ERR_UNARY_RECEIVER, (uint16_t) (depth + 1));
20029 pm_call_node_t *node = pm_call_node_unary_create(parser, &operator, receiver, "-@");
20030
20031 return UP(node);
20032 }
20033 case PM_TOKEN_UMINUS_NUM: {
20034 parser_lex(parser);
20035
20036 pm_token_t operator = parser->previous;
20037 pm_node_t *node = parse_expression(parser, pm_binding_powers[parser->previous.type].right, false, false, PM_ERR_UNARY_RECEIVER, (uint16_t) (depth + 1));
20038
20039 if (accept1(parser, PM_TOKEN_STAR_STAR)) {
20040 pm_token_t exponent_operator = parser->previous;
20041 pm_node_t *exponent = parse_expression(parser, pm_binding_powers[exponent_operator.type].right, false, false, PM_ERR_EXPECT_ARGUMENT, (uint16_t) (depth + 1));
20042 node = UP(pm_call_node_binary_create(parser, node, &exponent_operator, exponent, 0));
20043 node = UP(pm_call_node_unary_create(parser, &operator, node, "-@"));
20044 } else {
20045 switch (PM_NODE_TYPE(node)) {
20046 case PM_INTEGER_NODE:
20047 case PM_FLOAT_NODE:
20048 case PM_RATIONAL_NODE:
20049 case PM_IMAGINARY_NODE:
20050 parse_negative_numeric(node);
20051 break;
20052 default:
20053 node = UP(pm_call_node_unary_create(parser, &operator, node, "-@"));
20054 break;
20055 }
20056 }
20057
20058 return node;
20059 }
20060 case PM_TOKEN_MINUS_GREATER: {
20061 int previous_lambda_enclosure_nesting = parser->lambda_enclosure_nesting;
20062 parser->lambda_enclosure_nesting = parser->enclosure_nesting;
20063
20064 size_t opening_newline_index = token_newline_index(parser);
20065 pm_accepts_block_stack_push(parser, true);
20066 parser_lex(parser);
20067
20068 pm_token_t operator = parser->previous;
20069 pm_parser_scope_push(parser, false);
20070
20071 pm_block_parameters_node_t *block_parameters;
20072
20073 switch (parser->current.type) {
20074 case PM_TOKEN_PARENTHESIS_LEFT: {
20075 pm_token_t opening = parser->current;
20076 parser_lex(parser);
20077
20078 if (match1(parser, PM_TOKEN_PARENTHESIS_RIGHT)) {
20079 block_parameters = pm_block_parameters_node_create(parser, NULL, &opening);
20080 } else {
20081 block_parameters = parse_block_parameters(parser, false, &opening, true, true, (uint16_t) (depth + 1));
20082 }
20083
20084 accept1(parser, PM_TOKEN_NEWLINE);
20085 expect1(parser, PM_TOKEN_PARENTHESIS_RIGHT, PM_ERR_EXPECT_RPAREN);
20086
20087 pm_block_parameters_node_closing_set(block_parameters, &parser->previous);
20088 break;
20089 }
20090 case PM_CASE_PARAMETER: {
20091 pm_accepts_block_stack_push(parser, false);
20092 pm_token_t opening = not_provided(parser);
20093 block_parameters = parse_block_parameters(parser, false, &opening, true, false, (uint16_t) (depth + 1));
20094 pm_accepts_block_stack_pop(parser);
20095 break;
20096 }
20097 default: {
20098 block_parameters = NULL;
20099 break;
20100 }
20101 }
20102
20103 pm_token_t opening;
20104 pm_node_t *body = NULL;
20105 parser->lambda_enclosure_nesting = previous_lambda_enclosure_nesting;
20106
20107 if (accept1(parser, PM_TOKEN_LAMBDA_BEGIN)) {
20108 opening = parser->previous;
20109
20110 if (!match1(parser, PM_TOKEN_BRACE_RIGHT)) {
20111 body = UP(parse_statements(parser, PM_CONTEXT_LAMBDA_BRACES, (uint16_t) (depth + 1)));
20112 }
20113
20114 parser_warn_indentation_mismatch(parser, opening_newline_index, &operator, false, false);
20115 expect1_opening(parser, PM_TOKEN_BRACE_RIGHT, PM_ERR_LAMBDA_TERM_BRACE, &opening);
20116 } else {
20117 expect1(parser, PM_TOKEN_KEYWORD_DO, PM_ERR_LAMBDA_OPEN);
20118 opening = parser->previous;
20119
20120 if (!match3(parser, PM_TOKEN_KEYWORD_END, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE)) {
20121 pm_accepts_block_stack_push(parser, true);
20122 body = UP(parse_statements(parser, PM_CONTEXT_LAMBDA_DO_END, (uint16_t) (depth + 1)));
20123 pm_accepts_block_stack_pop(parser);
20124 }
20125
20126 if (match2(parser, PM_TOKEN_KEYWORD_RESCUE, PM_TOKEN_KEYWORD_ENSURE)) {
20127 assert(body == NULL || PM_NODE_TYPE_P(body, PM_STATEMENTS_NODE));
20128 body = UP(parse_rescues_implicit_begin(parser, opening_newline_index, &operator, opening.start, (pm_statements_node_t *) body, PM_RESCUES_LAMBDA, (uint16_t) (depth + 1)));
20129 } else {
20130 parser_warn_indentation_mismatch(parser, opening_newline_index, &operator, false, false);
20131 }
20132
20133 expect1_opening(parser, PM_TOKEN_KEYWORD_END, PM_ERR_LAMBDA_TERM_END, &operator);
20134 }
20135
20136 pm_constant_id_list_t locals;
20137 pm_locals_order(parser, &parser->current_scope->locals, &locals, pm_parser_scope_toplevel_p(parser));
20138 pm_node_t *parameters = parse_blocklike_parameters(parser, UP(block_parameters), &operator, &parser->previous);
20139
20140 pm_parser_scope_pop(parser);
20141 pm_accepts_block_stack_pop(parser);
20142
20143 return UP(pm_lambda_node_create(parser, &locals, &operator, &opening, &parser->previous, parameters, body));
20144 }
20145 case PM_TOKEN_UPLUS: {
20146 if (binding_power > PM_BINDING_POWER_UNARY) {
20147 pm_parser_err_prefix(parser, PM_ERR_UNARY_DISALLOWED);
20148 }
20149 parser_lex(parser);
20150
20151 pm_token_t operator = parser->previous;
20152 pm_node_t *receiver = parse_expression(parser, pm_binding_powers[parser->previous.type].right, false, false, PM_ERR_UNARY_RECEIVER, (uint16_t) (depth + 1));
20153 pm_call_node_t *node = pm_call_node_unary_create(parser, &operator, receiver, "+@");
20154
20155 return UP(node);
20156 }
20157 case PM_TOKEN_STRING_BEGIN:
20158 return parse_strings(parser, NULL, accepts_label, (uint16_t) (depth + 1));
20159 case PM_TOKEN_SYMBOL_BEGIN: {
20160 pm_lex_mode_t lex_mode = *parser->lex_modes.current;
20161 parser_lex(parser);
20162
20163 return parse_symbol(parser, &lex_mode, PM_LEX_STATE_END, (uint16_t) (depth + 1));
20164 }
20165 default: {
20166 pm_context_t recoverable = context_recoverable(parser, &parser->current);
20167
20168 if (recoverable != PM_CONTEXT_NONE) {
20169 parser->recovering = true;
20170
20171 // If the given error is not the generic one, then we'll add it
20172 // here because it will provide more context in addition to the
20173 // recoverable error that we will also add.
20174 if (diag_id != PM_ERR_CANNOT_PARSE_EXPRESSION) {
20175 pm_parser_err_prefix(parser, diag_id);
20176 }
20177
20178 // If we get here, then we are assuming this token is closing a
20179 // parent context, so we'll indicate that to the user so that
20180 // they know how we behaved.
20181 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_UNEXPECTED_TOKEN_CLOSE_CONTEXT, pm_token_type_human(parser->current.type), context_human(recoverable));
20182 } else if (diag_id == PM_ERR_CANNOT_PARSE_EXPRESSION) {
20183 // We're going to make a special case here, because "cannot
20184 // parse expression" is pretty generic, and we know here that we
20185 // have an unexpected token.
20186 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_UNEXPECTED_TOKEN_IGNORE, pm_token_type_human(parser->current.type));
20187 } else {
20188 pm_parser_err_prefix(parser, diag_id);
20189 }
20190
20191 return UP(pm_missing_node_create(parser, parser->previous.start, parser->previous.end));
20192 }
20193 }
20194 }
20195
20196 /**
20197 * Parse a value that is going to be written to some kind of variable or method
20198 * call. We need to handle this separately because the rescue modifier is
20199 * permitted on the end of the these expressions, which is a deviation from its
20200 * normal binding power.
20201 *
20202 * Note that this will only be called after an operator write, as in &&=, ||=,
20203 * or any of the binary operators that can be written to a variable.
20204 */
20205 static pm_node_t *
20206 parse_assignment_value(pm_parser_t *parser, pm_binding_power_t previous_binding_power, pm_binding_power_t binding_power, bool accepts_command_call, pm_diagnostic_id_t diag_id, uint16_t depth) {
20207 pm_node_t *value = parse_value_expression(parser, binding_power, previous_binding_power == PM_BINDING_POWER_ASSIGNMENT ? accepts_command_call : previous_binding_power < PM_BINDING_POWER_MATCH, false, diag_id, (uint16_t) (depth + 1));
20208
20209 // Contradicting binding powers, the right-hand-side value of the assignment
20210 // allows the `rescue` modifier.
20211 if (match1(parser, PM_TOKEN_KEYWORD_RESCUE_MODIFIER)) {
20212 context_push(parser, PM_CONTEXT_RESCUE_MODIFIER);
20213
20214 pm_token_t rescue = parser->current;
20215 parser_lex(parser);
20216
20217 pm_node_t *right = parse_expression(parser, pm_binding_powers[PM_TOKEN_KEYWORD_RESCUE_MODIFIER].right, false, false, PM_ERR_RESCUE_MODIFIER_VALUE, (uint16_t) (depth + 1));
20218 context_pop(parser);
20219
20220 return UP(pm_rescue_modifier_node_create(parser, value, &rescue, right));
20221 }
20222
20223 return value;
20224 }
20225
20226 /**
20227 * When a local variable write node is the value being written in a different
20228 * write, the local variable is considered "used".
20229 */
20230 static void
20231 parse_assignment_value_local(pm_parser_t *parser, const pm_node_t *node) {
20232 switch (PM_NODE_TYPE(node)) {
20233 case PM_BEGIN_NODE: {
20234 const pm_begin_node_t *cast = (const pm_begin_node_t *) node;
20235 if (cast->statements != NULL) parse_assignment_value_local(parser, (const pm_node_t *) cast->statements);
20236 break;
20237 }
20238 case PM_LOCAL_VARIABLE_WRITE_NODE: {
20239 const pm_local_variable_write_node_t *cast = (const pm_local_variable_write_node_t *) node;
20240 pm_locals_read(&pm_parser_scope_find(parser, cast->depth)->locals, cast->name);
20241 break;
20242 }
20243 case PM_PARENTHESES_NODE: {
20244 const pm_parentheses_node_t *cast = (const pm_parentheses_node_t *) node;
20245 if (cast->body != NULL) parse_assignment_value_local(parser, cast->body);
20246 break;
20247 }
20248 case PM_STATEMENTS_NODE: {
20249 const pm_statements_node_t *cast = (const pm_statements_node_t *) node;
20250 const pm_node_t *statement;
20251
20252 PM_NODE_LIST_FOREACH(&cast->body, index, statement) {
20253 parse_assignment_value_local(parser, statement);
20254 }
20255 break;
20256 }
20257 default:
20258 break;
20259 }
20260 }
20261
20262 /**
20263 * Parse the value (or values, through an implicit array) that is going to be
20264 * written to some kind of variable or method call. We need to handle this
20265 * separately because the rescue modifier is permitted on the end of the these
20266 * expressions, which is a deviation from its normal binding power.
20267 *
20268 * Additionally, if the value is a local variable write node (e.g., a = a = 1),
20269 * the "a" is marked as being used so the parser should not warn on it.
20270 *
20271 * Note that this will only be called after an = operator, as that is the only
20272 * operator that allows multiple values after it.
20273 */
20274 static pm_node_t *
20275 parse_assignment_values(pm_parser_t *parser, pm_binding_power_t previous_binding_power, pm_binding_power_t binding_power, bool accepts_command_call, pm_diagnostic_id_t diag_id, uint16_t depth) {
20276 bool permitted = true;
20277 if (previous_binding_power != PM_BINDING_POWER_STATEMENT && match1(parser, PM_TOKEN_USTAR)) permitted = false;
20278
20279 pm_node_t *value = parse_starred_expression(parser, binding_power, previous_binding_power == PM_BINDING_POWER_ASSIGNMENT ? accepts_command_call : previous_binding_power < PM_BINDING_POWER_MODIFIER, diag_id, (uint16_t) (depth + 1));
20280 if (!permitted) pm_parser_err_node(parser, value, PM_ERR_UNEXPECTED_MULTI_WRITE);
20281
20282 parse_assignment_value_local(parser, value);
20283 bool single_value = true;
20284
20285 if (previous_binding_power == PM_BINDING_POWER_STATEMENT && (PM_NODE_TYPE_P(value, PM_SPLAT_NODE) || match1(parser, PM_TOKEN_COMMA))) {
20286 single_value = false;
20287
20288 pm_token_t opening = not_provided(parser);
20289 pm_array_node_t *array = pm_array_node_create(parser, &opening);
20290
20291 pm_array_node_elements_append(array, value);
20292 value = UP(array);
20293
20294 while (accept1(parser, PM_TOKEN_COMMA)) {
20295 pm_node_t *element = parse_starred_expression(parser, binding_power, false, PM_ERR_ARRAY_ELEMENT, (uint16_t) (depth + 1));
20296
20297 pm_array_node_elements_append(array, element);
20298 if (PM_NODE_TYPE_P(element, PM_MISSING_NODE)) break;
20299
20300 parse_assignment_value_local(parser, element);
20301 }
20302 }
20303
20304 // Contradicting binding powers, the right-hand-side value of the assignment
20305 // allows the `rescue` modifier.
20306 if ((single_value || (binding_power == (PM_BINDING_POWER_MULTI_ASSIGNMENT + 1))) && match1(parser, PM_TOKEN_KEYWORD_RESCUE_MODIFIER)) {
20307 context_push(parser, PM_CONTEXT_RESCUE_MODIFIER);
20308
20309 pm_token_t rescue = parser->current;
20310 parser_lex(parser);
20311
20312 bool accepts_command_call_inner = false;
20313
20314 // RHS can accept command call iff the value is a call with arguments
20315 // but without parenthesis.
20316 if (PM_NODE_TYPE_P(value, PM_CALL_NODE)) {
20317 pm_call_node_t *call_node = (pm_call_node_t *) value;
20318 if ((call_node->arguments != NULL) && (call_node->opening_loc.start == NULL)) {
20319 accepts_command_call_inner = true;
20320 }
20321 }
20322
20323 pm_node_t *right = parse_expression(parser, pm_binding_powers[PM_TOKEN_KEYWORD_RESCUE_MODIFIER].right, accepts_command_call_inner, false, PM_ERR_RESCUE_MODIFIER_VALUE, (uint16_t) (depth + 1));
20324 context_pop(parser);
20325
20326 return UP(pm_rescue_modifier_node_create(parser, value, &rescue, right));
20327 }
20328
20329 return value;
20330 }
20331
20332 /**
20333 * Ensure a call node that is about to become a call operator node does not
20334 * have arguments or a block attached. If it does, then we'll need to add an
20335 * error message and destroy the arguments/block. Ideally we would keep the node
20336 * around so that consumers would still have access to it, but we don't have a
20337 * great structure for that at the moment.
20338 */
20339 static void
20340 parse_call_operator_write(pm_parser_t *parser, pm_call_node_t *call_node, const pm_token_t *operator) {
20341 if (call_node->arguments != NULL) {
20342 pm_parser_err_token(parser, operator, PM_ERR_OPERATOR_WRITE_ARGUMENTS);
20343 pm_node_unreference(parser, UP(call_node->arguments));
20344 pm_node_destroy(parser, UP(call_node->arguments));
20345 call_node->arguments = NULL;
20346 }
20347
20348 if (call_node->block != NULL) {
20349 pm_parser_err_token(parser, operator, PM_ERR_OPERATOR_WRITE_BLOCK);
20350 pm_node_unreference(parser, UP(call_node->block));
20351 pm_node_destroy(parser, UP(call_node->block));
20352 call_node->block = NULL;
20353 }
20354 }
20355
20356 /**
20357 * This struct is used to pass information between the regular expression parser
20358 * and the named capture callback.
20359 */
20360 typedef struct {
20361 /** The parser that is parsing the regular expression. */
20362 pm_parser_t *parser;
20363
20364 /** The call node wrapping the regular expression node. */
20365 pm_call_node_t *call;
20366
20367 /** The match write node that is being created. */
20368 pm_match_write_node_t *match;
20369
20370 /** The list of names that have been parsed. */
20371 pm_constant_id_list_t names;
20372
20373 /**
20374 * Whether the content of the regular expression is shared. This impacts
20375 * whether or not we used owned constants or shared constants in the
20376 * constant pool for the names of the captures.
20377 */
20378 bool shared;
20379 } parse_regular_expression_named_capture_data_t;
20380
20381 static inline const uint8_t *
20382 pm_named_capture_escape_hex(pm_buffer_t *unescaped, const uint8_t *cursor, const uint8_t *end) {
20383 cursor++;
20384
20385 if (cursor < end && pm_char_is_hexadecimal_digit(*cursor)) {
20386 uint8_t value = escape_hexadecimal_digit(*cursor);
20387 cursor++;
20388
20389 if (cursor < end && pm_char_is_hexadecimal_digit(*cursor)) {
20390 value = (uint8_t) ((value << 4) | escape_hexadecimal_digit(*cursor));
20391 cursor++;
20392 }
20393
20394 pm_buffer_append_byte(unescaped, value);
20395 } else {
20396 pm_buffer_append_string(unescaped, "\\x", 2);
20397 }
20398
20399 return cursor;
20400 }
20401
20402 static inline const uint8_t *
20403 pm_named_capture_escape_octal(pm_buffer_t *unescaped, const uint8_t *cursor, const uint8_t *end) {
20404 uint8_t value = (uint8_t) (*cursor - '0');
20405 cursor++;
20406
20407 if (cursor < end && pm_char_is_octal_digit(*cursor)) {
20408 value = ((uint8_t) (value << 3)) | ((uint8_t) (*cursor - '0'));
20409 cursor++;
20410
20411 if (cursor < end && pm_char_is_octal_digit(*cursor)) {
20412 value = ((uint8_t) (value << 3)) | ((uint8_t) (*cursor - '0'));
20413 cursor++;
20414 }
20415 }
20416
20417 pm_buffer_append_byte(unescaped, value);
20418 return cursor;
20419 }
20420
20421 static inline const uint8_t *
20422 pm_named_capture_escape_unicode(pm_parser_t *parser, pm_buffer_t *unescaped, const uint8_t *cursor, const uint8_t *end, const pm_location_t *error_location) {
20423 const uint8_t *start = cursor - 1;
20424 cursor++;
20425
20426 if (cursor >= end) {
20427 pm_buffer_append_string(unescaped, "\\u", 2);
20428 return cursor;
20429 }
20430
20431 if (*cursor != '{') {
20432 size_t length = pm_strspn_hexadecimal_digit(cursor, MIN(end - cursor, 4));
20433 uint32_t value = escape_unicode(parser, cursor, length, error_location);
20434
20435 if (!pm_buffer_append_unicode_codepoint(unescaped, value)) {
20436 pm_buffer_append_string(unescaped, (const char *) start, (size_t) ((cursor + length) - start));
20437 }
20438
20439 return cursor + length;
20440 }
20441
20442 cursor++;
20443 for (;;) {
20444 while (cursor < end && *cursor == ' ') cursor++;
20445
20446 if (cursor >= end) break;
20447 if (*cursor == '}') {
20448 cursor++;
20449 break;
20450 }
20451
20452 size_t length = pm_strspn_hexadecimal_digit(cursor, end - cursor);
20453 if (length == 0) {
20454 break;
20455 }
20456 uint32_t value = escape_unicode(parser, cursor, length, error_location);
20457
20458 (void) pm_buffer_append_unicode_codepoint(unescaped, value);
20459 cursor += length;
20460 }
20461
20462 return cursor;
20463 }
20464
20465 static void
20466 pm_named_capture_escape(pm_parser_t *parser, pm_buffer_t *unescaped, const uint8_t *source, const size_t length, const uint8_t *cursor, const pm_location_t *error_location) {
20467 const uint8_t *end = source + length;
20468 pm_buffer_append_string(unescaped, (const char *) source, (size_t) (cursor - source));
20469
20470 for (;;) {
20471 if (++cursor >= end) {
20472 pm_buffer_append_byte(unescaped, '\\');
20473 return;
20474 }
20475
20476 switch (*cursor) {
20477 case 'x':
20478 cursor = pm_named_capture_escape_hex(unescaped, cursor, end);
20479 break;
20480 case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7':
20481 cursor = pm_named_capture_escape_octal(unescaped, cursor, end);
20482 break;
20483 case 'u':
20484 cursor = pm_named_capture_escape_unicode(parser, unescaped, cursor, end, error_location);
20485 break;
20486 default:
20487 pm_buffer_append_byte(unescaped, '\\');
20488 break;
20489 }
20490
20491 const uint8_t *next_cursor = pm_memchr(cursor, '\\', (size_t) (end - cursor), parser->encoding_changed, parser->encoding);
20492 if (next_cursor == NULL) break;
20493
20494 pm_buffer_append_string(unescaped, (const char *) cursor, (size_t) (next_cursor - cursor));
20495 cursor = next_cursor;
20496 }
20497
20498 pm_buffer_append_string(unescaped, (const char *) cursor, (size_t) (end - cursor));
20499 }
20500
20501 /**
20502 * This callback is called when the regular expression parser encounters a named
20503 * capture group.
20504 */
20505 static void
20506 parse_regular_expression_named_capture(const pm_string_t *capture, void *data) {
20507 parse_regular_expression_named_capture_data_t *callback_data = (parse_regular_expression_named_capture_data_t *) data;
20508
20509 pm_parser_t *parser = callback_data->parser;
20510 pm_call_node_t *call = callback_data->call;
20511 pm_constant_id_list_t *names = &callback_data->names;
20512
20513 const uint8_t *source = pm_string_source(capture);
20514 size_t length = pm_string_length(capture);
20515 pm_buffer_t unescaped = { 0 };
20516
20517 // First, we need to handle escapes within the name of the capture group.
20518 // This is because regular expressions have three different representations
20519 // in prism. The first is the plain source code. The second is the
20520 // representation that will be sent to the regular expression engine, which
20521 // is the value of the "unescaped" field. This is poorly named, because it
20522 // actually still contains escapes, just a subset of them that the regular
20523 // expression engine knows how to handle. The third representation is fully
20524 // unescaped, which is what we need.
20525 const uint8_t *cursor = pm_memchr(source, '\\', length, parser->encoding_changed, parser->encoding);
20526 if (PRISM_UNLIKELY(cursor != NULL)) {
20527 pm_named_capture_escape(parser, &unescaped, source, length, cursor, callback_data->shared ? NULL : &call->receiver->location);
20528 source = (const uint8_t *) pm_buffer_value(&unescaped);
20529 length = pm_buffer_length(&unescaped);
20530 }
20531
20532 pm_location_t location;
20533 pm_constant_id_t name;
20534
20535 // If the name of the capture group isn't a valid identifier, we do
20536 // not add it to the local table.
20537 if (!pm_slice_is_valid_local(parser, source, source + length)) {
20538 pm_buffer_free(&unescaped);
20539 return;
20540 }
20541
20542 if (callback_data->shared) {
20543 // If the unescaped string is a slice of the source, then we can
20544 // copy the names directly. The pointers will line up.
20545 location = (pm_location_t) { .start = source, .end = source + length };
20546 name = pm_parser_constant_id_location(parser, location.start, location.end);
20547 } else {
20548 // Otherwise, the name is a slice of the malloc-ed owned string,
20549 // in which case we need to copy it out into a new string.
20550 location = (pm_location_t) { .start = call->receiver->location.start, .end = call->receiver->location.end };
20551
20552 void *memory = xmalloc(length);
20553 if (memory == NULL) abort();
20554
20555 memcpy(memory, source, length);
20556 name = pm_parser_constant_id_owned(parser, (uint8_t *) memory, length);
20557 }
20558
20559 // Add this name to the list of constants if it is valid, not duplicated,
20560 // and not a keyword.
20561 if (name != 0 && !pm_constant_id_list_includes(names, name)) {
20562 pm_constant_id_list_append(names, name);
20563
20564 int depth;
20565 if ((depth = pm_parser_local_depth_constant_id(parser, name)) == -1) {
20566 // If the local is not already a local but it is a keyword, then we
20567 // do not want to add a capture for this.
20568 if (pm_local_is_keyword((const char *) source, length)) {
20569 pm_buffer_free(&unescaped);
20570 return;
20571 }
20572
20573 // If the identifier is not already a local, then we will add it to
20574 // the local table.
20575 pm_parser_local_add(parser, name, location.start, location.end, 0);
20576 }
20577
20578 // Here we lazily create the MatchWriteNode since we know we're
20579 // about to add a target.
20580 if (callback_data->match == NULL) {
20581 callback_data->match = pm_match_write_node_create(parser, call);
20582 }
20583
20584 // Next, create the local variable target and add it to the list of
20585 // targets for the match.
20586 pm_node_t *target = UP(pm_local_variable_target_node_create(parser, &location, name, depth == -1 ? 0 : (uint32_t) depth));
20587 pm_node_list_append(&callback_data->match->targets, target);
20588 }
20589
20590 pm_buffer_free(&unescaped);
20591 }
20592
20593 /**
20594 * Potentially change a =~ with a regular expression with named captures into a
20595 * match write node.
20596 */
20597 static pm_node_t *
20598 parse_regular_expression_named_captures(pm_parser_t *parser, const pm_string_t *content, pm_call_node_t *call, bool extended_mode) {
20599 parse_regular_expression_named_capture_data_t callback_data = {
20600 .parser = parser,
20601 .call = call,
20602 .names = { 0 },
20603 .shared = content->type == PM_STRING_SHARED
20604 };
20605
20606 parse_regular_expression_error_data_t error_data = {
20607 .parser = parser,
20608 .start = call->receiver->location.start,
20609 .end = call->receiver->location.end,
20610 .shared = content->type == PM_STRING_SHARED
20611 };
20612
20613 pm_regexp_parse(parser, pm_string_source(content), pm_string_length(content), extended_mode, parse_regular_expression_named_capture, &callback_data, parse_regular_expression_error, &error_data);
20614 pm_constant_id_list_free(&callback_data.names);
20615
20616 if (callback_data.match != NULL) {
20617 return UP(callback_data.match);
20618 } else {
20619 return UP(call);
20620 }
20621 }
20622
20623 static inline pm_node_t *
20624 parse_expression_infix(pm_parser_t *parser, pm_node_t *node, pm_binding_power_t previous_binding_power, pm_binding_power_t binding_power, bool accepts_command_call, uint16_t depth) {
20625 pm_token_t token = parser->current;
20626
20627 switch (token.type) {
20628 case PM_TOKEN_EQUAL: {
20629 switch (PM_NODE_TYPE(node)) {
20630 case PM_CALL_NODE: {
20631 // If we have no arguments to the call node and we need this
20632 // to be a target then this is either a method call or a
20633 // local variable write. This _must_ happen before the value
20634 // is parsed because it could be referenced in the value.
20635 pm_call_node_t *call_node = (pm_call_node_t *) node;
20636 if (PM_NODE_FLAG_P(call_node, PM_CALL_NODE_FLAGS_VARIABLE_CALL)) {
20637 pm_parser_local_add_location(parser, call_node->message_loc.start, call_node->message_loc.end, 0);
20638 }
20639 }
20640 PRISM_FALLTHROUGH
20641 case PM_CASE_WRITABLE: {
20642 // When we have `it = value`, we need to add `it` as a local
20643 // variable before parsing the value, in case the value
20644 // references the variable.
20645 if (PM_NODE_TYPE_P(node, PM_IT_LOCAL_VARIABLE_READ_NODE)) {
20646 pm_parser_local_add_location(parser, node->location.start, node->location.end, 0);
20647 }
20648
20649 parser_lex(parser);
20650 pm_node_t *value = parse_assignment_values(parser, previous_binding_power, PM_NODE_TYPE_P(node, PM_MULTI_TARGET_NODE) ? PM_BINDING_POWER_MULTI_ASSIGNMENT + 1 : binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_EQUAL, (uint16_t) (depth + 1));
20651
20652 if (PM_NODE_TYPE_P(node, PM_MULTI_TARGET_NODE) && previous_binding_power != PM_BINDING_POWER_STATEMENT) {
20653 pm_parser_err_node(parser, node, PM_ERR_UNEXPECTED_MULTI_WRITE);
20654 }
20655
20656 return parse_write(parser, node, &token, value);
20657 }
20658 case PM_SPLAT_NODE: {
20659 pm_multi_target_node_t *multi_target = pm_multi_target_node_create(parser);
20660 pm_multi_target_node_targets_append(parser, multi_target, node);
20661
20662 parser_lex(parser);
20663 pm_node_t *value = parse_assignment_values(parser, previous_binding_power, PM_BINDING_POWER_MULTI_ASSIGNMENT + 1, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_EQUAL, (uint16_t) (depth + 1));
20664 return parse_write(parser, UP(multi_target), &token, value);
20665 }
20666 case PM_SOURCE_ENCODING_NODE:
20667 case PM_FALSE_NODE:
20668 case PM_SOURCE_FILE_NODE:
20669 case PM_SOURCE_LINE_NODE:
20670 case PM_NIL_NODE:
20671 case PM_SELF_NODE:
20672 case PM_TRUE_NODE: {
20673 // In these special cases, we have specific error messages
20674 // and we will replace them with local variable writes.
20675 parser_lex(parser);
20676 pm_node_t *value = parse_assignment_values(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_EQUAL, (uint16_t) (depth + 1));
20677 return parse_unwriteable_write(parser, node, &token, value);
20678 }
20679 default:
20680 // In this case we have an = sign, but we don't know what
20681 // it's for. We need to treat it as an error. We'll mark it
20682 // as an error and skip past it.
20683 parser_lex(parser);
20684 pm_parser_err_token(parser, &token, PM_ERR_EXPRESSION_NOT_WRITABLE);
20685 return node;
20686 }
20687 }
20688 case PM_TOKEN_AMPERSAND_AMPERSAND_EQUAL: {
20689 switch (PM_NODE_TYPE(node)) {
20690 case PM_BACK_REFERENCE_READ_NODE:
20691 case PM_NUMBERED_REFERENCE_READ_NODE:
20692 PM_PARSER_ERR_NODE_FORMAT_CONTENT(parser, node, PM_ERR_WRITE_TARGET_READONLY);
20693 PRISM_FALLTHROUGH
20694 case PM_GLOBAL_VARIABLE_READ_NODE: {
20695 parser_lex(parser);
20696
20697 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ, (uint16_t) (depth + 1));
20698 pm_node_t *result = UP(pm_global_variable_and_write_node_create(parser, node, &token, value));
20699
20700 pm_node_destroy(parser, node);
20701 return result;
20702 }
20703 case PM_CLASS_VARIABLE_READ_NODE: {
20704 parser_lex(parser);
20705
20706 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ, (uint16_t) (depth + 1));
20707 pm_node_t *result = UP(pm_class_variable_and_write_node_create(parser, (pm_class_variable_read_node_t *) node, &token, value));
20708
20709 pm_node_destroy(parser, node);
20710 return result;
20711 }
20712 case PM_CONSTANT_PATH_NODE: {
20713 parser_lex(parser);
20714
20715 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ, (uint16_t) (depth + 1));
20716 pm_node_t *write = UP(pm_constant_path_and_write_node_create(parser, (pm_constant_path_node_t *) node, &token, value));
20717
20718 return parse_shareable_constant_write(parser, write);
20719 }
20720 case PM_CONSTANT_READ_NODE: {
20721 parser_lex(parser);
20722
20723 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ, (uint16_t) (depth + 1));
20724 pm_node_t *write = UP(pm_constant_and_write_node_create(parser, (pm_constant_read_node_t *) node, &token, value));
20725
20726 pm_node_destroy(parser, node);
20727 return parse_shareable_constant_write(parser, write);
20728 }
20729 case PM_INSTANCE_VARIABLE_READ_NODE: {
20730 parser_lex(parser);
20731
20732 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ, (uint16_t) (depth + 1));
20733 pm_node_t *result = UP(pm_instance_variable_and_write_node_create(parser, (pm_instance_variable_read_node_t *) node, &token, value));
20734
20735 pm_node_destroy(parser, node);
20736 return result;
20737 }
20738 case PM_IT_LOCAL_VARIABLE_READ_NODE: {
20739 pm_constant_id_t name = pm_parser_local_add_constant(parser, "it", 2);
20740 parser_lex(parser);
20741
20742 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ, (uint16_t) (depth + 1));
20743 pm_node_t *result = UP(pm_local_variable_and_write_node_create(parser, node, &token, value, name, 0));
20744
20745 pm_node_unreference(parser, node);
20746 pm_node_destroy(parser, node);
20747 return result;
20748 }
20749 case PM_LOCAL_VARIABLE_READ_NODE: {
20750 if (pm_token_is_numbered_parameter(node->location.start, node->location.end)) {
20751 PM_PARSER_ERR_FORMAT(parser, node->location.start, node->location.end, PM_ERR_PARAMETER_NUMBERED_RESERVED, node->location.start);
20752 pm_node_unreference(parser, node);
20753 }
20754
20755 pm_local_variable_read_node_t *cast = (pm_local_variable_read_node_t *) node;
20756 parser_lex(parser);
20757
20758 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ, (uint16_t) (depth + 1));
20759 pm_node_t *result = UP(pm_local_variable_and_write_node_create(parser, node, &token, value, cast->name, cast->depth));
20760
20761 pm_node_destroy(parser, node);
20762 return result;
20763 }
20764 case PM_CALL_NODE: {
20765 pm_call_node_t *cast = (pm_call_node_t *) node;
20766
20767 // If we have a vcall (a method with no arguments and no
20768 // receiver that could have been a local variable) then we
20769 // will transform it into a local variable write.
20770 if (PM_NODE_FLAG_P(cast, PM_CALL_NODE_FLAGS_VARIABLE_CALL)) {
20771 pm_location_t *message_loc = &cast->message_loc;
20772 pm_refute_numbered_parameter(parser, message_loc->start, message_loc->end);
20773
20774 pm_constant_id_t constant_id = pm_parser_local_add_location(parser, message_loc->start, message_loc->end, 1);
20775 parser_lex(parser);
20776
20777 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ, (uint16_t) (depth + 1));
20778 pm_node_t *result = UP(pm_local_variable_and_write_node_create(parser, UP(cast), &token, value, constant_id, 0));
20779
20780 pm_node_destroy(parser, UP(cast));
20781 return result;
20782 }
20783
20784 // Move past the token here so that we have already added
20785 // the local variable by this point.
20786 parser_lex(parser);
20787
20788 // If there is no call operator and the message is "[]" then
20789 // this is an aref expression, and we can transform it into
20790 // an aset expression.
20791 if (PM_NODE_FLAG_P(cast, PM_CALL_NODE_FLAGS_INDEX)) {
20792 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ, (uint16_t) (depth + 1));
20793 return UP(pm_index_and_write_node_create(parser, cast, &token, value));
20794 }
20795
20796 // If this node cannot be writable, then we have an error.
20797 if (pm_call_node_writable_p(parser, cast)) {
20798 parse_write_name(parser, &cast->name);
20799 } else {
20800 pm_parser_err_node(parser, node, PM_ERR_WRITE_TARGET_UNEXPECTED);
20801 }
20802
20803 parse_call_operator_write(parser, cast, &token);
20804 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ, (uint16_t) (depth + 1));
20805 return UP(pm_call_and_write_node_create(parser, cast, &token, value));
20806 }
20807 case PM_MULTI_WRITE_NODE: {
20808 parser_lex(parser);
20809 pm_parser_err_token(parser, &token, PM_ERR_AMPAMPEQ_MULTI_ASSIGN);
20810 return node;
20811 }
20812 default:
20813 parser_lex(parser);
20814
20815 // In this case we have an &&= sign, but we don't know what it's for.
20816 // We need to treat it as an error. For now, we'll mark it as an error
20817 // and just skip right past it.
20818 pm_parser_err_token(parser, &token, PM_ERR_EXPECT_EXPRESSION_AFTER_AMPAMPEQ);
20819 return node;
20820 }
20821 }
20822 case PM_TOKEN_PIPE_PIPE_EQUAL: {
20823 switch (PM_NODE_TYPE(node)) {
20824 case PM_BACK_REFERENCE_READ_NODE:
20825 case PM_NUMBERED_REFERENCE_READ_NODE:
20826 PM_PARSER_ERR_NODE_FORMAT_CONTENT(parser, node, PM_ERR_WRITE_TARGET_READONLY);
20827 PRISM_FALLTHROUGH
20828 case PM_GLOBAL_VARIABLE_READ_NODE: {
20829 parser_lex(parser);
20830
20831 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ, (uint16_t) (depth + 1));
20832 pm_node_t *result = UP(pm_global_variable_or_write_node_create(parser, node, &token, value));
20833
20834 pm_node_destroy(parser, node);
20835 return result;
20836 }
20837 case PM_CLASS_VARIABLE_READ_NODE: {
20838 parser_lex(parser);
20839
20840 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ, (uint16_t) (depth + 1));
20841 pm_node_t *result = UP(pm_class_variable_or_write_node_create(parser, (pm_class_variable_read_node_t *) node, &token, value));
20842
20843 pm_node_destroy(parser, node);
20844 return result;
20845 }
20846 case PM_CONSTANT_PATH_NODE: {
20847 parser_lex(parser);
20848
20849 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ, (uint16_t) (depth + 1));
20850 pm_node_t *write = UP(pm_constant_path_or_write_node_create(parser, (pm_constant_path_node_t *) node, &token, value));
20851
20852 return parse_shareable_constant_write(parser, write);
20853 }
20854 case PM_CONSTANT_READ_NODE: {
20855 parser_lex(parser);
20856
20857 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ, (uint16_t) (depth + 1));
20858 pm_node_t *write = UP(pm_constant_or_write_node_create(parser, (pm_constant_read_node_t *) node, &token, value));
20859
20860 pm_node_destroy(parser, node);
20861 return parse_shareable_constant_write(parser, write);
20862 }
20863 case PM_INSTANCE_VARIABLE_READ_NODE: {
20864 parser_lex(parser);
20865
20866 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ, (uint16_t) (depth + 1));
20867 pm_node_t *result = UP(pm_instance_variable_or_write_node_create(parser, (pm_instance_variable_read_node_t *) node, &token, value));
20868
20869 pm_node_destroy(parser, node);
20870 return result;
20871 }
20872 case PM_IT_LOCAL_VARIABLE_READ_NODE: {
20873 pm_constant_id_t name = pm_parser_local_add_constant(parser, "it", 2);
20874 parser_lex(parser);
20875
20876 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ, (uint16_t) (depth + 1));
20877 pm_node_t *result = UP(pm_local_variable_or_write_node_create(parser, node, &token, value, name, 0));
20878
20879 pm_node_unreference(parser, node);
20880 pm_node_destroy(parser, node);
20881 return result;
20882 }
20883 case PM_LOCAL_VARIABLE_READ_NODE: {
20884 if (pm_token_is_numbered_parameter(node->location.start, node->location.end)) {
20885 PM_PARSER_ERR_FORMAT(parser, node->location.start, node->location.end, PM_ERR_PARAMETER_NUMBERED_RESERVED, node->location.start);
20886 pm_node_unreference(parser, node);
20887 }
20888
20889 pm_local_variable_read_node_t *cast = (pm_local_variable_read_node_t *) node;
20890 parser_lex(parser);
20891
20892 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ, (uint16_t) (depth + 1));
20893 pm_node_t *result = UP(pm_local_variable_or_write_node_create(parser, node, &token, value, cast->name, cast->depth));
20894
20895 pm_node_destroy(parser, node);
20896 return result;
20897 }
20898 case PM_CALL_NODE: {
20899 pm_call_node_t *cast = (pm_call_node_t *) node;
20900
20901 // If we have a vcall (a method with no arguments and no
20902 // receiver that could have been a local variable) then we
20903 // will transform it into a local variable write.
20904 if (PM_NODE_FLAG_P(cast, PM_CALL_NODE_FLAGS_VARIABLE_CALL)) {
20905 pm_location_t *message_loc = &cast->message_loc;
20906 pm_refute_numbered_parameter(parser, message_loc->start, message_loc->end);
20907
20908 pm_constant_id_t constant_id = pm_parser_local_add_location(parser, message_loc->start, message_loc->end, 1);
20909 parser_lex(parser);
20910
20911 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ, (uint16_t) (depth + 1));
20912 pm_node_t *result = UP(pm_local_variable_or_write_node_create(parser, UP(cast), &token, value, constant_id, 0));
20913
20914 pm_node_destroy(parser, UP(cast));
20915 return result;
20916 }
20917
20918 // Move past the token here so that we have already added
20919 // the local variable by this point.
20920 parser_lex(parser);
20921
20922 // If there is no call operator and the message is "[]" then
20923 // this is an aref expression, and we can transform it into
20924 // an aset expression.
20925 if (PM_NODE_FLAG_P(cast, PM_CALL_NODE_FLAGS_INDEX)) {
20926 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ, (uint16_t) (depth + 1));
20927 return UP(pm_index_or_write_node_create(parser, cast, &token, value));
20928 }
20929
20930 // If this node cannot be writable, then we have an error.
20931 if (pm_call_node_writable_p(parser, cast)) {
20932 parse_write_name(parser, &cast->name);
20933 } else {
20934 pm_parser_err_node(parser, node, PM_ERR_WRITE_TARGET_UNEXPECTED);
20935 }
20936
20937 parse_call_operator_write(parser, cast, &token);
20938 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ, (uint16_t) (depth + 1));
20939 return UP(pm_call_or_write_node_create(parser, cast, &token, value));
20940 }
20941 case PM_MULTI_WRITE_NODE: {
20942 parser_lex(parser);
20943 pm_parser_err_token(parser, &token, PM_ERR_PIPEPIPEEQ_MULTI_ASSIGN);
20944 return node;
20945 }
20946 default:
20947 parser_lex(parser);
20948
20949 // In this case we have an ||= sign, but we don't know what it's for.
20950 // We need to treat it as an error. For now, we'll mark it as an error
20951 // and just skip right past it.
20952 pm_parser_err_token(parser, &token, PM_ERR_EXPECT_EXPRESSION_AFTER_PIPEPIPEEQ);
20953 return node;
20954 }
20955 }
20956 case PM_TOKEN_AMPERSAND_EQUAL:
20957 case PM_TOKEN_CARET_EQUAL:
20958 case PM_TOKEN_GREATER_GREATER_EQUAL:
20959 case PM_TOKEN_LESS_LESS_EQUAL:
20960 case PM_TOKEN_MINUS_EQUAL:
20961 case PM_TOKEN_PERCENT_EQUAL:
20962 case PM_TOKEN_PIPE_EQUAL:
20963 case PM_TOKEN_PLUS_EQUAL:
20964 case PM_TOKEN_SLASH_EQUAL:
20965 case PM_TOKEN_STAR_EQUAL:
20966 case PM_TOKEN_STAR_STAR_EQUAL: {
20967 switch (PM_NODE_TYPE(node)) {
20968 case PM_BACK_REFERENCE_READ_NODE:
20969 case PM_NUMBERED_REFERENCE_READ_NODE:
20970 PM_PARSER_ERR_NODE_FORMAT_CONTENT(parser, node, PM_ERR_WRITE_TARGET_READONLY);
20971 PRISM_FALLTHROUGH
20972 case PM_GLOBAL_VARIABLE_READ_NODE: {
20973 parser_lex(parser);
20974
20975 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
20976 pm_node_t *result = UP(pm_global_variable_operator_write_node_create(parser, node, &token, value));
20977
20978 pm_node_destroy(parser, node);
20979 return result;
20980 }
20981 case PM_CLASS_VARIABLE_READ_NODE: {
20982 parser_lex(parser);
20983
20984 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
20985 pm_node_t *result = UP(pm_class_variable_operator_write_node_create(parser, (pm_class_variable_read_node_t *) node, &token, value));
20986
20987 pm_node_destroy(parser, node);
20988 return result;
20989 }
20990 case PM_CONSTANT_PATH_NODE: {
20991 parser_lex(parser);
20992
20993 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
20994 pm_node_t *write = UP(pm_constant_path_operator_write_node_create(parser, (pm_constant_path_node_t *) node, &token, value));
20995
20996 return parse_shareable_constant_write(parser, write);
20997 }
20998 case PM_CONSTANT_READ_NODE: {
20999 parser_lex(parser);
21000
21001 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21002 pm_node_t *write = UP(pm_constant_operator_write_node_create(parser, (pm_constant_read_node_t *) node, &token, value));
21003
21004 pm_node_destroy(parser, node);
21005 return parse_shareable_constant_write(parser, write);
21006 }
21007 case PM_INSTANCE_VARIABLE_READ_NODE: {
21008 parser_lex(parser);
21009
21010 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21011 pm_node_t *result = UP(pm_instance_variable_operator_write_node_create(parser, (pm_instance_variable_read_node_t *) node, &token, value));
21012
21013 pm_node_destroy(parser, node);
21014 return result;
21015 }
21016 case PM_IT_LOCAL_VARIABLE_READ_NODE: {
21017 pm_constant_id_t name = pm_parser_local_add_constant(parser, "it", 2);
21018 parser_lex(parser);
21019
21020 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21021 pm_node_t *result = UP(pm_local_variable_operator_write_node_create(parser, node, &token, value, name, 0));
21022
21023 pm_node_unreference(parser, node);
21024 pm_node_destroy(parser, node);
21025 return result;
21026 }
21027 case PM_LOCAL_VARIABLE_READ_NODE: {
21028 if (pm_token_is_numbered_parameter(node->location.start, node->location.end)) {
21029 PM_PARSER_ERR_FORMAT(parser, node->location.start, node->location.end, PM_ERR_PARAMETER_NUMBERED_RESERVED, node->location.start);
21030 pm_node_unreference(parser, node);
21031 }
21032
21033 pm_local_variable_read_node_t *cast = (pm_local_variable_read_node_t *) node;
21034 parser_lex(parser);
21035
21036 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21037 pm_node_t *result = UP(pm_local_variable_operator_write_node_create(parser, node, &token, value, cast->name, cast->depth));
21038
21039 pm_node_destroy(parser, node);
21040 return result;
21041 }
21042 case PM_CALL_NODE: {
21043 parser_lex(parser);
21044 pm_call_node_t *cast = (pm_call_node_t *) node;
21045
21046 // If we have a vcall (a method with no arguments and no
21047 // receiver that could have been a local variable) then we
21048 // will transform it into a local variable write.
21049 if (PM_NODE_FLAG_P(cast, PM_CALL_NODE_FLAGS_VARIABLE_CALL)) {
21050 pm_location_t *message_loc = &cast->message_loc;
21051 pm_refute_numbered_parameter(parser, message_loc->start, message_loc->end);
21052
21053 pm_constant_id_t constant_id = pm_parser_local_add_location(parser, message_loc->start, message_loc->end, 1);
21054 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21055 pm_node_t *result = UP(pm_local_variable_operator_write_node_create(parser, UP(cast), &token, value, constant_id, 0));
21056
21057 pm_node_destroy(parser, UP(cast));
21058 return result;
21059 }
21060
21061 // If there is no call operator and the message is "[]" then
21062 // this is an aref expression, and we can transform it into
21063 // an aset expression.
21064 if (PM_NODE_FLAG_P(cast, PM_CALL_NODE_FLAGS_INDEX)) {
21065 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21066 return UP(pm_index_operator_write_node_create(parser, cast, &token, value));
21067 }
21068
21069 // If this node cannot be writable, then we have an error.
21070 if (pm_call_node_writable_p(parser, cast)) {
21071 parse_write_name(parser, &cast->name);
21072 } else {
21073 pm_parser_err_node(parser, node, PM_ERR_WRITE_TARGET_UNEXPECTED);
21074 }
21075
21076 parse_call_operator_write(parser, cast, &token);
21077 pm_node_t *value = parse_assignment_value(parser, previous_binding_power, binding_power, accepts_command_call, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21078 return UP(pm_call_operator_write_node_create(parser, cast, &token, value));
21079 }
21080 case PM_MULTI_WRITE_NODE: {
21081 parser_lex(parser);
21082 pm_parser_err_token(parser, &token, PM_ERR_OPERATOR_MULTI_ASSIGN);
21083 return node;
21084 }
21085 default:
21086 parser_lex(parser);
21087
21088 // In this case we have an operator but we don't know what it's for.
21089 // We need to treat it as an error. For now, we'll mark it as an error
21090 // and just skip right past it.
21091 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->previous, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, pm_token_type_human(parser->current.type));
21092 return node;
21093 }
21094 }
21095 case PM_TOKEN_AMPERSAND_AMPERSAND:
21096 case PM_TOKEN_KEYWORD_AND: {
21097 parser_lex(parser);
21098
21099 pm_node_t *right = parse_expression(parser, binding_power, parser->previous.type == PM_TOKEN_KEYWORD_AND, false, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21100 return UP(pm_and_node_create(parser, node, &token, right));
21101 }
21102 case PM_TOKEN_KEYWORD_OR:
21103 case PM_TOKEN_PIPE_PIPE: {
21104 parser_lex(parser);
21105
21106 pm_node_t *right = parse_expression(parser, binding_power, parser->previous.type == PM_TOKEN_KEYWORD_OR, false, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21107 return UP(pm_or_node_create(parser, node, &token, right));
21108 }
21109 case PM_TOKEN_EQUAL_TILDE: {
21110 // Note that we _must_ parse the value before adding the local
21111 // variables in order to properly mirror the behavior of Ruby. For
21112 // example,
21113 //
21114 // /(?<foo>bar)/ =~ foo
21115 //
21116 // In this case, `foo` should be a method call and not a local yet.
21117 parser_lex(parser);
21118 pm_node_t *argument = parse_expression(parser, binding_power, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21119
21120 // By default, we're going to create a call node and then return it.
21121 pm_call_node_t *call = pm_call_node_binary_create(parser, node, &token, argument, 0);
21122 pm_node_t *result = UP(call);
21123
21124 // If the receiver of this =~ is a regular expression node, then we
21125 // need to introduce local variables for it based on its named
21126 // capture groups.
21127 if (PM_NODE_TYPE_P(node, PM_INTERPOLATED_REGULAR_EXPRESSION_NODE)) {
21128 // It's possible to have an interpolated regular expression node
21129 // that only contains strings. This is because it can be split
21130 // up by a heredoc. In this case we need to concat the unescaped
21131 // strings together and then parse them as a regular expression.
21132 pm_node_list_t *parts = &((pm_interpolated_regular_expression_node_t *) node)->parts;
21133
21134 bool interpolated = false;
21135 size_t total_length = 0;
21136
21137 pm_node_t *part;
21138 PM_NODE_LIST_FOREACH(parts, index, part) {
21139 if (PM_NODE_TYPE_P(part, PM_STRING_NODE)) {
21140 total_length += pm_string_length(&((pm_string_node_t *) part)->unescaped);
21141 } else {
21142 interpolated = true;
21143 break;
21144 }
21145 }
21146
21147 if (!interpolated && total_length > 0) {
21148 void *memory = xmalloc(total_length);
21149 if (!memory) abort();
21150
21151 uint8_t *cursor = memory;
21152 PM_NODE_LIST_FOREACH(parts, index, part) {
21153 pm_string_t *unescaped = &((pm_string_node_t *) part)->unescaped;
21154 size_t length = pm_string_length(unescaped);
21155
21156 memcpy(cursor, pm_string_source(unescaped), length);
21157 cursor += length;
21158 }
21159
21160 pm_string_t owned;
21161 pm_string_owned_init(&owned, (uint8_t *) memory, total_length);
21162
21163 result = parse_regular_expression_named_captures(parser, &owned, call, PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_EXTENDED));
21164 pm_string_free(&owned);
21165 }
21166 } else if (PM_NODE_TYPE_P(node, PM_REGULAR_EXPRESSION_NODE)) {
21167 // If we have a regular expression node, then we can just parse
21168 // the named captures directly off the unescaped string.
21169 const pm_string_t *content = &((pm_regular_expression_node_t *) node)->unescaped;
21170 result = parse_regular_expression_named_captures(parser, content, call, PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_EXTENDED));
21171 }
21172
21173 return result;
21174 }
21175 case PM_TOKEN_UAMPERSAND:
21176 case PM_TOKEN_USTAR:
21177 case PM_TOKEN_USTAR_STAR:
21178 // The only times this will occur are when we are in an error state,
21179 // but we'll put them in here so that errors can propagate.
21180 case PM_TOKEN_BANG_EQUAL:
21181 case PM_TOKEN_BANG_TILDE:
21182 case PM_TOKEN_EQUAL_EQUAL:
21183 case PM_TOKEN_EQUAL_EQUAL_EQUAL:
21184 case PM_TOKEN_LESS_EQUAL_GREATER:
21185 case PM_TOKEN_CARET:
21186 case PM_TOKEN_PIPE:
21187 case PM_TOKEN_AMPERSAND:
21188 case PM_TOKEN_GREATER_GREATER:
21189 case PM_TOKEN_LESS_LESS:
21190 case PM_TOKEN_MINUS:
21191 case PM_TOKEN_PLUS:
21192 case PM_TOKEN_PERCENT:
21193 case PM_TOKEN_SLASH:
21194 case PM_TOKEN_STAR:
21195 case PM_TOKEN_STAR_STAR: {
21196 parser_lex(parser);
21197 pm_token_t operator = parser->previous;
21198 switch (PM_NODE_TYPE(node)) {
21199 case PM_RESCUE_MODIFIER_NODE: {
21200 pm_rescue_modifier_node_t *cast = (pm_rescue_modifier_node_t *) node;
21201 if (PM_NODE_TYPE_P(cast->rescue_expression, PM_MATCH_PREDICATE_NODE) || PM_NODE_TYPE_P(cast->rescue_expression, PM_MATCH_REQUIRED_NODE)) {
21202 PM_PARSER_ERR_TOKEN_FORMAT(parser, operator, PM_ERR_EXPECT_EOL_AFTER_STATEMENT, pm_token_type_human(operator.type));
21203 }
21204 break;
21205 }
21206 case PM_AND_NODE: {
21207 pm_and_node_t *cast = (pm_and_node_t *) node;
21208 if (PM_NODE_TYPE_P(cast->right, PM_MATCH_PREDICATE_NODE) || PM_NODE_TYPE_P(cast->right, PM_MATCH_REQUIRED_NODE)) {
21209 PM_PARSER_ERR_TOKEN_FORMAT(parser, operator, PM_ERR_EXPECT_EOL_AFTER_STATEMENT, pm_token_type_human(operator.type));
21210 }
21211 break;
21212 }
21213 case PM_OR_NODE: {
21214 pm_or_node_t *cast = (pm_or_node_t *) node;
21215 if (PM_NODE_TYPE_P(cast->right, PM_MATCH_PREDICATE_NODE) || PM_NODE_TYPE_P(cast->right, PM_MATCH_REQUIRED_NODE)) {
21216 PM_PARSER_ERR_TOKEN_FORMAT(parser, operator, PM_ERR_EXPECT_EOL_AFTER_STATEMENT, pm_token_type_human(operator.type));
21217 }
21218 break;
21219 }
21220 default:
21221 break;
21222 }
21223
21224 pm_node_t *argument = parse_expression(parser, binding_power, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21225 return UP(pm_call_node_binary_create(parser, node, &token, argument, 0));
21226 }
21227 case PM_TOKEN_GREATER:
21228 case PM_TOKEN_GREATER_EQUAL:
21229 case PM_TOKEN_LESS:
21230 case PM_TOKEN_LESS_EQUAL: {
21231 if (PM_NODE_TYPE_P(node, PM_CALL_NODE) && PM_NODE_FLAG_P(node, PM_CALL_NODE_FLAGS_COMPARISON)) {
21232 PM_PARSER_WARN_TOKEN_FORMAT_CONTENT(parser, parser->current, PM_WARN_COMPARISON_AFTER_COMPARISON);
21233 }
21234
21235 parser_lex(parser);
21236 pm_node_t *argument = parse_expression(parser, binding_power, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21237 return UP(pm_call_node_binary_create(parser, node, &token, argument, PM_CALL_NODE_FLAGS_COMPARISON));
21238 }
21239 case PM_TOKEN_AMPERSAND_DOT:
21240 case PM_TOKEN_DOT: {
21241 parser_lex(parser);
21242 pm_token_t operator = parser->previous;
21243 pm_arguments_t arguments = { 0 };
21244
21245 // This if statement handles the foo.() syntax.
21246 if (match1(parser, PM_TOKEN_PARENTHESIS_LEFT)) {
21247 parse_arguments_list(parser, &arguments, true, false, (uint16_t) (depth + 1));
21248 return UP(pm_call_node_shorthand_create(parser, node, &operator, &arguments));
21249 }
21250
21251 switch (PM_NODE_TYPE(node)) {
21252 case PM_RESCUE_MODIFIER_NODE: {
21253 pm_rescue_modifier_node_t *cast = (pm_rescue_modifier_node_t *) node;
21254 if (PM_NODE_TYPE_P(cast->rescue_expression, PM_MATCH_PREDICATE_NODE) || PM_NODE_TYPE_P(cast->rescue_expression, PM_MATCH_REQUIRED_NODE)) {
21255 PM_PARSER_ERR_TOKEN_FORMAT(parser, operator, PM_ERR_EXPECT_EOL_AFTER_STATEMENT, pm_token_type_human(operator.type));
21256 }
21257 break;
21258 }
21259 case PM_AND_NODE: {
21260 pm_and_node_t *cast = (pm_and_node_t *) node;
21261 if (PM_NODE_TYPE_P(cast->right, PM_MATCH_PREDICATE_NODE) || PM_NODE_TYPE_P(cast->right, PM_MATCH_REQUIRED_NODE)) {
21262 PM_PARSER_ERR_TOKEN_FORMAT(parser, operator, PM_ERR_EXPECT_EOL_AFTER_STATEMENT, pm_token_type_human(operator.type));
21263 }
21264 break;
21265 }
21266 case PM_OR_NODE: {
21267 pm_or_node_t *cast = (pm_or_node_t *) node;
21268 if (PM_NODE_TYPE_P(cast->right, PM_MATCH_PREDICATE_NODE) || PM_NODE_TYPE_P(cast->right, PM_MATCH_REQUIRED_NODE)) {
21269 PM_PARSER_ERR_TOKEN_FORMAT(parser, operator, PM_ERR_EXPECT_EOL_AFTER_STATEMENT, pm_token_type_human(operator.type));
21270 }
21271 break;
21272 }
21273 default:
21274 break;
21275 }
21276
21277 pm_token_t message;
21278
21279 switch (parser->current.type) {
21280 case PM_CASE_OPERATOR:
21281 case PM_CASE_KEYWORD:
21282 case PM_TOKEN_CONSTANT:
21283 case PM_TOKEN_IDENTIFIER:
21284 case PM_TOKEN_METHOD_NAME: {
21285 parser_lex(parser);
21286 message = parser->previous;
21287 break;
21288 }
21289 default: {
21290 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_EXPECT_MESSAGE, pm_token_type_human(parser->current.type));
21291 message = (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->previous.end, .end = parser->previous.end };
21292 }
21293 }
21294
21295 parse_arguments_list(parser, &arguments, true, accepts_command_call, (uint16_t) (depth + 1));
21296 pm_call_node_t *call = pm_call_node_call_create(parser, node, &operator, &message, &arguments);
21297
21298 if (
21299 (previous_binding_power == PM_BINDING_POWER_STATEMENT) &&
21300 arguments.arguments == NULL &&
21301 arguments.opening_loc.start == NULL &&
21302 match1(parser, PM_TOKEN_COMMA)
21303 ) {
21304 return parse_targets_validate(parser, UP(call), PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
21305 } else {
21306 return UP(call);
21307 }
21308 }
21309 case PM_TOKEN_DOT_DOT:
21310 case PM_TOKEN_DOT_DOT_DOT: {
21311 parser_lex(parser);
21312
21313 pm_node_t *right = NULL;
21314 if (token_begins_expression_p(parser->current.type)) {
21315 right = parse_expression(parser, binding_power, false, false, PM_ERR_EXPECT_EXPRESSION_AFTER_OPERATOR, (uint16_t) (depth + 1));
21316 }
21317
21318 return UP(pm_range_node_create(parser, node, &token, right));
21319 }
21320 case PM_TOKEN_KEYWORD_IF_MODIFIER: {
21321 pm_token_t keyword = parser->current;
21322 parser_lex(parser);
21323
21324 pm_node_t *predicate = parse_value_expression(parser, binding_power, true, false, PM_ERR_CONDITIONAL_IF_PREDICATE, (uint16_t) (depth + 1));
21325 return UP(pm_if_node_modifier_create(parser, node, &keyword, predicate));
21326 }
21327 case PM_TOKEN_KEYWORD_UNLESS_MODIFIER: {
21328 pm_token_t keyword = parser->current;
21329 parser_lex(parser);
21330
21331 pm_node_t *predicate = parse_value_expression(parser, binding_power, true, false, PM_ERR_CONDITIONAL_UNLESS_PREDICATE, (uint16_t) (depth + 1));
21332 return UP(pm_unless_node_modifier_create(parser, node, &keyword, predicate));
21333 }
21334 case PM_TOKEN_KEYWORD_UNTIL_MODIFIER: {
21335 parser_lex(parser);
21336 pm_statements_node_t *statements = pm_statements_node_create(parser);
21337 pm_statements_node_body_append(parser, statements, node, true);
21338
21339 pm_node_t *predicate = parse_value_expression(parser, binding_power, true, false, PM_ERR_CONDITIONAL_UNTIL_PREDICATE, (uint16_t) (depth + 1));
21340 return UP(pm_until_node_modifier_create(parser, &token, predicate, statements, PM_NODE_TYPE_P(node, PM_BEGIN_NODE) ? PM_LOOP_FLAGS_BEGIN_MODIFIER : 0));
21341 }
21342 case PM_TOKEN_KEYWORD_WHILE_MODIFIER: {
21343 parser_lex(parser);
21344 pm_statements_node_t *statements = pm_statements_node_create(parser);
21345 pm_statements_node_body_append(parser, statements, node, true);
21346
21347 pm_node_t *predicate = parse_value_expression(parser, binding_power, true, false, PM_ERR_CONDITIONAL_WHILE_PREDICATE, (uint16_t) (depth + 1));
21348 return UP(pm_while_node_modifier_create(parser, &token, predicate, statements, PM_NODE_TYPE_P(node, PM_BEGIN_NODE) ? PM_LOOP_FLAGS_BEGIN_MODIFIER : 0));
21349 }
21350 case PM_TOKEN_QUESTION_MARK: {
21351 context_push(parser, PM_CONTEXT_TERNARY);
21352 pm_node_list_t current_block_exits = { 0 };
21353 pm_node_list_t *previous_block_exits = push_block_exits(parser, &current_block_exits);
21354
21355 pm_token_t qmark = parser->current;
21356 parser_lex(parser);
21357
21358 pm_node_t *true_expression = parse_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_TERNARY_EXPRESSION_TRUE, (uint16_t) (depth + 1));
21359
21360 if (parser->recovering) {
21361 // If parsing the true expression of this ternary resulted in a syntax
21362 // error that we can recover from, then we're going to put missing nodes
21363 // and tokens into the remaining places. We want to be sure to do this
21364 // before the `expect` function call to make sure it doesn't
21365 // accidentally move past a ':' token that occurs after the syntax
21366 // error.
21367 pm_token_t colon = (pm_token_t) { .type = PM_TOKEN_MISSING, .start = parser->previous.end, .end = parser->previous.end };
21368 pm_node_t *false_expression = UP(pm_missing_node_create(parser, colon.start, colon.end));
21369
21370 context_pop(parser);
21371 pop_block_exits(parser, previous_block_exits);
21372 pm_node_list_free(&current_block_exits);
21373
21374 return UP(pm_if_node_ternary_create(parser, node, &qmark, true_expression, &colon, false_expression));
21375 }
21376
21377 accept1(parser, PM_TOKEN_NEWLINE);
21378 expect1(parser, PM_TOKEN_COLON, PM_ERR_TERNARY_COLON);
21379
21380 pm_token_t colon = parser->previous;
21381 pm_node_t *false_expression = parse_expression(parser, PM_BINDING_POWER_DEFINED, false, false, PM_ERR_TERNARY_EXPRESSION_FALSE, (uint16_t) (depth + 1));
21382
21383 context_pop(parser);
21384 pop_block_exits(parser, previous_block_exits);
21385 pm_node_list_free(&current_block_exits);
21386
21387 return UP(pm_if_node_ternary_create(parser, node, &qmark, true_expression, &colon, false_expression));
21388 }
21389 case PM_TOKEN_COLON_COLON: {
21390 parser_lex(parser);
21391 pm_token_t delimiter = parser->previous;
21392
21393 switch (parser->current.type) {
21394 case PM_TOKEN_CONSTANT: {
21395 parser_lex(parser);
21396 pm_node_t *path;
21397
21398 if (
21399 (parser->current.type == PM_TOKEN_PARENTHESIS_LEFT) ||
21400 (accepts_command_call && (token_begins_expression_p(parser->current.type) || match3(parser, PM_TOKEN_UAMPERSAND, PM_TOKEN_USTAR, PM_TOKEN_USTAR_STAR)))
21401 ) {
21402 // If we have a constant immediately following a '::' operator, then
21403 // this can either be a constant path or a method call, depending on
21404 // what follows the constant.
21405 //
21406 // If we have parentheses, then this is a method call. That would
21407 // look like Foo::Bar().
21408 pm_token_t message = parser->previous;
21409 pm_arguments_t arguments = { 0 };
21410
21411 parse_arguments_list(parser, &arguments, true, accepts_command_call, (uint16_t) (depth + 1));
21412 path = UP(pm_call_node_call_create(parser, node, &delimiter, &message, &arguments));
21413 } else {
21414 // Otherwise, this is a constant path. That would look like Foo::Bar.
21415 path = UP(pm_constant_path_node_create(parser, node, &delimiter, &parser->previous));
21416 }
21417
21418 // If this is followed by a comma then it is a multiple assignment.
21419 if (previous_binding_power == PM_BINDING_POWER_STATEMENT && match1(parser, PM_TOKEN_COMMA)) {
21420 return parse_targets_validate(parser, path, PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
21421 }
21422
21423 return path;
21424 }
21425 case PM_CASE_OPERATOR:
21426 case PM_CASE_KEYWORD:
21427 case PM_TOKEN_IDENTIFIER:
21428 case PM_TOKEN_METHOD_NAME: {
21429 parser_lex(parser);
21430 pm_token_t message = parser->previous;
21431
21432 // If we have an identifier following a '::' operator, then it is for
21433 // sure a method call.
21434 pm_arguments_t arguments = { 0 };
21435 parse_arguments_list(parser, &arguments, true, accepts_command_call, (uint16_t) (depth + 1));
21436 pm_call_node_t *call = pm_call_node_call_create(parser, node, &delimiter, &message, &arguments);
21437
21438 // If this is followed by a comma then it is a multiple assignment.
21439 if (previous_binding_power == PM_BINDING_POWER_STATEMENT && match1(parser, PM_TOKEN_COMMA)) {
21440 return parse_targets_validate(parser, UP(call), PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
21441 }
21442
21443 return UP(call);
21444 }
21445 case PM_TOKEN_PARENTHESIS_LEFT: {
21446 // If we have a parenthesis following a '::' operator, then it is the
21447 // method call shorthand. That would look like Foo::(bar).
21448 pm_arguments_t arguments = { 0 };
21449 parse_arguments_list(parser, &arguments, true, false, (uint16_t) (depth + 1));
21450
21451 return UP(pm_call_node_shorthand_create(parser, node, &delimiter, &arguments));
21452 }
21453 default: {
21454 expect1(parser, PM_TOKEN_CONSTANT, PM_ERR_CONSTANT_PATH_COLON_COLON_CONSTANT);
21455 return UP(pm_constant_path_node_create(parser, node, &delimiter, &parser->previous));
21456 }
21457 }
21458 }
21459 case PM_TOKEN_KEYWORD_RESCUE_MODIFIER: {
21460 context_push(parser, PM_CONTEXT_RESCUE_MODIFIER);
21461 parser_lex(parser);
21462 accept1(parser, PM_TOKEN_NEWLINE);
21463
21464 pm_node_t *value = parse_expression(parser, binding_power, true, false, PM_ERR_RESCUE_MODIFIER_VALUE, (uint16_t) (depth + 1));
21465 context_pop(parser);
21466
21467 return UP(pm_rescue_modifier_node_create(parser, node, &token, value));
21468 }
21469 case PM_TOKEN_BRACKET_LEFT: {
21470 parser_lex(parser);
21471
21472 pm_arguments_t arguments = { 0 };
21473 arguments.opening_loc = PM_LOCATION_TOKEN_VALUE(&parser->previous);
21474
21475 if (!accept1(parser, PM_TOKEN_BRACKET_RIGHT)) {
21476 pm_accepts_block_stack_push(parser, true);
21477 parse_arguments(parser, &arguments, false, PM_TOKEN_BRACKET_RIGHT, (uint16_t) (depth + 1));
21478 pm_accepts_block_stack_pop(parser);
21479 expect1(parser, PM_TOKEN_BRACKET_RIGHT, PM_ERR_EXPECT_RBRACKET);
21480 }
21481
21482 arguments.closing_loc = PM_LOCATION_TOKEN_VALUE(&parser->previous);
21483
21484 // If we have a comma after the closing bracket then this is a multiple
21485 // assignment and we should parse the targets.
21486 if (previous_binding_power == PM_BINDING_POWER_STATEMENT && match1(parser, PM_TOKEN_COMMA)) {
21487 pm_call_node_t *aref = pm_call_node_aref_create(parser, node, &arguments);
21488 return parse_targets_validate(parser, UP(aref), PM_BINDING_POWER_INDEX, (uint16_t) (depth + 1));
21489 }
21490
21491 // If we're at the end of the arguments, we can now check if there is a
21492 // block node that starts with a {. If there is, then we can parse it and
21493 // add it to the arguments.
21494 pm_block_node_t *block = NULL;
21495 if (accept1(parser, PM_TOKEN_BRACE_LEFT)) {
21496 block = parse_block(parser, (uint16_t) (depth + 1));
21497 pm_arguments_validate_block(parser, &arguments, block);
21498 } else if (pm_accepts_block_stack_p(parser) && accept1(parser, PM_TOKEN_KEYWORD_DO)) {
21499 block = parse_block(parser, (uint16_t) (depth + 1));
21500 }
21501
21502 if (block != NULL) {
21503 if (arguments.block != NULL) {
21504 pm_parser_err_node(parser, UP(block), PM_ERR_ARGUMENT_AFTER_BLOCK);
21505 if (arguments.arguments == NULL) {
21506 arguments.arguments = pm_arguments_node_create(parser);
21507 }
21508 pm_arguments_node_arguments_append(arguments.arguments, arguments.block);
21509 }
21510
21511 arguments.block = UP(block);
21512 }
21513
21514 return UP(pm_call_node_aref_create(parser, node, &arguments));
21515 }
21516 case PM_TOKEN_KEYWORD_IN: {
21517 bool previous_pattern_matching_newlines = parser->pattern_matching_newlines;
21518 parser->pattern_matching_newlines = true;
21519
21520 pm_token_t operator = parser->current;
21521 parser->command_start = false;
21522 lex_state_set(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_LABEL);
21523 parser_lex(parser);
21524
21525 pm_constant_id_list_t captures = { 0 };
21526 pm_node_t *pattern = parse_pattern(parser, &captures, PM_PARSE_PATTERN_TOP | PM_PARSE_PATTERN_MULTI, PM_ERR_PATTERN_EXPRESSION_AFTER_IN, (uint16_t) (depth + 1));
21527
21528 parser->pattern_matching_newlines = previous_pattern_matching_newlines;
21529 pm_constant_id_list_free(&captures);
21530
21531 return UP(pm_match_predicate_node_create(parser, node, pattern, &operator));
21532 }
21533 case PM_TOKEN_EQUAL_GREATER: {
21534 bool previous_pattern_matching_newlines = parser->pattern_matching_newlines;
21535 parser->pattern_matching_newlines = true;
21536
21537 pm_token_t operator = parser->current;
21538 parser->command_start = false;
21539 lex_state_set(parser, PM_LEX_STATE_BEG | PM_LEX_STATE_LABEL);
21540 parser_lex(parser);
21541
21542 pm_constant_id_list_t captures = { 0 };
21543 pm_node_t *pattern = parse_pattern(parser, &captures, PM_PARSE_PATTERN_TOP | PM_PARSE_PATTERN_MULTI, PM_ERR_PATTERN_EXPRESSION_AFTER_HROCKET, (uint16_t) (depth + 1));
21544
21545 parser->pattern_matching_newlines = previous_pattern_matching_newlines;
21546 pm_constant_id_list_free(&captures);
21547
21548 return UP(pm_match_required_node_create(parser, node, pattern, &operator));
21549 }
21550 default:
21551 assert(false && "unreachable");
21552 return NULL;
21553 }
21554 }
21555
21556 #undef PM_PARSE_PATTERN_SINGLE
21557 #undef PM_PARSE_PATTERN_TOP
21558 #undef PM_PARSE_PATTERN_MULTI
21559
21560 /**
21561 * Determine if a given call node looks like a "command", which means it has
21562 * arguments but does not have parentheses.
21563 */
21564 static inline bool
21565 pm_call_node_command_p(const pm_call_node_t *node) {
21566 return (
21567 (node->opening_loc.start == NULL) &&
21568 (node->block == NULL || PM_NODE_TYPE_P(node->block, PM_BLOCK_ARGUMENT_NODE)) &&
21569 (node->arguments != NULL || node->block != NULL)
21570 );
21571 }
21572
21573 /**
21574 * Parse an expression at the given point of the parser using the given binding
21575 * power to parse subsequent chains. If this function finds a syntax error, it
21576 * will append the error message to the parser's error list.
21577 *
21578 * Consumers of this function should always check parser->recovering to
21579 * determine if they need to perform additional cleanup.
21580 */
21581 static pm_node_t *
21582 parse_expression(pm_parser_t *parser, pm_binding_power_t binding_power, bool accepts_command_call, bool accepts_label, pm_diagnostic_id_t diag_id, uint16_t depth) {
21583 if (PRISM_UNLIKELY(depth >= PRISM_DEPTH_MAXIMUM)) {
21584 pm_parser_err_current(parser, PM_ERR_NESTING_TOO_DEEP);
21585 return UP(pm_missing_node_create(parser, parser->current.start, parser->current.end));
21586 }
21587
21588 pm_node_t *node = parse_expression_prefix(parser, binding_power, accepts_command_call, accepts_label, diag_id, depth);
21589
21590 switch (PM_NODE_TYPE(node)) {
21591 case PM_MISSING_NODE:
21592 // If we found a syntax error, then the type of node returned by
21593 // parse_expression_prefix is going to be a missing node.
21594 return node;
21595 case PM_PRE_EXECUTION_NODE:
21596 case PM_POST_EXECUTION_NODE:
21597 case PM_ALIAS_GLOBAL_VARIABLE_NODE:
21598 case PM_ALIAS_METHOD_NODE:
21599 case PM_MULTI_WRITE_NODE:
21600 case PM_UNDEF_NODE:
21601 // These expressions are statements, and cannot be followed by
21602 // operators (except modifiers).
21603 if (pm_binding_powers[parser->current.type].left > PM_BINDING_POWER_MODIFIER) {
21604 return node;
21605 }
21606 break;
21607 case PM_CALL_NODE:
21608 // If we have a call node, then we need to check if it looks like a
21609 // method call without parentheses that contains arguments. If it
21610 // does, then it has different rules for parsing infix operators,
21611 // namely that it only accepts composition (and/or) and modifiers
21612 // (if/unless/etc.).
21613 if ((pm_binding_powers[parser->current.type].left > PM_BINDING_POWER_COMPOSITION) && pm_call_node_command_p((pm_call_node_t *) node)) {
21614 return node;
21615 }
21616 break;
21617 case PM_SYMBOL_NODE:
21618 // If we have a symbol node that is being parsed as a label, then we
21619 // need to immediately return, because there should never be an
21620 // infix operator following this node.
21621 if (pm_symbol_node_label_p(node)) {
21622 return node;
21623 }
21624 break;
21625 default:
21626 break;
21627 }
21628
21629 // Otherwise we'll look and see if the next token can be parsed as an infix
21630 // operator. If it can, then we'll parse it using parse_expression_infix.
21631 pm_binding_powers_t current_binding_powers;
21632 pm_token_type_t current_token_type;
21633
21634 while (
21635 current_token_type = parser->current.type,
21636 current_binding_powers = pm_binding_powers[current_token_type],
21637 binding_power <= current_binding_powers.left &&
21638 current_binding_powers.binary
21639 ) {
21640 node = parse_expression_infix(parser, node, binding_power, current_binding_powers.right, accepts_command_call, (uint16_t) (depth + 1));
21641
21642 if (context_terminator(parser->current_context->context, &parser->current)) {
21643 // If this token terminates the current context, then we need to
21644 // stop parsing the expression, as it has become a statement.
21645 return node;
21646 }
21647
21648 switch (PM_NODE_TYPE(node)) {
21649 case PM_MULTI_WRITE_NODE:
21650 // Multi-write nodes are statements, and cannot be followed by
21651 // operators except modifiers.
21652 if (pm_binding_powers[parser->current.type].left > PM_BINDING_POWER_MODIFIER) {
21653 return node;
21654 }
21655 break;
21656 case PM_CLASS_VARIABLE_WRITE_NODE:
21657 case PM_CONSTANT_PATH_WRITE_NODE:
21658 case PM_CONSTANT_WRITE_NODE:
21659 case PM_GLOBAL_VARIABLE_WRITE_NODE:
21660 case PM_INSTANCE_VARIABLE_WRITE_NODE:
21661 case PM_LOCAL_VARIABLE_WRITE_NODE:
21662 // These expressions are statements, by virtue of the right-hand
21663 // side of their write being an implicit array.
21664 if (PM_NODE_FLAG_P(node, PM_WRITE_NODE_FLAGS_IMPLICIT_ARRAY) && pm_binding_powers[parser->current.type].left > PM_BINDING_POWER_MODIFIER) {
21665 return node;
21666 }
21667 break;
21668 case PM_CALL_NODE:
21669 // These expressions are also statements, by virtue of the
21670 // right-hand side of the expression (i.e., the last argument to
21671 // the call node) being an implicit array.
21672 if (PM_NODE_FLAG_P(node, PM_CALL_NODE_FLAGS_IMPLICIT_ARRAY) && pm_binding_powers[parser->current.type].left > PM_BINDING_POWER_MODIFIER) {
21673 return node;
21674 }
21675 break;
21676 default:
21677 break;
21678 }
21679
21680 // If the operator is nonassoc and we should not be able to parse the
21681 // upcoming infix operator, break.
21682 if (current_binding_powers.nonassoc) {
21683 // If this is a non-assoc operator and we are about to parse the
21684 // exact same operator, then we need to add an error.
21685 if (match1(parser, current_token_type)) {
21686 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_NON_ASSOCIATIVE_OPERATOR, pm_token_type_human(parser->current.type), pm_token_type_human(current_token_type));
21687 break;
21688 }
21689
21690 // If this is an endless range, then we need to reject a couple of
21691 // additional operators because it violates the normal operator
21692 // precedence rules. Those patterns are:
21693 //
21694 // 1.. & 2
21695 // 1.. * 2
21696 //
21697 if (PM_NODE_TYPE_P(node, PM_RANGE_NODE) && ((pm_range_node_t *) node)->right == NULL) {
21698 if (match4(parser, PM_TOKEN_UAMPERSAND, PM_TOKEN_USTAR, PM_TOKEN_DOT, PM_TOKEN_AMPERSAND_DOT)) {
21699 PM_PARSER_ERR_TOKEN_FORMAT(parser, parser->current, PM_ERR_NON_ASSOCIATIVE_OPERATOR, pm_token_type_human(parser->current.type), pm_token_type_human(current_token_type));
21700 break;
21701 }
21702
21703 if (PM_BINDING_POWER_TERM <= pm_binding_powers[parser->current.type].left) {
21704 break;
21705 }
21706 } else if (current_binding_powers.left <= pm_binding_powers[parser->current.type].left) {
21707 break;
21708 }
21709 }
21710
21711 if (accepts_command_call) {
21712 // A command-style method call is only accepted on method chains.
21713 // Thus, we check whether the parsed node can continue method chains.
21714 // The method chain can continue if the parsed node is one of the following five kinds:
21715 // (1) index access: foo[1]
21716 // (2) attribute access: foo.bar
21717 // (3) method call with parenthesis: foo.bar(1)
21718 // (4) method call with a block: foo.bar do end
21719 // (5) constant path: foo::Bar
21720 switch (node->type) {
21721 case PM_CALL_NODE: {
21722 pm_call_node_t *cast = (pm_call_node_t *)node;
21723 if (
21724 // (1) foo[1]
21725 !(
21726 cast->call_operator_loc.start == NULL &&
21727 cast->message_loc.start != NULL &&
21728 cast->message_loc.start[0] == '[' &&
21729 cast->message_loc.end[-1] == ']'
21730 ) &&
21731 // (2) foo.bar
21732 !(
21733 cast->call_operator_loc.start != NULL &&
21734 cast->arguments == NULL &&
21735 cast->block == NULL &&
21736 cast->opening_loc.start == NULL
21737 ) &&
21738 // (3) foo.bar(1)
21739 !(
21740 cast->call_operator_loc.start != NULL &&
21741 cast->opening_loc.start != NULL
21742 ) &&
21743 // (4) foo.bar do end
21744 !(
21745 cast->block != NULL && PM_NODE_TYPE_P(cast->block, PM_BLOCK_NODE)
21746 )
21747 ) {
21748 accepts_command_call = false;
21749 }
21750 break;
21751 }
21752 // (5) foo::Bar
21753 case PM_CONSTANT_PATH_NODE:
21754 break;
21755 default:
21756 accepts_command_call = false;
21757 break;
21758 }
21759 }
21760 }
21761
21762 return node;
21763 }
21764
21765 /**
21766 * ruby -p, ruby -n, ruby -a, and ruby -l options will mutate the AST. We
21767 * perform that mutation here.
21768 */
21769 static pm_statements_node_t *
21770 wrap_statements(pm_parser_t *parser, pm_statements_node_t *statements) {
21771 if (PM_PARSER_COMMAND_LINE_OPTION_P(parser)) {
21772 if (statements == NULL) {
21773 statements = pm_statements_node_create(parser);
21774 }
21775
21776 pm_arguments_node_t *arguments = pm_arguments_node_create(parser);
21777 pm_arguments_node_arguments_append(
21778 arguments,
21779 UP(pm_global_variable_read_node_synthesized_create(parser, pm_parser_constant_id_constant(parser, "$_", 2)))
21780 );
21781
21782 pm_statements_node_body_append(parser, statements, UP(pm_call_node_fcall_synthesized_create(
21783 parser,
21784 arguments,
21785 pm_parser_constant_id_constant(parser, "print", 5)
21786 )), true);
21787 }
21788
21789 if (PM_PARSER_COMMAND_LINE_OPTION_N(parser)) {
21790 if (PM_PARSER_COMMAND_LINE_OPTION_A(parser)) {
21791 if (statements == NULL) {
21792 statements = pm_statements_node_create(parser);
21793 }
21794
21795 pm_arguments_node_t *arguments = pm_arguments_node_create(parser);
21796 pm_arguments_node_arguments_append(
21797 arguments,
21798 UP(pm_global_variable_read_node_synthesized_create(parser, pm_parser_constant_id_constant(parser, "$;", 2)))
21799 );
21800
21801 pm_global_variable_read_node_t *receiver = pm_global_variable_read_node_synthesized_create(parser, pm_parser_constant_id_constant(parser, "$_", 2));
21802 pm_call_node_t *call = pm_call_node_call_synthesized_create(parser, UP(receiver), "split", arguments);
21803
21804 pm_global_variable_write_node_t *write = pm_global_variable_write_node_synthesized_create(
21805 parser,
21806 pm_parser_constant_id_constant(parser, "$F", 2),
21807 UP(call)
21808 );
21809
21810 pm_statements_node_body_prepend(statements, UP(write));
21811 }
21812
21813 pm_arguments_node_t *arguments = pm_arguments_node_create(parser);
21814 pm_arguments_node_arguments_append(
21815 arguments,
21816 UP(pm_global_variable_read_node_synthesized_create(parser, pm_parser_constant_id_constant(parser, "$/", 2)))
21817 );
21818
21819 if (PM_PARSER_COMMAND_LINE_OPTION_L(parser)) {
21820 pm_keyword_hash_node_t *keywords = pm_keyword_hash_node_create(parser);
21821 pm_keyword_hash_node_elements_append(keywords, UP(pm_assoc_node_create(
21822 parser,
21823 UP(pm_symbol_node_synthesized_create(parser, "chomp")),
21824 &(pm_token_t) { .type = PM_TOKEN_NOT_PROVIDED, .start = parser->start, .end = parser->start },
21825 UP(pm_true_node_synthesized_create(parser))
21826 )));
21827
21828 pm_arguments_node_arguments_append(arguments, UP(keywords));
21829 pm_node_flag_set(UP(arguments), PM_ARGUMENTS_NODE_FLAGS_CONTAINS_KEYWORDS);
21830 }
21831
21832 pm_statements_node_t *wrapped_statements = pm_statements_node_create(parser);
21833 pm_statements_node_body_append(parser, wrapped_statements, UP(pm_while_node_synthesized_create(
21834 parser,
21835 UP(pm_call_node_fcall_synthesized_create(parser, arguments, pm_parser_constant_id_constant(parser, "gets", 4))),
21836 statements
21837 )), true);
21838
21839 statements = wrapped_statements;
21840 }
21841
21842 return statements;
21843 }
21844
21845 /**
21846 * Parse the top-level program node.
21847 */
21848 static pm_node_t *
21849 parse_program(pm_parser_t *parser) {
21850 // If the current scope is NULL, then we want to push a new top level scope.
21851 // The current scope could exist in the event that we are parsing an eval
21852 // and the user has passed into scopes that already exist.
21853 if (parser->current_scope == NULL) {
21854 pm_parser_scope_push(parser, true);
21855 }
21856
21857 pm_node_list_t current_block_exits = { 0 };
21858 pm_node_list_t *previous_block_exits = push_block_exits(parser, &current_block_exits);
21859
21860 parser_lex(parser);
21861 pm_statements_node_t *statements = parse_statements(parser, PM_CONTEXT_MAIN, 0);
21862
21863 if (statements != NULL && !parser->parsing_eval) {
21864 // If we have statements, then the top-level statement should be
21865 // explicitly checked as well. We have to do this here because
21866 // everywhere else we check all but the last statement.
21867 assert(statements->body.size > 0);
21868 pm_void_statement_check(parser, statements->body.nodes[statements->body.size - 1]);
21869 }
21870
21871 pm_constant_id_list_t locals;
21872 pm_locals_order(parser, &parser->current_scope->locals, &locals, true);
21873 pm_parser_scope_pop(parser);
21874
21875 // At the top level, see if we need to wrap the statements in a program
21876 // node with a while loop based on the options.
21877 if (parser->command_line & (PM_OPTIONS_COMMAND_LINE_P | PM_OPTIONS_COMMAND_LINE_N)) {
21878 statements = wrap_statements(parser, statements);
21879 } else {
21880 flush_block_exits(parser, previous_block_exits);
21881 }
21882
21883 pm_node_list_free(&current_block_exits);
21884
21885 // If this is an empty file, then we're still going to parse all of the
21886 // statements in order to gather up all of the comments and such. Here we'll
21887 // correct the location information.
21888 if (statements == NULL) {
21889 statements = pm_statements_node_create(parser);
21890 pm_statements_node_location_set(statements, parser->start, parser->start);
21891 }
21892
21893 return UP(pm_program_node_create(parser, &locals, statements));
21894 }
21895
21896 /******************************************************************************/
21897 /* External functions */
21898 /******************************************************************************/
21899
21900 /**
21901 * A vendored version of strnstr that is used to find a substring within a
21902 * string with a given length. This function is used to search for the Ruby
21903 * engine name within a shebang when the -x option is passed to Ruby.
21904 *
21905 * The only modification that we made here is that we don't do NULL byte checks
21906 * because we know the little parameter will not have a NULL byte and we allow
21907 * the big parameter to have them.
21908 */
21909 static const char *
21910 pm_strnstr(const char *big, const char *little, size_t big_length) {
21911 size_t little_length = strlen(little);
21912
21913 for (const char *max = big + big_length - little_length; big <= max; big++) {
21914 if (*big == *little && memcmp(big, little, little_length) == 0) return big;
21915 }
21916
21917 return NULL;
21918 }
21919
21920 #ifdef _WIN32
21921 #define pm_parser_warn_shebang_carriage_return(parser, start, length) ((void) 0)
21922 #else
21923 /**
21924 * Potentially warn the user if the shebang that has been found to include
21925 * "ruby" has a carriage return at the end, as that can cause problems on some
21926 * platforms.
21927 */
21928 static void
21929 pm_parser_warn_shebang_carriage_return(pm_parser_t *parser, const uint8_t *start, size_t length) {
21930 if (length > 2 && start[length - 2] == '\r' && start[length - 1] == '\n') {
21931 pm_parser_warn(parser, start, start + length, PM_WARN_SHEBANG_CARRIAGE_RETURN);
21932 }
21933 }
21934 #endif
21935
21936 /**
21937 * Process the shebang when initializing the parser. This function assumes that
21938 * the shebang_callback option has already been checked for nullability.
21939 */
21940 static void
21941 pm_parser_init_shebang(pm_parser_t *parser, const pm_options_t *options, const char *engine, size_t length) {
21942 const char *switches = pm_strnstr(engine, " -", length);
21943 if (switches == NULL) return;
21944
21945 pm_options_t next_options = *options;
21946 options->shebang_callback(
21947 &next_options,
21948 (const uint8_t *) (switches + 1),
21949 length - ((size_t) (switches - engine)) - 1,
21950 options->shebang_callback_data
21951 );
21952
21953 size_t encoding_length;
21954 if ((encoding_length = pm_string_length(&next_options.encoding)) > 0) {
21955 const uint8_t *encoding_source = pm_string_source(&next_options.encoding);
21956 parser_lex_magic_comment_encoding_value(parser, encoding_source, encoding_source + encoding_length);
21957 }
21958
21959 parser->command_line = next_options.command_line;
21960 parser->frozen_string_literal = next_options.frozen_string_literal;
21961 }
21962
21963 /**
21964 * Initialize a parser with the given start and end pointers.
21965 */
21966 PRISM_EXPORTED_FUNCTION void
21967 pm_parser_init(pm_parser_t *parser, const uint8_t *source, size_t size, const pm_options_t *options) {
21968 assert(source != NULL);
21969
21970 *parser = (pm_parser_t) {
21971 .node_id = 0,
21972 .lex_state = PM_LEX_STATE_BEG,
21973 .enclosure_nesting = 0,
21974 .lambda_enclosure_nesting = -1,
21975 .brace_nesting = 0,
21976 .do_loop_stack = 0,
21977 .accepts_block_stack = 0,
21978 .lex_modes = {
21979 .index = 0,
21980 .stack = {{ .mode = PM_LEX_DEFAULT }},
21981 .current = &parser->lex_modes.stack[0],
21982 },
21983 .start = source,
21984 .end = source + size,
21985 .previous = { .type = PM_TOKEN_EOF, .start = source, .end = source },
21986 .current = { .type = PM_TOKEN_EOF, .start = source, .end = source },
21987 .next_start = NULL,
21988 .heredoc_end = NULL,
21989 .data_loc = { .start = NULL, .end = NULL },
21990 .comment_list = { 0 },
21991 .magic_comment_list = { 0 },
21992 .warning_list = { 0 },
21993 .error_list = { 0 },
21994 .current_scope = NULL,
21995 .current_context = NULL,
21996 .encoding = PM_ENCODING_UTF_8_ENTRY,
21997 .encoding_changed_callback = NULL,
21998 .encoding_comment_start = source,
21999 .lex_callback = NULL,
22000 .filepath = { 0 },
22001 .constant_pool = { 0 },
22002 .newline_list = { 0 },
22003 .integer_base = 0,
22004 .current_string = PM_STRING_EMPTY,
22005 .start_line = 1,
22006 .explicit_encoding = NULL,
22007 .command_line = 0,
22008 .parsing_eval = false,
22009 .partial_script = false,
22010 .command_start = true,
22011 .recovering = false,
22012 .encoding_locked = false,
22013 .encoding_changed = false,
22014 .pattern_matching_newlines = false,
22015 .in_keyword_arg = false,
22016 .current_block_exits = NULL,
22017 .semantic_token_seen = false,
22018 .frozen_string_literal = PM_OPTIONS_FROZEN_STRING_LITERAL_UNSET,
22019 .current_regular_expression_ascii_only = false,
22020 .warn_mismatched_indentation = true
22021 };
22022
22023 // Initialize the constant pool. We're going to completely guess as to the
22024 // number of constants that we'll need based on the size of the input. The
22025 // ratio we chose here is actually less arbitrary than you might think.
22026 //
22027 // We took ~50K Ruby files and measured the size of the file versus the
22028 // number of constants that were found in those files. Then we found the
22029 // average and standard deviation of the ratios of constants/bytesize. Then
22030 // we added 1.34 standard deviations to the average to get a ratio that
22031 // would fit 75% of the files (for a two-tailed distribution). This works
22032 // because there was about a 0.77 correlation and the distribution was
22033 // roughly normal.
22034 //
22035 // This ratio will need to change if we add more constants to the constant
22036 // pool for another node type.
22037 uint32_t constant_size = ((uint32_t) size) / 95;
22038 pm_constant_pool_init(&parser->constant_pool, constant_size < 4 ? 4 : constant_size);
22039
22040 // Initialize the newline list. Similar to the constant pool, we're going to
22041 // guess at the number of newlines that we'll need based on the size of the
22042 // input.
22043 size_t newline_size = size / 22;
22044 pm_newline_list_init(&parser->newline_list, source, newline_size < 4 ? 4 : newline_size);
22045
22046 // If options were provided to this parse, establish them here.
22047 if (options != NULL) {
22048 // filepath option
22049 parser->filepath = options->filepath;
22050
22051 // line option
22052 parser->start_line = options->line;
22053
22054 // encoding option
22055 size_t encoding_length = pm_string_length(&options->encoding);
22056 if (encoding_length > 0) {
22057 const uint8_t *encoding_source = pm_string_source(&options->encoding);
22058 parser_lex_magic_comment_encoding_value(parser, encoding_source, encoding_source + encoding_length);
22059 }
22060
22061 // encoding_locked option
22062 parser->encoding_locked = options->encoding_locked;
22063
22064 // frozen_string_literal option
22065 parser->frozen_string_literal = options->frozen_string_literal;
22066
22067 // command_line option
22068 parser->command_line = options->command_line;
22069
22070 // version option
22071 parser->version = options->version;
22072
22073 // partial_script
22074 parser->partial_script = options->partial_script;
22075
22076 // scopes option
22077 parser->parsing_eval = options->scopes_count > 0;
22078 if (parser->parsing_eval) parser->warn_mismatched_indentation = false;
22079
22080 for (size_t scope_index = 0; scope_index < options->scopes_count; scope_index++) {
22081 const pm_options_scope_t *scope = pm_options_scope_get(options, scope_index);
22082 pm_parser_scope_push(parser, scope_index == 0);
22083
22084 // Scopes given from the outside are not allowed to have numbered
22085 // parameters.
22086 parser->current_scope->parameters = ((pm_scope_parameters_t) scope->forwarding) | PM_SCOPE_PARAMETERS_IMPLICIT_DISALLOWED;
22087
22088 for (size_t local_index = 0; local_index < scope->locals_count; local_index++) {
22089 const pm_string_t *local = pm_options_scope_local_get(scope, local_index);
22090
22091 const uint8_t *source = pm_string_source(local);
22092 size_t length = pm_string_length(local);
22093
22094 void *allocated = xmalloc(length);
22095 if (allocated == NULL) continue;
22096
22097 memcpy(allocated, source, length);
22098 pm_parser_local_add_owned(parser, (uint8_t *) allocated, length);
22099 }
22100 }
22101 }
22102
22103 // Now that we have established the user-provided options, check if
22104 // a version was given and parse as the latest version otherwise.
22105 if (parser->version == PM_OPTIONS_VERSION_UNSET) {
22106 parser->version = PM_OPTIONS_VERSION_LATEST;
22107 }
22108
22109 pm_accepts_block_stack_push(parser, true);
22110
22111 // Skip past the UTF-8 BOM if it exists.
22112 if (size >= 3 && source[0] == 0xef && source[1] == 0xbb && source[2] == 0xbf) {
22113 parser->current.end += 3;
22114 parser->encoding_comment_start += 3;
22115
22116 if (parser->encoding != PM_ENCODING_UTF_8_ENTRY) {
22117 parser->encoding = PM_ENCODING_UTF_8_ENTRY;
22118 if (parser->encoding_changed_callback != NULL) parser->encoding_changed_callback(parser);
22119 }
22120 }
22121
22122 // If the -x command line flag is set, or the first shebang of the file does
22123 // not include "ruby", then we'll search for a shebang that does include
22124 // "ruby" and start parsing from there.
22125 bool search_shebang = PM_PARSER_COMMAND_LINE_OPTION_X(parser);
22126
22127 // If the first two bytes of the source are a shebang, then we will do a bit
22128 // of extra processing.
22129 //
22130 // First, we'll indicate that the encoding comment is at the end of the
22131 // shebang. This means that when a shebang is present the encoding comment
22132 // can begin on the second line.
22133 //
22134 // Second, we will check if the shebang includes "ruby". If it does, then we
22135 // we will start parsing from there. We will also potentially warning the
22136 // user if there is a carriage return at the end of the shebang. We will
22137 // also potentially call the shebang callback if this is the main script to
22138 // allow the caller to parse the shebang and find any command-line options.
22139 // If the shebang does not include "ruby" and this is the main script being
22140 // parsed, then we will start searching the file for a shebang that does
22141 // contain "ruby" as if -x were passed on the command line.
22142 const uint8_t *newline = next_newline(parser->current.end, parser->end - parser->current.end);
22143 size_t length = (size_t) ((newline != NULL ? newline : parser->end) - parser->current.end);
22144
22145 if (length > 2 && parser->current.end[0] == '#' && parser->current.end[1] == '!') {
22146 const char *engine;
22147
22148 if ((engine = pm_strnstr((const char *) parser->start, "ruby", length)) != NULL) {
22149 if (newline != NULL) {
22150 parser->encoding_comment_start = newline + 1;
22151
22152 if (options == NULL || options->main_script) {
22153 pm_parser_warn_shebang_carriage_return(parser, parser->start, length + 1);
22154 }
22155 }
22156
22157 if (options != NULL && options->main_script && options->shebang_callback != NULL) {
22158 pm_parser_init_shebang(parser, options, engine, length - ((size_t) (engine - (const char *) parser->start)));
22159 }
22160
22161 search_shebang = false;
22162 } else if (options != NULL && options->main_script && !parser->parsing_eval) {
22163 search_shebang = true;
22164 }
22165 }
22166
22167 // Here we're going to find the first shebang that includes "ruby" and start
22168 // parsing from there.
22169 if (search_shebang) {
22170 // If a shebang that includes "ruby" is not found, then we're going to a
22171 // a load error to the list of errors on the parser.
22172 bool found_shebang = false;
22173
22174 // This is going to point to the start of each line as we check it.
22175 // We'll maintain a moving window looking at each line at they come.
22176 const uint8_t *cursor = parser->start;
22177
22178 // The newline pointer points to the end of the current line that we're
22179 // considering. If it is NULL, then we're at the end of the file.
22180 const uint8_t *newline = next_newline(cursor, parser->end - cursor);
22181
22182 while (newline != NULL) {
22183 pm_newline_list_append(&parser->newline_list, newline);
22184
22185 cursor = newline + 1;
22186 newline = next_newline(cursor, parser->end - cursor);
22187
22188 size_t length = (size_t) ((newline != NULL ? newline : parser->end) - cursor);
22189 if (length > 2 && cursor[0] == '#' && cursor[1] == '!') {
22190 const char *engine;
22191 if ((engine = pm_strnstr((const char *) cursor, "ruby", length)) != NULL) {
22192 found_shebang = true;
22193
22194 if (newline != NULL) {
22195 pm_parser_warn_shebang_carriage_return(parser, cursor, length + 1);
22196 parser->encoding_comment_start = newline + 1;
22197 }
22198
22199 if (options != NULL && options->shebang_callback != NULL) {
22200 pm_parser_init_shebang(parser, options, engine, length - ((size_t) (engine - (const char *) cursor)));
22201 }
22202
22203 break;
22204 }
22205 }
22206 }
22207
22208 if (found_shebang) {
22209 parser->previous = (pm_token_t) { .type = PM_TOKEN_EOF, .start = cursor, .end = cursor };
22210 parser->current = (pm_token_t) { .type = PM_TOKEN_EOF, .start = cursor, .end = cursor };
22211 } else {
22212 pm_parser_err(parser, parser->start, parser->start, PM_ERR_SCRIPT_NOT_FOUND);
22213 pm_newline_list_clear(&parser->newline_list);
22214 }
22215 }
22216
22217 // The encoding comment can start after any amount of inline whitespace, so
22218 // here we'll advance it to the first non-inline-whitespace character so
22219 // that it is ready for future comparisons.
22220 parser->encoding_comment_start += pm_strspn_inline_whitespace(parser->encoding_comment_start, parser->end - parser->encoding_comment_start);
22221 }
22222
22223 /**
22224 * Register a callback that will be called whenever prism changes the encoding
22225 * it is using to parse based on the magic comment.
22226 */
22227 PRISM_EXPORTED_FUNCTION void
22228 pm_parser_register_encoding_changed_callback(pm_parser_t *parser, pm_encoding_changed_callback_t callback) {
22229 parser->encoding_changed_callback = callback;
22230 }
22231
22232 /**
22233 * Free all of the memory associated with the comment list.
22234 */
22235 static inline void
22236 pm_comment_list_free(pm_list_t *list) {
22237 pm_list_node_t *node, *next;
22238
22239 for (node = list->head; node != NULL; node = next) {
22240 next = node->next;
22241
22242 pm_comment_t *comment = (pm_comment_t *) node;
22243 xfree(comment);
22244 }
22245 }
22246
22247 /**
22248 * Free all of the memory associated with the magic comment list.
22249 */
22250 static inline void
22251 pm_magic_comment_list_free(pm_list_t *list) {
22252 pm_list_node_t *node, *next;
22253
22254 for (node = list->head; node != NULL; node = next) {
22255 next = node->next;
22256
22257 pm_magic_comment_t *magic_comment = (pm_magic_comment_t *) node;
22258 xfree(magic_comment);
22259 }
22260 }
22261
22262 /**
22263 * Free any memory associated with the given parser.
22264 */
22265 PRISM_EXPORTED_FUNCTION void
22266 pm_parser_free(pm_parser_t *parser) {
22267 pm_string_free(&parser->filepath);
22268 pm_diagnostic_list_free(&parser->error_list);
22269 pm_diagnostic_list_free(&parser->warning_list);
22270 pm_comment_list_free(&parser->comment_list);
22271 pm_magic_comment_list_free(&parser->magic_comment_list);
22272 pm_constant_pool_free(&parser->constant_pool);
22273 pm_newline_list_free(&parser->newline_list);
22274
22275 while (parser->current_scope != NULL) {
22276 // Normally, popping the scope doesn't free the locals since it is
22277 // assumed that ownership has transferred to the AST. However if we have
22278 // scopes while we're freeing the parser, it's likely they came from
22279 // eval scopes and we need to free them explicitly here.
22280 pm_parser_scope_pop(parser);
22281 }
22282
22283 while (parser->lex_modes.index >= PM_LEX_STACK_SIZE) {
22284 lex_mode_pop(parser);
22285 }
22286 }
22287
22288 /**
22289 * Parse the Ruby source associated with the given parser and return the tree.
22290 */
22291 PRISM_EXPORTED_FUNCTION pm_node_t *
22292 pm_parse(pm_parser_t *parser) {
22293 return parse_program(parser);
22294 }
22295
22296 /**
22297 * Read into the stream until the gets callback returns false. If the last read
22298 * line from the stream matches an __END__ marker, then halt and return false,
22299 * otherwise return true.
22300 */
22301 static bool
22302 pm_parse_stream_read(pm_buffer_t *buffer, void *stream, pm_parse_stream_fgets_t *stream_fgets, pm_parse_stream_feof_t *stream_feof) {
22303 #define LINE_SIZE 4096
22304 char line[LINE_SIZE];
22305
22306 while (memset(line, '\n', LINE_SIZE), stream_fgets(line, LINE_SIZE, stream) != NULL) {
22307 size_t length = LINE_SIZE;
22308 while (length > 0 && line[length - 1] == '\n') length--;
22309
22310 if (length == LINE_SIZE) {
22311 // If we read a line that is the maximum size and it doesn't end
22312 // with a newline, then we'll just append it to the buffer and
22313 // continue reading.
22314 length--;
22315 pm_buffer_append_string(buffer, line, length);
22316 continue;
22317 }
22318
22319 // Append the line to the buffer.
22320 length--;
22321 pm_buffer_append_string(buffer, line, length);
22322
22323 // Check if the line matches the __END__ marker. If it does, then stop
22324 // reading and return false. In most circumstances, this means we should
22325 // stop reading from the stream so that the DATA constant can pick it
22326 // up.
22327 switch (length) {
22328 case 7:
22329 if (strncmp(line, "__END__", 7) == 0) return false;
22330 break;
22331 case 8:
22332 if (strncmp(line, "__END__\n", 8) == 0) return false;
22333 break;
22334 case 9:
22335 if (strncmp(line, "__END__\r\n", 9) == 0) return false;
22336 break;
22337 }
22338
22339 // All data should be read via gets. If the string returned by gets
22340 // _doesn't_ end with a newline, then we assume we hit EOF condition.
22341 if (stream_feof(stream)) {
22342 break;
22343 }
22344 }
22345
22346 return true;
22347 #undef LINE_SIZE
22348 }
22349
22350 /**
22351 * Determine if there was an unterminated heredoc at the end of the input, which
22352 * would mean the stream isn't finished and we should keep reading.
22353 *
22354 * For the other lex modes we can check if the lex mode has been closed, but for
22355 * heredocs when we hit EOF we close the lex mode and then go back to parse the
22356 * rest of the line after the heredoc declaration so that we get more of the
22357 * syntax tree.
22358 */
22359 static bool
22360 pm_parse_stream_unterminated_heredoc_p(pm_parser_t *parser) {
22361 pm_diagnostic_t *diagnostic = (pm_diagnostic_t *) parser->error_list.head;
22362
22363 for (; diagnostic != NULL; diagnostic = (pm_diagnostic_t *) diagnostic->node.next) {
22364 if (diagnostic->diag_id == PM_ERR_HEREDOC_TERM) {
22365 return true;
22366 }
22367 }
22368
22369 return false;
22370 }
22371
22372 /**
22373 * Parse a stream of Ruby source and return the tree.
22374 *
22375 * Prism is designed around having the entire source in memory at once, but you
22376 * can stream stdin in to Ruby so we need to support a streaming API.
22377 */
22378 PRISM_EXPORTED_FUNCTION pm_node_t *
22379 pm_parse_stream(pm_parser_t *parser, pm_buffer_t *buffer, void *stream, pm_parse_stream_fgets_t *stream_fgets, pm_parse_stream_feof_t *stream_feof, const pm_options_t *options) {
22380 pm_buffer_init(buffer);
22381
22382 bool eof = pm_parse_stream_read(buffer, stream, stream_fgets, stream_feof);
22383
22384 pm_parser_init(parser, (const uint8_t *) pm_buffer_value(buffer), pm_buffer_length(buffer), options);
22385 pm_node_t *node = pm_parse(parser);
22386
22387 while (!eof && parser->error_list.size > 0 && (parser->lex_modes.index > 0 || pm_parse_stream_unterminated_heredoc_p(parser))) {
22388 pm_node_destroy(parser, node);
22389 eof = pm_parse_stream_read(buffer, stream, stream_fgets, stream_feof);
22390
22391 pm_parser_free(parser);
22392 pm_parser_init(parser, (const uint8_t *) pm_buffer_value(buffer), pm_buffer_length(buffer), options);
22393 node = pm_parse(parser);
22394 }
22395
22396 return node;
22397 }
22398
22399 /**
22400 * Parse the source and return true if it parses without errors or warnings.
22401 */
22402 PRISM_EXPORTED_FUNCTION bool
22403 pm_parse_success_p(const uint8_t *source, size_t size, const char *data) {
22404 pm_options_t options = { 0 };
22405 pm_options_read(&options, data);
22406
22407 pm_parser_t parser;
22408 pm_parser_init(&parser, source, size, &options);
22409
22410 pm_node_t *node = pm_parse(&parser);
22411 pm_node_destroy(&parser, node);
22412
22413 bool result = parser.error_list.size == 0;
22414 pm_parser_free(&parser);
22415 pm_options_free(&options);
22416
22417 return result;
22418 }
22419
22420 #undef PM_CASE_KEYWORD
22421 #undef PM_CASE_OPERATOR
22422 #undef PM_CASE_WRITABLE
22423 #undef PM_STRING_EMPTY
22424
22425 // We optionally support serializing to a binary string. For systems that don't
22426 // want or need this functionality, it can be turned off with the
22427 // PRISM_EXCLUDE_SERIALIZATION define.
22428 #ifndef PRISM_EXCLUDE_SERIALIZATION
22429
22430 static inline void
22431 pm_serialize_header(pm_buffer_t *buffer) {
22432 pm_buffer_append_string(buffer, "PRISM", 5);
22433 pm_buffer_append_byte(buffer, PRISM_VERSION_MAJOR);
22434 pm_buffer_append_byte(buffer, PRISM_VERSION_MINOR);
22435 pm_buffer_append_byte(buffer, PRISM_VERSION_PATCH);
22436 pm_buffer_append_byte(buffer, PRISM_SERIALIZE_ONLY_SEMANTICS_FIELDS ? 1 : 0);
22437 }
22438
22439 /**
22440 * Serialize the AST represented by the given node to the given buffer.
22441 */
22442 PRISM_EXPORTED_FUNCTION void
22443 pm_serialize(pm_parser_t *parser, pm_node_t *node, pm_buffer_t *buffer) {
22444 pm_serialize_header(buffer);
22445 pm_serialize_content(parser, node, buffer);
22446 pm_buffer_append_byte(buffer, '\0');
22447 }
22448
22449 /**
22450 * Parse and serialize the AST represented by the given source to the given
22451 * buffer.
22452 */
22453 PRISM_EXPORTED_FUNCTION void
22454 pm_serialize_parse(pm_buffer_t *buffer, const uint8_t *source, size_t size, const char *data) {
22455 pm_options_t options = { 0 };
22456 pm_options_read(&options, data);
22457
22458 pm_parser_t parser;
22459 pm_parser_init(&parser, source, size, &options);
22460
22461 pm_node_t *node = pm_parse(&parser);
22462
22463 pm_serialize_header(buffer);
22464 pm_serialize_content(&parser, node, buffer);
22465 pm_buffer_append_byte(buffer, '\0');
22466
22467 pm_node_destroy(&parser, node);
22468 pm_parser_free(&parser);
22469 pm_options_free(&options);
22470 }
22471
22472 /**
22473 * Parse and serialize the AST represented by the source that is read out of the
22474 * given stream into to the given buffer.
22475 */
22476 PRISM_EXPORTED_FUNCTION void
22477 pm_serialize_parse_stream(pm_buffer_t *buffer, void *stream, pm_parse_stream_fgets_t *stream_fgets, pm_parse_stream_feof_t *stream_feof, const char *data) {
22478 pm_parser_t parser;
22479 pm_options_t options = { 0 };
22480 pm_options_read(&options, data);
22481
22482 pm_buffer_t parser_buffer;
22483 pm_node_t *node = pm_parse_stream(&parser, &parser_buffer, stream, stream_fgets, stream_feof, &options);
22484 pm_serialize_header(buffer);
22485 pm_serialize_content(&parser, node, buffer);
22486 pm_buffer_append_byte(buffer, '\0');
22487
22488 pm_node_destroy(&parser, node);
22489 pm_buffer_free(&parser_buffer);
22490 pm_parser_free(&parser);
22491 pm_options_free(&options);
22492 }
22493
22494 /**
22495 * Parse and serialize the comments in the given source to the given buffer.
22496 */
22497 PRISM_EXPORTED_FUNCTION void
22498 pm_serialize_parse_comments(pm_buffer_t *buffer, const uint8_t *source, size_t size, const char *data) {
22499 pm_options_t options = { 0 };
22500 pm_options_read(&options, data);
22501
22502 pm_parser_t parser;
22503 pm_parser_init(&parser, source, size, &options);
22504
22505 pm_node_t *node = pm_parse(&parser);
22506 pm_serialize_header(buffer);
22507 pm_serialize_encoding(parser.encoding, buffer);
22508 pm_buffer_append_varsint(buffer, parser.start_line);
22509 pm_serialize_comment_list(&parser, &parser.comment_list, buffer);
22510
22511 pm_node_destroy(&parser, node);
22512 pm_parser_free(&parser);
22513 pm_options_free(&options);
22514 }
22515
22516 #endif
22517
22518 /******************************************************************************/
22519 /* Slice queries for the Ruby API */
22520 /******************************************************************************/
22521
22522 /** The category of slice returned from pm_slice_type. */
22523 typedef enum {
22524 /** Returned when the given encoding name is invalid. */
22525 PM_SLICE_TYPE_ERROR = -1,
22526
22527 /** Returned when no other types apply to the slice. */
22528 PM_SLICE_TYPE_NONE,
22529
22530 /** Returned when the slice is a valid local variable name. */
22531 PM_SLICE_TYPE_LOCAL,
22532
22533 /** Returned when the slice is a valid constant name. */
22534 PM_SLICE_TYPE_CONSTANT,
22535
22536 /** Returned when the slice is a valid method name. */
22537 PM_SLICE_TYPE_METHOD_NAME
22538 } pm_slice_type_t;
22539
22540 /**
22541 * Check that the slice is a valid local variable name or constant.
22542 */
22543 pm_slice_type_t
22544 pm_slice_type(const uint8_t *source, size_t length, const char *encoding_name) {
22545 // first, get the right encoding object
22546 const pm_encoding_t *encoding = pm_encoding_find((const uint8_t *) encoding_name, (const uint8_t *) (encoding_name + strlen(encoding_name)));
22547 if (encoding == NULL) return PM_SLICE_TYPE_ERROR;
22548
22549 // check that there is at least one character
22550 if (length == 0) return PM_SLICE_TYPE_NONE;
22551
22552 size_t width;
22553 if ((width = encoding->alpha_char(source, (ptrdiff_t) length)) != 0) {
22554 // valid because alphabetical
22555 } else if (*source == '_') {
22556 // valid because underscore
22557 width = 1;
22558 } else if ((*source >= 0x80) && ((width = encoding->char_width(source, (ptrdiff_t) length)) > 0)) {
22559 // valid because multibyte
22560 } else {
22561 // invalid because no match
22562 return PM_SLICE_TYPE_NONE;
22563 }
22564
22565 // determine the type of the slice based on the first character
22566 const uint8_t *end = source + length;
22567 pm_slice_type_t result = encoding->isupper_char(source, end - source) ? PM_SLICE_TYPE_CONSTANT : PM_SLICE_TYPE_LOCAL;
22568
22569 // next, iterate through all of the bytes of the string to ensure that they
22570 // are all valid identifier characters
22571 source += width;
22572
22573 while (source < end) {
22574 if ((width = encoding->alnum_char(source, end - source)) != 0) {
22575 // valid because alphanumeric
22576 source += width;
22577 } else if (*source == '_') {
22578 // valid because underscore
22579 source++;
22580 } else if ((*source >= 0x80) && ((width = encoding->char_width(source, end - source)) > 0)) {
22581 // valid because multibyte
22582 source += width;
22583 } else {
22584 // invalid because no match
22585 break;
22586 }
22587 }
22588
22589 // accept a ! or ? at the end of the slice as a method name
22590 if (*source == '!' || *source == '?' || *source == '=') {
22591 source++;
22592 result = PM_SLICE_TYPE_METHOD_NAME;
22593 }
22594
22595 // valid if we are at the end of the slice
22596 return source == end ? result : PM_SLICE_TYPE_NONE;
22597 }
22598
22599 /**
22600 * Check that the slice is a valid local variable name.
22601 */
22602 PRISM_EXPORTED_FUNCTION pm_string_query_t
22603 pm_string_query_local(const uint8_t *source, size_t length, const char *encoding_name) {
22604 switch (pm_slice_type(source, length, encoding_name)) {
22605 case PM_SLICE_TYPE_ERROR:
22606 return PM_STRING_QUERY_ERROR;
22607 case PM_SLICE_TYPE_NONE:
22608 case PM_SLICE_TYPE_CONSTANT:
22609 case PM_SLICE_TYPE_METHOD_NAME:
22610 return PM_STRING_QUERY_FALSE;
22611 case PM_SLICE_TYPE_LOCAL:
22612 return PM_STRING_QUERY_TRUE;
22613 }
22614
22615 assert(false && "unreachable");
22616 return PM_STRING_QUERY_FALSE;
22617 }
22618
22619 /**
22620 * Check that the slice is a valid constant name.
22621 */
22622 PRISM_EXPORTED_FUNCTION pm_string_query_t
22623 pm_string_query_constant(const uint8_t *source, size_t length, const char *encoding_name) {
22624 switch (pm_slice_type(source, length, encoding_name)) {
22625 case PM_SLICE_TYPE_ERROR:
22626 return PM_STRING_QUERY_ERROR;
22627 case PM_SLICE_TYPE_NONE:
22628 case PM_SLICE_TYPE_LOCAL:
22629 case PM_SLICE_TYPE_METHOD_NAME:
22630 return PM_STRING_QUERY_FALSE;
22631 case PM_SLICE_TYPE_CONSTANT:
22632 return PM_STRING_QUERY_TRUE;
22633 }
22634
22635 assert(false && "unreachable");
22636 return PM_STRING_QUERY_FALSE;
22637 }
22638
22639 /**
22640 * Check that the slice is a valid method name.
22641 */
22642 PRISM_EXPORTED_FUNCTION pm_string_query_t
22643 pm_string_query_method_name(const uint8_t *source, size_t length, const char *encoding_name) {
22644 #define B(p) ((p) ? PM_STRING_QUERY_TRUE : PM_STRING_QUERY_FALSE)
22645 #define C1(c) (*source == c)
22646 #define C2(s) (memcmp(source, s, 2) == 0)
22647 #define C3(s) (memcmp(source, s, 3) == 0)
22648
22649 switch (pm_slice_type(source, length, encoding_name)) {
22650 case PM_SLICE_TYPE_ERROR:
22651 return PM_STRING_QUERY_ERROR;
22652 case PM_SLICE_TYPE_NONE:
22653 break;
22654 case PM_SLICE_TYPE_LOCAL:
22655 // numbered parameters are not valid method names
22656 return B((length != 2) || (source[0] != '_') || (source[1] == '0') || !pm_char_is_decimal_digit(source[1]));
22657 case PM_SLICE_TYPE_CONSTANT:
22658 // all constants are valid method names
22659 case PM_SLICE_TYPE_METHOD_NAME:
22660 // all method names are valid method names
22661 return PM_STRING_QUERY_TRUE;
22662 }
22663
22664 switch (length) {
22665 case 1:
22666 return B(C1('&') || C1('`') || C1('!') || C1('^') || C1('>') || C1('<') || C1('-') || C1('%') || C1('|') || C1('+') || C1('/') || C1('*') || C1('~'));
22667 case 2:
22668 return B(C2("!=") || C2("!~") || C2("[]") || C2("==") || C2("=~") || C2(">=") || C2(">>") || C2("<=") || C2("<<") || C2("**"));
22669 case 3:
22670 return B(C3("===") || C3("<=>") || C3("[]="));
22671 default:
22672 return PM_STRING_QUERY_FALSE;
22673 }
22674
22675 #undef B
22676 #undef C1
22677 #undef C2
22678 #undef C3
22679 }