Ruby 4.0.6p0 (2026-07-14 revision 03b6d3f8898a28604fe6cb00eae3226b821168f4)
prism_compile.c
1#include "prism.h"
2#include "ruby/version.h"
3
9typedef struct {
11 int32_t line;
12
14 uint32_t node_id;
16
17/******************************************************************************/
18/* These macros operate on pm_node_location_t structs as opposed to NODE*s. */
19/******************************************************************************/
20
21#define PUSH_ADJUST(seq, location, label) \
22 ADD_ELEM((seq), (LINK_ELEMENT *) new_adjust_body(iseq, (label), (int) (location).line))
23
24#define PUSH_ADJUST_RESTORE(seq, label) \
25 ADD_ELEM((seq), (LINK_ELEMENT *) new_adjust_body(iseq, (label), -1))
26
27#define PUSH_INSN(seq, location, insn) \
28 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_body(iseq, (int) (location).line, (int) (location).node_id, BIN(insn), 0))
29
30#define PUSH_INSN1(seq, location, insn, op1) \
31 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_body(iseq, (int) (location).line, (int) (location).node_id, BIN(insn), 1, (VALUE)(op1)))
32
33#define PUSH_INSN2(seq, location, insn, op1, op2) \
34 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_body(iseq, (int) (location).line, (int) (location).node_id, BIN(insn), 2, (VALUE)(op1), (VALUE)(op2)))
35
36#define PUSH_INSN3(seq, location, insn, op1, op2, op3) \
37 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_body(iseq, (int) (location).line, (int) (location).node_id, BIN(insn), 3, (VALUE)(op1), (VALUE)(op2), (VALUE)(op3)))
38
39#define PUSH_INSNL(seq, location, insn, label) \
40 (PUSH_INSN1(seq, location, insn, label), LABEL_REF(label))
41
42#define PUSH_LABEL(seq, label) \
43 ADD_ELEM((seq), (LINK_ELEMENT *) (label))
44
45#define PUSH_SEND_R(seq, location, id, argc, block, flag, keywords) \
46 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_send(iseq, (int) (location).line, (int) (location).node_id, (id), (VALUE)(argc), (block), (VALUE)(flag), (keywords)))
47
48#define PUSH_SEND(seq, location, id, argc) \
49 PUSH_SEND_R((seq), location, (id), (argc), NULL, (VALUE)INT2FIX(0), NULL)
50
51#define PUSH_SEND_WITH_FLAG(seq, location, id, argc, flag) \
52 PUSH_SEND_R((seq), location, (id), (argc), NULL, (VALUE)(flag), NULL)
53
54#define PUSH_SEND_WITH_BLOCK(seq, location, id, argc, block) \
55 PUSH_SEND_R((seq), location, (id), (argc), (block), (VALUE)INT2FIX(0), NULL)
56
57#define PUSH_CALL(seq, location, id, argc) \
58 PUSH_SEND_R((seq), location, (id), (argc), NULL, (VALUE)INT2FIX(VM_CALL_FCALL), NULL)
59
60#define PUSH_CALL_WITH_BLOCK(seq, location, id, argc, block) \
61 PUSH_SEND_R((seq), location, (id), (argc), (block), (VALUE)INT2FIX(VM_CALL_FCALL), NULL)
62
63#define PUSH_TRACE(seq, event) \
64 ADD_ELEM((seq), (LINK_ELEMENT *) new_trace_body(iseq, (event), 0))
65
66#define PUSH_CATCH_ENTRY(type, ls, le, iseqv, lc) \
67 ADD_CATCH_ENTRY((type), (ls), (le), (iseqv), (lc))
68
69#define PUSH_SEQ(seq1, seq2) \
70 APPEND_LIST((seq1), (seq2))
71
72#define PUSH_SYNTHETIC_PUTNIL(seq, iseq) \
73 do { \
74 int lineno = ISEQ_COMPILE_DATA(iseq)->last_line; \
75 if (lineno == 0) lineno = FIX2INT(rb_iseq_first_lineno(iseq)); \
76 ADD_SYNTHETIC_INSN(seq, lineno, -1, putnil); \
77 } while (0)
78
79/******************************************************************************/
80/* These functions compile getlocal/setlocal instructions but operate on */
81/* prism locations instead of NODEs. */
82/******************************************************************************/
83
84static void
85pm_iseq_add_getlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, int line, int node_id, int idx, int level)
86{
87 if (iseq_local_block_param_p(iseq, idx, level)) {
88 ADD_ELEM(seq, (LINK_ELEMENT *) new_insn_body(iseq, line, node_id, BIN(getblockparam), 2, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)));
89 }
90 else {
91 ADD_ELEM(seq, (LINK_ELEMENT *) new_insn_body(iseq, line, node_id, BIN(getlocal), 2, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)));
92 }
93 if (level > 0) access_outer_variables(iseq, level, iseq_lvar_id(iseq, idx, level), Qfalse);
94}
95
96static void
97pm_iseq_add_setlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, int line, int node_id, int idx, int level)
98{
99 if (iseq_local_block_param_p(iseq, idx, level)) {
100 ADD_ELEM(seq, (LINK_ELEMENT *) new_insn_body(iseq, line, node_id, BIN(setblockparam), 2, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)));
101 }
102 else {
103 ADD_ELEM(seq, (LINK_ELEMENT *) new_insn_body(iseq, line, node_id, BIN(setlocal), 2, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)));
104 }
105 update_lvar_state(iseq, level, idx);
106 if (level > 0) access_outer_variables(iseq, level, iseq_lvar_id(iseq, idx, level), Qtrue);
107}
108
109#define PUSH_GETLOCAL(seq, location, idx, level) \
110 pm_iseq_add_getlocal(iseq, (seq), (int) (location).line, (int) (location).node_id, (idx), (level))
111
112#define PUSH_SETLOCAL(seq, location, idx, level) \
113 pm_iseq_add_setlocal(iseq, (seq), (int) (location).line, (int) (location).node_id, (idx), (level))
114
115/******************************************************************************/
116/* These are helper macros for the compiler. */
117/******************************************************************************/
118
119#define OLD_ISEQ NEW_ISEQ
120#undef NEW_ISEQ
121
122#define NEW_ISEQ(node, name, type, line_no) \
123 pm_new_child_iseq(iseq, (node), rb_fstring(name), 0, (type), (line_no))
124
125#define OLD_CHILD_ISEQ NEW_CHILD_ISEQ
126#undef NEW_CHILD_ISEQ
127
128#define NEW_CHILD_ISEQ(node, name, type, line_no) \
129 pm_new_child_iseq(iseq, (node), rb_fstring(name), iseq, (type), (line_no))
130
131#define PM_COMPILE(node) \
132 pm_compile_node(iseq, (node), ret, popped, scope_node)
133
134#define PM_COMPILE_INTO_ANCHOR(_ret, node) \
135 pm_compile_node(iseq, (node), _ret, popped, scope_node)
136
137#define PM_COMPILE_POPPED(node) \
138 pm_compile_node(iseq, (node), ret, true, scope_node)
139
140#define PM_COMPILE_NOT_POPPED(node) \
141 pm_compile_node(iseq, (node), ret, false, scope_node)
142
143#define PM_NODE_START_LOCATION(parser, node) \
144 ((pm_node_location_t) { .line = pm_newline_list_line(&(parser)->newline_list, ((const pm_node_t *) (node))->location.start, (parser)->start_line), .node_id = ((const pm_node_t *) (node))->node_id })
145
146#define PM_NODE_END_LOCATION(parser, node) \
147 ((pm_node_location_t) { .line = pm_newline_list_line(&(parser)->newline_list, ((const pm_node_t *) (node))->location.end, (parser)->start_line), .node_id = ((const pm_node_t *) (node))->node_id })
148
149#define PM_LOCATION_START_LOCATION(parser, location, id) \
150 ((pm_node_location_t) { .line = pm_newline_list_line(&(parser)->newline_list, (location)->start, (parser)->start_line), .node_id = id })
151
152#define PM_NODE_START_LINE_COLUMN(parser, node) \
153 pm_newline_list_line_column(&(parser)->newline_list, ((const pm_node_t *) (node))->location.start, (parser)->start_line)
154
155#define PM_NODE_END_LINE_COLUMN(parser, node) \
156 pm_newline_list_line_column(&(parser)->newline_list, ((const pm_node_t *) (node))->location.end, (parser)->start_line)
157
158#define PM_LOCATION_START_LINE_COLUMN(parser, location) \
159 pm_newline_list_line_column(&(parser)->newline_list, (location)->start, (parser)->start_line)
160
161static int
162pm_node_line_number(const pm_parser_t *parser, const pm_node_t *node)
163{
164 return (int) pm_newline_list_line(&parser->newline_list, node->location.start, parser->start_line);
165}
166
167static int
168pm_location_line_number(const pm_parser_t *parser, const pm_location_t *location) {
169 return (int) pm_newline_list_line(&parser->newline_list, location->start, parser->start_line);
170}
171
175static VALUE
176parse_integer_value(const pm_integer_t *integer)
177{
178 VALUE result;
179
180 if (integer->values == NULL) {
181 result = UINT2NUM(integer->value);
182 }
183 else {
184 VALUE string = rb_str_new(NULL, integer->length * 8);
185 unsigned char *bytes = (unsigned char *) RSTRING_PTR(string);
186
187 size_t offset = integer->length * 8;
188 for (size_t value_index = 0; value_index < integer->length; value_index++) {
189 uint32_t value = integer->values[value_index];
190
191 for (int index = 0; index < 8; index++) {
192 int byte = (value >> (4 * index)) & 0xf;
193 bytes[--offset] = byte < 10 ? byte + '0' : byte - 10 + 'a';
194 }
195 }
196
197 result = rb_funcall(string, rb_intern("to_i"), 1, UINT2NUM(16));
198 }
199
200 if (integer->negative) {
201 result = rb_funcall(result, rb_intern("-@"), 0);
202 }
203
204 if (!SPECIAL_CONST_P(result)) {
205 RB_OBJ_SET_SHAREABLE(result); // bignum
206 }
207
208 return result;
209}
210
214static inline VALUE
215parse_integer(const pm_integer_node_t *node)
216{
217 return parse_integer_value(&node->value);
218}
219
223static VALUE
224parse_float(const pm_float_node_t *node)
225{
226 VALUE val = DBL2NUM(node->value);
227 if (!FLONUM_P(val)) {
228 RB_OBJ_SET_SHAREABLE(val);
229 }
230 return val;
231}
232
239static VALUE
240parse_rational(const pm_rational_node_t *node)
241{
242 VALUE numerator = parse_integer_value(&node->numerator);
243 VALUE denominator = parse_integer_value(&node->denominator);
244
245 return rb_ractor_make_shareable(rb_rational_new(numerator, denominator));
246}
247
254static VALUE
255parse_imaginary(const pm_imaginary_node_t *node)
256{
257 VALUE imaginary_part;
258 switch (PM_NODE_TYPE(node->numeric)) {
259 case PM_FLOAT_NODE: {
260 imaginary_part = parse_float((const pm_float_node_t *) node->numeric);
261 break;
262 }
263 case PM_INTEGER_NODE: {
264 imaginary_part = parse_integer((const pm_integer_node_t *) node->numeric);
265 break;
266 }
267 case PM_RATIONAL_NODE: {
268 imaginary_part = parse_rational((const pm_rational_node_t *) node->numeric);
269 break;
270 }
271 default:
272 rb_bug("Unexpected numeric type on imaginary number %s\n", pm_node_type_to_str(PM_NODE_TYPE(node->numeric)));
273 }
274
275 return RB_OBJ_SET_SHAREABLE(rb_complex_raw(INT2FIX(0), imaginary_part));
276}
277
278static inline VALUE
279parse_string(const pm_scope_node_t *scope_node, const pm_string_t *string)
280{
281 return rb_enc_str_new((const char *) pm_string_source(string), pm_string_length(string), scope_node->encoding);
282}
283
289static inline VALUE
290parse_string_encoded(const pm_node_t *node, const pm_string_t *string, rb_encoding *default_encoding)
291{
292 rb_encoding *encoding;
293
294 if (node->flags & PM_ENCODING_FLAGS_FORCED_BINARY_ENCODING) {
295 encoding = rb_ascii8bit_encoding();
296 }
297 else if (node->flags & PM_ENCODING_FLAGS_FORCED_UTF8_ENCODING) {
298 encoding = rb_utf8_encoding();
299 }
300 else {
301 encoding = default_encoding;
302 }
303
304 return rb_enc_str_new((const char *) pm_string_source(string), pm_string_length(string), encoding);
305}
306
307static inline VALUE
308parse_static_literal_string(rb_iseq_t *iseq, const pm_scope_node_t *scope_node, const pm_node_t *node, const pm_string_t *string)
309{
310 rb_encoding *encoding;
311
312 if (node->flags & PM_STRING_FLAGS_FORCED_BINARY_ENCODING) {
313 encoding = rb_ascii8bit_encoding();
314 }
315 else if (node->flags & PM_STRING_FLAGS_FORCED_UTF8_ENCODING) {
316 encoding = rb_utf8_encoding();
317 }
318 else {
319 encoding = scope_node->encoding;
320 }
321
322 VALUE value = rb_enc_literal_str((const char *) pm_string_source(string), pm_string_length(string), encoding);
324
325 if (ISEQ_COMPILE_DATA(iseq)->option->debug_frozen_string_literal || RTEST(ruby_debug)) {
326 int line_number = pm_node_line_number(scope_node->parser, node);
327 value = rb_ractor_make_shareable(rb_str_with_debug_created_info(value, rb_iseq_path(iseq), line_number));
328 }
329
330 return value;
331}
332
333static inline ID
334parse_string_symbol(const pm_scope_node_t *scope_node, const pm_symbol_node_t *symbol)
335{
336 rb_encoding *encoding;
337 if (symbol->base.flags & PM_SYMBOL_FLAGS_FORCED_UTF8_ENCODING) {
338 encoding = rb_utf8_encoding();
339 }
340 else if (symbol->base.flags & PM_SYMBOL_FLAGS_FORCED_BINARY_ENCODING) {
341 encoding = rb_ascii8bit_encoding();
342 }
343 else if (symbol->base.flags & PM_SYMBOL_FLAGS_FORCED_US_ASCII_ENCODING) {
344 encoding = rb_usascii_encoding();
345 }
346 else {
347 encoding = scope_node->encoding;
348 }
349
350 return rb_intern3((const char *) pm_string_source(&symbol->unescaped), pm_string_length(&symbol->unescaped), encoding);
351}
352
353static int
354pm_optimizable_range_item_p(const pm_node_t *node)
355{
356 return (!node || PM_NODE_TYPE_P(node, PM_INTEGER_NODE) || PM_NODE_TYPE_P(node, PM_NIL_NODE));
357}
358
360static VALUE
361parse_regexp_error(rb_iseq_t *iseq, int32_t line_number, const char *fmt, ...)
362{
363 va_list args;
364 va_start(args, fmt);
365 VALUE error = rb_syntax_error_append(Qnil, rb_iseq_path(iseq), line_number, -1, NULL, "%" PRIsVALUE, args);
366 va_end(args);
367 rb_exc_raise(error);
368}
369
370static VALUE
371parse_regexp_string_part(rb_iseq_t *iseq, const pm_scope_node_t *scope_node, const pm_node_t *node, const pm_string_t *unescaped, rb_encoding *implicit_regexp_encoding, rb_encoding *explicit_regexp_encoding)
372{
373 // If we were passed an explicit regexp encoding, then we need to double
374 // check that it's okay here for this fragment of the string.
375 rb_encoding *encoding;
376
377 if (explicit_regexp_encoding != NULL) {
378 encoding = explicit_regexp_encoding;
379 }
380 else if (node->flags & PM_STRING_FLAGS_FORCED_BINARY_ENCODING) {
381 encoding = rb_ascii8bit_encoding();
382 }
383 else if (node->flags & PM_STRING_FLAGS_FORCED_UTF8_ENCODING) {
384 encoding = rb_utf8_encoding();
385 }
386 else {
387 encoding = implicit_regexp_encoding;
388 }
389
390 VALUE string = rb_enc_str_new((const char *) pm_string_source(unescaped), pm_string_length(unescaped), encoding);
391 VALUE error = rb_reg_check_preprocess(string);
392
393 if (error != Qnil) parse_regexp_error(iseq, pm_node_line_number(scope_node->parser, node), "%" PRIsVALUE, rb_obj_as_string(error));
394 return string;
395}
396
397static VALUE
398pm_static_literal_concat(rb_iseq_t *iseq, const pm_node_list_t *nodes, const pm_scope_node_t *scope_node, rb_encoding *implicit_regexp_encoding, rb_encoding *explicit_regexp_encoding, bool top)
399{
400 VALUE current = Qnil;
401
402 for (size_t index = 0; index < nodes->size; index++) {
403 const pm_node_t *part = nodes->nodes[index];
404 VALUE string;
405
406 switch (PM_NODE_TYPE(part)) {
407 case PM_STRING_NODE:
408 if (implicit_regexp_encoding != NULL) {
409 if (top) {
410 string = parse_regexp_string_part(iseq, scope_node, part, &((const pm_string_node_t *) part)->unescaped, implicit_regexp_encoding, explicit_regexp_encoding);
411 }
412 else {
413 string = parse_string_encoded(part, &((const pm_string_node_t *) part)->unescaped, scope_node->encoding);
414 VALUE error = rb_reg_check_preprocess(string);
415 if (error != Qnil) parse_regexp_error(iseq, pm_node_line_number(scope_node->parser, part), "%" PRIsVALUE, rb_obj_as_string(error));
416 }
417 }
418 else {
419 string = parse_string_encoded(part, &((const pm_string_node_t *) part)->unescaped, scope_node->encoding);
420 }
421 break;
422 case PM_INTERPOLATED_STRING_NODE:
423 string = pm_static_literal_concat(iseq, &((const pm_interpolated_string_node_t *) part)->parts, scope_node, implicit_regexp_encoding, explicit_regexp_encoding, false);
424 break;
425 case PM_EMBEDDED_STATEMENTS_NODE: {
426 const pm_embedded_statements_node_t *cast = (const pm_embedded_statements_node_t *) part;
427 string = pm_static_literal_concat(iseq, &cast->statements->body, scope_node, implicit_regexp_encoding, explicit_regexp_encoding, false);
428 break;
429 }
430 default:
431 RUBY_ASSERT(false && "unexpected node type in pm_static_literal_concat");
432 return Qnil;
433 }
434
435 if (current != Qnil) {
436 current = rb_str_concat(current, string);
437 }
438 else {
439 current = string;
440 }
441 }
442
443 return top ? rb_fstring(current) : current;
444}
445
446#define RE_OPTION_ENCODING_SHIFT 8
447#define RE_OPTION_ENCODING(encoding) (((encoding) & 0xFF) << RE_OPTION_ENCODING_SHIFT)
448#define ARG_ENCODING_NONE 32
449#define ARG_ENCODING_FIXED 16
450#define ENC_ASCII8BIT 1
451#define ENC_EUC_JP 2
452#define ENC_Windows_31J 3
453#define ENC_UTF8 4
454
459static int
460parse_regexp_flags(const pm_node_t *node)
461{
462 int flags = 0;
463
464 // Check "no encoding" first so that flags don't get clobbered
465 // We're calling `rb_char_to_option_kcode` in this case so that
466 // we don't need to have access to `ARG_ENCODING_NONE`
467 if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_ASCII_8BIT)) {
468 flags |= ARG_ENCODING_NONE;
469 }
470
471 if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_EUC_JP)) {
472 flags |= (ARG_ENCODING_FIXED | RE_OPTION_ENCODING(ENC_EUC_JP));
473 }
474
475 if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_WINDOWS_31J)) {
476 flags |= (ARG_ENCODING_FIXED | RE_OPTION_ENCODING(ENC_Windows_31J));
477 }
478
479 if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_UTF_8)) {
480 flags |= (ARG_ENCODING_FIXED | RE_OPTION_ENCODING(ENC_UTF8));
481 }
482
483 if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_IGNORE_CASE)) {
484 flags |= ONIG_OPTION_IGNORECASE;
485 }
486
487 if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_MULTI_LINE)) {
488 flags |= ONIG_OPTION_MULTILINE;
489 }
490
491 if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_EXTENDED)) {
492 flags |= ONIG_OPTION_EXTEND;
493 }
494
495 return flags;
496}
497
498#undef RE_OPTION_ENCODING_SHIFT
499#undef RE_OPTION_ENCODING
500#undef ARG_ENCODING_FIXED
501#undef ARG_ENCODING_NONE
502#undef ENC_ASCII8BIT
503#undef ENC_EUC_JP
504#undef ENC_Windows_31J
505#undef ENC_UTF8
506
507static rb_encoding *
508parse_regexp_encoding(const pm_scope_node_t *scope_node, const pm_node_t *node)
509{
510 if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_FORCED_BINARY_ENCODING) || PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_ASCII_8BIT)) {
511 return rb_ascii8bit_encoding();
512 }
513 else if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_UTF_8)) {
514 return rb_utf8_encoding();
515 }
516 else if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_EUC_JP)) {
517 return rb_enc_get_from_index(ENCINDEX_EUC_JP);
518 }
519 else if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_WINDOWS_31J)) {
520 return rb_enc_get_from_index(ENCINDEX_Windows_31J);
521 }
522 else {
523 return NULL;
524 }
525}
526
527static VALUE
528parse_regexp(rb_iseq_t *iseq, const pm_scope_node_t *scope_node, const pm_node_t *node, VALUE string)
529{
530 VALUE errinfo = rb_errinfo();
531
532 int32_t line_number = pm_node_line_number(scope_node->parser, node);
533 VALUE regexp = rb_reg_compile(string, parse_regexp_flags(node), (const char *) pm_string_source(&scope_node->parser->filepath), line_number);
534
535 if (NIL_P(regexp)) {
536 VALUE message = rb_attr_get(rb_errinfo(), idMesg);
537 rb_set_errinfo(errinfo);
538
539 parse_regexp_error(iseq, line_number, "%" PRIsVALUE, message);
540 return Qnil;
541 }
542
543 return RB_OBJ_SET_SHAREABLE(rb_obj_freeze(regexp));
544}
545
546static inline VALUE
547parse_regexp_literal(rb_iseq_t *iseq, const pm_scope_node_t *scope_node, const pm_node_t *node, const pm_string_t *unescaped)
548{
549 rb_encoding *regexp_encoding = parse_regexp_encoding(scope_node, node);
550 if (regexp_encoding == NULL) regexp_encoding = scope_node->encoding;
551
552 VALUE string = rb_enc_str_new((const char *) pm_string_source(unescaped), pm_string_length(unescaped), regexp_encoding);
553 RB_OBJ_SET_SHAREABLE(string);
554 return parse_regexp(iseq, scope_node, node, string);
555}
556
557static inline VALUE
558parse_regexp_concat(rb_iseq_t *iseq, const pm_scope_node_t *scope_node, const pm_node_t *node, const pm_node_list_t *parts)
559{
560 rb_encoding *explicit_regexp_encoding = parse_regexp_encoding(scope_node, node);
561 rb_encoding *implicit_regexp_encoding = explicit_regexp_encoding != NULL ? explicit_regexp_encoding : scope_node->encoding;
562
563 VALUE string = pm_static_literal_concat(iseq, parts, scope_node, implicit_regexp_encoding, explicit_regexp_encoding, false);
564 return parse_regexp(iseq, scope_node, node, string);
565}
566
567static void pm_compile_node(rb_iseq_t *iseq, const pm_node_t *node, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node);
568
569static int
570pm_interpolated_node_compile(rb_iseq_t *iseq, const pm_node_list_t *parts, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node, rb_encoding *implicit_regexp_encoding, rb_encoding *explicit_regexp_encoding, bool mutable_result, bool frozen_result)
571{
572 int stack_size = 0;
573 size_t parts_size = parts->size;
574 bool interpolated = false;
575
576 if (parts_size > 0) {
577 VALUE current_string = Qnil;
578 pm_node_location_t current_location = *node_location;
579
580 for (size_t index = 0; index < parts_size; index++) {
581 const pm_node_t *part = parts->nodes[index];
582
583 if (PM_NODE_TYPE_P(part, PM_STRING_NODE)) {
584 const pm_string_node_t *string_node = (const pm_string_node_t *) part;
585 VALUE string_value;
586
587 if (implicit_regexp_encoding == NULL) {
588 string_value = parse_string_encoded(part, &string_node->unescaped, scope_node->encoding);
589 }
590 else {
591 string_value = parse_regexp_string_part(iseq, scope_node, (const pm_node_t *) string_node, &string_node->unescaped, implicit_regexp_encoding, explicit_regexp_encoding);
592 }
593
594 if (RTEST(current_string)) {
595 current_string = rb_str_concat(current_string, string_value);
596 }
597 else {
598 current_string = string_value;
599 if (index != 0) current_location = PM_NODE_END_LOCATION(scope_node->parser, part);
600 }
601 }
602 else {
603 interpolated = true;
604
605 if (
606 PM_NODE_TYPE_P(part, PM_EMBEDDED_STATEMENTS_NODE) &&
607 ((const pm_embedded_statements_node_t *) part)->statements != NULL &&
608 ((const pm_embedded_statements_node_t *) part)->statements->body.size == 1 &&
609 PM_NODE_TYPE_P(((const pm_embedded_statements_node_t *) part)->statements->body.nodes[0], PM_STRING_NODE)
610 ) {
611 const pm_string_node_t *string_node = (const pm_string_node_t *) ((const pm_embedded_statements_node_t *) part)->statements->body.nodes[0];
612 VALUE string_value;
613
614 if (implicit_regexp_encoding == NULL) {
615 string_value = parse_string_encoded(part, &string_node->unescaped, scope_node->encoding);
616 }
617 else {
618 string_value = parse_regexp_string_part(iseq, scope_node, (const pm_node_t *) string_node, &string_node->unescaped, implicit_regexp_encoding, explicit_regexp_encoding);
619 }
620
621 if (RTEST(current_string)) {
622 current_string = rb_str_concat(current_string, string_value);
623 }
624 else {
625 current_string = string_value;
626 current_location = PM_NODE_START_LOCATION(scope_node->parser, part);
627 }
628 }
629 else {
630 if (!RTEST(current_string)) {
631 rb_encoding *encoding;
632
633 if (implicit_regexp_encoding != NULL) {
634 if (explicit_regexp_encoding != NULL) {
635 encoding = explicit_regexp_encoding;
636 }
637 else if (scope_node->parser->encoding == PM_ENCODING_US_ASCII_ENTRY) {
638 encoding = rb_ascii8bit_encoding();
639 }
640 else {
641 encoding = implicit_regexp_encoding;
642 }
643 }
644 else {
645 encoding = scope_node->encoding;
646 }
647
648 if (parts_size == 1) {
649 current_string = rb_enc_str_new(NULL, 0, encoding);
650 }
651 }
652
653 if (RTEST(current_string)) {
654 VALUE operand = rb_fstring(current_string);
655 PUSH_INSN1(ret, current_location, putobject, operand);
656 stack_size++;
657 }
658
659 PM_COMPILE_NOT_POPPED(part);
660
661 const pm_node_location_t current_location = PM_NODE_START_LOCATION(scope_node->parser, part);
662 PUSH_INSN(ret, current_location, dup);
663
664 {
665 const struct rb_callinfo *callinfo = new_callinfo(iseq, idTo_s, 0, VM_CALL_FCALL | VM_CALL_ARGS_SIMPLE, NULL, FALSE);
666 PUSH_INSN1(ret, current_location, objtostring, callinfo);
667 }
668
669 PUSH_INSN(ret, current_location, anytostring);
670
671 current_string = Qnil;
672 stack_size++;
673 }
674 }
675 }
676
677 if (RTEST(current_string)) {
678 current_string = rb_fstring(current_string);
679
680 if (stack_size == 0) {
681 if (frozen_result) {
682 PUSH_INSN1(ret, current_location, putobject, current_string);
683 } else if (mutable_result || interpolated) {
684 PUSH_INSN1(ret, current_location, putstring, current_string);
685 } else {
686 PUSH_INSN1(ret, current_location, putchilledstring, current_string);
687 }
688 } else {
689 PUSH_INSN1(ret, current_location, putobject, current_string);
690 }
691
692 current_string = Qnil;
693 stack_size++;
694 }
695 }
696 else {
697 PUSH_INSN(ret, *node_location, putnil);
698 }
699
700 return stack_size;
701}
702
703static void
704pm_compile_regexp_dynamic(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_list_t *parts, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
705{
706 rb_encoding *explicit_regexp_encoding = parse_regexp_encoding(scope_node, node);
707 rb_encoding *implicit_regexp_encoding = explicit_regexp_encoding != NULL ? explicit_regexp_encoding : scope_node->encoding;
708
709 int length = pm_interpolated_node_compile(iseq, parts, node_location, ret, popped, scope_node, implicit_regexp_encoding, explicit_regexp_encoding, false, false);
710 PUSH_INSN2(ret, *node_location, toregexp, INT2FIX(parse_regexp_flags(node) & 0xFF), INT2FIX(length));
711}
712
713static VALUE
714pm_source_file_value(const pm_source_file_node_t *node, const pm_scope_node_t *scope_node)
715{
716 const pm_string_t *filepath = &node->filepath;
717 size_t length = pm_string_length(filepath);
718
719 if (length > 0) {
720 rb_encoding *filepath_encoding = scope_node->filepath_encoding != NULL ? scope_node->filepath_encoding : rb_utf8_encoding();
721 return rb_enc_interned_str((const char *) pm_string_source(filepath), length, filepath_encoding);
722 }
723 else {
724 return rb_fstring_lit("<compiled>");
725 }
726}
727
732static VALUE
733pm_static_literal_string(rb_iseq_t *iseq, VALUE string, int line_number)
734{
735 if (ISEQ_COMPILE_DATA(iseq)->option->debug_frozen_string_literal || RTEST(ruby_debug)) {
736 VALUE str = rb_str_with_debug_created_info(string, rb_iseq_path(iseq), line_number);
737 RB_OBJ_SET_SHAREABLE(str);
738 return str;
739 }
740 else {
741 return rb_fstring(string);
742 }
743}
744
750static VALUE
751pm_static_literal_value(rb_iseq_t *iseq, const pm_node_t *node, const pm_scope_node_t *scope_node)
752{
753 // Every node that comes into this function should already be marked as
754 // static literal. If it's not, then we have a bug somewhere.
755 RUBY_ASSERT(PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL));
756
757 switch (PM_NODE_TYPE(node)) {
758 case PM_ARRAY_NODE: {
759 const pm_array_node_t *cast = (const pm_array_node_t *) node;
760 const pm_node_list_t *elements = &cast->elements;
761
762 VALUE value = rb_ary_hidden_new(elements->size);
763 for (size_t index = 0; index < elements->size; index++) {
764 rb_ary_push(value, pm_static_literal_value(iseq, elements->nodes[index], scope_node));
765 }
766
767 RB_OBJ_SET_FROZEN_SHAREABLE(value);
768 return value;
769 }
770 case PM_FALSE_NODE:
771 return Qfalse;
772 case PM_FLOAT_NODE:
773 return parse_float((const pm_float_node_t *) node);
774 case PM_HASH_NODE: {
775 const pm_hash_node_t *cast = (const pm_hash_node_t *) node;
776 const pm_node_list_t *elements = &cast->elements;
777
778 VALUE array = rb_ary_hidden_new(elements->size * 2);
779 for (size_t index = 0; index < elements->size; index++) {
780 RUBY_ASSERT(PM_NODE_TYPE_P(elements->nodes[index], PM_ASSOC_NODE));
781 const pm_assoc_node_t *cast = (const pm_assoc_node_t *) elements->nodes[index];
782 VALUE pair[2] = { pm_static_literal_value(iseq, cast->key, scope_node), pm_static_literal_value(iseq, cast->value, scope_node) };
783 rb_ary_cat(array, pair, 2);
784 }
785
786 VALUE value = rb_hash_new_with_size(elements->size);
787 rb_hash_bulk_insert(RARRAY_LEN(array), RARRAY_CONST_PTR(array), value);
788 RB_GC_GUARD(array);
789
790 value = rb_obj_hide(value);
791 RB_OBJ_SET_FROZEN_SHAREABLE(value);
792 return value;
793 }
794 case PM_IMAGINARY_NODE:
795 return parse_imaginary((const pm_imaginary_node_t *) node);
796 case PM_INTEGER_NODE:
797 return parse_integer((const pm_integer_node_t *) node);
798 case PM_INTERPOLATED_MATCH_LAST_LINE_NODE: {
799 const pm_interpolated_match_last_line_node_t *cast = (const pm_interpolated_match_last_line_node_t *) node;
800 return parse_regexp_concat(iseq, scope_node, (const pm_node_t *) cast, &cast->parts);
801 }
802 case PM_INTERPOLATED_REGULAR_EXPRESSION_NODE: {
803 const pm_interpolated_regular_expression_node_t *cast = (const pm_interpolated_regular_expression_node_t *) node;
804 return parse_regexp_concat(iseq, scope_node, (const pm_node_t *) cast, &cast->parts);
805 }
806 case PM_INTERPOLATED_STRING_NODE: {
807 VALUE string = pm_static_literal_concat(iseq, &((const pm_interpolated_string_node_t *) node)->parts, scope_node, NULL, NULL, false);
808 int line_number = pm_node_line_number(scope_node->parser, node);
809 return pm_static_literal_string(iseq, string, line_number);
810 }
811 case PM_INTERPOLATED_SYMBOL_NODE: {
812 const pm_interpolated_symbol_node_t *cast = (const pm_interpolated_symbol_node_t *) node;
813 VALUE string = pm_static_literal_concat(iseq, &cast->parts, scope_node, NULL, NULL, true);
814
815 return ID2SYM(rb_intern_str(string));
816 }
817 case PM_MATCH_LAST_LINE_NODE: {
818 const pm_match_last_line_node_t *cast = (const pm_match_last_line_node_t *) node;
819 return parse_regexp_literal(iseq, scope_node, (const pm_node_t *) cast, &cast->unescaped);
820 }
821 case PM_NIL_NODE:
822 return Qnil;
823 case PM_RATIONAL_NODE:
824 return parse_rational((const pm_rational_node_t *) node);
825 case PM_REGULAR_EXPRESSION_NODE: {
826 const pm_regular_expression_node_t *cast = (const pm_regular_expression_node_t *) node;
827 return parse_regexp_literal(iseq, scope_node, (const pm_node_t *) cast, &cast->unescaped);
828 }
829 case PM_SOURCE_ENCODING_NODE:
830 return rb_enc_from_encoding(scope_node->encoding);
831 case PM_SOURCE_FILE_NODE: {
832 const pm_source_file_node_t *cast = (const pm_source_file_node_t *) node;
833 return pm_source_file_value(cast, scope_node);
834 }
835 case PM_SOURCE_LINE_NODE:
836 return INT2FIX(pm_node_line_number(scope_node->parser, node));
837 case PM_STRING_NODE: {
838 const pm_string_node_t *cast = (const pm_string_node_t *) node;
839 return parse_static_literal_string(iseq, scope_node, node, &cast->unescaped);
840 }
841 case PM_SYMBOL_NODE:
842 return ID2SYM(parse_string_symbol(scope_node, (const pm_symbol_node_t *) node));
843 case PM_TRUE_NODE:
844 return Qtrue;
845 default:
846 rb_bug("Don't have a literal value for node type %s", pm_node_type_to_str(PM_NODE_TYPE(node)));
847 return Qfalse;
848 }
849}
850
854static rb_code_location_t
855pm_code_location(const pm_scope_node_t *scope_node, const pm_node_t *node)
856{
857 const pm_line_column_t start_location = PM_NODE_START_LINE_COLUMN(scope_node->parser, node);
858 const pm_line_column_t end_location = PM_NODE_END_LINE_COLUMN(scope_node->parser, node);
859
860 return (rb_code_location_t) {
861 .beg_pos = { .lineno = start_location.line, .column = start_location.column },
862 .end_pos = { .lineno = end_location.line, .column = end_location.column }
863 };
864}
865
871#define PM_BRANCH_COVERAGE_P(iseq) (ISEQ_COVERAGE(iseq) && ISEQ_BRANCH_COVERAGE(iseq))
872
873static void
874pm_compile_branch_condition(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const pm_node_t *cond,
875 LABEL *then_label, LABEL *else_label, pm_scope_node_t *scope_node);
876
877static void
878pm_compile_logical(rb_iseq_t *iseq, LINK_ANCHOR *const ret, pm_node_t *cond, LABEL *then_label, LABEL *else_label, pm_scope_node_t *scope_node)
879{
880 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, cond);
881
882 DECL_ANCHOR(seq);
883
884 LABEL *label = NEW_LABEL(location.line);
885 if (!then_label) then_label = label;
886 else if (!else_label) else_label = label;
887
888 pm_compile_branch_condition(iseq, seq, cond, then_label, else_label, scope_node);
889
890 if (LIST_INSN_SIZE_ONE(seq)) {
891 INSN *insn = (INSN *) ELEM_FIRST_INSN(FIRST_ELEMENT(seq));
892 if (insn->insn_id == BIN(jump) && (LABEL *)(insn->operands[0]) == label) return;
893 }
894
895 if (label->refcnt) {
896 PUSH_LABEL(seq, label);
897 }
898
899 PUSH_SEQ(ret, seq);
900 return;
901}
902
903static void
904pm_compile_flip_flop_bound(rb_iseq_t *iseq, const pm_node_t *node, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
905{
906 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
907
908 if (PM_NODE_TYPE_P(node, PM_INTEGER_NODE)) {
909 PM_COMPILE_NOT_POPPED(node);
910
911 VALUE operand = ID2SYM(rb_intern("$."));
912 PUSH_INSN1(ret, location, getglobal, operand);
913
914 PUSH_SEND(ret, location, idEq, INT2FIX(1));
915 if (popped) PUSH_INSN(ret, location, pop);
916 }
917 else {
918 PM_COMPILE(node);
919 }
920}
921
922static void
923pm_compile_flip_flop(const pm_flip_flop_node_t *flip_flop_node, LABEL *else_label, LABEL *then_label, rb_iseq_t *iseq, const int lineno, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
924{
925 const pm_node_location_t location = { .line = lineno, .node_id = -1 };
926 LABEL *lend = NEW_LABEL(location.line);
927
928 int again = !(flip_flop_node->base.flags & PM_RANGE_FLAGS_EXCLUDE_END);
929
930 rb_num_t count = ISEQ_FLIP_CNT_INCREMENT(ISEQ_BODY(iseq)->local_iseq) + VM_SVAR_FLIPFLOP_START;
931 VALUE key = INT2FIX(count);
932
933 PUSH_INSN2(ret, location, getspecial, key, INT2FIX(0));
934 PUSH_INSNL(ret, location, branchif, lend);
935
936 if (flip_flop_node->left) {
937 pm_compile_flip_flop_bound(iseq, flip_flop_node->left, ret, popped, scope_node);
938 }
939 else {
940 PUSH_INSN(ret, location, putnil);
941 }
942
943 PUSH_INSNL(ret, location, branchunless, else_label);
944 PUSH_INSN1(ret, location, putobject, Qtrue);
945 PUSH_INSN1(ret, location, setspecial, key);
946 if (!again) {
947 PUSH_INSNL(ret, location, jump, then_label);
948 }
949
950 PUSH_LABEL(ret, lend);
951 if (flip_flop_node->right) {
952 pm_compile_flip_flop_bound(iseq, flip_flop_node->right, ret, popped, scope_node);
953 }
954 else {
955 PUSH_INSN(ret, location, putnil);
956 }
957
958 PUSH_INSNL(ret, location, branchunless, then_label);
959 PUSH_INSN1(ret, location, putobject, Qfalse);
960 PUSH_INSN1(ret, location, setspecial, key);
961 PUSH_INSNL(ret, location, jump, then_label);
962}
963
964static void pm_compile_defined_expr(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node, bool in_condition);
965
966static void
967pm_compile_branch_condition(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const pm_node_t *cond, LABEL *then_label, LABEL *else_label, pm_scope_node_t *scope_node)
968{
969 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, cond);
970
971again:
972 switch (PM_NODE_TYPE(cond)) {
973 case PM_AND_NODE: {
974 const pm_and_node_t *cast = (const pm_and_node_t *) cond;
975 pm_compile_logical(iseq, ret, cast->left, NULL, else_label, scope_node);
976
977 cond = cast->right;
978 goto again;
979 }
980 case PM_OR_NODE: {
981 const pm_or_node_t *cast = (const pm_or_node_t *) cond;
982 pm_compile_logical(iseq, ret, cast->left, then_label, NULL, scope_node);
983
984 cond = cast->right;
985 goto again;
986 }
987 case PM_FALSE_NODE:
988 case PM_NIL_NODE:
989 PUSH_INSNL(ret, location, jump, else_label);
990 return;
991 case PM_FLOAT_NODE:
992 case PM_IMAGINARY_NODE:
993 case PM_INTEGER_NODE:
994 case PM_LAMBDA_NODE:
995 case PM_RATIONAL_NODE:
996 case PM_REGULAR_EXPRESSION_NODE:
997 case PM_STRING_NODE:
998 case PM_SYMBOL_NODE:
999 case PM_TRUE_NODE:
1000 PUSH_INSNL(ret, location, jump, then_label);
1001 return;
1002 case PM_FLIP_FLOP_NODE:
1003 pm_compile_flip_flop((const pm_flip_flop_node_t *) cond, else_label, then_label, iseq, location.line, ret, false, scope_node);
1004 return;
1005 case PM_DEFINED_NODE: {
1006 const pm_defined_node_t *cast = (const pm_defined_node_t *) cond;
1007 pm_compile_defined_expr(iseq, cast->value, &location, ret, false, scope_node, true);
1008 break;
1009 }
1010 default: {
1011 DECL_ANCHOR(cond_seq);
1012 pm_compile_node(iseq, cond, cond_seq, false, scope_node);
1013
1014 if (LIST_INSN_SIZE_ONE(cond_seq)) {
1015 INSN *insn = (INSN *) ELEM_FIRST_INSN(FIRST_ELEMENT(cond_seq));
1016
1017 if (insn->insn_id == BIN(putobject)) {
1018 if (RTEST(insn->operands[0])) {
1019 PUSH_INSNL(ret, location, jump, then_label);
1020 // maybe unreachable
1021 return;
1022 }
1023 else {
1024 PUSH_INSNL(ret, location, jump, else_label);
1025 return;
1026 }
1027 }
1028 }
1029
1030 PUSH_SEQ(ret, cond_seq);
1031 break;
1032 }
1033 }
1034
1035 PUSH_INSNL(ret, location, branchunless, else_label);
1036 PUSH_INSNL(ret, location, jump, then_label);
1037}
1038
1042static void
1043pm_compile_conditional(rb_iseq_t *iseq, const pm_node_location_t *node_location, pm_node_type_t type, const pm_node_t *node, const pm_statements_node_t *statements, const pm_node_t *subsequent, const pm_node_t *predicate, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
1044{
1045 const pm_node_location_t location = *node_location;
1046 LABEL *then_label = NEW_LABEL(location.line);
1047 LABEL *else_label = NEW_LABEL(location.line);
1048 LABEL *end_label = NULL;
1049
1050 DECL_ANCHOR(cond_seq);
1051 pm_compile_branch_condition(iseq, cond_seq, predicate, then_label, else_label, scope_node);
1052 PUSH_SEQ(ret, cond_seq);
1053
1054 rb_code_location_t conditional_location = { 0 };
1055 VALUE branches = Qfalse;
1056
1057 if (then_label->refcnt && else_label->refcnt && PM_BRANCH_COVERAGE_P(iseq)) {
1058 conditional_location = pm_code_location(scope_node, node);
1059 branches = decl_branch_base(iseq, PTR2NUM(node), &conditional_location, type == PM_IF_NODE ? "if" : "unless");
1060 }
1061
1062 if (then_label->refcnt) {
1063 PUSH_LABEL(ret, then_label);
1064
1065 DECL_ANCHOR(then_seq);
1066
1067 if (statements != NULL) {
1068 pm_compile_node(iseq, (const pm_node_t *) statements, then_seq, popped, scope_node);
1069 }
1070 else if (!popped) {
1071 PUSH_SYNTHETIC_PUTNIL(then_seq, iseq);
1072 }
1073
1074 if (else_label->refcnt) {
1075 // Establish branch coverage for the then block.
1076 if (PM_BRANCH_COVERAGE_P(iseq)) {
1077 rb_code_location_t branch_location;
1078
1079 if (statements != NULL) {
1080 branch_location = pm_code_location(scope_node, (const pm_node_t *) statements);
1081 } else if (type == PM_IF_NODE) {
1082 pm_line_column_t predicate_end = PM_NODE_END_LINE_COLUMN(scope_node->parser, predicate);
1083 branch_location = (rb_code_location_t) {
1084 .beg_pos = { .lineno = predicate_end.line, .column = predicate_end.column },
1085 .end_pos = { .lineno = predicate_end.line, .column = predicate_end.column }
1086 };
1087 } else {
1088 branch_location = conditional_location;
1089 }
1090
1091 add_trace_branch_coverage(iseq, ret, &branch_location, branch_location.beg_pos.column, 0, type == PM_IF_NODE ? "then" : "else", branches);
1092 }
1093
1094 end_label = NEW_LABEL(location.line);
1095 PUSH_INSNL(then_seq, location, jump, end_label);
1096 if (!popped) PUSH_INSN(then_seq, location, pop);
1097 }
1098
1099 PUSH_SEQ(ret, then_seq);
1100 }
1101
1102 if (else_label->refcnt) {
1103 PUSH_LABEL(ret, else_label);
1104
1105 DECL_ANCHOR(else_seq);
1106
1107 if (subsequent != NULL) {
1108 pm_compile_node(iseq, subsequent, else_seq, popped, scope_node);
1109 }
1110 else if (!popped) {
1111 PUSH_SYNTHETIC_PUTNIL(else_seq, iseq);
1112 }
1113
1114 // Establish branch coverage for the else block.
1115 if (then_label->refcnt && PM_BRANCH_COVERAGE_P(iseq)) {
1116 rb_code_location_t branch_location;
1117
1118 if (subsequent == NULL) {
1119 branch_location = conditional_location;
1120 } else if (PM_NODE_TYPE_P(subsequent, PM_ELSE_NODE)) {
1121 const pm_else_node_t *else_node = (const pm_else_node_t *) subsequent;
1122 branch_location = pm_code_location(scope_node, else_node->statements != NULL ? ((const pm_node_t *) else_node->statements) : (const pm_node_t *) else_node);
1123 } else {
1124 branch_location = pm_code_location(scope_node, (const pm_node_t *) subsequent);
1125 }
1126
1127 add_trace_branch_coverage(iseq, ret, &branch_location, branch_location.beg_pos.column, 1, type == PM_IF_NODE ? "else" : "then", branches);
1128 }
1129
1130 PUSH_SEQ(ret, else_seq);
1131 }
1132
1133 if (end_label) {
1134 PUSH_LABEL(ret, end_label);
1135 }
1136
1137 return;
1138}
1139
1143static void
1144pm_compile_loop(rb_iseq_t *iseq, const pm_node_location_t *node_location, pm_node_flags_t flags, enum pm_node_type type, const pm_node_t *node, const pm_statements_node_t *statements, const pm_node_t *predicate, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
1145{
1146 const pm_node_location_t location = *node_location;
1147
1148 LABEL *prev_start_label = ISEQ_COMPILE_DATA(iseq)->start_label;
1149 LABEL *prev_end_label = ISEQ_COMPILE_DATA(iseq)->end_label;
1150 LABEL *prev_redo_label = ISEQ_COMPILE_DATA(iseq)->redo_label;
1151
1152 LABEL *next_label = ISEQ_COMPILE_DATA(iseq)->start_label = NEW_LABEL(location.line); /* next */
1153 LABEL *redo_label = ISEQ_COMPILE_DATA(iseq)->redo_label = NEW_LABEL(location.line); /* redo */
1154 LABEL *break_label = ISEQ_COMPILE_DATA(iseq)->end_label = NEW_LABEL(location.line); /* break */
1155 LABEL *end_label = NEW_LABEL(location.line);
1156 LABEL *adjust_label = NEW_LABEL(location.line);
1157
1158 LABEL *next_catch_label = NEW_LABEL(location.line);
1159 LABEL *tmp_label = NULL;
1160
1161 // We're pushing onto the ensure stack because breaks need to break out of
1162 // this loop and not break into the ensure statements within the same
1163 // lexical scope.
1165 push_ensure_entry(iseq, &enl, NULL, NULL);
1166
1167 // begin; end while true
1168 if (flags & PM_LOOP_FLAGS_BEGIN_MODIFIER) {
1169 tmp_label = NEW_LABEL(location.line);
1170 PUSH_INSNL(ret, location, jump, tmp_label);
1171 }
1172 else {
1173 // while true; end
1174 PUSH_INSNL(ret, location, jump, next_label);
1175 }
1176
1177 PUSH_LABEL(ret, adjust_label);
1178 PUSH_INSN(ret, location, putnil);
1179 PUSH_LABEL(ret, next_catch_label);
1180 PUSH_INSN(ret, location, pop);
1181 PUSH_INSNL(ret, location, jump, next_label);
1182 if (tmp_label) PUSH_LABEL(ret, tmp_label);
1183
1184 PUSH_LABEL(ret, redo_label);
1185
1186 // Establish branch coverage for the loop.
1187 if (PM_BRANCH_COVERAGE_P(iseq)) {
1188 rb_code_location_t loop_location = pm_code_location(scope_node, node);
1189 VALUE branches = decl_branch_base(iseq, PTR2NUM(node), &loop_location, type == PM_WHILE_NODE ? "while" : "until");
1190
1191 rb_code_location_t branch_location = statements != NULL ? pm_code_location(scope_node, (const pm_node_t *) statements) : loop_location;
1192 add_trace_branch_coverage(iseq, ret, &branch_location, branch_location.beg_pos.column, 0, "body", branches);
1193 }
1194
1195 if (statements != NULL) PM_COMPILE_POPPED((const pm_node_t *) statements);
1196 PUSH_LABEL(ret, next_label);
1197
1198 if (type == PM_WHILE_NODE) {
1199 pm_compile_branch_condition(iseq, ret, predicate, redo_label, end_label, scope_node);
1200 }
1201 else if (type == PM_UNTIL_NODE) {
1202 pm_compile_branch_condition(iseq, ret, predicate, end_label, redo_label, scope_node);
1203 }
1204
1205 PUSH_LABEL(ret, end_label);
1206 PUSH_ADJUST_RESTORE(ret, adjust_label);
1207 PUSH_INSN(ret, location, putnil);
1208
1209 PUSH_LABEL(ret, break_label);
1210 if (popped) PUSH_INSN(ret, location, pop);
1211
1212 PUSH_CATCH_ENTRY(CATCH_TYPE_BREAK, redo_label, break_label, NULL, break_label);
1213 PUSH_CATCH_ENTRY(CATCH_TYPE_NEXT, redo_label, break_label, NULL, next_catch_label);
1214 PUSH_CATCH_ENTRY(CATCH_TYPE_REDO, redo_label, break_label, NULL, ISEQ_COMPILE_DATA(iseq)->redo_label);
1215
1216 ISEQ_COMPILE_DATA(iseq)->start_label = prev_start_label;
1217 ISEQ_COMPILE_DATA(iseq)->end_label = prev_end_label;
1218 ISEQ_COMPILE_DATA(iseq)->redo_label = prev_redo_label;
1219 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = ISEQ_COMPILE_DATA(iseq)->ensure_node_stack->prev;
1220
1221 return;
1222}
1223
1224// This recurses through scopes and finds the local index at any scope level
1225// It also takes a pointer to depth, and increments depth appropriately
1226// according to the depth of the local.
1227static pm_local_index_t
1228pm_lookup_local_index(rb_iseq_t *iseq, const pm_scope_node_t *scope_node, pm_constant_id_t constant_id, int start_depth)
1229{
1230 pm_local_index_t lindex = { 0 };
1231 st_data_t local_index;
1232
1233 int level;
1234 for (level = 0; level < start_depth; level++) {
1235 scope_node = scope_node->previous;
1236 }
1237
1238 while (!st_lookup(scope_node->index_lookup_table, constant_id, &local_index)) {
1239 level++;
1240
1241 if (scope_node->previous) {
1242 scope_node = scope_node->previous;
1243 }
1244 else {
1245 // We have recursed up all scope nodes
1246 // and have not found the local yet
1247 rb_bug("Local with constant_id %u does not exist", (unsigned int) constant_id);
1248 }
1249 }
1250
1251 lindex.level = level;
1252 lindex.index = scope_node->local_table_for_iseq_size - (int) local_index;
1253 return lindex;
1254}
1255
1256// This returns the CRuby ID which maps to the pm_constant_id_t
1257//
1258// Constant_ids in prism are indexes of the constants in prism's constant pool.
1259// We add a constants mapping on the scope_node which is a mapping from
1260// these constant_id indexes to the CRuby IDs that they represent.
1261// This helper method allows easy access to those IDs
1262static ID
1263pm_constant_id_lookup(const pm_scope_node_t *scope_node, pm_constant_id_t constant_id)
1264{
1265 if (constant_id < 1 || constant_id > scope_node->parser->constant_pool.size) {
1266 rb_bug("constant_id out of range: %u", (unsigned int)constant_id);
1267 }
1268 return scope_node->constants[constant_id - 1];
1269}
1270
1271static rb_iseq_t *
1272pm_new_child_iseq(rb_iseq_t *iseq, pm_scope_node_t *node, VALUE name, const rb_iseq_t *parent, enum rb_iseq_type type, int line_no)
1273{
1274 debugs("[new_child_iseq]> ---------------------------------------\n");
1275 int isolated_depth = ISEQ_COMPILE_DATA(iseq)->isolated_depth;
1276 int error_state;
1277 rb_iseq_t *ret_iseq = pm_iseq_new_with_opt(node, name,
1278 rb_iseq_path(iseq), rb_iseq_realpath(iseq),
1279 line_no, parent,
1280 isolated_depth ? isolated_depth + 1 : 0,
1281 type, ISEQ_COMPILE_DATA(iseq)->option, &error_state);
1282
1283 if (error_state) {
1284 pm_scope_node_destroy(node);
1285 RUBY_ASSERT(ret_iseq == NULL);
1286 rb_jump_tag(error_state);
1287 }
1288 debugs("[new_child_iseq]< ---------------------------------------\n");
1289 return ret_iseq;
1290}
1291
1292static int
1293pm_compile_class_path(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
1294{
1295 if (PM_NODE_TYPE_P(node, PM_CONSTANT_PATH_NODE)) {
1296 const pm_node_t *parent = ((const pm_constant_path_node_t *) node)->parent;
1297
1298 if (parent) {
1299 /* Bar::Foo */
1300 PM_COMPILE(parent);
1301 return VM_DEFINECLASS_FLAG_SCOPED;
1302 }
1303 else {
1304 /* toplevel class ::Foo */
1305 PUSH_INSN1(ret, *node_location, putobject, rb_cObject);
1306 return VM_DEFINECLASS_FLAG_SCOPED;
1307 }
1308 }
1309 else {
1310 /* class at cbase Foo */
1311 PUSH_INSN1(ret, *node_location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE));
1312 return 0;
1313 }
1314}
1315
1320static void
1321pm_compile_call_and_or_write_node(rb_iseq_t *iseq, bool and_node, const pm_node_t *receiver, const pm_node_t *value, pm_constant_id_t write_name, pm_constant_id_t read_name, bool safe_nav, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
1322{
1323 const pm_node_location_t location = *node_location;
1324 LABEL *lfin = NEW_LABEL(location.line);
1325 LABEL *lcfin = NEW_LABEL(location.line);
1326 LABEL *lskip = NULL;
1327
1328 int flag = PM_NODE_TYPE_P(receiver, PM_SELF_NODE) ? VM_CALL_FCALL : 0;
1329 ID id_read_name = pm_constant_id_lookup(scope_node, read_name);
1330
1331 PM_COMPILE_NOT_POPPED(receiver);
1332 if (safe_nav) {
1333 lskip = NEW_LABEL(location.line);
1334 PUSH_INSN(ret, location, dup);
1335 PUSH_INSNL(ret, location, branchnil, lskip);
1336 }
1337
1338 PUSH_INSN(ret, location, dup);
1339 PUSH_SEND_WITH_FLAG(ret, location, id_read_name, INT2FIX(0), INT2FIX(flag));
1340 if (!popped) PUSH_INSN(ret, location, dup);
1341
1342 if (and_node) {
1343 PUSH_INSNL(ret, location, branchunless, lcfin);
1344 }
1345 else {
1346 PUSH_INSNL(ret, location, branchif, lcfin);
1347 }
1348
1349 if (!popped) PUSH_INSN(ret, location, pop);
1350 PM_COMPILE_NOT_POPPED(value);
1351
1352 if (!popped) {
1353 PUSH_INSN(ret, location, swap);
1354 PUSH_INSN1(ret, location, topn, INT2FIX(1));
1355 }
1356
1357 ID id_write_name = pm_constant_id_lookup(scope_node, write_name);
1358 PUSH_SEND_WITH_FLAG(ret, location, id_write_name, INT2FIX(1), INT2FIX(flag));
1359 PUSH_INSNL(ret, location, jump, lfin);
1360
1361 PUSH_LABEL(ret, lcfin);
1362 if (!popped) PUSH_INSN(ret, location, swap);
1363
1364 PUSH_LABEL(ret, lfin);
1365
1366 if (lskip && popped) PUSH_LABEL(ret, lskip);
1367 PUSH_INSN(ret, location, pop);
1368 if (lskip && !popped) PUSH_LABEL(ret, lskip);
1369}
1370
1371static void pm_compile_shareable_constant_value(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_flags_t shareability, VALUE path, LINK_ANCHOR *const ret, pm_scope_node_t *scope_node, bool top);
1372
1378static void
1379pm_compile_hash_elements(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_list_t *elements, const pm_node_flags_t shareability, VALUE path, bool argument, LINK_ANCHOR *const ret, pm_scope_node_t *scope_node)
1380{
1381 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
1382
1383 // If this element is not popped, then we need to create the hash on the
1384 // stack. Neighboring plain assoc nodes should be grouped together (either
1385 // by newhash or hash merge). Double splat nodes should be merged using the
1386 // merge_kwd method call.
1387 const int max_stack_length = 0x100;
1388 const unsigned int min_tmp_hash_length = 0x800;
1389
1390 int stack_length = 0;
1391 bool first_chunk = true;
1392
1393 // This is an optimization wherein we keep track of whether or not the
1394 // previous element was a static literal. If it was, then we do not attempt
1395 // to check if we have a subhash that can be optimized. If it was not, then
1396 // we do check.
1397 bool static_literal = false;
1398
1399 DECL_ANCHOR(anchor);
1400
1401 // Convert pushed elements to a hash, and merge if needed.
1402#define FLUSH_CHUNK \
1403 if (stack_length) { \
1404 if (first_chunk) { \
1405 PUSH_SEQ(ret, anchor); \
1406 PUSH_INSN1(ret, location, newhash, INT2FIX(stack_length)); \
1407 first_chunk = false; \
1408 } \
1409 else { \
1410 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); \
1411 PUSH_INSN(ret, location, swap); \
1412 PUSH_SEQ(ret, anchor); \
1413 PUSH_SEND(ret, location, id_core_hash_merge_ptr, INT2FIX(stack_length + 1)); \
1414 } \
1415 INIT_ANCHOR(anchor); \
1416 stack_length = 0; \
1417 }
1418
1419 for (size_t index = 0; index < elements->size; index++) {
1420 const pm_node_t *element = elements->nodes[index];
1421
1422 switch (PM_NODE_TYPE(element)) {
1423 case PM_ASSOC_NODE: {
1424 // Pre-allocation check (this branch can be omitted).
1425 if (
1426 (shareability == 0) &&
1427 PM_NODE_FLAG_P(element, PM_NODE_FLAG_STATIC_LITERAL) && (
1428 (!static_literal && ((index + min_tmp_hash_length) < elements->size)) ||
1429 (first_chunk && stack_length == 0)
1430 )
1431 ) {
1432 // Count the elements that are statically-known.
1433 size_t count = 1;
1434 while (index + count < elements->size && PM_NODE_FLAG_P(elements->nodes[index + count], PM_NODE_FLAG_STATIC_LITERAL)) count++;
1435
1436 if ((first_chunk && stack_length == 0) || count >= min_tmp_hash_length) {
1437 // The subsequence of elements in this hash is long enough
1438 // to merit its own hash.
1439 VALUE ary = rb_ary_hidden_new(count);
1440
1441 // Create a hidden hash.
1442 for (size_t tmp_end = index + count; index < tmp_end; index++) {
1443 const pm_assoc_node_t *assoc = (const pm_assoc_node_t *) elements->nodes[index];
1444
1445 VALUE elem[2] = {
1446 pm_static_literal_value(iseq, assoc->key, scope_node),
1447 pm_static_literal_value(iseq, assoc->value, scope_node)
1448 };
1449
1450 rb_ary_cat(ary, elem, 2);
1451 }
1452 index --;
1453
1454 VALUE hash = rb_hash_new_with_size(RARRAY_LEN(ary) / 2);
1455 rb_hash_bulk_insert(RARRAY_LEN(ary), RARRAY_CONST_PTR(ary), hash);
1456 RB_GC_GUARD(ary);
1457 hash = rb_obj_hide(hash);
1458 RB_OBJ_SET_FROZEN_SHAREABLE(hash);
1459
1460 // Emit optimized code.
1461 FLUSH_CHUNK;
1462 if (first_chunk) {
1463 PUSH_INSN1(ret, location, duphash, hash);
1464 first_chunk = false;
1465 }
1466 else {
1467 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
1468 PUSH_INSN(ret, location, swap);
1469 PUSH_INSN1(ret, location, putobject, hash);
1470 PUSH_SEND(ret, location, id_core_hash_merge_kwd, INT2FIX(2));
1471 }
1472
1473 break;
1474 }
1475 else {
1476 static_literal = true;
1477 }
1478 }
1479 else {
1480 static_literal = false;
1481 }
1482
1483 // If this is a plain assoc node, then we can compile it directly
1484 // and then add the total number of values on the stack.
1485 if (shareability == 0) {
1486 pm_compile_node(iseq, element, anchor, false, scope_node);
1487 }
1488 else {
1489 const pm_assoc_node_t *assoc = (const pm_assoc_node_t *) element;
1490 pm_compile_shareable_constant_value(iseq, assoc->key, shareability, path, ret, scope_node, false);
1491 pm_compile_shareable_constant_value(iseq, assoc->value, shareability, path, ret, scope_node, false);
1492 }
1493
1494 if ((stack_length += 2) >= max_stack_length) FLUSH_CHUNK;
1495 break;
1496 }
1497 case PM_ASSOC_SPLAT_NODE: {
1498 FLUSH_CHUNK;
1499
1500 const pm_assoc_splat_node_t *assoc_splat = (const pm_assoc_splat_node_t *) element;
1501 bool empty_hash = assoc_splat->value != NULL && (
1502 (PM_NODE_TYPE_P(assoc_splat->value, PM_HASH_NODE) && ((const pm_hash_node_t *) assoc_splat->value)->elements.size == 0) ||
1503 PM_NODE_TYPE_P(assoc_splat->value, PM_NIL_NODE)
1504 );
1505
1506 bool first_element = first_chunk && stack_length == 0;
1507 bool last_element = index == elements->size - 1;
1508 bool only_element = first_element && last_element;
1509
1510 if (empty_hash) {
1511 if (only_element && argument) {
1512 // **{} appears at the only keyword argument in method call,
1513 // so it won't be modified.
1514 //
1515 // This is only done for method calls and not for literal
1516 // hashes, because literal hashes should always result in a
1517 // new hash.
1518 PUSH_INSN(ret, location, putnil);
1519 }
1520 else if (first_element) {
1521 // **{} appears as the first keyword argument, so it may be
1522 // modified. We need to create a fresh hash object.
1523 PUSH_INSN1(ret, location, newhash, INT2FIX(0));
1524 }
1525 // Any empty keyword splats that are not the first can be
1526 // ignored since merging an empty hash into the existing hash is
1527 // the same as not merging it.
1528 }
1529 else {
1530 if (only_element && argument) {
1531 // ** is only keyword argument in the method call. Use it
1532 // directly. This will be not be flagged as mutable. This is
1533 // only done for method calls and not for literal hashes,
1534 // because literal hashes should always result in a new
1535 // hash.
1536 if (shareability == 0) {
1537 PM_COMPILE_NOT_POPPED(element);
1538 }
1539 else {
1540 pm_compile_shareable_constant_value(iseq, element, shareability, path, ret, scope_node, false);
1541 }
1542 }
1543 else {
1544 // There is more than one keyword argument, or this is not a
1545 // method call. In that case, we need to add an empty hash
1546 // (if first keyword), or merge the hash to the accumulated
1547 // hash (if not the first keyword).
1548 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
1549
1550 if (first_element) {
1551 PUSH_INSN1(ret, location, newhash, INT2FIX(0));
1552 }
1553 else {
1554 PUSH_INSN(ret, location, swap);
1555 }
1556
1557 if (shareability == 0) {
1558 PM_COMPILE_NOT_POPPED(element);
1559 }
1560 else {
1561 pm_compile_shareable_constant_value(iseq, element, shareability, path, ret, scope_node, false);
1562 }
1563
1564 PUSH_SEND(ret, location, id_core_hash_merge_kwd, INT2FIX(2));
1565 }
1566 }
1567
1568 first_chunk = false;
1569 static_literal = false;
1570 break;
1571 }
1572 default:
1573 RUBY_ASSERT("Invalid node type for hash" && false);
1574 break;
1575 }
1576 }
1577
1578 FLUSH_CHUNK;
1579#undef FLUSH_CHUNK
1580}
1581
1582#define SPLATARRAY_FALSE 0
1583#define SPLATARRAY_TRUE 1
1584#define DUP_SINGLE_KW_SPLAT 2
1585
1586// This is details. Users should call pm_setup_args() instead.
1587static int
1588pm_setup_args_core(const pm_arguments_node_t *arguments_node, const pm_node_t *block, int *flags, const bool has_regular_blockarg, struct rb_callinfo_kwarg **kw_arg, int *dup_rest, rb_iseq_t *iseq, LINK_ANCHOR *const ret, pm_scope_node_t *scope_node, const pm_node_location_t *node_location)
1589{
1590 const pm_node_location_t location = *node_location;
1591
1592 int orig_argc = 0;
1593 bool has_splat = false;
1594 bool has_keyword_splat = false;
1595
1596 if (arguments_node == NULL) {
1597 if (*flags & VM_CALL_FCALL) {
1598 *flags |= VM_CALL_VCALL;
1599 }
1600 }
1601 else {
1602 const pm_node_list_t *arguments = &arguments_node->arguments;
1603 has_keyword_splat = PM_NODE_FLAG_P(arguments_node, PM_ARGUMENTS_NODE_FLAGS_CONTAINS_KEYWORD_SPLAT);
1604
1605 // We count the number of elements post the splat node that are not keyword elements to
1606 // eventually pass as an argument to newarray
1607 int post_splat_counter = 0;
1608 const pm_node_t *argument;
1609
1610 PM_NODE_LIST_FOREACH(arguments, index, argument) {
1611 switch (PM_NODE_TYPE(argument)) {
1612 // A keyword hash node contains all keyword arguments as AssocNodes and AssocSplatNodes
1613 case PM_KEYWORD_HASH_NODE: {
1614 const pm_keyword_hash_node_t *keyword_arg = (const pm_keyword_hash_node_t *) argument;
1615 const pm_node_list_t *elements = &keyword_arg->elements;
1616
1617 if (has_keyword_splat || has_splat) {
1618 *flags |= VM_CALL_KW_SPLAT;
1619 has_keyword_splat = true;
1620
1621 if (elements->size > 1 || !(elements->size == 1 && PM_NODE_TYPE_P(elements->nodes[0], PM_ASSOC_SPLAT_NODE))) {
1622 // A new hash will be created for the keyword arguments
1623 // in this case, so mark the method as passing mutable
1624 // keyword splat.
1625 *flags |= VM_CALL_KW_SPLAT_MUT;
1626 pm_compile_hash_elements(iseq, argument, elements, 0, Qundef, true, ret, scope_node);
1627 }
1628 else if (*dup_rest & DUP_SINGLE_KW_SPLAT) {
1629 *flags |= VM_CALL_KW_SPLAT_MUT;
1630 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
1631 PUSH_INSN1(ret, location, newhash, INT2FIX(0));
1632 pm_compile_hash_elements(iseq, argument, elements, 0, Qundef, true, ret, scope_node);
1633 PUSH_SEND(ret, location, id_core_hash_merge_kwd, INT2FIX(2));
1634 }
1635 else {
1636 pm_compile_hash_elements(iseq, argument, elements, 0, Qundef, true, ret, scope_node);
1637 }
1638 }
1639 else {
1640 // We need to first figure out if all elements of the
1641 // KeywordHashNode are AssocNodes with symbol keys.
1642 if (PM_NODE_FLAG_P(keyword_arg, PM_KEYWORD_HASH_NODE_FLAGS_SYMBOL_KEYS)) {
1643 // If they are all symbol keys then we can pass them as
1644 // keyword arguments. The first thing we need to do is
1645 // deduplicate. We'll do this using the combination of a
1646 // Ruby hash and a Ruby array.
1647 VALUE stored_indices = rb_hash_new();
1648 VALUE keyword_indices = rb_ary_new_capa(elements->size);
1649
1650 size_t size = 0;
1651 for (size_t element_index = 0; element_index < elements->size; element_index++) {
1652 const pm_assoc_node_t *assoc = (const pm_assoc_node_t *) elements->nodes[element_index];
1653
1654 // Retrieve the stored index from the hash for this
1655 // keyword.
1656 VALUE keyword = pm_static_literal_value(iseq, assoc->key, scope_node);
1657 VALUE stored_index = rb_hash_aref(stored_indices, keyword);
1658
1659 // If this keyword was already seen in the hash,
1660 // then mark the array at that index as false and
1661 // decrement the keyword size.
1662 if (!NIL_P(stored_index)) {
1663 rb_ary_store(keyword_indices, NUM2LONG(stored_index), Qfalse);
1664 size--;
1665 }
1666
1667 // Store (and possibly overwrite) the index for this
1668 // keyword in the hash, mark the array at that index
1669 // as true, and increment the keyword size.
1670 rb_hash_aset(stored_indices, keyword, ULONG2NUM(element_index));
1671 rb_ary_store(keyword_indices, (long) element_index, Qtrue);
1672 size++;
1673 }
1674
1675 if (size > VM_CALL_KW_LEN_MAX) {
1676 COMPILE_ERROR(iseq, node_location->line, "too many keyword arguments (%d, maximum is %d)",
1677 (int) size, (int) VM_CALL_KW_LEN_MAX);
1678 }
1679
1680 *kw_arg = rb_xmalloc_mul_add(size, sizeof(VALUE), sizeof(struct rb_callinfo_kwarg));
1681 *flags |= VM_CALL_KWARG;
1682
1683 VALUE *keywords = (*kw_arg)->keywords;
1684 (*kw_arg)->references = 0;
1685 (*kw_arg)->keyword_len = (int) size;
1686
1687 size_t keyword_index = 0;
1688 for (size_t element_index = 0; element_index < elements->size; element_index++) {
1689 const pm_assoc_node_t *assoc = (const pm_assoc_node_t *) elements->nodes[element_index];
1690 bool popped = true;
1691
1692 if (rb_ary_entry(keyword_indices, (long) element_index) == Qtrue) {
1693 keywords[keyword_index++] = pm_static_literal_value(iseq, assoc->key, scope_node);
1694 popped = false;
1695 }
1696
1697 PM_COMPILE(assoc->value);
1698 }
1699
1700 RUBY_ASSERT(keyword_index == size);
1701 }
1702 else {
1703 // If they aren't all symbol keys then we need to
1704 // construct a new hash and pass that as an argument.
1705 orig_argc++;
1706 *flags |= VM_CALL_KW_SPLAT;
1707
1708 size_t size = elements->size;
1709 if (size > 1) {
1710 // A new hash will be created for the keyword
1711 // arguments in this case, so mark the method as
1712 // passing mutable keyword splat.
1713 *flags |= VM_CALL_KW_SPLAT_MUT;
1714 }
1715
1716 for (size_t element_index = 0; element_index < size; element_index++) {
1717 const pm_assoc_node_t *assoc = (const pm_assoc_node_t *) elements->nodes[element_index];
1718 PM_COMPILE_NOT_POPPED(assoc->key);
1719 PM_COMPILE_NOT_POPPED(assoc->value);
1720 }
1721
1722 PUSH_INSN1(ret, location, newhash, INT2FIX(size * 2));
1723 }
1724 }
1725 break;
1726 }
1727 case PM_SPLAT_NODE: {
1728 *flags |= VM_CALL_ARGS_SPLAT;
1729 const pm_splat_node_t *splat_node = (const pm_splat_node_t *) argument;
1730
1731 if (splat_node->expression) {
1732 PM_COMPILE_NOT_POPPED(splat_node->expression);
1733 }
1734 else {
1735 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, PM_CONSTANT_MULT, 0);
1736 PUSH_GETLOCAL(ret, location, index.index, index.level);
1737 }
1738
1739 bool first_splat = !has_splat;
1740
1741 if (first_splat) {
1742 // If this is the first splat array seen and it's not the
1743 // last parameter, we want splatarray to dup it.
1744 //
1745 // foo(a, *b, c)
1746 // ^^
1747 if (index + 1 < arguments->size || has_regular_blockarg) {
1748 PUSH_INSN1(ret, location, splatarray, (*dup_rest & SPLATARRAY_TRUE) ? Qtrue : Qfalse);
1749 if (*dup_rest & SPLATARRAY_TRUE) *dup_rest &= ~SPLATARRAY_TRUE;
1750 }
1751 // If this is the first spalt array seen and it's the last
1752 // parameter, we don't want splatarray to dup it.
1753 //
1754 // foo(a, *b)
1755 // ^^
1756 else {
1757 PUSH_INSN1(ret, location, splatarray, Qfalse);
1758 }
1759 }
1760 else {
1761 // If this is not the first splat array seen and it is also
1762 // the last parameter, we don't want splatarray to dup it
1763 // and we need to concat the array.
1764 //
1765 // foo(a, *b, *c)
1766 // ^^
1767 PUSH_INSN(ret, location, concattoarray);
1768 }
1769
1770 has_splat = true;
1771 post_splat_counter = 0;
1772
1773 break;
1774 }
1775 case PM_FORWARDING_ARGUMENTS_NODE: { // not counted in argc return value
1776 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
1777
1778 if (ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->param.flags.forwardable) {
1779 *flags |= VM_CALL_FORWARDING;
1780
1781 pm_local_index_t mult_local = pm_lookup_local_index(iseq, scope_node, PM_CONSTANT_DOT3, 0);
1782 PUSH_GETLOCAL(ret, location, mult_local.index, mult_local.level);
1783
1784 break;
1785 }
1786
1787 if (has_splat) {
1788 // If we already have a splat, we're concatenating to existing array
1789 orig_argc += 1;
1790 } else {
1791 orig_argc += 2;
1792 }
1793
1794 *flags |= VM_CALL_ARGS_SPLAT | VM_CALL_ARGS_BLOCKARG | VM_CALL_KW_SPLAT;
1795
1796 // Forwarding arguments nodes are treated as foo(*, **, &)
1797 // So foo(...) equals foo(*, **, &) and as such the local
1798 // table for this method is known in advance
1799 //
1800 // Push the *
1801 pm_local_index_t mult_local = pm_lookup_local_index(iseq, scope_node, PM_CONSTANT_MULT, 0);
1802 PUSH_GETLOCAL(ret, location, mult_local.index, mult_local.level);
1803
1804 if (has_splat) {
1805 // If we already have a splat, we need to concatenate arrays
1806 PUSH_INSN(ret, location, concattoarray);
1807 } else {
1808 PUSH_INSN1(ret, location, splatarray, Qfalse);
1809 }
1810
1811 // Push the **
1812 pm_local_index_t pow_local = pm_lookup_local_index(iseq, scope_node, PM_CONSTANT_POW, 0);
1813 PUSH_GETLOCAL(ret, location, pow_local.index, pow_local.level);
1814
1815 // Push the &
1816 pm_local_index_t and_local = pm_lookup_local_index(iseq, scope_node, PM_CONSTANT_AND, 0);
1817 PUSH_INSN2(ret, location, getblockparamproxy, INT2FIX(and_local.index + VM_ENV_DATA_SIZE - 1), INT2FIX(and_local.level));
1818
1819 break;
1820 }
1821 default: {
1822 post_splat_counter++;
1823 PM_COMPILE_NOT_POPPED(argument);
1824
1825 // If we have a splat and we've seen a splat, we need to process
1826 // everything after the splat.
1827 if (has_splat) {
1828 // Stack items are turned into an array and concatenated in
1829 // the following cases:
1830 //
1831 // If the next node is a splat:
1832 //
1833 // foo(*a, b, *c)
1834 //
1835 // If the next node is a kwarg or kwarg splat:
1836 //
1837 // foo(*a, b, c: :d)
1838 // foo(*a, b, **c)
1839 //
1840 // If the next node is a forwarding argument:
1841 //
1842 // foo(*a, b, ...)
1843 //
1844 // If the next node is NULL (we have hit the end):
1845 //
1846 // foo(*a, b)
1847 if (index == arguments->size - 1) {
1848 RUBY_ASSERT(post_splat_counter > 0);
1849 PUSH_INSN1(ret, location, pushtoarray, INT2FIX(post_splat_counter));
1850 }
1851 else {
1852 pm_node_t *next_arg = arguments->nodes[index + 1];
1853
1854 switch (PM_NODE_TYPE(next_arg)) {
1855 // A keyword hash node contains all keyword arguments as AssocNodes and AssocSplatNodes
1856 case PM_KEYWORD_HASH_NODE: {
1857 PUSH_INSN1(ret, location, newarray, INT2FIX(post_splat_counter));
1858 PUSH_INSN(ret, location, concatarray);
1859 break;
1860 }
1861 case PM_SPLAT_NODE: {
1862 PUSH_INSN1(ret, location, newarray, INT2FIX(post_splat_counter));
1863 PUSH_INSN(ret, location, concatarray);
1864 break;
1865 }
1866 case PM_FORWARDING_ARGUMENTS_NODE: {
1867 PUSH_INSN1(ret, location, pushtoarray, INT2FIX(post_splat_counter));
1868 break;
1869 }
1870 default:
1871 break;
1872 }
1873 }
1874 }
1875 else {
1876 orig_argc++;
1877 }
1878 }
1879 }
1880 }
1881 }
1882
1883 if (has_splat) orig_argc++;
1884 if (has_keyword_splat) orig_argc++;
1885 return orig_argc;
1886}
1887
1892static inline bool
1893pm_setup_args_dup_rest_p(const pm_node_t *node)
1894{
1895 switch (PM_NODE_TYPE(node)) {
1896 case PM_BACK_REFERENCE_READ_NODE:
1897 case PM_CLASS_VARIABLE_READ_NODE:
1898 case PM_CONSTANT_READ_NODE:
1899 case PM_FALSE_NODE:
1900 case PM_FLOAT_NODE:
1901 case PM_GLOBAL_VARIABLE_READ_NODE:
1902 case PM_IMAGINARY_NODE:
1903 case PM_INSTANCE_VARIABLE_READ_NODE:
1904 case PM_INTEGER_NODE:
1905 case PM_LAMBDA_NODE:
1906 case PM_LOCAL_VARIABLE_READ_NODE:
1907 case PM_NIL_NODE:
1908 case PM_NUMBERED_REFERENCE_READ_NODE:
1909 case PM_RATIONAL_NODE:
1910 case PM_REGULAR_EXPRESSION_NODE:
1911 case PM_SELF_NODE:
1912 case PM_STRING_NODE:
1913 case PM_SYMBOL_NODE:
1914 case PM_TRUE_NODE:
1915 return false;
1916 case PM_CONSTANT_PATH_NODE: {
1917 const pm_constant_path_node_t *cast = (const pm_constant_path_node_t *) node;
1918 if (cast->parent != NULL) {
1919 return pm_setup_args_dup_rest_p(cast->parent);
1920 }
1921 return false;
1922 }
1923 case PM_IMPLICIT_NODE:
1924 return pm_setup_args_dup_rest_p(((const pm_implicit_node_t *) node)->value);
1925 case PM_ARRAY_NODE: {
1926 const pm_array_node_t *cast = (const pm_array_node_t *) node;
1927 for (size_t index = 0; index < cast->elements.size; index++) {
1928 if (pm_setup_args_dup_rest_p(cast->elements.nodes[index])) {
1929 return true;
1930 }
1931 }
1932 return false;
1933 }
1934 default:
1935 return true;
1936 }
1937}
1938
1942static int
1943pm_setup_args(const pm_arguments_node_t *arguments_node, const pm_node_t *block, int *flags, struct rb_callinfo_kwarg **kw_arg, rb_iseq_t *iseq, LINK_ANCHOR *const ret, pm_scope_node_t *scope_node, const pm_node_location_t *node_location)
1944{
1945 int dup_rest = SPLATARRAY_TRUE;
1946
1947 const pm_node_list_t *arguments;
1948 size_t arguments_size;
1949
1950 // Calls like foo(1, *f, **hash) that use splat and kwsplat could be
1951 // eligible for eliding duping the rest array (dup_reset=false).
1952 if (
1953 arguments_node != NULL &&
1954 (arguments = &arguments_node->arguments, arguments_size = arguments->size) >= 2 &&
1955 PM_NODE_FLAG_P(arguments_node, PM_ARGUMENTS_NODE_FLAGS_CONTAINS_SPLAT) &&
1956 !PM_NODE_FLAG_P(arguments_node, PM_ARGUMENTS_NODE_FLAGS_CONTAINS_MULTIPLE_SPLATS) &&
1957 PM_NODE_TYPE_P(arguments->nodes[arguments_size - 1], PM_KEYWORD_HASH_NODE)
1958 ) {
1959 // Start by assuming that dup_rest=false, then check each element of the
1960 // hash to ensure we don't need to flip it back to true (in case one of
1961 // the elements could potentially mutate the array).
1962 dup_rest = SPLATARRAY_FALSE;
1963
1964 const pm_keyword_hash_node_t *keyword_hash = (const pm_keyword_hash_node_t *) arguments->nodes[arguments_size - 1];
1965 const pm_node_list_t *elements = &keyword_hash->elements;
1966
1967 for (size_t index = 0; dup_rest == SPLATARRAY_FALSE && index < elements->size; index++) {
1968 const pm_node_t *element = elements->nodes[index];
1969
1970 switch (PM_NODE_TYPE(element)) {
1971 case PM_ASSOC_NODE: {
1972 const pm_assoc_node_t *assoc = (const pm_assoc_node_t *) element;
1973 if (pm_setup_args_dup_rest_p(assoc->key) || pm_setup_args_dup_rest_p(assoc->value)) dup_rest = SPLATARRAY_TRUE;
1974 break;
1975 }
1976 case PM_ASSOC_SPLAT_NODE: {
1977 const pm_assoc_splat_node_t *assoc = (const pm_assoc_splat_node_t *) element;
1978 if (assoc->value != NULL && pm_setup_args_dup_rest_p(assoc->value)) dup_rest = SPLATARRAY_TRUE;
1979 break;
1980 }
1981 default:
1982 break;
1983 }
1984 }
1985 }
1986
1987 int initial_dup_rest = dup_rest;
1988 int argc;
1989
1990 if (block && PM_NODE_TYPE_P(block, PM_BLOCK_ARGUMENT_NODE)) {
1991 // We compile the `&block_arg` expression first and stitch it later
1992 // since the nature of the expression influences whether splat should
1993 // duplicate the array.
1994 bool regular_block_arg = true;
1995 const pm_node_t *block_expr = ((const pm_block_argument_node_t *)block)->expression;
1996
1997 if (block_expr && pm_setup_args_dup_rest_p(block_expr)) {
1998 dup_rest = SPLATARRAY_TRUE | DUP_SINGLE_KW_SPLAT;
1999 initial_dup_rest = dup_rest;
2000 }
2001
2002 DECL_ANCHOR(block_arg);
2003 pm_compile_node(iseq, block, block_arg, false, scope_node);
2004
2005 *flags |= VM_CALL_ARGS_BLOCKARG;
2006
2007 if (LIST_INSN_SIZE_ONE(block_arg)) {
2008 LINK_ELEMENT *elem = FIRST_ELEMENT(block_arg);
2009 if (IS_INSN(elem)) {
2010 INSN *iobj = (INSN *) elem;
2011 if (iobj->insn_id == BIN(getblockparam)) {
2012 iobj->insn_id = BIN(getblockparamproxy);
2013 }
2014
2015 // Allow splat without duplication for simple one-instruction
2016 // block arguments like `&arg`. It is known that this
2017 // optimization can be too aggressive in some cases. See
2018 // [Bug #16504].
2019 regular_block_arg = false;
2020 }
2021 }
2022
2023 argc = pm_setup_args_core(arguments_node, block, flags, regular_block_arg, kw_arg, &dup_rest, iseq, ret, scope_node, node_location);
2024 PUSH_SEQ(ret, block_arg);
2025 }
2026 else {
2027 argc = pm_setup_args_core(arguments_node, block, flags, false, kw_arg, &dup_rest, iseq, ret, scope_node, node_location);
2028 }
2029
2030 // If the dup_rest flag was consumed while compiling the arguments (which
2031 // effectively means we found the splat node), then it would have changed
2032 // during the call to pm_setup_args_core. In this case, we want to add the
2033 // VM_CALL_ARGS_SPLAT_MUT flag.
2034 if (*flags & VM_CALL_ARGS_SPLAT && dup_rest != initial_dup_rest) {
2035 *flags |= VM_CALL_ARGS_SPLAT_MUT;
2036 }
2037
2038 return argc;
2039}
2040
2051static void
2052pm_compile_index_operator_write_node(rb_iseq_t *iseq, const pm_index_operator_write_node_t *node, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
2053{
2054 const pm_node_location_t location = *node_location;
2055 if (!popped) PUSH_INSN(ret, location, putnil);
2056
2057 PM_COMPILE_NOT_POPPED(node->receiver);
2058
2059 int boff = (node->block == NULL ? 0 : 1);
2060 int flag = PM_NODE_TYPE_P(node->receiver, PM_SELF_NODE) ? VM_CALL_FCALL : 0;
2061 struct rb_callinfo_kwarg *keywords = NULL;
2062 int argc = pm_setup_args(node->arguments, (const pm_node_t *) node->block, &flag, &keywords, iseq, ret, scope_node, node_location);
2063
2064 if ((argc > 0 || boff) && (flag & VM_CALL_KW_SPLAT)) {
2065 if (boff) {
2066 PUSH_INSN(ret, location, splatkw);
2067 }
2068 else {
2069 PUSH_INSN(ret, location, dup);
2070 PUSH_INSN(ret, location, splatkw);
2071 PUSH_INSN(ret, location, pop);
2072 }
2073 }
2074
2075 int dup_argn = argc + 1 + boff;
2076 int keyword_len = 0;
2077
2078 if (keywords) {
2079 keyword_len = keywords->keyword_len;
2080 dup_argn += keyword_len;
2081 }
2082
2083 PUSH_INSN1(ret, location, dupn, INT2FIX(dup_argn));
2084 PUSH_SEND_R(ret, location, idAREF, INT2FIX(argc), NULL, INT2FIX(flag & ~(VM_CALL_ARGS_SPLAT_MUT | VM_CALL_KW_SPLAT_MUT)), keywords);
2085 PM_COMPILE_NOT_POPPED(node->value);
2086
2087 ID id_operator = pm_constant_id_lookup(scope_node, node->binary_operator);
2088 PUSH_SEND(ret, location, id_operator, INT2FIX(1));
2089
2090 if (!popped) {
2091 PUSH_INSN1(ret, location, setn, INT2FIX(dup_argn + 1));
2092 }
2093 if (flag & VM_CALL_ARGS_SPLAT) {
2094 if (flag & VM_CALL_KW_SPLAT) {
2095 PUSH_INSN1(ret, location, topn, INT2FIX(2 + boff));
2096
2097 if (!(flag & VM_CALL_ARGS_SPLAT_MUT)) {
2098 PUSH_INSN1(ret, location, splatarray, Qtrue);
2099 flag |= VM_CALL_ARGS_SPLAT_MUT;
2100 }
2101
2102 PUSH_INSN(ret, location, swap);
2103 PUSH_INSN1(ret, location, pushtoarray, INT2FIX(1));
2104 PUSH_INSN1(ret, location, setn, INT2FIX(2 + boff));
2105 PUSH_INSN(ret, location, pop);
2106 }
2107 else {
2108 if (boff > 0) {
2109 PUSH_INSN1(ret, location, dupn, INT2FIX(3));
2110 PUSH_INSN(ret, location, swap);
2111 PUSH_INSN(ret, location, pop);
2112 }
2113 if (!(flag & VM_CALL_ARGS_SPLAT_MUT)) {
2114 PUSH_INSN(ret, location, swap);
2115 PUSH_INSN1(ret, location, splatarray, Qtrue);
2116 PUSH_INSN(ret, location, swap);
2117 flag |= VM_CALL_ARGS_SPLAT_MUT;
2118 }
2119 PUSH_INSN1(ret, location, pushtoarray, INT2FIX(1));
2120 if (boff > 0) {
2121 PUSH_INSN1(ret, location, setn, INT2FIX(3));
2122 PUSH_INSN(ret, location, pop);
2123 PUSH_INSN(ret, location, pop);
2124 }
2125 }
2126
2127 PUSH_SEND_R(ret, location, idASET, INT2FIX(argc), NULL, INT2FIX(flag), keywords);
2128 }
2129 else if (flag & VM_CALL_KW_SPLAT) {
2130 if (boff > 0) {
2131 PUSH_INSN1(ret, location, topn, INT2FIX(2));
2132 PUSH_INSN(ret, location, swap);
2133 PUSH_INSN1(ret, location, setn, INT2FIX(3));
2134 PUSH_INSN(ret, location, pop);
2135 }
2136 PUSH_INSN(ret, location, swap);
2137 PUSH_SEND_R(ret, location, idASET, INT2FIX(argc + 1), NULL, INT2FIX(flag), keywords);
2138 }
2139 else if (keyword_len) {
2140 PUSH_INSN(ret, location, dup);
2141 PUSH_INSN1(ret, location, opt_reverse, INT2FIX(keyword_len + boff + 2));
2142 PUSH_INSN1(ret, location, opt_reverse, INT2FIX(keyword_len + boff + 1));
2143 PUSH_INSN(ret, location, pop);
2144 PUSH_SEND_R(ret, location, idASET, INT2FIX(argc + 1), NULL, INT2FIX(flag), keywords);
2145 }
2146 else {
2147 if (boff > 0) {
2148 PUSH_INSN(ret, location, swap);
2149 }
2150 PUSH_SEND_R(ret, location, idASET, INT2FIX(argc + 1), NULL, INT2FIX(flag), keywords);
2151 }
2152
2153 PUSH_INSN(ret, location, pop);
2154}
2155
2168static void
2169pm_compile_index_control_flow_write_node(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_t *receiver, const pm_arguments_node_t *arguments, const pm_block_argument_node_t *block, const pm_node_t *value, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
2170{
2171 const pm_node_location_t location = *node_location;
2172 if (!popped) PUSH_INSN(ret, location, putnil);
2173 PM_COMPILE_NOT_POPPED(receiver);
2174
2175 int boff = (block == NULL ? 0 : 1);
2176 int flag = PM_NODE_TYPE_P(receiver, PM_SELF_NODE) ? VM_CALL_FCALL : 0;
2177 struct rb_callinfo_kwarg *keywords = NULL;
2178 int argc = pm_setup_args(arguments, (const pm_node_t *) block, &flag, &keywords, iseq, ret, scope_node, node_location);
2179
2180 if ((argc > 0 || boff) && (flag & VM_CALL_KW_SPLAT)) {
2181 if (boff) {
2182 PUSH_INSN(ret, location, splatkw);
2183 }
2184 else {
2185 PUSH_INSN(ret, location, dup);
2186 PUSH_INSN(ret, location, splatkw);
2187 PUSH_INSN(ret, location, pop);
2188 }
2189 }
2190
2191 int dup_argn = argc + 1 + boff;
2192 int keyword_len = 0;
2193
2194 if (keywords) {
2195 keyword_len = keywords->keyword_len;
2196 dup_argn += keyword_len;
2197 }
2198
2199 PUSH_INSN1(ret, location, dupn, INT2FIX(dup_argn));
2200 PUSH_SEND_R(ret, location, idAREF, INT2FIX(argc), NULL, INT2FIX(flag & ~(VM_CALL_ARGS_SPLAT_MUT | VM_CALL_KW_SPLAT_MUT)), keywords);
2201
2202 LABEL *label = NEW_LABEL(location.line);
2203 LABEL *lfin = NEW_LABEL(location.line);
2204
2205 PUSH_INSN(ret, location, dup);
2206 if (PM_NODE_TYPE_P(node, PM_INDEX_AND_WRITE_NODE)) {
2207 PUSH_INSNL(ret, location, branchunless, label);
2208 }
2209 else {
2210 PUSH_INSNL(ret, location, branchif, label);
2211 }
2212
2213 PUSH_INSN(ret, location, pop);
2214 PM_COMPILE_NOT_POPPED(value);
2215
2216 if (!popped) {
2217 PUSH_INSN1(ret, location, setn, INT2FIX(dup_argn + 1));
2218 }
2219
2220 if (flag & VM_CALL_ARGS_SPLAT) {
2221 if (flag & VM_CALL_KW_SPLAT) {
2222 PUSH_INSN1(ret, location, topn, INT2FIX(2 + boff));
2223 if (!(flag & VM_CALL_ARGS_SPLAT_MUT)) {
2224 PUSH_INSN1(ret, location, splatarray, Qtrue);
2225 flag |= VM_CALL_ARGS_SPLAT_MUT;
2226 }
2227
2228 PUSH_INSN(ret, location, swap);
2229 PUSH_INSN1(ret, location, pushtoarray, INT2FIX(1));
2230 PUSH_INSN1(ret, location, setn, INT2FIX(2 + boff));
2231 PUSH_INSN(ret, location, pop);
2232 }
2233 else {
2234 if (boff > 0) {
2235 PUSH_INSN1(ret, location, dupn, INT2FIX(3));
2236 PUSH_INSN(ret, location, swap);
2237 PUSH_INSN(ret, location, pop);
2238 }
2239 if (!(flag & VM_CALL_ARGS_SPLAT_MUT)) {
2240 PUSH_INSN(ret, location, swap);
2241 PUSH_INSN1(ret, location, splatarray, Qtrue);
2242 PUSH_INSN(ret, location, swap);
2243 flag |= VM_CALL_ARGS_SPLAT_MUT;
2244 }
2245 PUSH_INSN1(ret, location, pushtoarray, INT2FIX(1));
2246 if (boff > 0) {
2247 PUSH_INSN1(ret, location, setn, INT2FIX(3));
2248 PUSH_INSN(ret, location, pop);
2249 PUSH_INSN(ret, location, pop);
2250 }
2251 }
2252
2253 PUSH_SEND_R(ret, location, idASET, INT2FIX(argc), NULL, INT2FIX(flag), keywords);
2254 }
2255 else if (flag & VM_CALL_KW_SPLAT) {
2256 if (boff > 0) {
2257 PUSH_INSN1(ret, location, topn, INT2FIX(2));
2258 PUSH_INSN(ret, location, swap);
2259 PUSH_INSN1(ret, location, setn, INT2FIX(3));
2260 PUSH_INSN(ret, location, pop);
2261 }
2262
2263 PUSH_INSN(ret, location, swap);
2264 PUSH_SEND_R(ret, location, idASET, INT2FIX(argc + 1), NULL, INT2FIX(flag), keywords);
2265 }
2266 else if (keyword_len) {
2267 PUSH_INSN1(ret, location, opt_reverse, INT2FIX(keyword_len + boff + 1));
2268 PUSH_INSN1(ret, location, opt_reverse, INT2FIX(keyword_len + boff + 0));
2269 PUSH_SEND_R(ret, location, idASET, INT2FIX(argc + 1), NULL, INT2FIX(flag), keywords);
2270 }
2271 else {
2272 if (boff > 0) {
2273 PUSH_INSN(ret, location, swap);
2274 }
2275 PUSH_SEND_R(ret, location, idASET, INT2FIX(argc + 1), NULL, INT2FIX(flag), keywords);
2276 }
2277
2278 PUSH_INSN(ret, location, pop);
2279 PUSH_INSNL(ret, location, jump, lfin);
2280 PUSH_LABEL(ret, label);
2281 if (!popped) {
2282 PUSH_INSN1(ret, location, setn, INT2FIX(dup_argn + 1));
2283 }
2284 PUSH_INSN1(ret, location, adjuststack, INT2FIX(dup_argn + 1));
2285 PUSH_LABEL(ret, lfin);
2286}
2287
2288// When we compile a pattern matching expression, we use the stack as a scratch
2289// space to store lots of different values (consider it like we have a pattern
2290// matching function and we need space for a bunch of different local
2291// variables). The "base index" refers to the index on the stack where we
2292// started compiling the pattern matching expression. These offsets from that
2293// base index indicate the location of the various locals we need.
2294#define PM_PATTERN_BASE_INDEX_OFFSET_DECONSTRUCTED_CACHE 0
2295#define PM_PATTERN_BASE_INDEX_OFFSET_ERROR_STRING 1
2296#define PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_P 2
2297#define PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_MATCHEE 3
2298#define PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_KEY 4
2299
2300// A forward declaration because this is the recursive function that handles
2301// compiling a pattern. It can be reentered by nesting patterns, as in the case
2302// of arrays or hashes.
2303static int pm_compile_pattern(rb_iseq_t *iseq, pm_scope_node_t *scope_node, const pm_node_t *node, LINK_ANCHOR *const ret, LABEL *matched_label, LABEL *unmatched_label, bool in_single_pattern, bool use_deconstructed_cache, unsigned int base_index);
2304
2309static int
2310pm_compile_pattern_generic_error(rb_iseq_t *iseq, pm_scope_node_t *scope_node, const pm_node_t *node, LINK_ANCHOR *const ret, VALUE message, unsigned int base_index)
2311{
2312 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
2313 LABEL *match_succeeded_label = NEW_LABEL(location.line);
2314
2315 PUSH_INSN(ret, location, dup);
2316 PUSH_INSNL(ret, location, branchif, match_succeeded_label);
2317
2318 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
2319 PUSH_INSN1(ret, location, putobject, message);
2320 PUSH_INSN1(ret, location, topn, INT2FIX(3));
2321 PUSH_SEND(ret, location, id_core_sprintf, INT2FIX(2));
2322 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_ERROR_STRING + 1));
2323
2324 PUSH_INSN1(ret, location, putobject, Qfalse);
2325 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_P + 2));
2326
2327 PUSH_INSN(ret, location, pop);
2328 PUSH_INSN(ret, location, pop);
2329 PUSH_LABEL(ret, match_succeeded_label);
2330
2331 return COMPILE_OK;
2332}
2333
2339static int
2340pm_compile_pattern_length_error(rb_iseq_t *iseq, pm_scope_node_t *scope_node, const pm_node_t *node, LINK_ANCHOR *const ret, VALUE message, VALUE length, unsigned int base_index)
2341{
2342 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
2343 LABEL *match_succeeded_label = NEW_LABEL(location.line);
2344
2345 PUSH_INSN(ret, location, dup);
2346 PUSH_INSNL(ret, location, branchif, match_succeeded_label);
2347
2348 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
2349 PUSH_INSN1(ret, location, putobject, message);
2350 PUSH_INSN1(ret, location, topn, INT2FIX(3));
2351 PUSH_INSN(ret, location, dup);
2352 PUSH_SEND(ret, location, idLength, INT2FIX(0));
2353 PUSH_INSN1(ret, location, putobject, length);
2354 PUSH_SEND(ret, location, id_core_sprintf, INT2FIX(4));
2355 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_ERROR_STRING + 1));
2356
2357 PUSH_INSN1(ret, location, putobject, Qfalse);
2358 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_P + 2));
2359
2360 PUSH_INSN(ret, location, pop);
2361 PUSH_INSN(ret, location, pop);
2362 PUSH_LABEL(ret, match_succeeded_label);
2363
2364 return COMPILE_OK;
2365}
2366
2372static int
2373pm_compile_pattern_eqq_error(rb_iseq_t *iseq, pm_scope_node_t *scope_node, const pm_node_t *node, LINK_ANCHOR *const ret, unsigned int base_index)
2374{
2375 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
2376 LABEL *match_succeeded_label = NEW_LABEL(location.line);
2377
2378 PUSH_INSN(ret, location, dup);
2379 PUSH_INSNL(ret, location, branchif, match_succeeded_label);
2380 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
2381
2382 VALUE operand = rb_fstring_lit("%p === %p does not return true");
2383 PUSH_INSN1(ret, location, putobject, operand);
2384
2385 PUSH_INSN1(ret, location, topn, INT2FIX(3));
2386 PUSH_INSN1(ret, location, topn, INT2FIX(5));
2387 PUSH_SEND(ret, location, id_core_sprintf, INT2FIX(3));
2388 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_ERROR_STRING + 1));
2389 PUSH_INSN1(ret, location, putobject, Qfalse);
2390 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_P + 2));
2391 PUSH_INSN(ret, location, pop);
2392 PUSH_INSN(ret, location, pop);
2393
2394 PUSH_LABEL(ret, match_succeeded_label);
2395 PUSH_INSN1(ret, location, setn, INT2FIX(2));
2396 PUSH_INSN(ret, location, pop);
2397 PUSH_INSN(ret, location, pop);
2398
2399 return COMPILE_OK;
2400}
2401
2408static int
2409pm_compile_pattern_match(rb_iseq_t *iseq, pm_scope_node_t *scope_node, const pm_node_t *node, LINK_ANCHOR *const ret, LABEL *unmatched_label, bool in_single_pattern, bool use_deconstructed_cache, unsigned int base_index)
2410{
2411 LABEL *matched_label = NEW_LABEL(pm_node_line_number(scope_node->parser, node));
2412 CHECK(pm_compile_pattern(iseq, scope_node, node, ret, matched_label, unmatched_label, in_single_pattern, use_deconstructed_cache, base_index));
2413 PUSH_LABEL(ret, matched_label);
2414 return COMPILE_OK;
2415}
2416
2422static int
2423pm_compile_pattern_deconstruct(rb_iseq_t *iseq, pm_scope_node_t *scope_node, const pm_node_t *node, LINK_ANCHOR *const ret, LABEL *deconstruct_label, LABEL *match_failed_label, LABEL *deconstructed_label, LABEL *type_error_label, bool in_single_pattern, bool use_deconstructed_cache, unsigned int base_index)
2424{
2425 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
2426
2427 if (use_deconstructed_cache) {
2428 PUSH_INSN1(ret, location, topn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_DECONSTRUCTED_CACHE));
2429 PUSH_INSNL(ret, location, branchnil, deconstruct_label);
2430
2431 PUSH_INSN1(ret, location, topn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_DECONSTRUCTED_CACHE));
2432 PUSH_INSNL(ret, location, branchunless, match_failed_label);
2433
2434 PUSH_INSN(ret, location, pop);
2435 PUSH_INSN1(ret, location, topn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_DECONSTRUCTED_CACHE - 1));
2436 PUSH_INSNL(ret, location, jump, deconstructed_label);
2437 }
2438 else {
2439 PUSH_INSNL(ret, location, jump, deconstruct_label);
2440 }
2441
2442 PUSH_LABEL(ret, deconstruct_label);
2443 PUSH_INSN(ret, location, dup);
2444
2445 VALUE operand = ID2SYM(rb_intern("deconstruct"));
2446 PUSH_INSN1(ret, location, putobject, operand);
2447 PUSH_SEND(ret, location, idRespond_to, INT2FIX(1));
2448
2449 if (use_deconstructed_cache) {
2450 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_DECONSTRUCTED_CACHE + 1));
2451 }
2452
2453 if (in_single_pattern) {
2454 CHECK(pm_compile_pattern_generic_error(iseq, scope_node, node, ret, rb_fstring_lit("%p does not respond to #deconstruct"), base_index + 1));
2455 }
2456
2457 PUSH_INSNL(ret, location, branchunless, match_failed_label);
2458 PUSH_SEND(ret, location, rb_intern("deconstruct"), INT2FIX(0));
2459
2460 if (use_deconstructed_cache) {
2461 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_DECONSTRUCTED_CACHE));
2462 }
2463
2464 PUSH_INSN(ret, location, dup);
2465 PUSH_INSN1(ret, location, checktype, INT2FIX(T_ARRAY));
2466 PUSH_INSNL(ret, location, branchunless, type_error_label);
2467 PUSH_LABEL(ret, deconstructed_label);
2468
2469 return COMPILE_OK;
2470}
2471
2476static int
2477pm_compile_pattern_constant(rb_iseq_t *iseq, pm_scope_node_t *scope_node, const pm_node_t *node, LINK_ANCHOR *const ret, LABEL *match_failed_label, bool in_single_pattern, unsigned int base_index)
2478{
2479 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
2480
2481 PUSH_INSN(ret, location, dup);
2482 PM_COMPILE_NOT_POPPED(node);
2483
2484 if (in_single_pattern) {
2485 PUSH_INSN1(ret, location, dupn, INT2FIX(2));
2486 }
2487 PUSH_INSN1(ret, location, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE));
2488 if (in_single_pattern) {
2489 CHECK(pm_compile_pattern_eqq_error(iseq, scope_node, node, ret, base_index + 3));
2490 }
2491 PUSH_INSNL(ret, location, branchunless, match_failed_label);
2492 return COMPILE_OK;
2493}
2494
2499static void
2500pm_compile_pattern_error_handler(rb_iseq_t *iseq, const pm_scope_node_t *scope_node, const pm_node_t *node, LINK_ANCHOR *const ret, LABEL *done_label, bool popped)
2501{
2502 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
2503 LABEL *key_error_label = NEW_LABEL(location.line);
2504 LABEL *cleanup_label = NEW_LABEL(location.line);
2505
2506 struct rb_callinfo_kwarg *kw_arg = rb_xmalloc_mul_add(2, sizeof(VALUE), sizeof(struct rb_callinfo_kwarg));
2507 kw_arg->references = 0;
2508 kw_arg->keyword_len = 2;
2509 kw_arg->keywords[0] = ID2SYM(rb_intern("matchee"));
2510 kw_arg->keywords[1] = ID2SYM(rb_intern("key"));
2511
2512 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
2513 PUSH_INSN1(ret, location, topn, INT2FIX(PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_P + 2));
2514 PUSH_INSNL(ret, location, branchif, key_error_label);
2515
2516 PUSH_INSN1(ret, location, putobject, rb_eNoMatchingPatternError);
2517 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
2518
2519 {
2520 VALUE operand = rb_fstring_lit("%p: %s");
2521 PUSH_INSN1(ret, location, putobject, operand);
2522 }
2523
2524 PUSH_INSN1(ret, location, topn, INT2FIX(4));
2525 PUSH_INSN1(ret, location, topn, INT2FIX(PM_PATTERN_BASE_INDEX_OFFSET_ERROR_STRING + 6));
2526 PUSH_SEND(ret, location, id_core_sprintf, INT2FIX(3));
2527 PUSH_SEND(ret, location, id_core_raise, INT2FIX(2));
2528 PUSH_INSNL(ret, location, jump, cleanup_label);
2529
2530 PUSH_LABEL(ret, key_error_label);
2531 PUSH_INSN1(ret, location, putobject, rb_eNoMatchingPatternKeyError);
2532 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
2533
2534 {
2535 VALUE operand = rb_fstring_lit("%p: %s");
2536 PUSH_INSN1(ret, location, putobject, operand);
2537 }
2538
2539 PUSH_INSN1(ret, location, topn, INT2FIX(4));
2540 PUSH_INSN1(ret, location, topn, INT2FIX(PM_PATTERN_BASE_INDEX_OFFSET_ERROR_STRING + 6));
2541 PUSH_SEND(ret, location, id_core_sprintf, INT2FIX(3));
2542 PUSH_INSN1(ret, location, topn, INT2FIX(PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_MATCHEE + 4));
2543 PUSH_INSN1(ret, location, topn, INT2FIX(PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_KEY + 5));
2544 PUSH_SEND_R(ret, location, rb_intern("new"), INT2FIX(1), NULL, INT2FIX(VM_CALL_KWARG), kw_arg);
2545 PUSH_SEND(ret, location, id_core_raise, INT2FIX(1));
2546 PUSH_LABEL(ret, cleanup_label);
2547
2548 PUSH_INSN1(ret, location, adjuststack, INT2FIX(7));
2549 if (!popped) PUSH_INSN(ret, location, putnil);
2550 PUSH_INSNL(ret, location, jump, done_label);
2551 PUSH_INSN1(ret, location, dupn, INT2FIX(5));
2552 if (popped) PUSH_INSN(ret, location, putnil);
2553}
2554
2558static int
2559pm_compile_pattern(rb_iseq_t *iseq, pm_scope_node_t *scope_node, const pm_node_t *node, LINK_ANCHOR *const ret, LABEL *matched_label, LABEL *unmatched_label, bool in_single_pattern, bool use_deconstructed_cache, unsigned int base_index)
2560{
2561 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
2562
2563 switch (PM_NODE_TYPE(node)) {
2564 case PM_ARRAY_PATTERN_NODE: {
2565 // Array patterns in pattern matching are triggered by using commas in
2566 // a pattern or wrapping it in braces. They are represented by a
2567 // ArrayPatternNode. This looks like:
2568 //
2569 // foo => [1, 2, 3]
2570 //
2571 // It can optionally have a splat in the middle of it, which can
2572 // optionally have a name attached.
2573 const pm_array_pattern_node_t *cast = (const pm_array_pattern_node_t *) node;
2574
2575 const size_t requireds_size = cast->requireds.size;
2576 const size_t posts_size = cast->posts.size;
2577 const size_t minimum_size = requireds_size + posts_size;
2578
2579 bool rest_named = false;
2580 bool use_rest_size = false;
2581
2582 if (cast->rest != NULL) {
2583 rest_named = (PM_NODE_TYPE_P(cast->rest, PM_SPLAT_NODE) && ((const pm_splat_node_t *) cast->rest)->expression != NULL);
2584 use_rest_size = (rest_named || (!rest_named && posts_size > 0));
2585 }
2586
2587 LABEL *match_failed_label = NEW_LABEL(location.line);
2588 LABEL *type_error_label = NEW_LABEL(location.line);
2589 LABEL *deconstruct_label = NEW_LABEL(location.line);
2590 LABEL *deconstructed_label = NEW_LABEL(location.line);
2591
2592 if (use_rest_size) {
2593 PUSH_INSN1(ret, location, putobject, INT2FIX(0));
2594 PUSH_INSN(ret, location, swap);
2595 base_index++;
2596 }
2597
2598 if (cast->constant != NULL) {
2599 CHECK(pm_compile_pattern_constant(iseq, scope_node, cast->constant, ret, match_failed_label, in_single_pattern, base_index));
2600 }
2601
2602 CHECK(pm_compile_pattern_deconstruct(iseq, scope_node, node, ret, deconstruct_label, match_failed_label, deconstructed_label, type_error_label, in_single_pattern, use_deconstructed_cache, base_index));
2603
2604 PUSH_INSN(ret, location, dup);
2605 PUSH_SEND(ret, location, idLength, INT2FIX(0));
2606 PUSH_INSN1(ret, location, putobject, INT2FIX(minimum_size));
2607 PUSH_SEND(ret, location, cast->rest == NULL ? idEq : idGE, INT2FIX(1));
2608 if (in_single_pattern) {
2609 VALUE message = cast->rest == NULL ? rb_fstring_lit("%p length mismatch (given %p, expected %p)") : rb_fstring_lit("%p length mismatch (given %p, expected %p+)");
2610 CHECK(pm_compile_pattern_length_error(iseq, scope_node, node, ret, message, INT2FIX(minimum_size), base_index + 1));
2611 }
2612 PUSH_INSNL(ret, location, branchunless, match_failed_label);
2613
2614 for (size_t index = 0; index < requireds_size; index++) {
2615 const pm_node_t *required = cast->requireds.nodes[index];
2616 PUSH_INSN(ret, location, dup);
2617 PUSH_INSN1(ret, location, putobject, INT2FIX(index));
2618 PUSH_SEND(ret, location, idAREF, INT2FIX(1));
2619 CHECK(pm_compile_pattern_match(iseq, scope_node, required, ret, match_failed_label, in_single_pattern, false, base_index + 1));
2620 }
2621
2622 if (cast->rest != NULL) {
2623 if (rest_named) {
2624 PUSH_INSN(ret, location, dup);
2625 PUSH_INSN1(ret, location, putobject, INT2FIX(requireds_size));
2626 PUSH_INSN1(ret, location, topn, INT2FIX(1));
2627 PUSH_SEND(ret, location, idLength, INT2FIX(0));
2628 PUSH_INSN1(ret, location, putobject, INT2FIX(minimum_size));
2629 PUSH_SEND(ret, location, idMINUS, INT2FIX(1));
2630 PUSH_INSN1(ret, location, setn, INT2FIX(4));
2631 PUSH_SEND(ret, location, idAREF, INT2FIX(2));
2632 CHECK(pm_compile_pattern_match(iseq, scope_node, ((const pm_splat_node_t *) cast->rest)->expression, ret, match_failed_label, in_single_pattern, false, base_index + 1));
2633 }
2634 else if (posts_size > 0) {
2635 PUSH_INSN(ret, location, dup);
2636 PUSH_SEND(ret, location, idLength, INT2FIX(0));
2637 PUSH_INSN1(ret, location, putobject, INT2FIX(minimum_size));
2638 PUSH_SEND(ret, location, idMINUS, INT2FIX(1));
2639 PUSH_INSN1(ret, location, setn, INT2FIX(2));
2640 PUSH_INSN(ret, location, pop);
2641 }
2642 }
2643
2644 for (size_t index = 0; index < posts_size; index++) {
2645 const pm_node_t *post = cast->posts.nodes[index];
2646 PUSH_INSN(ret, location, dup);
2647
2648 PUSH_INSN1(ret, location, putobject, INT2FIX(requireds_size + index));
2649 PUSH_INSN1(ret, location, topn, INT2FIX(3));
2650 PUSH_SEND(ret, location, idPLUS, INT2FIX(1));
2651 PUSH_SEND(ret, location, idAREF, INT2FIX(1));
2652 CHECK(pm_compile_pattern_match(iseq, scope_node, post, ret, match_failed_label, in_single_pattern, false, base_index + 1));
2653 }
2654
2655 PUSH_INSN(ret, location, pop);
2656 if (use_rest_size) {
2657 PUSH_INSN(ret, location, pop);
2658 }
2659
2660 PUSH_INSNL(ret, location, jump, matched_label);
2661 PUSH_INSN(ret, location, putnil);
2662 if (use_rest_size) {
2663 PUSH_INSN(ret, location, putnil);
2664 }
2665
2666 PUSH_LABEL(ret, type_error_label);
2667 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
2668 PUSH_INSN1(ret, location, putobject, rb_eTypeError);
2669
2670 {
2671 VALUE operand = rb_fstring_lit("deconstruct must return Array");
2672 PUSH_INSN1(ret, location, putobject, operand);
2673 }
2674
2675 PUSH_SEND(ret, location, id_core_raise, INT2FIX(2));
2676 PUSH_INSN(ret, location, pop);
2677
2678 PUSH_LABEL(ret, match_failed_label);
2679 PUSH_INSN(ret, location, pop);
2680 if (use_rest_size) {
2681 PUSH_INSN(ret, location, pop);
2682 }
2683
2684 PUSH_INSNL(ret, location, jump, unmatched_label);
2685 break;
2686 }
2687 case PM_FIND_PATTERN_NODE: {
2688 // Find patterns in pattern matching are triggered by using commas in
2689 // a pattern or wrapping it in braces and using a splat on both the left
2690 // and right side of the pattern. This looks like:
2691 //
2692 // foo => [*, 1, 2, 3, *]
2693 //
2694 // There can be any number of requireds in the middle. The splats on
2695 // both sides can optionally have names attached.
2696 const pm_find_pattern_node_t *cast = (const pm_find_pattern_node_t *) node;
2697 const size_t size = cast->requireds.size;
2698
2699 LABEL *match_failed_label = NEW_LABEL(location.line);
2700 LABEL *type_error_label = NEW_LABEL(location.line);
2701 LABEL *deconstruct_label = NEW_LABEL(location.line);
2702 LABEL *deconstructed_label = NEW_LABEL(location.line);
2703
2704 if (cast->constant) {
2705 CHECK(pm_compile_pattern_constant(iseq, scope_node, cast->constant, ret, match_failed_label, in_single_pattern, base_index));
2706 }
2707
2708 CHECK(pm_compile_pattern_deconstruct(iseq, scope_node, node, ret, deconstruct_label, match_failed_label, deconstructed_label, type_error_label, in_single_pattern, use_deconstructed_cache, base_index));
2709
2710 PUSH_INSN(ret, location, dup);
2711 PUSH_SEND(ret, location, idLength, INT2FIX(0));
2712 PUSH_INSN1(ret, location, putobject, INT2FIX(size));
2713 PUSH_SEND(ret, location, idGE, INT2FIX(1));
2714 if (in_single_pattern) {
2715 CHECK(pm_compile_pattern_length_error(iseq, scope_node, node, ret, rb_fstring_lit("%p length mismatch (given %p, expected %p+)"), INT2FIX(size), base_index + 1));
2716 }
2717 PUSH_INSNL(ret, location, branchunless, match_failed_label);
2718
2719 {
2720 LABEL *while_begin_label = NEW_LABEL(location.line);
2721 LABEL *next_loop_label = NEW_LABEL(location.line);
2722 LABEL *find_succeeded_label = NEW_LABEL(location.line);
2723 LABEL *find_failed_label = NEW_LABEL(location.line);
2724
2725 PUSH_INSN(ret, location, dup);
2726 PUSH_SEND(ret, location, idLength, INT2FIX(0));
2727
2728 PUSH_INSN(ret, location, dup);
2729 PUSH_INSN1(ret, location, putobject, INT2FIX(size));
2730 PUSH_SEND(ret, location, idMINUS, INT2FIX(1));
2731 PUSH_INSN1(ret, location, putobject, INT2FIX(0));
2732 PUSH_LABEL(ret, while_begin_label);
2733
2734 PUSH_INSN(ret, location, dup);
2735 PUSH_INSN1(ret, location, topn, INT2FIX(2));
2736 PUSH_SEND(ret, location, idLE, INT2FIX(1));
2737 PUSH_INSNL(ret, location, branchunless, find_failed_label);
2738
2739 for (size_t index = 0; index < size; index++) {
2740 PUSH_INSN1(ret, location, topn, INT2FIX(3));
2741 PUSH_INSN1(ret, location, topn, INT2FIX(1));
2742
2743 if (index != 0) {
2744 PUSH_INSN1(ret, location, putobject, INT2FIX(index));
2745 PUSH_SEND(ret, location, idPLUS, INT2FIX(1));
2746 }
2747
2748 PUSH_SEND(ret, location, idAREF, INT2FIX(1));
2749 CHECK(pm_compile_pattern_match(iseq, scope_node, cast->requireds.nodes[index], ret, next_loop_label, in_single_pattern, false, base_index + 4));
2750 }
2751
2752 const pm_splat_node_t *left = cast->left;
2753
2754 if (left->expression != NULL) {
2755 PUSH_INSN1(ret, location, topn, INT2FIX(3));
2756 PUSH_INSN1(ret, location, putobject, INT2FIX(0));
2757 PUSH_INSN1(ret, location, topn, INT2FIX(2));
2758 PUSH_SEND(ret, location, idAREF, INT2FIX(2));
2759 CHECK(pm_compile_pattern_match(iseq, scope_node, left->expression, ret, find_failed_label, in_single_pattern, false, base_index + 4));
2760 }
2761
2762 RUBY_ASSERT(PM_NODE_TYPE_P(cast->right, PM_SPLAT_NODE));
2763 const pm_splat_node_t *right = (const pm_splat_node_t *) cast->right;
2764
2765 if (right->expression != NULL) {
2766 PUSH_INSN1(ret, location, topn, INT2FIX(3));
2767 PUSH_INSN1(ret, location, topn, INT2FIX(1));
2768 PUSH_INSN1(ret, location, putobject, INT2FIX(size));
2769 PUSH_SEND(ret, location, idPLUS, INT2FIX(1));
2770 PUSH_INSN1(ret, location, topn, INT2FIX(3));
2771 PUSH_SEND(ret, location, idAREF, INT2FIX(2));
2772 pm_compile_pattern_match(iseq, scope_node, right->expression, ret, find_failed_label, in_single_pattern, false, base_index + 4);
2773 }
2774
2775 PUSH_INSNL(ret, location, jump, find_succeeded_label);
2776
2777 PUSH_LABEL(ret, next_loop_label);
2778 PUSH_INSN1(ret, location, putobject, INT2FIX(1));
2779 PUSH_SEND(ret, location, idPLUS, INT2FIX(1));
2780 PUSH_INSNL(ret, location, jump, while_begin_label);
2781
2782 PUSH_LABEL(ret, find_failed_label);
2783 PUSH_INSN1(ret, location, adjuststack, INT2FIX(3));
2784 if (in_single_pattern) {
2785 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
2786
2787 {
2788 VALUE operand = rb_fstring_lit("%p does not match to find pattern");
2789 PUSH_INSN1(ret, location, putobject, operand);
2790 }
2791
2792 PUSH_INSN1(ret, location, topn, INT2FIX(2));
2793 PUSH_SEND(ret, location, id_core_sprintf, INT2FIX(2));
2794 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_ERROR_STRING + 1));
2795
2796 PUSH_INSN1(ret, location, putobject, Qfalse);
2797 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_P + 2));
2798
2799 PUSH_INSN(ret, location, pop);
2800 PUSH_INSN(ret, location, pop);
2801 }
2802 PUSH_INSNL(ret, location, jump, match_failed_label);
2803 PUSH_INSN1(ret, location, dupn, INT2FIX(3));
2804
2805 PUSH_LABEL(ret, find_succeeded_label);
2806 PUSH_INSN1(ret, location, adjuststack, INT2FIX(3));
2807 }
2808
2809 PUSH_INSN(ret, location, pop);
2810 PUSH_INSNL(ret, location, jump, matched_label);
2811 PUSH_INSN(ret, location, putnil);
2812
2813 PUSH_LABEL(ret, type_error_label);
2814 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
2815 PUSH_INSN1(ret, location, putobject, rb_eTypeError);
2816
2817 {
2818 VALUE operand = rb_fstring_lit("deconstruct must return Array");
2819 PUSH_INSN1(ret, location, putobject, operand);
2820 }
2821
2822 PUSH_SEND(ret, location, id_core_raise, INT2FIX(2));
2823 PUSH_INSN(ret, location, pop);
2824
2825 PUSH_LABEL(ret, match_failed_label);
2826 PUSH_INSN(ret, location, pop);
2827 PUSH_INSNL(ret, location, jump, unmatched_label);
2828
2829 break;
2830 }
2831 case PM_HASH_PATTERN_NODE: {
2832 // Hash patterns in pattern matching are triggered by using labels and
2833 // values in a pattern or by using the ** operator. They are represented
2834 // by the HashPatternNode. This looks like:
2835 //
2836 // foo => { a: 1, b: 2, **bar }
2837 //
2838 // It can optionally have an assoc splat in the middle of it, which can
2839 // optionally have a name.
2840 const pm_hash_pattern_node_t *cast = (const pm_hash_pattern_node_t *) node;
2841
2842 // We don't consider it a "rest" parameter if it's a ** that is unnamed.
2843 bool has_rest = cast->rest != NULL && !(PM_NODE_TYPE_P(cast->rest, PM_ASSOC_SPLAT_NODE) && ((const pm_assoc_splat_node_t *) cast->rest)->value == NULL);
2844 bool has_keys = cast->elements.size > 0 || cast->rest != NULL;
2845
2846 LABEL *match_failed_label = NEW_LABEL(location.line);
2847 LABEL *type_error_label = NEW_LABEL(location.line);
2848 VALUE keys = Qnil;
2849
2850 if (has_keys && !has_rest) {
2851 keys = rb_ary_new_capa(cast->elements.size);
2852
2853 for (size_t index = 0; index < cast->elements.size; index++) {
2854 const pm_node_t *element = cast->elements.nodes[index];
2855 RUBY_ASSERT(PM_NODE_TYPE_P(element, PM_ASSOC_NODE));
2856
2857 const pm_node_t *key = ((const pm_assoc_node_t *) element)->key;
2858 RUBY_ASSERT(PM_NODE_TYPE_P(key, PM_SYMBOL_NODE));
2859
2860 VALUE symbol = ID2SYM(parse_string_symbol(scope_node, (const pm_symbol_node_t *) key));
2861 rb_ary_push(keys, symbol);
2862 }
2863 }
2864
2865 if (cast->constant) {
2866 CHECK(pm_compile_pattern_constant(iseq, scope_node, cast->constant, ret, match_failed_label, in_single_pattern, base_index));
2867 }
2868
2869 PUSH_INSN(ret, location, dup);
2870
2871 {
2872 VALUE operand = ID2SYM(rb_intern("deconstruct_keys"));
2873 PUSH_INSN1(ret, location, putobject, operand);
2874 }
2875
2876 PUSH_SEND(ret, location, idRespond_to, INT2FIX(1));
2877 if (in_single_pattern) {
2878 CHECK(pm_compile_pattern_generic_error(iseq, scope_node, node, ret, rb_fstring_lit("%p does not respond to #deconstruct_keys"), base_index + 1));
2879 }
2880 PUSH_INSNL(ret, location, branchunless, match_failed_label);
2881
2882 if (NIL_P(keys)) {
2883 PUSH_INSN(ret, location, putnil);
2884 }
2885 else {
2886 rb_obj_hide(keys);
2887 RB_OBJ_SET_FROZEN_SHAREABLE(keys);
2888 PUSH_INSN1(ret, location, duparray, keys);
2889 RB_OBJ_WRITTEN(iseq, Qundef, keys);
2890 }
2891 PUSH_SEND(ret, location, rb_intern("deconstruct_keys"), INT2FIX(1));
2892
2893 PUSH_INSN(ret, location, dup);
2894 PUSH_INSN1(ret, location, checktype, INT2FIX(T_HASH));
2895 PUSH_INSNL(ret, location, branchunless, type_error_label);
2896
2897 if (has_rest) {
2898 PUSH_SEND(ret, location, rb_intern("dup"), INT2FIX(0));
2899 }
2900
2901 if (has_keys) {
2902 DECL_ANCHOR(match_values);
2903
2904 for (size_t index = 0; index < cast->elements.size; index++) {
2905 const pm_node_t *element = cast->elements.nodes[index];
2906 RUBY_ASSERT(PM_NODE_TYPE_P(element, PM_ASSOC_NODE));
2907
2908 const pm_assoc_node_t *assoc = (const pm_assoc_node_t *) element;
2909 const pm_node_t *key = assoc->key;
2910 RUBY_ASSERT(PM_NODE_TYPE_P(key, PM_SYMBOL_NODE));
2911
2912 VALUE symbol = ID2SYM(parse_string_symbol(scope_node, (const pm_symbol_node_t *) key));
2913 PUSH_INSN(ret, location, dup);
2914 PUSH_INSN1(ret, location, putobject, symbol);
2915 PUSH_SEND(ret, location, rb_intern("key?"), INT2FIX(1));
2916
2917 if (in_single_pattern) {
2918 LABEL *match_succeeded_label = NEW_LABEL(location.line);
2919
2920 PUSH_INSN(ret, location, dup);
2921 PUSH_INSNL(ret, location, branchif, match_succeeded_label);
2922
2923 {
2924 VALUE operand = rb_str_freeze(rb_sprintf("key not found: %+"PRIsVALUE, symbol));
2925 RB_OBJ_SET_SHAREABLE(operand);
2926 PUSH_INSN1(ret, location, putobject, operand);
2927 }
2928
2929 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_ERROR_STRING + 2));
2930 PUSH_INSN1(ret, location, putobject, Qtrue);
2931 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_P + 3));
2932 PUSH_INSN1(ret, location, topn, INT2FIX(3));
2933 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_MATCHEE + 4));
2934 PUSH_INSN1(ret, location, putobject, symbol);
2935 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_KEY + 5));
2936
2937 PUSH_INSN1(ret, location, adjuststack, INT2FIX(4));
2938 PUSH_LABEL(ret, match_succeeded_label);
2939 }
2940
2941 PUSH_INSNL(ret, location, branchunless, match_failed_label);
2942 PUSH_INSN(match_values, location, dup);
2943 PUSH_INSN1(match_values, location, putobject, symbol);
2944 PUSH_SEND(match_values, location, has_rest ? rb_intern("delete") : idAREF, INT2FIX(1));
2945
2946 const pm_node_t *value = assoc->value;
2947 if (PM_NODE_TYPE_P(value, PM_IMPLICIT_NODE)) {
2948 value = ((const pm_implicit_node_t *) value)->value;
2949 }
2950
2951 CHECK(pm_compile_pattern_match(iseq, scope_node, value, match_values, match_failed_label, in_single_pattern, false, base_index + 1));
2952 }
2953
2954 PUSH_SEQ(ret, match_values);
2955 }
2956 else {
2957 PUSH_INSN(ret, location, dup);
2958 PUSH_SEND(ret, location, idEmptyP, INT2FIX(0));
2959 if (in_single_pattern) {
2960 CHECK(pm_compile_pattern_generic_error(iseq, scope_node, node, ret, rb_fstring_lit("%p is not empty"), base_index + 1));
2961 }
2962 PUSH_INSNL(ret, location, branchunless, match_failed_label);
2963 }
2964
2965 if (has_rest) {
2966 switch (PM_NODE_TYPE(cast->rest)) {
2967 case PM_NO_KEYWORDS_PARAMETER_NODE: {
2968 PUSH_INSN(ret, location, dup);
2969 PUSH_SEND(ret, location, idEmptyP, INT2FIX(0));
2970 if (in_single_pattern) {
2971 pm_compile_pattern_generic_error(iseq, scope_node, node, ret, rb_fstring_lit("rest of %p is not empty"), base_index + 1);
2972 }
2973 PUSH_INSNL(ret, location, branchunless, match_failed_label);
2974 break;
2975 }
2976 case PM_ASSOC_SPLAT_NODE: {
2977 const pm_assoc_splat_node_t *splat = (const pm_assoc_splat_node_t *) cast->rest;
2978 PUSH_INSN(ret, location, dup);
2979 pm_compile_pattern_match(iseq, scope_node, splat->value, ret, match_failed_label, in_single_pattern, false, base_index + 1);
2980 break;
2981 }
2982 default:
2983 rb_bug("unreachable");
2984 break;
2985 }
2986 }
2987
2988 PUSH_INSN(ret, location, pop);
2989 PUSH_INSNL(ret, location, jump, matched_label);
2990 PUSH_INSN(ret, location, putnil);
2991
2992 PUSH_LABEL(ret, type_error_label);
2993 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
2994 PUSH_INSN1(ret, location, putobject, rb_eTypeError);
2995
2996 {
2997 VALUE operand = rb_fstring_lit("deconstruct_keys must return Hash");
2998 PUSH_INSN1(ret, location, putobject, operand);
2999 }
3000
3001 PUSH_SEND(ret, location, id_core_raise, INT2FIX(2));
3002 PUSH_INSN(ret, location, pop);
3003
3004 PUSH_LABEL(ret, match_failed_label);
3005 PUSH_INSN(ret, location, pop);
3006 PUSH_INSNL(ret, location, jump, unmatched_label);
3007 break;
3008 }
3009 case PM_CAPTURE_PATTERN_NODE: {
3010 // Capture patterns allow you to pattern match against an element in a
3011 // pattern and also capture the value into a local variable. This looks
3012 // like:
3013 //
3014 // [1] => [Integer => foo]
3015 //
3016 // In this case the `Integer => foo` will be represented by a
3017 // CapturePatternNode, which has both a value (the pattern to match
3018 // against) and a target (the place to write the variable into).
3019 const pm_capture_pattern_node_t *cast = (const pm_capture_pattern_node_t *) node;
3020
3021 LABEL *match_failed_label = NEW_LABEL(location.line);
3022
3023 PUSH_INSN(ret, location, dup);
3024 CHECK(pm_compile_pattern_match(iseq, scope_node, cast->value, ret, match_failed_label, in_single_pattern, use_deconstructed_cache, base_index + 1));
3025 CHECK(pm_compile_pattern(iseq, scope_node, (const pm_node_t *) cast->target, ret, matched_label, match_failed_label, in_single_pattern, false, base_index));
3026 PUSH_INSN(ret, location, putnil);
3027
3028 PUSH_LABEL(ret, match_failed_label);
3029 PUSH_INSN(ret, location, pop);
3030 PUSH_INSNL(ret, location, jump, unmatched_label);
3031
3032 break;
3033 }
3034 case PM_LOCAL_VARIABLE_TARGET_NODE: {
3035 // Local variables can be targeted by placing identifiers in the place
3036 // of a pattern. For example, foo in bar. This results in the value
3037 // being matched being written to that local variable.
3038 const pm_local_variable_target_node_t *cast = (const pm_local_variable_target_node_t *) node;
3039 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, cast->name, cast->depth);
3040
3041 PUSH_SETLOCAL(ret, location, index.index, index.level);
3042 PUSH_INSNL(ret, location, jump, matched_label);
3043 break;
3044 }
3045 case PM_ALTERNATION_PATTERN_NODE: {
3046 // Alternation patterns allow you to specify multiple patterns in a
3047 // single expression using the | operator.
3048 const pm_alternation_pattern_node_t *cast = (const pm_alternation_pattern_node_t *) node;
3049
3050 LABEL *matched_left_label = NEW_LABEL(location.line);
3051 LABEL *unmatched_left_label = NEW_LABEL(location.line);
3052
3053 // First, we're going to attempt to match against the left pattern. If
3054 // that pattern matches, then we'll skip matching the right pattern.
3055 PUSH_INSN(ret, location, dup);
3056 CHECK(pm_compile_pattern(iseq, scope_node, cast->left, ret, matched_left_label, unmatched_left_label, in_single_pattern, use_deconstructed_cache, base_index + 1));
3057
3058 // If we get here, then we matched on the left pattern. In this case we
3059 // should pop out the duplicate value that we preemptively added to
3060 // match against the right pattern and then jump to the match label.
3061 PUSH_LABEL(ret, matched_left_label);
3062 PUSH_INSN(ret, location, pop);
3063 PUSH_INSNL(ret, location, jump, matched_label);
3064 PUSH_INSN(ret, location, putnil);
3065
3066 // If we get here, then we didn't match on the left pattern. In this
3067 // case we attempt to match against the right pattern.
3068 PUSH_LABEL(ret, unmatched_left_label);
3069 CHECK(pm_compile_pattern(iseq, scope_node, cast->right, ret, matched_label, unmatched_label, in_single_pattern, use_deconstructed_cache, base_index));
3070 break;
3071 }
3072 case PM_PARENTHESES_NODE:
3073 // Parentheses are allowed to wrap expressions in pattern matching and
3074 // they do nothing since they can only wrap individual expressions and
3075 // not groups. In this case we'll recurse back into this same function
3076 // with the body of the parentheses.
3077 return pm_compile_pattern(iseq, scope_node, ((const pm_parentheses_node_t *) node)->body, ret, matched_label, unmatched_label, in_single_pattern, use_deconstructed_cache, base_index);
3078 case PM_PINNED_EXPRESSION_NODE:
3079 // Pinned expressions are a way to match against the value of an
3080 // expression that should be evaluated at runtime. This looks like:
3081 // foo in ^(bar). To compile these, we compile the expression as if it
3082 // were a literal value by falling through to the literal case.
3083 node = ((const pm_pinned_expression_node_t *) node)->expression;
3084 /* fallthrough */
3085 case PM_ARRAY_NODE:
3086 case PM_CLASS_VARIABLE_READ_NODE:
3087 case PM_CONSTANT_PATH_NODE:
3088 case PM_CONSTANT_READ_NODE:
3089 case PM_FALSE_NODE:
3090 case PM_FLOAT_NODE:
3091 case PM_GLOBAL_VARIABLE_READ_NODE:
3092 case PM_IMAGINARY_NODE:
3093 case PM_INSTANCE_VARIABLE_READ_NODE:
3094 case PM_IT_LOCAL_VARIABLE_READ_NODE:
3095 case PM_INTEGER_NODE:
3096 case PM_INTERPOLATED_REGULAR_EXPRESSION_NODE:
3097 case PM_INTERPOLATED_STRING_NODE:
3098 case PM_INTERPOLATED_SYMBOL_NODE:
3099 case PM_INTERPOLATED_X_STRING_NODE:
3100 case PM_LAMBDA_NODE:
3101 case PM_LOCAL_VARIABLE_READ_NODE:
3102 case PM_NIL_NODE:
3103 case PM_SOURCE_ENCODING_NODE:
3104 case PM_SOURCE_FILE_NODE:
3105 case PM_SOURCE_LINE_NODE:
3106 case PM_RANGE_NODE:
3107 case PM_RATIONAL_NODE:
3108 case PM_REGULAR_EXPRESSION_NODE:
3109 case PM_SELF_NODE:
3110 case PM_STRING_NODE:
3111 case PM_SYMBOL_NODE:
3112 case PM_TRUE_NODE:
3113 case PM_X_STRING_NODE: {
3114 // These nodes are all simple patterns, which means we'll use the
3115 // checkmatch instruction to match against them, which is effectively a
3116 // VM-level === operator.
3117 PM_COMPILE_NOT_POPPED(node);
3118 if (in_single_pattern) {
3119 PUSH_INSN1(ret, location, dupn, INT2FIX(2));
3120 }
3121
3122 PUSH_INSN1(ret, location, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE));
3123
3124 if (in_single_pattern) {
3125 pm_compile_pattern_eqq_error(iseq, scope_node, node, ret, base_index + 2);
3126 }
3127
3128 PUSH_INSNL(ret, location, branchif, matched_label);
3129 PUSH_INSNL(ret, location, jump, unmatched_label);
3130 break;
3131 }
3132 case PM_PINNED_VARIABLE_NODE: {
3133 // Pinned variables are a way to match against the value of a variable
3134 // without it looking like you're trying to write to the variable. This
3135 // looks like: foo in ^@bar. To compile these, we compile the variable
3136 // that they hold.
3137 const pm_pinned_variable_node_t *cast = (const pm_pinned_variable_node_t *) node;
3138 CHECK(pm_compile_pattern(iseq, scope_node, cast->variable, ret, matched_label, unmatched_label, in_single_pattern, true, base_index));
3139 break;
3140 }
3141 case PM_IF_NODE:
3142 case PM_UNLESS_NODE: {
3143 // If and unless nodes can show up here as guards on `in` clauses. This
3144 // looks like:
3145 //
3146 // case foo
3147 // in bar if baz?
3148 // qux
3149 // end
3150 //
3151 // Because we know they're in the modifier form and they can't have any
3152 // variation on this pattern, we compile them differently (more simply)
3153 // here than we would in the normal compilation path.
3154 const pm_node_t *predicate;
3155 const pm_node_t *statement;
3156
3157 if (PM_NODE_TYPE_P(node, PM_IF_NODE)) {
3158 const pm_if_node_t *cast = (const pm_if_node_t *) node;
3159 predicate = cast->predicate;
3160
3161 RUBY_ASSERT(cast->statements != NULL && cast->statements->body.size == 1);
3162 statement = cast->statements->body.nodes[0];
3163 }
3164 else {
3165 const pm_unless_node_t *cast = (const pm_unless_node_t *) node;
3166 predicate = cast->predicate;
3167
3168 RUBY_ASSERT(cast->statements != NULL && cast->statements->body.size == 1);
3169 statement = cast->statements->body.nodes[0];
3170 }
3171
3172 CHECK(pm_compile_pattern_match(iseq, scope_node, statement, ret, unmatched_label, in_single_pattern, use_deconstructed_cache, base_index));
3173 PM_COMPILE_NOT_POPPED(predicate);
3174
3175 if (in_single_pattern) {
3176 LABEL *match_succeeded_label = NEW_LABEL(location.line);
3177
3178 PUSH_INSN(ret, location, dup);
3179 if (PM_NODE_TYPE_P(node, PM_IF_NODE)) {
3180 PUSH_INSNL(ret, location, branchif, match_succeeded_label);
3181 }
3182 else {
3183 PUSH_INSNL(ret, location, branchunless, match_succeeded_label);
3184 }
3185
3186 {
3187 VALUE operand = rb_fstring_lit("guard clause does not return true");
3188 PUSH_INSN1(ret, location, putobject, operand);
3189 }
3190
3191 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_ERROR_STRING + 1));
3192 PUSH_INSN1(ret, location, putobject, Qfalse);
3193 PUSH_INSN1(ret, location, setn, INT2FIX(base_index + PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_P + 2));
3194
3195 PUSH_INSN(ret, location, pop);
3196 PUSH_INSN(ret, location, pop);
3197
3198 PUSH_LABEL(ret, match_succeeded_label);
3199 }
3200
3201 if (PM_NODE_TYPE_P(node, PM_IF_NODE)) {
3202 PUSH_INSNL(ret, location, branchunless, unmatched_label);
3203 }
3204 else {
3205 PUSH_INSNL(ret, location, branchif, unmatched_label);
3206 }
3207
3208 PUSH_INSNL(ret, location, jump, matched_label);
3209 break;
3210 }
3211 default:
3212 // If we get here, then we have a node type that should not be in this
3213 // position. This would be a bug in the parser, because a different node
3214 // type should never have been created in this position in the tree.
3215 rb_bug("Unexpected node type in pattern matching expression: %s", pm_node_type_to_str(PM_NODE_TYPE(node)));
3216 break;
3217 }
3218
3219 return COMPILE_OK;
3220}
3221
3222#undef PM_PATTERN_BASE_INDEX_OFFSET_DECONSTRUCTED_CACHE
3223#undef PM_PATTERN_BASE_INDEX_OFFSET_ERROR_STRING
3224#undef PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_P
3225#undef PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_MATCHEE
3226#undef PM_PATTERN_BASE_INDEX_OFFSET_KEY_ERROR_KEY
3227
3228// Generate a scope node from the given node.
3229void
3230pm_scope_node_init(const pm_node_t *node, pm_scope_node_t *scope, pm_scope_node_t *previous)
3231{
3232 // This is very important, otherwise the scope node could be seen as having
3233 // certain flags set that _should not_ be set.
3234 memset(scope, 0, sizeof(pm_scope_node_t));
3235
3236 scope->base.type = PM_SCOPE_NODE;
3237 scope->base.location.start = node->location.start;
3238 scope->base.location.end = node->location.end;
3239
3240 scope->previous = previous;
3241 scope->ast_node = (pm_node_t *) node;
3242
3243 if (previous) {
3244 scope->parser = previous->parser;
3245 scope->encoding = previous->encoding;
3246 scope->filepath_encoding = previous->filepath_encoding;
3247 scope->constants = previous->constants;
3248 scope->coverage_enabled = previous->coverage_enabled;
3249 scope->script_lines = previous->script_lines;
3250 }
3251
3252 switch (PM_NODE_TYPE(node)) {
3253 case PM_BLOCK_NODE: {
3254 const pm_block_node_t *cast = (const pm_block_node_t *) node;
3255 scope->body = cast->body;
3256 scope->locals = cast->locals;
3257 scope->parameters = cast->parameters;
3258 break;
3259 }
3260 case PM_CLASS_NODE: {
3261 const pm_class_node_t *cast = (const pm_class_node_t *) node;
3262 scope->body = cast->body;
3263 scope->locals = cast->locals;
3264 break;
3265 }
3266 case PM_DEF_NODE: {
3267 const pm_def_node_t *cast = (const pm_def_node_t *) node;
3268 scope->parameters = (pm_node_t *) cast->parameters;
3269 scope->body = cast->body;
3270 scope->locals = cast->locals;
3271 break;
3272 }
3273 case PM_ENSURE_NODE: {
3274 const pm_ensure_node_t *cast = (const pm_ensure_node_t *) node;
3275 scope->body = (pm_node_t *) node;
3276
3277 if (cast->statements != NULL) {
3278 scope->base.location.start = cast->statements->base.location.start;
3279 scope->base.location.end = cast->statements->base.location.end;
3280 }
3281
3282 break;
3283 }
3284 case PM_FOR_NODE: {
3285 const pm_for_node_t *cast = (const pm_for_node_t *) node;
3286 scope->body = (pm_node_t *) cast->statements;
3287 break;
3288 }
3289 case PM_INTERPOLATED_REGULAR_EXPRESSION_NODE: {
3290 RUBY_ASSERT(node->flags & PM_REGULAR_EXPRESSION_FLAGS_ONCE);
3291 scope->body = (pm_node_t *) node;
3292 break;
3293 }
3294 case PM_LAMBDA_NODE: {
3295 const pm_lambda_node_t *cast = (const pm_lambda_node_t *) node;
3296 scope->parameters = cast->parameters;
3297 scope->body = cast->body;
3298 scope->locals = cast->locals;
3299
3300 if (cast->parameters != NULL) {
3301 scope->base.location.start = cast->parameters->location.start;
3302 }
3303 else {
3304 scope->base.location.start = cast->operator_loc.end;
3305 }
3306 break;
3307 }
3308 case PM_MODULE_NODE: {
3309 const pm_module_node_t *cast = (const pm_module_node_t *) node;
3310 scope->body = cast->body;
3311 scope->locals = cast->locals;
3312 break;
3313 }
3314 case PM_POST_EXECUTION_NODE: {
3315 const pm_post_execution_node_t *cast = (const pm_post_execution_node_t *) node;
3316 scope->body = (pm_node_t *) cast->statements;
3317 break;
3318 }
3319 case PM_PROGRAM_NODE: {
3320 const pm_program_node_t *cast = (const pm_program_node_t *) node;
3321 scope->body = (pm_node_t *) cast->statements;
3322 scope->locals = cast->locals;
3323 break;
3324 }
3325 case PM_RESCUE_NODE: {
3326 const pm_rescue_node_t *cast = (const pm_rescue_node_t *) node;
3327 scope->body = (pm_node_t *) cast->statements;
3328 break;
3329 }
3330 case PM_RESCUE_MODIFIER_NODE: {
3331 const pm_rescue_modifier_node_t *cast = (const pm_rescue_modifier_node_t *) node;
3332 scope->body = (pm_node_t *) cast->rescue_expression;
3333 break;
3334 }
3335 case PM_SINGLETON_CLASS_NODE: {
3336 const pm_singleton_class_node_t *cast = (const pm_singleton_class_node_t *) node;
3337 scope->body = cast->body;
3338 scope->locals = cast->locals;
3339 break;
3340 }
3341 case PM_STATEMENTS_NODE: {
3342 const pm_statements_node_t *cast = (const pm_statements_node_t *) node;
3343 scope->body = (pm_node_t *) cast;
3344 break;
3345 }
3346 default:
3347 rb_bug("unreachable");
3348 break;
3349 }
3350}
3351
3352void
3353pm_scope_node_destroy(pm_scope_node_t *scope_node)
3354{
3355 if (scope_node->index_lookup_table) {
3356 st_free_table(scope_node->index_lookup_table);
3357 }
3358}
3359
3371static void
3372pm_compile_retry_end_label(rb_iseq_t *iseq, LINK_ANCHOR *const ret, LABEL *retry_end_l)
3373{
3374 INSN *iobj;
3375 LINK_ELEMENT *last_elem = LAST_ELEMENT(ret);
3376 iobj = IS_INSN(last_elem) ? (INSN*) last_elem : (INSN*) get_prev_insn((INSN*) last_elem);
3377 while (!IS_INSN_ID(iobj, send) && !IS_INSN_ID(iobj, invokesuper) && !IS_INSN_ID(iobj, sendforward) && !IS_INSN_ID(iobj, invokesuperforward)) {
3378 iobj = (INSN*) get_prev_insn(iobj);
3379 }
3380 ELEM_INSERT_NEXT(&iobj->link, (LINK_ELEMENT*) retry_end_l);
3381
3382 // LINK_ANCHOR has a pointer to the last element, but
3383 // ELEM_INSERT_NEXT does not update it even if we add an insn to the
3384 // last of LINK_ANCHOR. So this updates it manually.
3385 if (&iobj->link == LAST_ELEMENT(ret)) {
3386 ret->last = (LINK_ELEMENT*) retry_end_l;
3387 }
3388}
3389
3390static const char *
3391pm_iseq_builtin_function_name(const pm_scope_node_t *scope_node, const pm_node_t *receiver, ID method_id)
3392{
3393 const char *name = rb_id2name(method_id);
3394 static const char prefix[] = "__builtin_";
3395 const size_t prefix_len = sizeof(prefix) - 1;
3396
3397 if (receiver == NULL) {
3398 if (UNLIKELY(strncmp(prefix, name, prefix_len) == 0)) {
3399 // __builtin_foo
3400 return &name[prefix_len];
3401 }
3402 }
3403 else if (PM_NODE_TYPE_P(receiver, PM_CALL_NODE)) {
3404 if (PM_NODE_FLAG_P(receiver, PM_CALL_NODE_FLAGS_VARIABLE_CALL)) {
3405 const pm_call_node_t *cast = (const pm_call_node_t *) receiver;
3406 if (pm_constant_id_lookup(scope_node, cast->name) == rb_intern_const("__builtin")) {
3407 // __builtin.foo
3408 return name;
3409 }
3410 }
3411 }
3412 else if (PM_NODE_TYPE_P(receiver, PM_CONSTANT_READ_NODE)) {
3413 const pm_constant_read_node_t *cast = (const pm_constant_read_node_t *) receiver;
3414 if (pm_constant_id_lookup(scope_node, cast->name) == rb_intern_const("Primitive")) {
3415 // Primitive.foo
3416 return name;
3417 }
3418 }
3419
3420 return NULL;
3421}
3422
3423// Compile Primitive.attr! :leaf, ...
3424static int
3425pm_compile_builtin_attr(rb_iseq_t *iseq, const pm_scope_node_t *scope_node, const pm_arguments_node_t *arguments, const pm_node_location_t *node_location)
3426{
3427 if (arguments == NULL) {
3428 COMPILE_ERROR(iseq, node_location->line, "attr!: no argument");
3429 return COMPILE_NG;
3430 }
3431
3432 const pm_node_t *argument;
3433 PM_NODE_LIST_FOREACH(&arguments->arguments, index, argument) {
3434 if (!PM_NODE_TYPE_P(argument, PM_SYMBOL_NODE)) {
3435 COMPILE_ERROR(iseq, node_location->line, "non symbol argument to attr!: %s", pm_node_type_to_str(PM_NODE_TYPE(argument)));
3436 return COMPILE_NG;
3437 }
3438
3439 VALUE symbol = pm_static_literal_value(iseq, argument, scope_node);
3440 VALUE string = rb_sym2str(symbol);
3441
3442 if (strcmp(RSTRING_PTR(string), "leaf") == 0) {
3443 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_LEAF;
3444 }
3445 else if (strcmp(RSTRING_PTR(string), "inline_block") == 0) {
3446 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_INLINE_BLOCK;
3447 }
3448 else if (strcmp(RSTRING_PTR(string), "use_block") == 0) {
3449 iseq_set_use_block(iseq);
3450 }
3451 else if (strcmp(RSTRING_PTR(string), "c_trace") == 0) {
3452 // Let the iseq act like a C method in backtraces
3453 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_C_TRACE;
3454 }
3455 else {
3456 COMPILE_ERROR(iseq, node_location->line, "unknown argument to attr!: %s", RSTRING_PTR(string));
3457 return COMPILE_NG;
3458 }
3459 }
3460
3461 return COMPILE_OK;
3462}
3463
3464static int
3465pm_compile_builtin_arg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const pm_scope_node_t *scope_node, const pm_arguments_node_t *arguments, const pm_node_location_t *node_location, int popped)
3466{
3467 if (arguments == NULL) {
3468 COMPILE_ERROR(iseq, node_location->line, "arg!: no argument");
3469 return COMPILE_NG;
3470 }
3471
3472 if (arguments->arguments.size != 1) {
3473 COMPILE_ERROR(iseq, node_location->line, "arg!: too many argument");
3474 return COMPILE_NG;
3475 }
3476
3477 const pm_node_t *argument = arguments->arguments.nodes[0];
3478 if (!PM_NODE_TYPE_P(argument, PM_SYMBOL_NODE)) {
3479 COMPILE_ERROR(iseq, node_location->line, "non symbol argument to arg!: %s", pm_node_type_to_str(PM_NODE_TYPE(argument)));
3480 return COMPILE_NG;
3481 }
3482
3483 if (!popped) {
3484 ID name = parse_string_symbol(scope_node, ((const pm_symbol_node_t *) argument));
3485 int index = ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->local_table_size - get_local_var_idx(iseq, name);
3486
3487 debugs("id: %s idx: %d\n", rb_id2name(name), index);
3488 PUSH_GETLOCAL(ret, *node_location, index, get_lvar_level(iseq));
3489 }
3490
3491 return COMPILE_OK;
3492}
3493
3494static int
3495pm_compile_builtin_mandatory_only_method(rb_iseq_t *iseq, pm_scope_node_t *scope_node, const pm_call_node_t *call_node, const pm_node_location_t *node_location)
3496{
3497 const pm_node_t *ast_node = scope_node->ast_node;
3498 if (!PM_NODE_TYPE_P(ast_node, PM_DEF_NODE)) {
3499 rb_bug("mandatory_only?: not in method definition");
3500 return COMPILE_NG;
3501 }
3502
3503 const pm_def_node_t *def_node = (const pm_def_node_t *) ast_node;
3504 const pm_parameters_node_t *parameters_node = def_node->parameters;
3505 if (parameters_node == NULL) {
3506 rb_bug("mandatory_only?: in method definition with no parameters");
3507 return COMPILE_NG;
3508 }
3509
3510 const pm_node_t *body_node = def_node->body;
3511 if (body_node == NULL || !PM_NODE_TYPE_P(body_node, PM_STATEMENTS_NODE) || (((const pm_statements_node_t *) body_node)->body.size != 1) || !PM_NODE_TYPE_P(((const pm_statements_node_t *) body_node)->body.nodes[0], PM_IF_NODE)) {
3512 rb_bug("mandatory_only?: not in method definition with plain statements");
3513 return COMPILE_NG;
3514 }
3515
3516 const pm_if_node_t *if_node = (const pm_if_node_t *) ((const pm_statements_node_t *) body_node)->body.nodes[0];
3517 if (if_node->predicate != ((const pm_node_t *) call_node)) {
3518 rb_bug("mandatory_only?: can't find mandatory node");
3519 return COMPILE_NG;
3520 }
3521
3522 pm_parameters_node_t parameters = {
3523 .base = parameters_node->base,
3524 .requireds = parameters_node->requireds
3525 };
3526
3527 const pm_def_node_t def = {
3528 .base = def_node->base,
3529 .name = def_node->name,
3530 .receiver = def_node->receiver,
3531 .parameters = &parameters,
3532 .body = (pm_node_t *) if_node->statements,
3533 .locals = {
3534 .ids = def_node->locals.ids,
3535 .size = parameters_node->requireds.size,
3536 .capacity = def_node->locals.capacity
3537 }
3538 };
3539
3540 pm_scope_node_t next_scope_node;
3541 pm_scope_node_init(&def.base, &next_scope_node, scope_node);
3542
3543 int error_state;
3544 const rb_iseq_t *mandatory_only_iseq = pm_iseq_new_with_opt(
3545 &next_scope_node,
3546 rb_iseq_base_label(iseq),
3547 rb_iseq_path(iseq),
3548 rb_iseq_realpath(iseq),
3549 node_location->line,
3550 NULL,
3551 0,
3552 ISEQ_TYPE_METHOD,
3553 ISEQ_COMPILE_DATA(iseq)->option,
3554 &error_state
3555 );
3556 RB_OBJ_WRITE(iseq, &ISEQ_BODY(iseq)->mandatory_only_iseq, (VALUE)mandatory_only_iseq);
3557
3558 if (error_state) {
3559 RUBY_ASSERT(ISEQ_BODY(iseq)->mandatory_only_iseq == NULL);
3560 rb_jump_tag(error_state);
3561 }
3562
3563 pm_scope_node_destroy(&next_scope_node);
3564 return COMPILE_OK;
3565}
3566
3567static int
3568pm_compile_builtin_function_call(rb_iseq_t *iseq, LINK_ANCHOR *const ret, pm_scope_node_t *scope_node, const pm_call_node_t *call_node, const pm_node_location_t *node_location, int popped, const rb_iseq_t *parent_block, const char *builtin_func)
3569{
3570 const pm_arguments_node_t *arguments = call_node->arguments;
3571
3572 if (parent_block != NULL) {
3573 COMPILE_ERROR(iseq, node_location->line, "should not call builtins here.");
3574 return COMPILE_NG;
3575 }
3576
3577#define BUILTIN_INLINE_PREFIX "_bi"
3578 char inline_func[sizeof(BUILTIN_INLINE_PREFIX) + DECIMAL_SIZE_OF(int)];
3579 bool cconst = false;
3580retry:;
3581 const struct rb_builtin_function *bf = iseq_builtin_function_lookup(iseq, builtin_func);
3582
3583 if (bf == NULL) {
3584 if (strcmp("cstmt!", builtin_func) == 0 || strcmp("cexpr!", builtin_func) == 0) {
3585 // ok
3586 }
3587 else if (strcmp("cconst!", builtin_func) == 0) {
3588 cconst = true;
3589 }
3590 else if (strcmp("cinit!", builtin_func) == 0) {
3591 // ignore
3592 return COMPILE_OK;
3593 }
3594 else if (strcmp("attr!", builtin_func) == 0) {
3595 return pm_compile_builtin_attr(iseq, scope_node, arguments, node_location);
3596 }
3597 else if (strcmp("arg!", builtin_func) == 0) {
3598 return pm_compile_builtin_arg(iseq, ret, scope_node, arguments, node_location, popped);
3599 }
3600 else if (strcmp("mandatory_only?", builtin_func) == 0) {
3601 if (popped) {
3602 rb_bug("mandatory_only? should be in if condition");
3603 }
3604 else if (!LIST_INSN_SIZE_ZERO(ret)) {
3605 rb_bug("mandatory_only? should be put on top");
3606 }
3607
3608 PUSH_INSN1(ret, *node_location, putobject, Qfalse);
3609 return pm_compile_builtin_mandatory_only_method(iseq, scope_node, call_node, node_location);
3610 }
3611 else if (1) {
3612 rb_bug("can't find builtin function:%s", builtin_func);
3613 }
3614 else {
3615 COMPILE_ERROR(iseq, node_location->line, "can't find builtin function:%s", builtin_func);
3616 return COMPILE_NG;
3617 }
3618
3619 int inline_index = node_location->line;
3620 snprintf(inline_func, sizeof(inline_func), BUILTIN_INLINE_PREFIX "%d", inline_index);
3621 builtin_func = inline_func;
3622 arguments = NULL;
3623 goto retry;
3624 }
3625
3626 if (cconst) {
3627 typedef VALUE(*builtin_func0)(void *, VALUE);
3628 VALUE const_val = (*(builtin_func0)(uintptr_t)bf->func_ptr)(NULL, Qnil);
3629 PUSH_INSN1(ret, *node_location, putobject, const_val);
3630 return COMPILE_OK;
3631 }
3632
3633 // fprintf(stderr, "func_name:%s -> %p\n", builtin_func, bf->func_ptr);
3634
3635 DECL_ANCHOR(args_seq);
3636
3637 int flags = 0;
3638 struct rb_callinfo_kwarg *keywords = NULL;
3639 int argc = pm_setup_args(arguments, call_node->block, &flags, &keywords, iseq, args_seq, scope_node, node_location);
3640
3641 if (argc != bf->argc) {
3642 COMPILE_ERROR(iseq, node_location->line, "argc is not match for builtin function:%s (expect %d but %d)", builtin_func, bf->argc, argc);
3643 return COMPILE_NG;
3644 }
3645
3646 unsigned int start_index;
3647 if (delegate_call_p(iseq, argc, args_seq, &start_index)) {
3648 PUSH_INSN2(ret, *node_location, opt_invokebuiltin_delegate, bf, INT2FIX(start_index));
3649 }
3650 else {
3651 PUSH_SEQ(ret, args_seq);
3652 PUSH_INSN1(ret, *node_location, invokebuiltin, bf);
3653 }
3654
3655 if (popped) PUSH_INSN(ret, *node_location, pop);
3656 return COMPILE_OK;
3657}
3658
3662static void
3663pm_compile_call(rb_iseq_t *iseq, const pm_call_node_t *call_node, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node, ID method_id, LABEL *start)
3664{
3665 const pm_location_t *message_loc = &call_node->message_loc;
3666 if (message_loc->start == NULL) message_loc = &call_node->base.location;
3667
3668 const pm_node_location_t location = PM_LOCATION_START_LOCATION(scope_node->parser, message_loc, call_node->base.node_id);
3669
3670 LABEL *else_label = NEW_LABEL(location.line);
3671 LABEL *end_label = NEW_LABEL(location.line);
3672 LABEL *retry_end_l = NEW_LABEL(location.line);
3673
3674 VALUE branches = Qfalse;
3675 rb_code_location_t code_location = { 0 };
3676 int node_id = location.node_id;
3677
3678 if (PM_NODE_FLAG_P(call_node, PM_CALL_NODE_FLAGS_SAFE_NAVIGATION)) {
3679 if (PM_BRANCH_COVERAGE_P(iseq)) {
3680 const uint8_t *cursors[3] = {
3681 call_node->closing_loc.end,
3682 call_node->arguments == NULL ? NULL : call_node->arguments->base.location.end,
3683 call_node->message_loc.end
3684 };
3685
3686 const uint8_t *end_cursor = cursors[0];
3687 end_cursor = (end_cursor == NULL || cursors[1] == NULL) ? cursors[1] : (end_cursor > cursors[1] ? end_cursor : cursors[1]);
3688 end_cursor = (end_cursor == NULL || cursors[2] == NULL) ? cursors[2] : (end_cursor > cursors[2] ? end_cursor : cursors[2]);
3689 if (!end_cursor) end_cursor = call_node->closing_loc.end;
3690
3691 const pm_line_column_t start_location = PM_NODE_START_LINE_COLUMN(scope_node->parser, call_node);
3692 const pm_line_column_t end_location = pm_newline_list_line_column(&scope_node->parser->newline_list, end_cursor, scope_node->parser->start_line);
3693
3694 code_location = (rb_code_location_t) {
3695 .beg_pos = { .lineno = start_location.line, .column = start_location.column },
3696 .end_pos = { .lineno = end_location.line, .column = end_location.column }
3697 };
3698
3699 branches = decl_branch_base(iseq, PTR2NUM(call_node), &code_location, "&.");
3700 }
3701
3702 PUSH_INSN(ret, location, dup);
3703 PUSH_INSNL(ret, location, branchnil, else_label);
3704
3705 add_trace_branch_coverage(iseq, ret, &code_location, node_id, 0, "then", branches);
3706 }
3707
3708 LINK_ELEMENT *opt_new_prelude = LAST_ELEMENT(ret);
3709
3710 int flags = 0;
3711 struct rb_callinfo_kwarg *kw_arg = NULL;
3712
3713 int orig_argc = pm_setup_args(call_node->arguments, call_node->block, &flags, &kw_arg, iseq, ret, scope_node, &location);
3714 const rb_iseq_t *previous_block = ISEQ_COMPILE_DATA(iseq)->current_block;
3715 const rb_iseq_t *block_iseq = NULL;
3716
3717 if (call_node->block != NULL && PM_NODE_TYPE_P(call_node->block, PM_BLOCK_NODE)) {
3718 // Scope associated with the block
3719 pm_scope_node_t next_scope_node;
3720 pm_scope_node_init(call_node->block, &next_scope_node, scope_node);
3721
3722 block_iseq = NEW_CHILD_ISEQ(&next_scope_node, make_name_for_block(iseq), ISEQ_TYPE_BLOCK, pm_node_line_number(scope_node->parser, call_node->block));
3723 pm_scope_node_destroy(&next_scope_node);
3724 ISEQ_COMPILE_DATA(iseq)->current_block = block_iseq;
3725 }
3726 else {
3727 if (PM_NODE_FLAG_P(call_node, PM_CALL_NODE_FLAGS_VARIABLE_CALL)) {
3728 flags |= VM_CALL_VCALL;
3729 }
3730
3731 if (!flags) {
3732 flags |= VM_CALL_ARGS_SIMPLE;
3733 }
3734 }
3735
3736 if (PM_NODE_FLAG_P(call_node, PM_CALL_NODE_FLAGS_IGNORE_VISIBILITY)) {
3737 flags |= VM_CALL_FCALL;
3738 }
3739
3740 if (!popped && PM_NODE_FLAG_P(call_node, PM_CALL_NODE_FLAGS_ATTRIBUTE_WRITE)) {
3741 if (flags & VM_CALL_ARGS_BLOCKARG) {
3742 PUSH_INSN1(ret, location, topn, INT2FIX(1));
3743 if (flags & VM_CALL_ARGS_SPLAT) {
3744 PUSH_INSN1(ret, location, putobject, INT2FIX(-1));
3745 PUSH_SEND_WITH_FLAG(ret, location, idAREF, INT2FIX(1), INT2FIX(0));
3746 }
3747 PUSH_INSN1(ret, location, setn, INT2FIX(orig_argc + 3));
3748 PUSH_INSN(ret, location, pop);
3749 }
3750 else if (flags & VM_CALL_ARGS_SPLAT) {
3751 PUSH_INSN(ret, location, dup);
3752 PUSH_INSN1(ret, location, putobject, INT2FIX(-1));
3753 PUSH_SEND_WITH_FLAG(ret, location, idAREF, INT2FIX(1), INT2FIX(0));
3754 PUSH_INSN1(ret, location, setn, INT2FIX(orig_argc + 2));
3755 PUSH_INSN(ret, location, pop);
3756 }
3757 else {
3758 PUSH_INSN1(ret, location, setn, INT2FIX(orig_argc + 1));
3759 }
3760 }
3761
3762 if ((flags & VM_CALL_KW_SPLAT) && (flags & VM_CALL_ARGS_BLOCKARG) && !(flags & VM_CALL_KW_SPLAT_MUT)) {
3763 PUSH_INSN(ret, location, splatkw);
3764 }
3765
3766 LABEL *not_basic_new = NEW_LABEL(location.line);
3767 LABEL *not_basic_new_finish = NEW_LABEL(location.line);
3768
3769 bool inline_new = ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction &&
3770 method_id == rb_intern("new") &&
3771 call_node->block == NULL &&
3772 (flags & VM_CALL_ARGS_BLOCKARG) == 0;
3773
3774 if (inline_new) {
3775 if (LAST_ELEMENT(ret) == opt_new_prelude) {
3776 PUSH_INSN(ret, location, putnil);
3777 PUSH_INSN(ret, location, swap);
3778 }
3779 else {
3780 ELEM_INSERT_NEXT(opt_new_prelude, &new_insn_body(iseq, location.line, location.node_id, BIN(swap), 0)->link);
3781 ELEM_INSERT_NEXT(opt_new_prelude, &new_insn_body(iseq, location.line, location.node_id, BIN(putnil), 0)->link);
3782 }
3783
3784 rb_callinfo_kwarg_retain(kw_arg);
3785
3786 // Jump unless the receiver uses the "basic" implementation of "new"
3787 VALUE ci;
3788 if (flags & VM_CALL_FORWARDING) {
3789 ci = (VALUE)new_callinfo(iseq, method_id, orig_argc + 1, flags, kw_arg, 0);
3790 }
3791 else {
3792 ci = (VALUE)new_callinfo(iseq, method_id, orig_argc, flags, kw_arg, 0);
3793 }
3794
3795 PUSH_INSN2(ret, location, opt_new, ci, not_basic_new);
3796 LABEL_REF(not_basic_new);
3797 // optimized path
3798 PUSH_SEND_R(ret, location, rb_intern("initialize"), INT2FIX(orig_argc), block_iseq, INT2FIX(flags | VM_CALL_FCALL), kw_arg);
3799 PUSH_INSNL(ret, location, jump, not_basic_new_finish);
3800
3801 PUSH_LABEL(ret, not_basic_new);
3802 // Fall back to normal send
3803 PUSH_SEND_R(ret, location, method_id, INT2FIX(orig_argc), block_iseq, INT2FIX(flags), kw_arg);
3804 PUSH_INSN(ret, location, swap);
3805
3806 PUSH_LABEL(ret, not_basic_new_finish);
3807 PUSH_INSN(ret, location, pop);
3808
3809 rb_callinfo_kwarg_release(kw_arg);
3810 }
3811 else {
3812 PUSH_SEND_R(ret, location, method_id, INT2FIX(orig_argc), block_iseq, INT2FIX(flags), kw_arg);
3813 }
3814
3815 if (block_iseq && ISEQ_BODY(block_iseq)->catch_table) {
3816 pm_compile_retry_end_label(iseq, ret, retry_end_l);
3817 PUSH_CATCH_ENTRY(CATCH_TYPE_BREAK, start, retry_end_l, block_iseq, retry_end_l);
3818 }
3819
3820 if (PM_NODE_FLAG_P(call_node, PM_CALL_NODE_FLAGS_SAFE_NAVIGATION)) {
3821 PUSH_INSNL(ret, location, jump, end_label);
3822 PUSH_LABEL(ret, else_label);
3823 add_trace_branch_coverage(iseq, ret, &code_location, node_id, 1, "else", branches);
3824 PUSH_LABEL(ret, end_label);
3825 }
3826
3827 if (PM_NODE_FLAG_P(call_node, PM_CALL_NODE_FLAGS_ATTRIBUTE_WRITE) && !popped) {
3828 PUSH_INSN(ret, location, pop);
3829 }
3830
3831 if (popped) PUSH_INSN(ret, location, pop);
3832 ISEQ_COMPILE_DATA(iseq)->current_block = previous_block;
3833}
3834
3839static inline VALUE
3840pm_compile_back_reference_ref(const pm_back_reference_read_node_t *node)
3841{
3842 const char *type = (const char *) (node->base.location.start + 1);
3843
3844 // Since a back reference is `$<char>`, Ruby represents the ID as an
3845 // rb_intern on the value after the `$`.
3846 return INT2FIX(rb_intern2(type, 1)) << 1 | 1;
3847}
3848
3853static inline VALUE
3854pm_compile_numbered_reference_ref(const pm_numbered_reference_read_node_t *node)
3855{
3856 return INT2FIX(node->number << 1);
3857}
3858
3859static void
3860pm_compile_defined_expr0(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node, bool in_condition, LABEL **lfinish, bool explicit_receiver)
3861{
3862#define PUSH_VAL(type) (in_condition ? Qtrue : rb_iseq_defined_string(type))
3863
3864 // in_condition is the same as compile.c's needstr
3865 enum defined_type dtype = DEFINED_NOT_DEFINED;
3866 const pm_node_location_t location = *node_location;
3867
3868 switch (PM_NODE_TYPE(node)) {
3869/* DEFINED_NIL ****************************************************************/
3870 case PM_NIL_NODE:
3871 // defined?(nil)
3872 // ^^^
3873 dtype = DEFINED_NIL;
3874 break;
3875/* DEFINED_IVAR ***************************************************************/
3876 case PM_INSTANCE_VARIABLE_READ_NODE: {
3877 // defined?(@a)
3878 // ^^
3879 const pm_instance_variable_read_node_t *cast = (const pm_instance_variable_read_node_t *) node;
3880 ID name = pm_constant_id_lookup(scope_node, cast->name);
3881
3882 PUSH_INSN3(ret, location, definedivar, ID2SYM(name), get_ivar_ic_value(iseq, name), PUSH_VAL(DEFINED_IVAR));
3883
3884 return;
3885 }
3886/* DEFINED_LVAR ***************************************************************/
3887 case PM_LOCAL_VARIABLE_READ_NODE:
3888 // a = 1; defined?(a)
3889 // ^
3890 case PM_IT_LOCAL_VARIABLE_READ_NODE:
3891 // 1.then { defined?(it) }
3892 // ^^
3893 dtype = DEFINED_LVAR;
3894 break;
3895/* DEFINED_GVAR ***************************************************************/
3896 case PM_GLOBAL_VARIABLE_READ_NODE: {
3897 // defined?($a)
3898 // ^^
3899 const pm_global_variable_read_node_t *cast = (const pm_global_variable_read_node_t *) node;
3900 ID name = pm_constant_id_lookup(scope_node, cast->name);
3901
3902 PUSH_INSN(ret, location, putnil);
3903 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_GVAR), ID2SYM(name), PUSH_VAL(DEFINED_GVAR));
3904
3905 return;
3906 }
3907/* DEFINED_CVAR ***************************************************************/
3908 case PM_CLASS_VARIABLE_READ_NODE: {
3909 // defined?(@@a)
3910 // ^^^
3911 const pm_class_variable_read_node_t *cast = (const pm_class_variable_read_node_t *) node;
3912 ID name = pm_constant_id_lookup(scope_node, cast->name);
3913
3914 PUSH_INSN(ret, location, putnil);
3915 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_CVAR), ID2SYM(name), PUSH_VAL(DEFINED_CVAR));
3916
3917 return;
3918 }
3919/* DEFINED_CONST **************************************************************/
3920 case PM_CONSTANT_READ_NODE: {
3921 // defined?(A)
3922 // ^
3923 const pm_constant_read_node_t *cast = (const pm_constant_read_node_t *) node;
3924 ID name = pm_constant_id_lookup(scope_node, cast->name);
3925
3926 PUSH_INSN(ret, location, putnil);
3927 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_CONST), ID2SYM(name), PUSH_VAL(DEFINED_CONST));
3928
3929 return;
3930 }
3931/* DEFINED_YIELD **************************************************************/
3932 case PM_YIELD_NODE:
3933 // defined?(yield)
3934 // ^^^^^
3935 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
3936
3937 PUSH_INSN(ret, location, putnil);
3938 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_YIELD), 0, PUSH_VAL(DEFINED_YIELD));
3939
3940 return;
3941/* DEFINED_ZSUPER *************************************************************/
3942 case PM_SUPER_NODE: {
3943 // defined?(super 1, 2)
3944 // ^^^^^^^^^^
3945 const pm_super_node_t *cast = (const pm_super_node_t *) node;
3946
3947 if (cast->block != NULL && !PM_NODE_TYPE_P(cast->block, PM_BLOCK_ARGUMENT_NODE)) {
3948 dtype = DEFINED_EXPR;
3949 break;
3950 }
3951
3952 PUSH_INSN(ret, location, putnil);
3953 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_ZSUPER), 0, PUSH_VAL(DEFINED_ZSUPER));
3954 return;
3955 }
3956 case PM_FORWARDING_SUPER_NODE: {
3957 // defined?(super)
3958 // ^^^^^
3959 const pm_forwarding_super_node_t *cast = (const pm_forwarding_super_node_t *) node;
3960
3961 if (cast->block != NULL) {
3962 dtype = DEFINED_EXPR;
3963 break;
3964 }
3965
3966 PUSH_INSN(ret, location, putnil);
3967 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_ZSUPER), 0, PUSH_VAL(DEFINED_ZSUPER));
3968 return;
3969 }
3970/* DEFINED_SELF ***************************************************************/
3971 case PM_SELF_NODE:
3972 // defined?(self)
3973 // ^^^^
3974 dtype = DEFINED_SELF;
3975 break;
3976/* DEFINED_TRUE ***************************************************************/
3977 case PM_TRUE_NODE:
3978 // defined?(true)
3979 // ^^^^
3980 dtype = DEFINED_TRUE;
3981 break;
3982/* DEFINED_FALSE **************************************************************/
3983 case PM_FALSE_NODE:
3984 // defined?(false)
3985 // ^^^^^
3986 dtype = DEFINED_FALSE;
3987 break;
3988/* DEFINED_ASGN ***************************************************************/
3989 case PM_CALL_AND_WRITE_NODE:
3990 // defined?(a.a &&= 1)
3991 // ^^^^^^^^^
3992 case PM_CALL_OPERATOR_WRITE_NODE:
3993 // defined?(a.a += 1)
3994 // ^^^^^^^^
3995 case PM_CALL_OR_WRITE_NODE:
3996 // defined?(a.a ||= 1)
3997 // ^^^^^^^^^
3998 case PM_CLASS_VARIABLE_AND_WRITE_NODE:
3999 // defined?(@@a &&= 1)
4000 // ^^^^^^^^^
4001 case PM_CLASS_VARIABLE_OPERATOR_WRITE_NODE:
4002 // defined?(@@a += 1)
4003 // ^^^^^^^^
4004 case PM_CLASS_VARIABLE_OR_WRITE_NODE:
4005 // defined?(@@a ||= 1)
4006 // ^^^^^^^^^
4007 case PM_CLASS_VARIABLE_WRITE_NODE:
4008 // defined?(@@a = 1)
4009 // ^^^^^^^
4010 case PM_CONSTANT_AND_WRITE_NODE:
4011 // defined?(A &&= 1)
4012 // ^^^^^^^
4013 case PM_CONSTANT_OPERATOR_WRITE_NODE:
4014 // defined?(A += 1)
4015 // ^^^^^^
4016 case PM_CONSTANT_OR_WRITE_NODE:
4017 // defined?(A ||= 1)
4018 // ^^^^^^^
4019 case PM_CONSTANT_PATH_AND_WRITE_NODE:
4020 // defined?(A::A &&= 1)
4021 // ^^^^^^^^^^
4022 case PM_CONSTANT_PATH_OPERATOR_WRITE_NODE:
4023 // defined?(A::A += 1)
4024 // ^^^^^^^^^
4025 case PM_CONSTANT_PATH_OR_WRITE_NODE:
4026 // defined?(A::A ||= 1)
4027 // ^^^^^^^^^^
4028 case PM_CONSTANT_PATH_WRITE_NODE:
4029 // defined?(A::A = 1)
4030 // ^^^^^^^^
4031 case PM_CONSTANT_WRITE_NODE:
4032 // defined?(A = 1)
4033 // ^^^^^
4034 case PM_GLOBAL_VARIABLE_AND_WRITE_NODE:
4035 // defined?($a &&= 1)
4036 // ^^^^^^^^
4037 case PM_GLOBAL_VARIABLE_OPERATOR_WRITE_NODE:
4038 // defined?($a += 1)
4039 // ^^^^^^^
4040 case PM_GLOBAL_VARIABLE_OR_WRITE_NODE:
4041 // defined?($a ||= 1)
4042 // ^^^^^^^^
4043 case PM_GLOBAL_VARIABLE_WRITE_NODE:
4044 // defined?($a = 1)
4045 // ^^^^^^
4046 case PM_INDEX_AND_WRITE_NODE:
4047 // defined?(a[1] &&= 1)
4048 // ^^^^^^^^^^
4049 case PM_INDEX_OPERATOR_WRITE_NODE:
4050 // defined?(a[1] += 1)
4051 // ^^^^^^^^^
4052 case PM_INDEX_OR_WRITE_NODE:
4053 // defined?(a[1] ||= 1)
4054 // ^^^^^^^^^^
4055 case PM_INSTANCE_VARIABLE_AND_WRITE_NODE:
4056 // defined?(@a &&= 1)
4057 // ^^^^^^^^
4058 case PM_INSTANCE_VARIABLE_OPERATOR_WRITE_NODE:
4059 // defined?(@a += 1)
4060 // ^^^^^^^
4061 case PM_INSTANCE_VARIABLE_OR_WRITE_NODE:
4062 // defined?(@a ||= 1)
4063 // ^^^^^^^^
4064 case PM_INSTANCE_VARIABLE_WRITE_NODE:
4065 // defined?(@a = 1)
4066 // ^^^^^^
4067 case PM_LOCAL_VARIABLE_AND_WRITE_NODE:
4068 // defined?(a &&= 1)
4069 // ^^^^^^^
4070 case PM_LOCAL_VARIABLE_OPERATOR_WRITE_NODE:
4071 // defined?(a += 1)
4072 // ^^^^^^
4073 case PM_LOCAL_VARIABLE_OR_WRITE_NODE:
4074 // defined?(a ||= 1)
4075 // ^^^^^^^
4076 case PM_LOCAL_VARIABLE_WRITE_NODE:
4077 // defined?(a = 1)
4078 // ^^^^^
4079 case PM_MULTI_WRITE_NODE:
4080 // defined?((a, = 1))
4081 // ^^^^^^
4082 dtype = DEFINED_ASGN;
4083 break;
4084/* DEFINED_EXPR ***************************************************************/
4085 case PM_ALIAS_GLOBAL_VARIABLE_NODE:
4086 // defined?((alias $a $b))
4087 // ^^^^^^^^^^^
4088 case PM_ALIAS_METHOD_NODE:
4089 // defined?((alias a b))
4090 // ^^^^^^^^^
4091 case PM_AND_NODE:
4092 // defined?(a and b)
4093 // ^^^^^^^
4094 case PM_BREAK_NODE:
4095 // defined?(break 1)
4096 // ^^^^^^^
4097 case PM_CASE_MATCH_NODE:
4098 // defined?(case 1; in 1; end)
4099 // ^^^^^^^^^^^^^^^^^
4100 case PM_CASE_NODE:
4101 // defined?(case 1; when 1; end)
4102 // ^^^^^^^^^^^^^^^^^^^
4103 case PM_CLASS_NODE:
4104 // defined?(class Foo; end)
4105 // ^^^^^^^^^^^^^^
4106 case PM_DEF_NODE:
4107 // defined?(def a() end)
4108 // ^^^^^^^^^^^
4109 case PM_DEFINED_NODE:
4110 // defined?(defined?(a))
4111 // ^^^^^^^^^^^
4112 case PM_FLIP_FLOP_NODE:
4113 // defined?(not (a .. b))
4114 // ^^^^^^
4115 case PM_FLOAT_NODE:
4116 // defined?(1.0)
4117 // ^^^
4118 case PM_FOR_NODE:
4119 // defined?(for a in 1 do end)
4120 // ^^^^^^^^^^^^^^^^^
4121 case PM_IF_NODE:
4122 // defined?(if a then end)
4123 // ^^^^^^^^^^^^^
4124 case PM_IMAGINARY_NODE:
4125 // defined?(1i)
4126 // ^^
4127 case PM_INTEGER_NODE:
4128 // defined?(1)
4129 // ^
4130 case PM_INTERPOLATED_MATCH_LAST_LINE_NODE:
4131 // defined?(not /#{1}/)
4132 // ^^^^^^
4133 case PM_INTERPOLATED_REGULAR_EXPRESSION_NODE:
4134 // defined?(/#{1}/)
4135 // ^^^^^^
4136 case PM_INTERPOLATED_STRING_NODE:
4137 // defined?("#{1}")
4138 // ^^^^^^
4139 case PM_INTERPOLATED_SYMBOL_NODE:
4140 // defined?(:"#{1}")
4141 // ^^^^^^^
4142 case PM_INTERPOLATED_X_STRING_NODE:
4143 // defined?(`#{1}`)
4144 // ^^^^^^
4145 case PM_LAMBDA_NODE:
4146 // defined?(-> {})
4147 // ^^^^^
4148 case PM_MATCH_LAST_LINE_NODE:
4149 // defined?(not //)
4150 // ^^^^^^
4151 case PM_MATCH_PREDICATE_NODE:
4152 // defined?(1 in 1)
4153 // ^^^^^^
4154 case PM_MATCH_REQUIRED_NODE:
4155 // defined?(1 => 1)
4156 // ^^^^^^
4157 case PM_MATCH_WRITE_NODE:
4158 // defined?(/(?<a>)/ =~ "")
4159 // ^^^^^^^^^^^^^^
4160 case PM_MODULE_NODE:
4161 // defined?(module A end)
4162 // ^^^^^^^^^^^^
4163 case PM_NEXT_NODE:
4164 // defined?(next 1)
4165 // ^^^^^^
4166 case PM_OR_NODE:
4167 // defined?(a or b)
4168 // ^^^^^^
4169 case PM_POST_EXECUTION_NODE:
4170 // defined?((END {}))
4171 // ^^^^^^^^
4172 case PM_RANGE_NODE:
4173 // defined?(1..1)
4174 // ^^^^
4175 case PM_RATIONAL_NODE:
4176 // defined?(1r)
4177 // ^^
4178 case PM_REDO_NODE:
4179 // defined?(redo)
4180 // ^^^^
4181 case PM_REGULAR_EXPRESSION_NODE:
4182 // defined?(//)
4183 // ^^
4184 case PM_RESCUE_MODIFIER_NODE:
4185 // defined?(a rescue b)
4186 // ^^^^^^^^^^
4187 case PM_RETRY_NODE:
4188 // defined?(retry)
4189 // ^^^^^
4190 case PM_RETURN_NODE:
4191 // defined?(return)
4192 // ^^^^^^
4193 case PM_SINGLETON_CLASS_NODE:
4194 // defined?(class << self; end)
4195 // ^^^^^^^^^^^^^^^^^^
4196 case PM_SOURCE_ENCODING_NODE:
4197 // defined?(__ENCODING__)
4198 // ^^^^^^^^^^^^
4199 case PM_SOURCE_FILE_NODE:
4200 // defined?(__FILE__)
4201 // ^^^^^^^^
4202 case PM_SOURCE_LINE_NODE:
4203 // defined?(__LINE__)
4204 // ^^^^^^^^
4205 case PM_STRING_NODE:
4206 // defined?("")
4207 // ^^
4208 case PM_SYMBOL_NODE:
4209 // defined?(:a)
4210 // ^^
4211 case PM_UNDEF_NODE:
4212 // defined?((undef a))
4213 // ^^^^^^^
4214 case PM_UNLESS_NODE:
4215 // defined?(unless a then end)
4216 // ^^^^^^^^^^^^^^^^^
4217 case PM_UNTIL_NODE:
4218 // defined?(until a do end)
4219 // ^^^^^^^^^^^^^^
4220 case PM_WHILE_NODE:
4221 // defined?(while a do end)
4222 // ^^^^^^^^^^^^^^
4223 case PM_X_STRING_NODE:
4224 // defined?(``)
4225 // ^^
4226 dtype = DEFINED_EXPR;
4227 break;
4228/* DEFINED_REF ****************************************************************/
4229 case PM_BACK_REFERENCE_READ_NODE: {
4230 // defined?($+)
4231 // ^^
4232 const pm_back_reference_read_node_t *cast = (const pm_back_reference_read_node_t *) node;
4233 VALUE ref = pm_compile_back_reference_ref(cast);
4234
4235 PUSH_INSN(ret, location, putnil);
4236 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_REF), ref, PUSH_VAL(DEFINED_GVAR));
4237
4238 return;
4239 }
4240 case PM_NUMBERED_REFERENCE_READ_NODE: {
4241 // defined?($1)
4242 // ^^
4243 const pm_numbered_reference_read_node_t *cast = (const pm_numbered_reference_read_node_t *) node;
4244 VALUE ref = pm_compile_numbered_reference_ref(cast);
4245
4246 PUSH_INSN(ret, location, putnil);
4247 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_REF), ref, PUSH_VAL(DEFINED_GVAR));
4248
4249 return;
4250 }
4251/* DEFINED_CONST_FROM *********************************************************/
4252 case PM_CONSTANT_PATH_NODE: {
4253 // defined?(A::A)
4254 // ^^^^
4255 const pm_constant_path_node_t *cast = (const pm_constant_path_node_t *) node;
4256 ID name = pm_constant_id_lookup(scope_node, cast->name);
4257
4258 if (cast->parent != NULL) {
4259 if (!lfinish[1]) lfinish[1] = NEW_LABEL(location.line);
4260 pm_compile_defined_expr0(iseq, cast->parent, node_location, ret, popped, scope_node, true, lfinish, false);
4261
4262 PUSH_INSNL(ret, location, branchunless, lfinish[1]);
4263 PM_COMPILE(cast->parent);
4264 }
4265 else {
4266 PUSH_INSN1(ret, location, putobject, rb_cObject);
4267 }
4268
4269 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_CONST_FROM), ID2SYM(name), PUSH_VAL(DEFINED_CONST));
4270 return;
4271 }
4272/* Containers *****************************************************************/
4273 case PM_BEGIN_NODE: {
4274 // defined?(begin end)
4275 // ^^^^^^^^^
4276 const pm_begin_node_t *cast = (const pm_begin_node_t *) node;
4277
4278 if (cast->rescue_clause == NULL && cast->ensure_clause == NULL && cast->else_clause == NULL) {
4279 if (cast->statements == NULL) {
4280 // If we have empty statements, then we want to return "nil".
4281 dtype = DEFINED_NIL;
4282 }
4283 else if (cast->statements->body.size == 1) {
4284 // If we have a begin node that is wrapping a single statement
4285 // then we want to recurse down to that statement and compile
4286 // it.
4287 pm_compile_defined_expr0(iseq, cast->statements->body.nodes[0], node_location, ret, popped, scope_node, in_condition, lfinish, false);
4288 return;
4289 }
4290 else {
4291 // Otherwise, we have a begin wrapping multiple statements, in
4292 // which case this is defined as "expression".
4293 dtype = DEFINED_EXPR;
4294 }
4295 } else {
4296 // If we have any of the other clauses besides the main begin/end,
4297 // this is defined as "expression".
4298 dtype = DEFINED_EXPR;
4299 }
4300
4301 break;
4302 }
4303 case PM_PARENTHESES_NODE: {
4304 // defined?(())
4305 // ^^
4306 const pm_parentheses_node_t *cast = (const pm_parentheses_node_t *) node;
4307
4308 if (cast->body == NULL) {
4309 // If we have empty parentheses, then we want to return "nil".
4310 dtype = DEFINED_NIL;
4311 }
4312 else if (PM_NODE_TYPE_P(cast->body, PM_STATEMENTS_NODE) && !PM_NODE_FLAG_P(cast, PM_PARENTHESES_NODE_FLAGS_MULTIPLE_STATEMENTS)) {
4313 // If we have a parentheses node that is wrapping a single statement
4314 // then we want to recurse down to that statement and compile it.
4315 pm_compile_defined_expr0(iseq, ((const pm_statements_node_t *) cast->body)->body.nodes[0], node_location, ret, popped, scope_node, in_condition, lfinish, false);
4316 return;
4317 }
4318 else {
4319 // Otherwise, we have parentheses wrapping multiple statements, in
4320 // which case this is defined as "expression".
4321 dtype = DEFINED_EXPR;
4322 }
4323
4324 break;
4325 }
4326 case PM_ARRAY_NODE: {
4327 // defined?([])
4328 // ^^
4329 const pm_array_node_t *cast = (const pm_array_node_t *) node;
4330
4331 if (cast->elements.size > 0 && !lfinish[1]) {
4332 lfinish[1] = NEW_LABEL(location.line);
4333 }
4334
4335 for (size_t index = 0; index < cast->elements.size; index++) {
4336 pm_compile_defined_expr0(iseq, cast->elements.nodes[index], node_location, ret, popped, scope_node, true, lfinish, false);
4337 PUSH_INSNL(ret, location, branchunless, lfinish[1]);
4338 }
4339
4340 dtype = DEFINED_EXPR;
4341 break;
4342 }
4343 case PM_HASH_NODE:
4344 // defined?({ a: 1 })
4345 // ^^^^^^^^
4346 case PM_KEYWORD_HASH_NODE: {
4347 // defined?(a(a: 1))
4348 // ^^^^
4349 const pm_node_list_t *elements;
4350
4351 if (PM_NODE_TYPE_P(node, PM_HASH_NODE)) {
4352 elements = &((const pm_hash_node_t *) node)->elements;
4353 }
4354 else {
4355 elements = &((const pm_keyword_hash_node_t *) node)->elements;
4356 }
4357
4358 if (elements->size > 0 && !lfinish[1]) {
4359 lfinish[1] = NEW_LABEL(location.line);
4360 }
4361
4362 for (size_t index = 0; index < elements->size; index++) {
4363 pm_compile_defined_expr0(iseq, elements->nodes[index], node_location, ret, popped, scope_node, true, lfinish, false);
4364 PUSH_INSNL(ret, location, branchunless, lfinish[1]);
4365 }
4366
4367 dtype = DEFINED_EXPR;
4368 break;
4369 }
4370 case PM_ASSOC_NODE: {
4371 // defined?({ a: 1 })
4372 // ^^^^
4373 const pm_assoc_node_t *cast = (const pm_assoc_node_t *) node;
4374
4375 pm_compile_defined_expr0(iseq, cast->key, node_location, ret, popped, scope_node, true, lfinish, false);
4376 PUSH_INSNL(ret, location, branchunless, lfinish[1]);
4377 pm_compile_defined_expr0(iseq, cast->value, node_location, ret, popped, scope_node, true, lfinish, false);
4378
4379 return;
4380 }
4381 case PM_ASSOC_SPLAT_NODE: {
4382 // defined?({ **a })
4383 // ^^^^
4384 const pm_assoc_splat_node_t *cast = (const pm_assoc_splat_node_t *) node;
4385
4386 if (cast->value == NULL) {
4387 dtype = DEFINED_EXPR;
4388 break;
4389 }
4390
4391 pm_compile_defined_expr0(iseq, cast->value, node_location, ret, popped, scope_node, true, lfinish, false);
4392 return;
4393 }
4394 case PM_IMPLICIT_NODE: {
4395 // defined?({ a: })
4396 // ^^
4397 const pm_implicit_node_t *cast = (const pm_implicit_node_t *) node;
4398 pm_compile_defined_expr0(iseq, cast->value, node_location, ret, popped, scope_node, in_condition, lfinish, false);
4399 return;
4400 }
4401 case PM_CALL_NODE: {
4402#define BLOCK_P(cast) ((cast)->block != NULL && PM_NODE_TYPE_P((cast)->block, PM_BLOCK_NODE))
4403
4404 // defined?(a(1, 2, 3))
4405 // ^^^^^^^^^^
4406 const pm_call_node_t *cast = ((const pm_call_node_t *) node);
4407
4408 if (BLOCK_P(cast)) {
4409 dtype = DEFINED_EXPR;
4410 break;
4411 }
4412
4413 if (cast->receiver || cast->arguments || (cast->block && PM_NODE_TYPE_P(cast->block, PM_BLOCK_ARGUMENT_NODE))) {
4414 if (!lfinish[1]) lfinish[1] = NEW_LABEL(location.line);
4415 if (!lfinish[2]) lfinish[2] = NEW_LABEL(location.line);
4416 }
4417
4418 if (cast->arguments) {
4419 pm_compile_defined_expr0(iseq, (const pm_node_t *) cast->arguments, node_location, ret, popped, scope_node, true, lfinish, false);
4420 PUSH_INSNL(ret, location, branchunless, lfinish[1]);
4421 }
4422
4423 if (cast->block && PM_NODE_TYPE_P(cast->block, PM_BLOCK_ARGUMENT_NODE)) {
4424 pm_compile_defined_expr0(iseq, cast->block, node_location, ret, popped, scope_node, true, lfinish, false);
4425 PUSH_INSNL(ret, location, branchunless, lfinish[1]);
4426 }
4427
4428 if (cast->receiver) {
4429 if (PM_NODE_TYPE_P(cast->receiver, PM_CALL_NODE) && !BLOCK_P((const pm_call_node_t *) cast->receiver)) {
4430 // Special behavior here where we chain calls together. This is
4431 // the only path that sets explicit_receiver to true.
4432 pm_compile_defined_expr0(iseq, cast->receiver, node_location, ret, popped, scope_node, true, lfinish, true);
4433 PUSH_INSNL(ret, location, branchunless, lfinish[2]);
4434
4435 const pm_call_node_t *receiver = (const pm_call_node_t *) cast->receiver;
4436 ID method_id = pm_constant_id_lookup(scope_node, receiver->name);
4437
4438 pm_compile_call(iseq, receiver, ret, popped, scope_node, method_id, NULL);
4439 }
4440 else {
4441 pm_compile_defined_expr0(iseq, cast->receiver, node_location, ret, popped, scope_node, true, lfinish, false);
4442 PUSH_INSNL(ret, location, branchunless, lfinish[1]);
4443 PM_COMPILE(cast->receiver);
4444 }
4445
4446 ID method_id = pm_constant_id_lookup(scope_node, cast->name);
4447
4448 if (explicit_receiver) PUSH_INSN(ret, location, dup);
4449 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_METHOD), rb_id2sym(method_id), PUSH_VAL(DEFINED_METHOD));
4450 }
4451 else {
4452 ID method_id = pm_constant_id_lookup(scope_node, cast->name);
4453
4454 PUSH_INSN(ret, location, putself);
4455 if (explicit_receiver) PUSH_INSN(ret, location, dup);
4456
4457 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_FUNC), rb_id2sym(method_id), PUSH_VAL(DEFINED_METHOD));
4458 }
4459
4460 return;
4461
4462#undef BLOCK_P
4463 }
4464 case PM_ARGUMENTS_NODE: {
4465 // defined?(a(1, 2, 3))
4466 // ^^^^^^^
4467 const pm_arguments_node_t *cast = (const pm_arguments_node_t *) node;
4468
4469 for (size_t index = 0; index < cast->arguments.size; index++) {
4470 pm_compile_defined_expr0(iseq, cast->arguments.nodes[index], node_location, ret, popped, scope_node, in_condition, lfinish, false);
4471 PUSH_INSNL(ret, location, branchunless, lfinish[1]);
4472 }
4473
4474 dtype = DEFINED_EXPR;
4475 break;
4476 }
4477 case PM_BLOCK_ARGUMENT_NODE:
4478 // defined?(a(&b))
4479 // ^^
4480 dtype = DEFINED_EXPR;
4481 break;
4482 case PM_FORWARDING_ARGUMENTS_NODE:
4483 // def a(...) = defined?(a(...))
4484 // ^^^
4485 dtype = DEFINED_EXPR;
4486 break;
4487 case PM_SPLAT_NODE: {
4488 // def a(*) = defined?(a(*))
4489 // ^
4490 const pm_splat_node_t *cast = (const pm_splat_node_t *) node;
4491
4492 if (cast->expression == NULL) {
4493 dtype = DEFINED_EXPR;
4494 break;
4495 }
4496
4497 pm_compile_defined_expr0(iseq, cast->expression, node_location, ret, popped, scope_node, in_condition, lfinish, false);
4498
4499 if (!lfinish[1]) lfinish[1] = NEW_LABEL(location.line);
4500 PUSH_INSNL(ret, location, branchunless, lfinish[1]);
4501
4502 dtype = DEFINED_EXPR;
4503 break;
4504 }
4505 case PM_SHAREABLE_CONSTANT_NODE:
4506 // # shareable_constant_value: literal
4507 // defined?(A = 1)
4508 // ^^^^^
4509 pm_compile_defined_expr0(iseq, ((const pm_shareable_constant_node_t *) node)->write, node_location, ret, popped, scope_node, in_condition, lfinish, explicit_receiver);
4510 return;
4511/* Unreachable (parameters) ***************************************************/
4512 case PM_BLOCK_LOCAL_VARIABLE_NODE:
4513 case PM_BLOCK_PARAMETER_NODE:
4514 case PM_BLOCK_PARAMETERS_NODE:
4515 case PM_FORWARDING_PARAMETER_NODE:
4516 case PM_IMPLICIT_REST_NODE:
4517 case PM_IT_PARAMETERS_NODE:
4518 case PM_PARAMETERS_NODE:
4519 case PM_KEYWORD_REST_PARAMETER_NODE:
4520 case PM_NO_KEYWORDS_PARAMETER_NODE:
4521 case PM_NUMBERED_PARAMETERS_NODE:
4522 case PM_OPTIONAL_KEYWORD_PARAMETER_NODE:
4523 case PM_OPTIONAL_PARAMETER_NODE:
4524 case PM_REQUIRED_KEYWORD_PARAMETER_NODE:
4525 case PM_REQUIRED_PARAMETER_NODE:
4526 case PM_REST_PARAMETER_NODE:
4527/* Unreachable (pattern matching) *********************************************/
4528 case PM_ALTERNATION_PATTERN_NODE:
4529 case PM_ARRAY_PATTERN_NODE:
4530 case PM_CAPTURE_PATTERN_NODE:
4531 case PM_FIND_PATTERN_NODE:
4532 case PM_HASH_PATTERN_NODE:
4533 case PM_PINNED_EXPRESSION_NODE:
4534 case PM_PINNED_VARIABLE_NODE:
4535/* Unreachable (indirect writes) **********************************************/
4536 case PM_CALL_TARGET_NODE:
4537 case PM_CLASS_VARIABLE_TARGET_NODE:
4538 case PM_CONSTANT_PATH_TARGET_NODE:
4539 case PM_CONSTANT_TARGET_NODE:
4540 case PM_GLOBAL_VARIABLE_TARGET_NODE:
4541 case PM_INDEX_TARGET_NODE:
4542 case PM_INSTANCE_VARIABLE_TARGET_NODE:
4543 case PM_LOCAL_VARIABLE_TARGET_NODE:
4544 case PM_MULTI_TARGET_NODE:
4545/* Unreachable (clauses) ******************************************************/
4546 case PM_ELSE_NODE:
4547 case PM_ENSURE_NODE:
4548 case PM_IN_NODE:
4549 case PM_RESCUE_NODE:
4550 case PM_WHEN_NODE:
4551/* Unreachable (miscellaneous) ************************************************/
4552 case PM_BLOCK_NODE:
4553 case PM_EMBEDDED_STATEMENTS_NODE:
4554 case PM_EMBEDDED_VARIABLE_NODE:
4555 case PM_MISSING_NODE:
4556 case PM_PRE_EXECUTION_NODE:
4557 case PM_PROGRAM_NODE:
4558 case PM_SCOPE_NODE:
4559 case PM_STATEMENTS_NODE:
4560 rb_bug("Unreachable node in defined?: %s", pm_node_type_to_str(PM_NODE_TYPE(node)));
4561 }
4562
4563 RUBY_ASSERT(dtype != DEFINED_NOT_DEFINED);
4564 PUSH_INSN1(ret, location, putobject, PUSH_VAL(dtype));
4565
4566#undef PUSH_VAL
4567}
4568
4569static void
4570pm_defined_expr(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node, bool in_condition, LABEL **lfinish)
4571{
4572 LINK_ELEMENT *lcur = ret->last;
4573 pm_compile_defined_expr0(iseq, node, node_location, ret, popped, scope_node, in_condition, lfinish, false);
4574
4575 if (lfinish[1]) {
4576 LABEL *lstart = NEW_LABEL(node_location->line);
4577 LABEL *lend = NEW_LABEL(node_location->line);
4578
4580 rb_iseq_new_with_callback_new_callback(build_defined_rescue_iseq, NULL);
4581
4582 const rb_iseq_t *rescue = new_child_iseq_with_callback(
4583 iseq,
4584 ifunc,
4585 rb_str_concat(rb_str_new2("defined guard in "), ISEQ_BODY(iseq)->location.label),
4586 iseq,
4587 ISEQ_TYPE_RESCUE,
4588 0
4589 );
4590
4591 lstart->rescued = LABEL_RESCUE_BEG;
4592 lend->rescued = LABEL_RESCUE_END;
4593
4594 APPEND_LABEL(ret, lcur, lstart);
4595 PUSH_LABEL(ret, lend);
4596 PUSH_CATCH_ENTRY(CATCH_TYPE_RESCUE, lstart, lend, rescue, lfinish[1]);
4597 }
4598}
4599
4600static void
4601pm_compile_defined_expr(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node, bool in_condition)
4602{
4603 LABEL *lfinish[3];
4604 LINK_ELEMENT *last = ret->last;
4605
4606 lfinish[0] = NEW_LABEL(node_location->line);
4607 lfinish[1] = 0;
4608 lfinish[2] = 0;
4609
4610 if (!popped) {
4611 pm_defined_expr(iseq, node, node_location, ret, popped, scope_node, in_condition, lfinish);
4612 }
4613
4614 if (lfinish[1]) {
4615 ELEM_INSERT_NEXT(last, &new_insn_body(iseq, node_location->line, node_location->node_id, BIN(putnil), 0)->link);
4616 PUSH_INSN(ret, *node_location, swap);
4617
4618 if (lfinish[2]) PUSH_LABEL(ret, lfinish[2]);
4619 PUSH_INSN(ret, *node_location, pop);
4620 PUSH_LABEL(ret, lfinish[1]);
4621
4622 }
4623
4624 PUSH_LABEL(ret, lfinish[0]);
4625}
4626
4627// This is exactly the same as add_ensure_iseq, except it compiled
4628// the node as a Prism node, and not a CRuby node
4629static void
4630pm_add_ensure_iseq(LINK_ANCHOR *const ret, rb_iseq_t *iseq, int is_return, pm_scope_node_t *scope_node)
4631{
4632 RUBY_ASSERT(can_add_ensure_iseq(iseq));
4633
4635 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack;
4636 struct iseq_compile_data_ensure_node_stack *prev_enlp = enlp;
4637 DECL_ANCHOR(ensure);
4638
4639 while (enlp) {
4640 if (enlp->erange != NULL) {
4641 DECL_ANCHOR(ensure_part);
4642 LABEL *lstart = NEW_LABEL(0);
4643 LABEL *lend = NEW_LABEL(0);
4644
4645 add_ensure_range(iseq, enlp->erange, lstart, lend);
4646
4647 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enlp->prev;
4648 PUSH_LABEL(ensure_part, lstart);
4649 bool popped = true;
4650 PM_COMPILE_INTO_ANCHOR(ensure_part, (const pm_node_t *) enlp->ensure_node);
4651 PUSH_LABEL(ensure_part, lend);
4652 PUSH_SEQ(ensure, ensure_part);
4653 }
4654 else {
4655 if (!is_return) {
4656 break;
4657 }
4658 }
4659 enlp = enlp->prev;
4660 }
4661 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = prev_enlp;
4662 PUSH_SEQ(ret, ensure);
4663}
4664
4666 pm_scope_node_t *scope_node;
4667 rb_ast_id_table_t *local_table_for_iseq;
4668 int local_index;
4669};
4670
4671static int
4672pm_local_table_insert_func(st_data_t *key, st_data_t *value, st_data_t arg, int existing)
4673{
4674 if (!existing) {
4675 pm_constant_id_t constant_id = (pm_constant_id_t) *key;
4676 struct pm_local_table_insert_ctx * ctx = (struct pm_local_table_insert_ctx *) arg;
4677
4678 pm_scope_node_t *scope_node = ctx->scope_node;
4679 rb_ast_id_table_t *local_table_for_iseq = ctx->local_table_for_iseq;
4680 int local_index = ctx->local_index;
4681
4682 ID local = pm_constant_id_lookup(scope_node, constant_id);
4683 local_table_for_iseq->ids[local_index] = local;
4684
4685 *value = (st_data_t)local_index;
4686
4687 ctx->local_index++;
4688 }
4689
4690 return ST_CONTINUE;
4691}
4692
4698static void
4699pm_insert_local_index(pm_constant_id_t constant_id, int local_index, st_table *index_lookup_table, rb_ast_id_table_t *local_table_for_iseq, pm_scope_node_t *scope_node)
4700{
4701 RUBY_ASSERT((constant_id & PM_SPECIAL_CONSTANT_FLAG) == 0);
4702
4703 ID local = pm_constant_id_lookup(scope_node, constant_id);
4704 local_table_for_iseq->ids[local_index] = local;
4705 st_insert(index_lookup_table, (st_data_t) constant_id, (st_data_t) local_index);
4706}
4707
4712static void
4713pm_insert_local_special(ID local_name, int local_index, st_table *index_lookup_table, rb_ast_id_table_t *local_table_for_iseq)
4714{
4715 local_table_for_iseq->ids[local_index] = local_name;
4716 st_insert(index_lookup_table, (st_data_t) (local_name | PM_SPECIAL_CONSTANT_FLAG), (st_data_t) local_index);
4717}
4718
4725static int
4726pm_compile_destructured_param_locals(const pm_multi_target_node_t *node, st_table *index_lookup_table, rb_ast_id_table_t *local_table_for_iseq, pm_scope_node_t *scope_node, int local_index)
4727{
4728 for (size_t index = 0; index < node->lefts.size; index++) {
4729 const pm_node_t *left = node->lefts.nodes[index];
4730
4731 if (PM_NODE_TYPE_P(left, PM_REQUIRED_PARAMETER_NODE)) {
4732 if (!PM_NODE_FLAG_P(left, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
4733 pm_insert_local_index(((const pm_required_parameter_node_t *) left)->name, local_index, index_lookup_table, local_table_for_iseq, scope_node);
4734 local_index++;
4735 }
4736 }
4737 else {
4738 RUBY_ASSERT(PM_NODE_TYPE_P(left, PM_MULTI_TARGET_NODE));
4739 local_index = pm_compile_destructured_param_locals((const pm_multi_target_node_t *) left, index_lookup_table, local_table_for_iseq, scope_node, local_index);
4740 }
4741 }
4742
4743 if (node->rest != NULL && PM_NODE_TYPE_P(node->rest, PM_SPLAT_NODE)) {
4744 const pm_splat_node_t *rest = (const pm_splat_node_t *) node->rest;
4745
4746 if (rest->expression != NULL) {
4747 RUBY_ASSERT(PM_NODE_TYPE_P(rest->expression, PM_REQUIRED_PARAMETER_NODE));
4748
4749 if (!PM_NODE_FLAG_P(rest->expression, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
4750 pm_insert_local_index(((const pm_required_parameter_node_t *) rest->expression)->name, local_index, index_lookup_table, local_table_for_iseq, scope_node);
4751 local_index++;
4752 }
4753 }
4754 }
4755
4756 for (size_t index = 0; index < node->rights.size; index++) {
4757 const pm_node_t *right = node->rights.nodes[index];
4758
4759 if (PM_NODE_TYPE_P(right, PM_REQUIRED_PARAMETER_NODE)) {
4760 if (!PM_NODE_FLAG_P(right, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
4761 pm_insert_local_index(((const pm_required_parameter_node_t *) right)->name, local_index, index_lookup_table, local_table_for_iseq, scope_node);
4762 local_index++;
4763 }
4764 }
4765 else {
4766 RUBY_ASSERT(PM_NODE_TYPE_P(right, PM_MULTI_TARGET_NODE));
4767 local_index = pm_compile_destructured_param_locals((const pm_multi_target_node_t *) right, index_lookup_table, local_table_for_iseq, scope_node, local_index);
4768 }
4769 }
4770
4771 return local_index;
4772}
4773
4778static inline void
4779pm_compile_destructured_param_write(rb_iseq_t *iseq, const pm_required_parameter_node_t *node, LINK_ANCHOR *const ret, const pm_scope_node_t *scope_node)
4780{
4781 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
4782 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, node->name, 0);
4783 PUSH_SETLOCAL(ret, location, index.index, index.level);
4784}
4785
4794static void
4795pm_compile_destructured_param_writes(rb_iseq_t *iseq, const pm_multi_target_node_t *node, LINK_ANCHOR *const ret, const pm_scope_node_t *scope_node)
4796{
4797 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
4798 bool has_rest = (node->rest && PM_NODE_TYPE_P(node->rest, PM_SPLAT_NODE) && (((const pm_splat_node_t *) node->rest)->expression) != NULL);
4799 bool has_rights = node->rights.size > 0;
4800
4801 int flag = (has_rest || has_rights) ? 1 : 0;
4802 PUSH_INSN2(ret, location, expandarray, INT2FIX(node->lefts.size), INT2FIX(flag));
4803
4804 for (size_t index = 0; index < node->lefts.size; index++) {
4805 const pm_node_t *left = node->lefts.nodes[index];
4806
4807 if (PM_NODE_TYPE_P(left, PM_REQUIRED_PARAMETER_NODE)) {
4808 pm_compile_destructured_param_write(iseq, (const pm_required_parameter_node_t *) left, ret, scope_node);
4809 }
4810 else {
4811 RUBY_ASSERT(PM_NODE_TYPE_P(left, PM_MULTI_TARGET_NODE));
4812 pm_compile_destructured_param_writes(iseq, (const pm_multi_target_node_t *) left, ret, scope_node);
4813 }
4814 }
4815
4816 if (has_rest) {
4817 if (has_rights) {
4818 PUSH_INSN2(ret, location, expandarray, INT2FIX(node->rights.size), INT2FIX(3));
4819 }
4820
4821 const pm_node_t *rest = ((const pm_splat_node_t *) node->rest)->expression;
4822 RUBY_ASSERT(PM_NODE_TYPE_P(rest, PM_REQUIRED_PARAMETER_NODE));
4823
4824 pm_compile_destructured_param_write(iseq, (const pm_required_parameter_node_t *) rest, ret, scope_node);
4825 }
4826
4827 if (has_rights) {
4828 if (!has_rest) {
4829 PUSH_INSN2(ret, location, expandarray, INT2FIX(node->rights.size), INT2FIX(2));
4830 }
4831
4832 for (size_t index = 0; index < node->rights.size; index++) {
4833 const pm_node_t *right = node->rights.nodes[index];
4834
4835 if (PM_NODE_TYPE_P(right, PM_REQUIRED_PARAMETER_NODE)) {
4836 pm_compile_destructured_param_write(iseq, (const pm_required_parameter_node_t *) right, ret, scope_node);
4837 }
4838 else {
4839 RUBY_ASSERT(PM_NODE_TYPE_P(right, PM_MULTI_TARGET_NODE));
4840 pm_compile_destructured_param_writes(iseq, (const pm_multi_target_node_t *) right, ret, scope_node);
4841 }
4842 }
4843 }
4844}
4845
4851 // The pointer to the topn instruction that will need to be modified after
4852 // we know the total stack size of all of the targets.
4853 INSN *topn;
4854
4855 // The index of the stack from the base of the entire multi target at which
4856 // the parent expression is located.
4857 size_t stack_index;
4858
4859 // The number of slots in the stack that this node occupies.
4860 size_t stack_size;
4861
4862 // The position of the node in the list of targets.
4863 size_t position;
4864
4865 // A pointer to the next node in this linked list.
4866 struct pm_multi_target_state_node *next;
4867} pm_multi_target_state_node_t;
4868
4876typedef struct {
4877 // The total number of slots in the stack that this multi target occupies.
4878 size_t stack_size;
4879
4880 // The position of the current node being compiled. This is forwarded to
4881 // nodes when they are allocated.
4882 size_t position;
4883
4884 // A pointer to the head of this linked list.
4885 pm_multi_target_state_node_t *head;
4886
4887 // A pointer to the tail of this linked list.
4888 pm_multi_target_state_node_t *tail;
4890
4894static void
4895pm_multi_target_state_push(pm_multi_target_state_t *state, INSN *topn, size_t stack_size)
4896{
4897 pm_multi_target_state_node_t *node = ALLOC(pm_multi_target_state_node_t);
4898 node->topn = topn;
4899 node->stack_index = state->stack_size + 1;
4900 node->stack_size = stack_size;
4901 node->position = state->position;
4902 node->next = NULL;
4903
4904 if (state->head == NULL) {
4905 state->head = node;
4906 state->tail = node;
4907 }
4908 else {
4909 state->tail->next = node;
4910 state->tail = node;
4911 }
4912
4913 state->stack_size += stack_size;
4914}
4915
4921static void
4922pm_multi_target_state_update(pm_multi_target_state_t *state)
4923{
4924 // If nothing was ever pushed onto the stack, then we don't need to do any
4925 // kind of updates.
4926 if (state->stack_size == 0) return;
4927
4928 pm_multi_target_state_node_t *current = state->head;
4929 pm_multi_target_state_node_t *previous;
4930
4931 while (current != NULL) {
4932 VALUE offset = INT2FIX(state->stack_size - current->stack_index + current->position);
4933 current->topn->operands[0] = offset;
4934
4935 // stack_size will be > 1 in the case that we compiled an index target
4936 // and it had arguments. In this case, we use multiple topn instructions
4937 // to grab up all of the arguments as well, so those offsets need to be
4938 // updated as well.
4939 if (current->stack_size > 1) {
4940 INSN *insn = current->topn;
4941
4942 for (size_t index = 1; index < current->stack_size; index += 1) {
4943 LINK_ELEMENT *element = get_next_insn(insn);
4944 RUBY_ASSERT(IS_INSN(element));
4945
4946 insn = (INSN *) element;
4947 RUBY_ASSERT(insn->insn_id == BIN(topn));
4948
4949 insn->operands[0] = offset;
4950 }
4951 }
4952
4953 previous = current;
4954 current = current->next;
4955
4956 xfree(previous);
4957 }
4958}
4959
4960static void
4961pm_compile_multi_target_node(rb_iseq_t *iseq, const pm_node_t *node, LINK_ANCHOR *const parents, LINK_ANCHOR *const writes, LINK_ANCHOR *const cleanup, pm_scope_node_t *scope_node, pm_multi_target_state_t *state);
4962
4991static void
4992pm_compile_target_node(rb_iseq_t *iseq, const pm_node_t *node, LINK_ANCHOR *const parents, LINK_ANCHOR *const writes, LINK_ANCHOR *const cleanup, pm_scope_node_t *scope_node, pm_multi_target_state_t *state)
4993{
4994 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
4995
4996 switch (PM_NODE_TYPE(node)) {
4997 case PM_LOCAL_VARIABLE_TARGET_NODE: {
4998 // Local variable targets have no parent expression, so they only need
4999 // to compile the write.
5000 //
5001 // for i in []; end
5002 //
5003 const pm_local_variable_target_node_t *cast = (const pm_local_variable_target_node_t *) node;
5004 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, cast->name, cast->depth);
5005
5006 PUSH_SETLOCAL(writes, location, index.index, index.level);
5007 break;
5008 }
5009 case PM_CLASS_VARIABLE_TARGET_NODE: {
5010 // Class variable targets have no parent expression, so they only need
5011 // to compile the write.
5012 //
5013 // for @@i in []; end
5014 //
5015 const pm_class_variable_target_node_t *cast = (const pm_class_variable_target_node_t *) node;
5016 ID name = pm_constant_id_lookup(scope_node, cast->name);
5017
5018 VALUE operand = ID2SYM(name);
5019 PUSH_INSN2(writes, location, setclassvariable, operand, get_cvar_ic_value(iseq, name));
5020 break;
5021 }
5022 case PM_CONSTANT_TARGET_NODE: {
5023 // Constant targets have no parent expression, so they only need to
5024 // compile the write.
5025 //
5026 // for I in []; end
5027 //
5028 const pm_constant_target_node_t *cast = (const pm_constant_target_node_t *) node;
5029 ID name = pm_constant_id_lookup(scope_node, cast->name);
5030
5031 VALUE operand = ID2SYM(name);
5032 PUSH_INSN1(writes, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE));
5033 PUSH_INSN1(writes, location, setconstant, operand);
5034 break;
5035 }
5036 case PM_GLOBAL_VARIABLE_TARGET_NODE: {
5037 // Global variable targets have no parent expression, so they only need
5038 // to compile the write.
5039 //
5040 // for $i in []; end
5041 //
5042 const pm_global_variable_target_node_t *cast = (const pm_global_variable_target_node_t *) node;
5043 ID name = pm_constant_id_lookup(scope_node, cast->name);
5044
5045 VALUE operand = ID2SYM(name);
5046 PUSH_INSN1(writes, location, setglobal, operand);
5047 break;
5048 }
5049 case PM_INSTANCE_VARIABLE_TARGET_NODE: {
5050 // Instance variable targets have no parent expression, so they only
5051 // need to compile the write.
5052 //
5053 // for @i in []; end
5054 //
5055 const pm_instance_variable_target_node_t *cast = (const pm_instance_variable_target_node_t *) node;
5056 ID name = pm_constant_id_lookup(scope_node, cast->name);
5057
5058 VALUE operand = ID2SYM(name);
5059 PUSH_INSN2(writes, location, setinstancevariable, operand, get_ivar_ic_value(iseq, name));
5060 break;
5061 }
5062 case PM_CONSTANT_PATH_TARGET_NODE: {
5063 // Constant path targets have a parent expression that is the object
5064 // that owns the constant. This needs to be compiled first into the
5065 // parents sequence. If no parent is found, then it represents using the
5066 // unary :: operator to indicate a top-level constant. In that case we
5067 // need to push Object onto the stack.
5068 //
5069 // for I::J in []; end
5070 //
5071 const pm_constant_path_target_node_t *cast = (const pm_constant_path_target_node_t *) node;
5072 ID name = pm_constant_id_lookup(scope_node, cast->name);
5073
5074 if (cast->parent != NULL) {
5075 pm_compile_node(iseq, cast->parent, parents, false, scope_node);
5076 }
5077 else {
5078 PUSH_INSN1(parents, location, putobject, rb_cObject);
5079 }
5080
5081 if (state == NULL) {
5082 PUSH_INSN(writes, location, swap);
5083 }
5084 else {
5085 PUSH_INSN1(writes, location, topn, INT2FIX(1));
5086 pm_multi_target_state_push(state, (INSN *) LAST_ELEMENT(writes), 1);
5087 }
5088
5089 VALUE operand = ID2SYM(name);
5090 PUSH_INSN1(writes, location, setconstant, operand);
5091
5092 if (state != NULL) {
5093 PUSH_INSN(cleanup, location, pop);
5094 }
5095
5096 break;
5097 }
5098 case PM_CALL_TARGET_NODE: {
5099 // Call targets have a parent expression that is the receiver of the
5100 // method being called. This needs to be compiled first into the parents
5101 // sequence. These nodes cannot have arguments, so the method call is
5102 // compiled with a single argument which represents the value being
5103 // written.
5104 //
5105 // for i.j in []; end
5106 //
5107 const pm_call_target_node_t *cast = (const pm_call_target_node_t *) node;
5108 ID method_id = pm_constant_id_lookup(scope_node, cast->name);
5109
5110 pm_compile_node(iseq, cast->receiver, parents, false, scope_node);
5111
5112 LABEL *safe_label = NULL;
5113 if (PM_NODE_FLAG_P(cast, PM_CALL_NODE_FLAGS_SAFE_NAVIGATION)) {
5114 safe_label = NEW_LABEL(location.line);
5115 PUSH_INSN(parents, location, dup);
5116 PUSH_INSNL(parents, location, branchnil, safe_label);
5117 }
5118
5119 if (state != NULL) {
5120 PUSH_INSN1(writes, location, topn, INT2FIX(1));
5121 pm_multi_target_state_push(state, (INSN *) LAST_ELEMENT(writes), 1);
5122 PUSH_INSN(writes, location, swap);
5123 }
5124
5125 int flags = VM_CALL_ARGS_SIMPLE;
5126 if (PM_NODE_FLAG_P(cast, PM_CALL_NODE_FLAGS_IGNORE_VISIBILITY)) flags |= VM_CALL_FCALL;
5127
5128 PUSH_SEND_WITH_FLAG(writes, location, method_id, INT2FIX(1), INT2FIX(flags));
5129 if (safe_label != NULL && state == NULL) PUSH_LABEL(writes, safe_label);
5130 PUSH_INSN(writes, location, pop);
5131 if (safe_label != NULL && state != NULL) PUSH_LABEL(writes, safe_label);
5132
5133 if (state != NULL) {
5134 PUSH_INSN(cleanup, location, pop);
5135 }
5136
5137 break;
5138 }
5139 case PM_INDEX_TARGET_NODE: {
5140 // Index targets have a parent expression that is the receiver of the
5141 // method being called and any additional arguments that are being
5142 // passed along with the value being written. The receiver and arguments
5143 // both need to be on the stack. Note that this is even more complicated
5144 // by the fact that these nodes can hold a block using the unary &
5145 // operator.
5146 //
5147 // for i[:j] in []; end
5148 //
5149 const pm_index_target_node_t *cast = (const pm_index_target_node_t *) node;
5150
5151 pm_compile_node(iseq, cast->receiver, parents, false, scope_node);
5152
5153 int flags = 0;
5154 struct rb_callinfo_kwarg *kwargs = NULL;
5155 int argc = pm_setup_args(cast->arguments, (const pm_node_t *) cast->block, &flags, &kwargs, iseq, parents, scope_node, &location);
5156
5157 if (state != NULL) {
5158 PUSH_INSN1(writes, location, topn, INT2FIX(argc + 1));
5159 pm_multi_target_state_push(state, (INSN *) LAST_ELEMENT(writes), argc + 1);
5160
5161 if (argc == 0) {
5162 PUSH_INSN(writes, location, swap);
5163 }
5164 else {
5165 for (int index = 0; index < argc; index++) {
5166 PUSH_INSN1(writes, location, topn, INT2FIX(argc + 1));
5167 }
5168 PUSH_INSN1(writes, location, topn, INT2FIX(argc + 1));
5169 }
5170 }
5171
5172 // The argc that we're going to pass to the send instruction is the
5173 // number of arguments + 1 for the value being written. If there's a
5174 // splat, then we need to insert newarray and concatarray instructions
5175 // after the arguments have been written.
5176 int ci_argc = argc + 1;
5177 if (flags & VM_CALL_ARGS_SPLAT) {
5178 ci_argc--;
5179 PUSH_INSN1(writes, location, newarray, INT2FIX(1));
5180 PUSH_INSN(writes, location, concatarray);
5181 }
5182
5183 PUSH_SEND_R(writes, location, idASET, INT2NUM(ci_argc), NULL, INT2FIX(flags), kwargs);
5184 PUSH_INSN(writes, location, pop);
5185
5186 if (state != NULL) {
5187 if (argc != 0) {
5188 PUSH_INSN(writes, location, pop);
5189 }
5190
5191 for (int index = 0; index < argc + 1; index++) {
5192 PUSH_INSN(cleanup, location, pop);
5193 }
5194 }
5195
5196 break;
5197 }
5198 case PM_MULTI_TARGET_NODE: {
5199 // Multi target nodes represent a set of writes to multiple variables.
5200 // The parent expressions are the combined set of the parent expressions
5201 // of its inner target nodes.
5202 //
5203 // for i, j in []; end
5204 //
5205 size_t before_position;
5206 if (state != NULL) {
5207 before_position = state->position;
5208 state->position--;
5209 }
5210
5211 pm_compile_multi_target_node(iseq, node, parents, writes, cleanup, scope_node, state);
5212 if (state != NULL) state->position = before_position;
5213
5214 break;
5215 }
5216 case PM_SPLAT_NODE: {
5217 // Splat nodes capture all values into an array. They can be used
5218 // as targets in assignments or for loops.
5219 //
5220 // for *x in []; end
5221 //
5222 const pm_splat_node_t *cast = (const pm_splat_node_t *) node;
5223
5224 if (cast->expression != NULL) {
5225 pm_compile_target_node(iseq, cast->expression, parents, writes, cleanup, scope_node, state);
5226 }
5227
5228 break;
5229 }
5230 default:
5231 rb_bug("Unexpected node type: %s", pm_node_type_to_str(PM_NODE_TYPE(node)));
5232 break;
5233 }
5234}
5235
5241static void
5242pm_compile_multi_target_node(rb_iseq_t *iseq, const pm_node_t *node, LINK_ANCHOR *const parents, LINK_ANCHOR *const writes, LINK_ANCHOR *const cleanup, pm_scope_node_t *scope_node, pm_multi_target_state_t *state)
5243{
5244 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
5245 const pm_node_list_t *lefts;
5246 const pm_node_t *rest;
5247 const pm_node_list_t *rights;
5248
5249 switch (PM_NODE_TYPE(node)) {
5250 case PM_MULTI_TARGET_NODE: {
5251 const pm_multi_target_node_t *cast = (const pm_multi_target_node_t *) node;
5252 lefts = &cast->lefts;
5253 rest = cast->rest;
5254 rights = &cast->rights;
5255 break;
5256 }
5257 case PM_MULTI_WRITE_NODE: {
5258 const pm_multi_write_node_t *cast = (const pm_multi_write_node_t *) node;
5259 lefts = &cast->lefts;
5260 rest = cast->rest;
5261 rights = &cast->rights;
5262 break;
5263 }
5264 default:
5265 rb_bug("Unsupported node %s", pm_node_type_to_str(PM_NODE_TYPE(node)));
5266 break;
5267 }
5268
5269 bool has_rest = (rest != NULL) && PM_NODE_TYPE_P(rest, PM_SPLAT_NODE) && ((const pm_splat_node_t *) rest)->expression != NULL;
5270 bool has_posts = rights->size > 0;
5271
5272 // The first instruction in the writes sequence is going to spread the
5273 // top value of the stack onto the number of values that we're going to
5274 // write.
5275 PUSH_INSN2(writes, location, expandarray, INT2FIX(lefts->size), INT2FIX((has_rest || has_posts) ? 1 : 0));
5276
5277 // We need to keep track of some additional state information as we're
5278 // going through the targets because we will need to revisit them once
5279 // we know how many values are being pushed onto the stack.
5280 pm_multi_target_state_t target_state = { 0 };
5281 if (state == NULL) state = &target_state;
5282
5283 size_t base_position = state->position;
5284 size_t splat_position = (has_rest || has_posts) ? 1 : 0;
5285
5286 // Next, we'll iterate through all of the leading targets.
5287 for (size_t index = 0; index < lefts->size; index++) {
5288 const pm_node_t *target = lefts->nodes[index];
5289 state->position = lefts->size - index + splat_position + base_position;
5290 pm_compile_target_node(iseq, target, parents, writes, cleanup, scope_node, state);
5291 }
5292
5293 // Next, we'll compile the rest target if there is one.
5294 if (has_rest) {
5295 const pm_node_t *target = ((const pm_splat_node_t *) rest)->expression;
5296 state->position = 1 + rights->size + base_position;
5297
5298 if (has_posts) {
5299 PUSH_INSN2(writes, location, expandarray, INT2FIX(rights->size), INT2FIX(3));
5300 }
5301
5302 pm_compile_target_node(iseq, target, parents, writes, cleanup, scope_node, state);
5303 }
5304
5305 // Finally, we'll compile the trailing targets.
5306 if (has_posts) {
5307 if (!has_rest && rest != NULL) {
5308 PUSH_INSN2(writes, location, expandarray, INT2FIX(rights->size), INT2FIX(2));
5309 }
5310
5311 for (size_t index = 0; index < rights->size; index++) {
5312 const pm_node_t *target = rights->nodes[index];
5313 state->position = rights->size - index + base_position;
5314 pm_compile_target_node(iseq, target, parents, writes, cleanup, scope_node, state);
5315 }
5316 }
5317}
5318
5324static void
5325pm_compile_for_node_index(rb_iseq_t *iseq, const pm_node_t *node, LINK_ANCHOR *const ret, pm_scope_node_t *scope_node)
5326{
5327 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
5328
5329 switch (PM_NODE_TYPE(node)) {
5330 case PM_LOCAL_VARIABLE_TARGET_NODE: {
5331 // For local variables, all we have to do is retrieve the value and then
5332 // compile the index node.
5333 PUSH_GETLOCAL(ret, location, 1, 0);
5334 pm_compile_target_node(iseq, node, ret, ret, ret, scope_node, NULL);
5335 break;
5336 }
5337 case PM_CLASS_VARIABLE_TARGET_NODE:
5338 case PM_CONSTANT_TARGET_NODE:
5339 case PM_GLOBAL_VARIABLE_TARGET_NODE:
5340 case PM_INSTANCE_VARIABLE_TARGET_NODE:
5341 case PM_CONSTANT_PATH_TARGET_NODE:
5342 case PM_CALL_TARGET_NODE:
5343 case PM_INDEX_TARGET_NODE: {
5344 // For other targets, we need to potentially compile the parent or
5345 // owning expression of this target, then retrieve the value, expand it,
5346 // and then compile the necessary writes.
5347 DECL_ANCHOR(writes);
5348 DECL_ANCHOR(cleanup);
5349
5350 pm_multi_target_state_t state = { 0 };
5351 state.position = 1;
5352 pm_compile_target_node(iseq, node, ret, writes, cleanup, scope_node, &state);
5353
5354 PUSH_GETLOCAL(ret, location, 1, 0);
5355 PUSH_INSN2(ret, location, expandarray, INT2FIX(1), INT2FIX(0));
5356
5357 PUSH_SEQ(ret, writes);
5358 PUSH_SEQ(ret, cleanup);
5359
5360 pm_multi_target_state_update(&state);
5361 break;
5362 }
5363 case PM_SPLAT_NODE:
5364 case PM_MULTI_TARGET_NODE: {
5365 DECL_ANCHOR(writes);
5366 DECL_ANCHOR(cleanup);
5367
5368 pm_compile_target_node(iseq, node, ret, writes, cleanup, scope_node, NULL);
5369
5370 LABEL *not_single = NEW_LABEL(location.line);
5371 LABEL *not_ary = NEW_LABEL(location.line);
5372
5373 // When there are multiple targets, we'll do a bunch of work to convert
5374 // the value into an array before we expand it. Effectively we're trying
5375 // to accomplish:
5376 //
5377 // (args.length == 1 && Array.try_convert(args[0])) || args
5378 //
5379 PUSH_GETLOCAL(ret, location, 1, 0);
5380 PUSH_INSN(ret, location, dup);
5381 PUSH_CALL(ret, location, idLength, INT2FIX(0));
5382 PUSH_INSN1(ret, location, putobject, INT2FIX(1));
5383 PUSH_CALL(ret, location, idEq, INT2FIX(1));
5384 PUSH_INSNL(ret, location, branchunless, not_single);
5385 PUSH_INSN(ret, location, dup);
5386 PUSH_INSN1(ret, location, putobject, INT2FIX(0));
5387 PUSH_CALL(ret, location, idAREF, INT2FIX(1));
5388 PUSH_INSN1(ret, location, putobject, rb_cArray);
5389 PUSH_INSN(ret, location, swap);
5390 PUSH_CALL(ret, location, rb_intern("try_convert"), INT2FIX(1));
5391 PUSH_INSN(ret, location, dup);
5392 PUSH_INSNL(ret, location, branchunless, not_ary);
5393 PUSH_INSN(ret, location, swap);
5394
5395 PUSH_LABEL(ret, not_ary);
5396 PUSH_INSN(ret, location, pop);
5397
5398 PUSH_LABEL(ret, not_single);
5399
5400 if (PM_NODE_TYPE_P(node, PM_SPLAT_NODE)) {
5401 const pm_splat_node_t *cast = (const pm_splat_node_t *) node;
5402 PUSH_INSN2(ret, location, expandarray, INT2FIX(0), INT2FIX(cast->expression == NULL ? 0 : 1));
5403 }
5404
5405 PUSH_SEQ(ret, writes);
5406 PUSH_SEQ(ret, cleanup);
5407 break;
5408 }
5409 default:
5410 rb_bug("Unexpected node type for index in for node: %s", pm_node_type_to_str(PM_NODE_TYPE(node)));
5411 break;
5412 }
5413}
5414
5415static void
5416pm_compile_rescue(rb_iseq_t *iseq, const pm_begin_node_t *cast, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
5417{
5418 const pm_parser_t *parser = scope_node->parser;
5419
5420 LABEL *lstart = NEW_LABEL(node_location->line);
5421 LABEL *lend = NEW_LABEL(node_location->line);
5422 LABEL *lcont = NEW_LABEL(node_location->line);
5423
5424 pm_scope_node_t rescue_scope_node;
5425 pm_scope_node_init((const pm_node_t *) cast->rescue_clause, &rescue_scope_node, scope_node);
5426
5427 rb_iseq_t *rescue_iseq = NEW_CHILD_ISEQ(
5428 &rescue_scope_node,
5429 rb_str_concat(rb_str_new2("rescue in "), ISEQ_BODY(iseq)->location.label),
5430 ISEQ_TYPE_RESCUE,
5431 pm_node_line_number(parser, (const pm_node_t *) cast->rescue_clause)
5432 );
5433
5434 pm_scope_node_destroy(&rescue_scope_node);
5435
5436 lstart->rescued = LABEL_RESCUE_BEG;
5437 lend->rescued = LABEL_RESCUE_END;
5438 PUSH_LABEL(ret, lstart);
5439
5440 bool prev_in_rescue = ISEQ_COMPILE_DATA(iseq)->in_rescue;
5441 ISEQ_COMPILE_DATA(iseq)->in_rescue = true;
5442
5443 if (cast->statements != NULL) {
5444 PM_COMPILE_NOT_POPPED((const pm_node_t *) cast->statements);
5445 }
5446 else {
5447 const pm_node_location_t location = PM_NODE_START_LOCATION(parser, cast->rescue_clause);
5448 PUSH_INSN(ret, location, putnil);
5449 }
5450
5451 ISEQ_COMPILE_DATA(iseq)->in_rescue = prev_in_rescue;
5452 PUSH_LABEL(ret, lend);
5453
5454 if (cast->else_clause != NULL) {
5455 if (!popped) PUSH_INSN(ret, *node_location, pop);
5456 PM_COMPILE((const pm_node_t *) cast->else_clause);
5457 }
5458
5459 PUSH_INSN(ret, *node_location, nop);
5460 PUSH_LABEL(ret, lcont);
5461
5462 if (popped) PUSH_INSN(ret, *node_location, pop);
5463 PUSH_CATCH_ENTRY(CATCH_TYPE_RESCUE, lstart, lend, rescue_iseq, lcont);
5464 PUSH_CATCH_ENTRY(CATCH_TYPE_RETRY, lend, lcont, NULL, lstart);
5465}
5466
5467static void
5468pm_compile_ensure(rb_iseq_t *iseq, const pm_begin_node_t *cast, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
5469{
5470 const pm_parser_t *parser = scope_node->parser;
5471 const pm_statements_node_t *statements = cast->ensure_clause->statements;
5472
5473 pm_node_location_t location;
5474 if (statements != NULL) {
5475 location = PM_NODE_START_LOCATION(parser, statements);
5476 }
5477 else {
5478 location = *node_location;
5479 }
5480
5481 LABEL *lstart = NEW_LABEL(location.line);
5482 LABEL *lend = NEW_LABEL(location.line);
5483 LABEL *lcont = NEW_LABEL(location.line);
5484
5485 struct ensure_range er;
5487 struct ensure_range *erange;
5488
5489 DECL_ANCHOR(ensr);
5490 if (statements != NULL) {
5491 pm_compile_node(iseq, (const pm_node_t *) statements, ensr, true, scope_node);
5492 }
5493
5494 LINK_ELEMENT *last = ensr->last;
5495 bool last_leave = last && IS_INSN(last) && IS_INSN_ID(last, leave);
5496
5497 er.begin = lstart;
5498 er.end = lend;
5499 er.next = 0;
5500 push_ensure_entry(iseq, &enl, &er, (void *) cast->ensure_clause);
5501
5502 PUSH_LABEL(ret, lstart);
5503 if (cast->rescue_clause != NULL) {
5504 pm_compile_rescue(iseq, cast, node_location, ret, popped | last_leave, scope_node);
5505 }
5506 else if (cast->statements != NULL) {
5507 pm_compile_node(iseq, (const pm_node_t *) cast->statements, ret, popped | last_leave, scope_node);
5508 }
5509 else if (!(popped | last_leave)) {
5510 PUSH_SYNTHETIC_PUTNIL(ret, iseq);
5511 }
5512
5513 PUSH_LABEL(ret, lend);
5514 PUSH_SEQ(ret, ensr);
5515 if (!popped && last_leave) PUSH_INSN(ret, *node_location, putnil);
5516 PUSH_LABEL(ret, lcont);
5517 if (last_leave) PUSH_INSN(ret, *node_location, pop);
5518
5519 pm_scope_node_t next_scope_node;
5520 pm_scope_node_init((const pm_node_t *) cast->ensure_clause, &next_scope_node, scope_node);
5521
5522 rb_iseq_t *child_iseq = NEW_CHILD_ISEQ(
5523 &next_scope_node,
5524 rb_str_concat(rb_str_new2("ensure in "), ISEQ_BODY(iseq)->location.label),
5525 ISEQ_TYPE_ENSURE,
5526 location.line
5527 );
5528
5529 pm_scope_node_destroy(&next_scope_node);
5530
5531 erange = ISEQ_COMPILE_DATA(iseq)->ensure_node_stack->erange;
5532 if (lstart->link.next != &lend->link) {
5533 while (erange) {
5534 PUSH_CATCH_ENTRY(CATCH_TYPE_ENSURE, erange->begin, erange->end, child_iseq, lcont);
5535 erange = erange->next;
5536 }
5537 }
5538 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enl.prev;
5539}
5540
5545static inline bool
5546pm_opt_str_freeze_p(const rb_iseq_t *iseq, const pm_call_node_t *node)
5547{
5548 return (
5549 !PM_NODE_FLAG_P(node, PM_CALL_NODE_FLAGS_SAFE_NAVIGATION) &&
5550 node->receiver != NULL &&
5551 PM_NODE_TYPE_P(node->receiver, PM_STRING_NODE) &&
5552 node->arguments == NULL &&
5553 node->block == NULL &&
5554 ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction
5555 );
5556}
5557
5562static void
5563pm_compile_constant_read(rb_iseq_t *iseq, VALUE name, const pm_location_t *name_loc, uint32_t node_id, LINK_ANCHOR *const ret, const pm_scope_node_t *scope_node)
5564{
5565 const pm_node_location_t location = PM_LOCATION_START_LOCATION(scope_node->parser, name_loc, node_id);
5566
5567 if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) {
5568 ISEQ_BODY(iseq)->ic_size++;
5569 VALUE segments = rb_ary_new_from_args(1, name);
5570 RB_OBJ_SET_SHAREABLE(segments);
5571 PUSH_INSN1(ret, location, opt_getconstant_path, segments);
5572 }
5573 else {
5574 PUSH_INSN(ret, location, putnil);
5575 PUSH_INSN1(ret, location, putobject, Qtrue);
5576 PUSH_INSN1(ret, location, getconstant, name);
5577 }
5578}
5579
5584static VALUE
5585pm_constant_path_parts(const pm_node_t *node, const pm_scope_node_t *scope_node)
5586{
5587 VALUE parts = rb_ary_new();
5588
5589 while (true) {
5590 switch (PM_NODE_TYPE(node)) {
5591 case PM_CONSTANT_READ_NODE: {
5592 const pm_constant_read_node_t *cast = (const pm_constant_read_node_t *) node;
5593 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, cast->name));
5594
5595 rb_ary_unshift(parts, name);
5596 return parts;
5597 }
5598 case PM_CONSTANT_PATH_NODE: {
5599 const pm_constant_path_node_t *cast = (const pm_constant_path_node_t *) node;
5600 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, cast->name));
5601
5602 rb_ary_unshift(parts, name);
5603 if (cast->parent == NULL) {
5604 rb_ary_unshift(parts, ID2SYM(idNULL));
5605 return parts;
5606 }
5607
5608 node = cast->parent;
5609 break;
5610 }
5611 default:
5612 return Qnil;
5613 }
5614 }
5615}
5616
5622static void
5623pm_compile_constant_path(rb_iseq_t *iseq, const pm_node_t *node, LINK_ANCHOR *const prefix, LINK_ANCHOR *const body, bool popped, pm_scope_node_t *scope_node)
5624{
5625 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
5626
5627 switch (PM_NODE_TYPE(node)) {
5628 case PM_CONSTANT_READ_NODE: {
5629 const pm_constant_read_node_t *cast = (const pm_constant_read_node_t *) node;
5630 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, cast->name));
5631
5632 PUSH_INSN1(body, location, putobject, Qtrue);
5633 PUSH_INSN1(body, location, getconstant, name);
5634 break;
5635 }
5636 case PM_CONSTANT_PATH_NODE: {
5637 const pm_constant_path_node_t *cast = (const pm_constant_path_node_t *) node;
5638 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, cast->name));
5639
5640 if (cast->parent == NULL) {
5641 PUSH_INSN(body, location, pop);
5642 PUSH_INSN1(body, location, putobject, rb_cObject);
5643 PUSH_INSN1(body, location, putobject, Qtrue);
5644 PUSH_INSN1(body, location, getconstant, name);
5645 }
5646 else {
5647 pm_compile_constant_path(iseq, cast->parent, prefix, body, false, scope_node);
5648 PUSH_INSN1(body, location, putobject, Qfalse);
5649 PUSH_INSN1(body, location, getconstant, name);
5650 }
5651 break;
5652 }
5653 default:
5654 PM_COMPILE_INTO_ANCHOR(prefix, node);
5655 break;
5656 }
5657}
5658
5662static VALUE
5663pm_compile_shareable_constant_literal(rb_iseq_t *iseq, const pm_node_t *node, const pm_scope_node_t *scope_node)
5664{
5665 switch (PM_NODE_TYPE(node)) {
5666 case PM_TRUE_NODE:
5667 case PM_FALSE_NODE:
5668 case PM_NIL_NODE:
5669 case PM_SYMBOL_NODE:
5670 case PM_REGULAR_EXPRESSION_NODE:
5671 case PM_SOURCE_LINE_NODE:
5672 case PM_INTEGER_NODE:
5673 case PM_FLOAT_NODE:
5674 case PM_RATIONAL_NODE:
5675 case PM_IMAGINARY_NODE:
5676 case PM_SOURCE_ENCODING_NODE:
5677 return pm_static_literal_value(iseq, node, scope_node);
5678 case PM_STRING_NODE:
5679 return parse_static_literal_string(iseq, scope_node, node, &((const pm_string_node_t *) node)->unescaped);
5680 case PM_SOURCE_FILE_NODE:
5681 return pm_source_file_value((const pm_source_file_node_t *) node, scope_node);
5682 case PM_ARRAY_NODE: {
5683 const pm_array_node_t *cast = (const pm_array_node_t *) node;
5684 VALUE result = rb_ary_new_capa(cast->elements.size);
5685
5686 for (size_t index = 0; index < cast->elements.size; index++) {
5687 VALUE element = pm_compile_shareable_constant_literal(iseq, cast->elements.nodes[index], scope_node);
5688 if (element == Qundef) return Qundef;
5689
5690 rb_ary_push(result, element);
5691 }
5692
5693 return rb_ractor_make_shareable(result);
5694 }
5695 case PM_HASH_NODE: {
5696 const pm_hash_node_t *cast = (const pm_hash_node_t *) node;
5697 VALUE result = rb_hash_new_capa(cast->elements.size);
5698
5699 for (size_t index = 0; index < cast->elements.size; index++) {
5700 const pm_node_t *element = cast->elements.nodes[index];
5701 if (!PM_NODE_TYPE_P(element, PM_ASSOC_NODE)) return Qundef;
5702
5703 const pm_assoc_node_t *assoc = (const pm_assoc_node_t *) element;
5704
5705 VALUE key = pm_compile_shareable_constant_literal(iseq, assoc->key, scope_node);
5706 if (key == Qundef) return Qundef;
5707
5708 VALUE value = pm_compile_shareable_constant_literal(iseq, assoc->value, scope_node);
5709 if (value == Qundef) return Qundef;
5710
5711 rb_hash_aset(result, key, value);
5712 }
5713
5714 return rb_ractor_make_shareable(result);
5715 }
5716 default:
5717 return Qundef;
5718 }
5719}
5720
5725static void
5726pm_compile_shareable_constant_value(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_flags_t shareability, VALUE path, LINK_ANCHOR *const ret, pm_scope_node_t *scope_node, bool top)
5727{
5728 VALUE literal = pm_compile_shareable_constant_literal(iseq, node, scope_node);
5729 if (literal != Qundef) {
5730 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
5731 PUSH_INSN1(ret, location, putobject, literal);
5732 return;
5733 }
5734
5735 const pm_node_location_t location = PM_NODE_START_LOCATION(scope_node->parser, node);
5736 switch (PM_NODE_TYPE(node)) {
5737 case PM_ARRAY_NODE: {
5738 const pm_array_node_t *cast = (const pm_array_node_t *) node;
5739
5740 if (top) {
5741 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
5742 }
5743
5744 for (size_t index = 0; index < cast->elements.size; index++) {
5745 pm_compile_shareable_constant_value(iseq, cast->elements.nodes[index], shareability, path, ret, scope_node, false);
5746 }
5747
5748 PUSH_INSN1(ret, location, newarray, INT2FIX(cast->elements.size));
5749
5750 if (top) {
5751 ID method_id = (shareability & PM_SHAREABLE_CONSTANT_NODE_FLAGS_EXPERIMENTAL_COPY) ? rb_intern("make_shareable_copy") : rb_intern("make_shareable");
5752 PUSH_SEND_WITH_FLAG(ret, location, method_id, INT2FIX(1), INT2FIX(VM_CALL_ARGS_SIMPLE));
5753 }
5754
5755 return;
5756 }
5757 case PM_HASH_NODE: {
5758 const pm_hash_node_t *cast = (const pm_hash_node_t *) node;
5759
5760 if (top) {
5761 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
5762 }
5763
5764 pm_compile_hash_elements(iseq, (const pm_node_t *) cast, &cast->elements, shareability, path, false, ret, scope_node);
5765
5766 if (top) {
5767 ID method_id = (shareability & PM_SHAREABLE_CONSTANT_NODE_FLAGS_EXPERIMENTAL_COPY) ? rb_intern("make_shareable_copy") : rb_intern("make_shareable");
5768 PUSH_SEND_WITH_FLAG(ret, location, method_id, INT2FIX(1), INT2FIX(VM_CALL_ARGS_SIMPLE));
5769 }
5770
5771 return;
5772 }
5773 default: {
5774 DECL_ANCHOR(value_seq);
5775
5776 pm_compile_node(iseq, node, value_seq, false, scope_node);
5777 if (PM_NODE_TYPE_P(node, PM_INTERPOLATED_STRING_NODE)) {
5778 PUSH_SEND_WITH_FLAG(value_seq, location, idUMinus, INT2FIX(0), INT2FIX(VM_CALL_ARGS_SIMPLE));
5779 }
5780
5781 if (shareability & PM_SHAREABLE_CONSTANT_NODE_FLAGS_LITERAL) {
5782 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
5783 PUSH_SEQ(ret, value_seq);
5784 if (!RB_OBJ_SHAREABLE_P(path)) {
5785 RB_OBJ_SET_SHAREABLE(path);
5786 }
5787 PUSH_INSN1(ret, location, putobject, path);
5788 PUSH_SEND_WITH_FLAG(ret, location, rb_intern("ensure_shareable"), INT2FIX(2), INT2FIX(VM_CALL_ARGS_SIMPLE));
5789 }
5790 else if (shareability & PM_SHAREABLE_CONSTANT_NODE_FLAGS_EXPERIMENTAL_COPY) {
5791 if (top) PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
5792 PUSH_SEQ(ret, value_seq);
5793 if (top) PUSH_SEND_WITH_FLAG(ret, location, rb_intern("make_shareable_copy"), INT2FIX(1), INT2FIX(VM_CALL_ARGS_SIMPLE));
5794 }
5795 else if (shareability & PM_SHAREABLE_CONSTANT_NODE_FLAGS_EXPERIMENTAL_EVERYTHING) {
5796 if (top) PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
5797 PUSH_SEQ(ret, value_seq);
5798 if (top) PUSH_SEND_WITH_FLAG(ret, location, rb_intern("make_shareable"), INT2FIX(1), INT2FIX(VM_CALL_ARGS_SIMPLE));
5799 }
5800
5801 break;
5802 }
5803 }
5804}
5805
5810static void
5811pm_compile_constant_write_node(rb_iseq_t *iseq, const pm_constant_write_node_t *node, const pm_node_flags_t shareability, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
5812{
5813 const pm_node_location_t location = *node_location;
5814 ID name_id = pm_constant_id_lookup(scope_node, node->name);
5815
5816 if (shareability != 0) {
5817 pm_compile_shareable_constant_value(iseq, node->value, shareability, rb_id2str(name_id), ret, scope_node, true);
5818 }
5819 else {
5820 PM_COMPILE_NOT_POPPED(node->value);
5821 }
5822
5823 if (!popped) PUSH_INSN(ret, location, dup);
5824 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE));
5825
5826 VALUE operand = ID2SYM(name_id);
5827 PUSH_INSN1(ret, location, setconstant, operand);
5828}
5829
5834static void
5835pm_compile_constant_and_write_node(rb_iseq_t *iseq, const pm_constant_and_write_node_t *node, const pm_node_flags_t shareability, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
5836{
5837 const pm_node_location_t location = *node_location;
5838
5839 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, node->name));
5840 LABEL *end_label = NEW_LABEL(location.line);
5841
5842 pm_compile_constant_read(iseq, name, &node->name_loc, location.node_id, ret, scope_node);
5843 if (!popped) PUSH_INSN(ret, location, dup);
5844
5845 PUSH_INSNL(ret, location, branchunless, end_label);
5846 if (!popped) PUSH_INSN(ret, location, pop);
5847
5848 if (shareability != 0) {
5849 pm_compile_shareable_constant_value(iseq, node->value, shareability, name, ret, scope_node, true);
5850 }
5851 else {
5852 PM_COMPILE_NOT_POPPED(node->value);
5853 }
5854
5855 if (!popped) PUSH_INSN(ret, location, dup);
5856 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE));
5857 PUSH_INSN1(ret, location, setconstant, name);
5858 PUSH_LABEL(ret, end_label);
5859}
5860
5865static void
5866pm_compile_constant_or_write_node(rb_iseq_t *iseq, const pm_constant_or_write_node_t *node, const pm_node_flags_t shareability, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
5867{
5868 const pm_node_location_t location = *node_location;
5869 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, node->name));
5870
5871 LABEL *set_label = NEW_LABEL(location.line);
5872 LABEL *end_label = NEW_LABEL(location.line);
5873
5874 PUSH_INSN(ret, location, putnil);
5875 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_CONST), name, Qtrue);
5876 PUSH_INSNL(ret, location, branchunless, set_label);
5877
5878 pm_compile_constant_read(iseq, name, &node->name_loc, location.node_id, ret, scope_node);
5879 if (!popped) PUSH_INSN(ret, location, dup);
5880
5881 PUSH_INSNL(ret, location, branchif, end_label);
5882 if (!popped) PUSH_INSN(ret, location, pop);
5883 PUSH_LABEL(ret, set_label);
5884
5885 if (shareability != 0) {
5886 pm_compile_shareable_constant_value(iseq, node->value, shareability, name, ret, scope_node, true);
5887 }
5888 else {
5889 PM_COMPILE_NOT_POPPED(node->value);
5890 }
5891
5892 if (!popped) PUSH_INSN(ret, location, dup);
5893 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE));
5894 PUSH_INSN1(ret, location, setconstant, name);
5895 PUSH_LABEL(ret, end_label);
5896}
5897
5902static void
5903pm_compile_constant_operator_write_node(rb_iseq_t *iseq, const pm_constant_operator_write_node_t *node, const pm_node_flags_t shareability, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
5904{
5905 const pm_node_location_t location = *node_location;
5906
5907 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, node->name));
5908 ID method_id = pm_constant_id_lookup(scope_node, node->binary_operator);
5909
5910 pm_compile_constant_read(iseq, name, &node->name_loc, location.node_id, ret, scope_node);
5911
5912 if (shareability != 0) {
5913 pm_compile_shareable_constant_value(iseq, node->value, shareability, name, ret, scope_node, true);
5914 }
5915 else {
5916 PM_COMPILE_NOT_POPPED(node->value);
5917 }
5918
5919 PUSH_SEND_WITH_FLAG(ret, location, method_id, INT2NUM(1), INT2FIX(VM_CALL_ARGS_SIMPLE));
5920 if (!popped) PUSH_INSN(ret, location, dup);
5921
5922 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE));
5923 PUSH_INSN1(ret, location, setconstant, name);
5924}
5925
5930static VALUE
5931pm_constant_path_path(const pm_constant_path_node_t *node, const pm_scope_node_t *scope_node)
5932{
5933 VALUE parts = rb_ary_new();
5934 rb_ary_push(parts, rb_id2str(pm_constant_id_lookup(scope_node, node->name)));
5935
5936 const pm_node_t *current = node->parent;
5937 while (current != NULL && PM_NODE_TYPE_P(current, PM_CONSTANT_PATH_NODE)) {
5938 const pm_constant_path_node_t *cast = (const pm_constant_path_node_t *) current;
5939 rb_ary_unshift(parts, rb_id2str(pm_constant_id_lookup(scope_node, cast->name)));
5940 current = cast->parent;
5941 }
5942
5943 if (current == NULL) {
5944 rb_ary_unshift(parts, rb_id2str(idNULL));
5945 }
5946 else if (PM_NODE_TYPE_P(current, PM_CONSTANT_READ_NODE)) {
5947 rb_ary_unshift(parts, rb_id2str(pm_constant_id_lookup(scope_node, ((const pm_constant_read_node_t *) current)->name)));
5948 }
5949 else {
5950 rb_ary_unshift(parts, rb_str_new_cstr("..."));
5951 }
5952
5953 return rb_ary_join(parts, rb_str_new_cstr("::"));
5954}
5955
5960static void
5961pm_compile_constant_path_write_node(rb_iseq_t *iseq, const pm_constant_path_write_node_t *node, const pm_node_flags_t shareability, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
5962{
5963 const pm_node_location_t location = *node_location;
5964 const pm_constant_path_node_t *target = node->target;
5965 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, target->name));
5966
5967 if (target->parent) {
5968 PM_COMPILE_NOT_POPPED((const pm_node_t *) target->parent);
5969 }
5970 else {
5971 PUSH_INSN1(ret, location, putobject, rb_cObject);
5972 }
5973
5974 if (shareability != 0) {
5975 pm_compile_shareable_constant_value(iseq, node->value, shareability, pm_constant_path_path(node->target, scope_node), ret, scope_node, true);
5976 }
5977 else {
5978 PM_COMPILE_NOT_POPPED(node->value);
5979 }
5980
5981 if (!popped) {
5982 PUSH_INSN(ret, location, swap);
5983 PUSH_INSN1(ret, location, topn, INT2FIX(1));
5984 }
5985
5986 PUSH_INSN(ret, location, swap);
5987 PUSH_INSN1(ret, location, setconstant, name);
5988}
5989
5994static void
5995pm_compile_constant_path_and_write_node(rb_iseq_t *iseq, const pm_constant_path_and_write_node_t *node, const pm_node_flags_t shareability, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
5996{
5997 const pm_node_location_t location = *node_location;
5998 const pm_constant_path_node_t *target = node->target;
5999
6000 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, target->name));
6001 LABEL *lfin = NEW_LABEL(location.line);
6002
6003 if (target->parent) {
6004 PM_COMPILE_NOT_POPPED(target->parent);
6005 }
6006 else {
6007 PUSH_INSN1(ret, location, putobject, rb_cObject);
6008 }
6009
6010 PUSH_INSN(ret, location, dup);
6011 PUSH_INSN1(ret, location, putobject, Qtrue);
6012 PUSH_INSN1(ret, location, getconstant, name);
6013
6014 if (!popped) PUSH_INSN(ret, location, dup);
6015 PUSH_INSNL(ret, location, branchunless, lfin);
6016
6017 if (!popped) PUSH_INSN(ret, location, pop);
6018
6019 if (shareability != 0) {
6020 pm_compile_shareable_constant_value(iseq, node->value, shareability, pm_constant_path_path(node->target, scope_node), ret, scope_node, true);
6021 }
6022 else {
6023 PM_COMPILE_NOT_POPPED(node->value);
6024 }
6025
6026 if (popped) {
6027 PUSH_INSN1(ret, location, topn, INT2FIX(1));
6028 }
6029 else {
6030 PUSH_INSN1(ret, location, dupn, INT2FIX(2));
6031 PUSH_INSN(ret, location, swap);
6032 }
6033
6034 PUSH_INSN1(ret, location, setconstant, name);
6035 PUSH_LABEL(ret, lfin);
6036
6037 if (!popped) PUSH_INSN(ret, location, swap);
6038 PUSH_INSN(ret, location, pop);
6039}
6040
6045static void
6046pm_compile_constant_path_or_write_node(rb_iseq_t *iseq, const pm_constant_path_or_write_node_t *node, const pm_node_flags_t shareability, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
6047{
6048 const pm_node_location_t location = *node_location;
6049 const pm_constant_path_node_t *target = node->target;
6050
6051 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, target->name));
6052 LABEL *lassign = NEW_LABEL(location.line);
6053 LABEL *lfin = NEW_LABEL(location.line);
6054
6055 if (target->parent) {
6056 PM_COMPILE_NOT_POPPED(target->parent);
6057 }
6058 else {
6059 PUSH_INSN1(ret, location, putobject, rb_cObject);
6060 }
6061
6062 PUSH_INSN(ret, location, dup);
6063 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_CONST_FROM), name, Qtrue);
6064 PUSH_INSNL(ret, location, branchunless, lassign);
6065
6066 PUSH_INSN(ret, location, dup);
6067 PUSH_INSN1(ret, location, putobject, Qtrue);
6068 PUSH_INSN1(ret, location, getconstant, name);
6069
6070 if (!popped) PUSH_INSN(ret, location, dup);
6071 PUSH_INSNL(ret, location, branchif, lfin);
6072
6073 if (!popped) PUSH_INSN(ret, location, pop);
6074 PUSH_LABEL(ret, lassign);
6075
6076 if (shareability != 0) {
6077 pm_compile_shareable_constant_value(iseq, node->value, shareability, pm_constant_path_path(node->target, scope_node), ret, scope_node, true);
6078 }
6079 else {
6080 PM_COMPILE_NOT_POPPED(node->value);
6081 }
6082
6083 if (popped) {
6084 PUSH_INSN1(ret, location, topn, INT2FIX(1));
6085 }
6086 else {
6087 PUSH_INSN1(ret, location, dupn, INT2FIX(2));
6088 PUSH_INSN(ret, location, swap);
6089 }
6090
6091 PUSH_INSN1(ret, location, setconstant, name);
6092 PUSH_LABEL(ret, lfin);
6093
6094 if (!popped) PUSH_INSN(ret, location, swap);
6095 PUSH_INSN(ret, location, pop);
6096}
6097
6102static void
6103pm_compile_constant_path_operator_write_node(rb_iseq_t *iseq, const pm_constant_path_operator_write_node_t *node, const pm_node_flags_t shareability, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
6104{
6105 const pm_node_location_t location = *node_location;
6106 const pm_constant_path_node_t *target = node->target;
6107
6108 ID method_id = pm_constant_id_lookup(scope_node, node->binary_operator);
6109 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, target->name));
6110
6111 if (target->parent) {
6112 PM_COMPILE_NOT_POPPED(target->parent);
6113 }
6114 else {
6115 PUSH_INSN1(ret, location, putobject, rb_cObject);
6116 }
6117
6118 PUSH_INSN(ret, location, dup);
6119 PUSH_INSN1(ret, location, putobject, Qtrue);
6120 PUSH_INSN1(ret, location, getconstant, name);
6121
6122 if (shareability != 0) {
6123 pm_compile_shareable_constant_value(iseq, node->value, shareability, pm_constant_path_path(node->target, scope_node), ret, scope_node, true);
6124 }
6125 else {
6126 PM_COMPILE_NOT_POPPED(node->value);
6127 }
6128
6129 PUSH_CALL(ret, location, method_id, INT2FIX(1));
6130 PUSH_INSN(ret, location, swap);
6131
6132 if (!popped) {
6133 PUSH_INSN1(ret, location, topn, INT2FIX(1));
6134 PUSH_INSN(ret, location, swap);
6135 }
6136
6137 PUSH_INSN1(ret, location, setconstant, name);
6138}
6139
6146#define PM_CONTAINER_P(node) (PM_NODE_TYPE_P(node, PM_ARRAY_NODE) || PM_NODE_TYPE_P(node, PM_HASH_NODE) || PM_NODE_TYPE_P(node, PM_RANGE_NODE))
6147
6152static inline void
6153pm_compile_scope_node(rb_iseq_t *iseq, pm_scope_node_t *scope_node, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped)
6154{
6155 const pm_node_location_t location = *node_location;
6156 struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
6157
6158 pm_constant_id_list_t *locals = &scope_node->locals;
6159 pm_parameters_node_t *parameters_node = NULL;
6160 pm_node_list_t *keywords_list = NULL;
6161 pm_node_list_t *optionals_list = NULL;
6162 pm_node_list_t *posts_list = NULL;
6163 pm_node_list_t *requireds_list = NULL;
6164 pm_node_list_t *block_locals = NULL;
6165 bool trailing_comma = false;
6166
6167 if (PM_NODE_TYPE_P(scope_node->ast_node, PM_CLASS_NODE) || PM_NODE_TYPE_P(scope_node->ast_node, PM_MODULE_NODE)) {
6168 PUSH_TRACE(ret, RUBY_EVENT_CLASS);
6169 }
6170
6171 if (scope_node->parameters != NULL) {
6172 switch (PM_NODE_TYPE(scope_node->parameters)) {
6173 case PM_BLOCK_PARAMETERS_NODE: {
6174 pm_block_parameters_node_t *cast = (pm_block_parameters_node_t *) scope_node->parameters;
6175 parameters_node = cast->parameters;
6176 block_locals = &cast->locals;
6177
6178 if (parameters_node) {
6179 if (parameters_node->rest && PM_NODE_TYPE_P(parameters_node->rest, PM_IMPLICIT_REST_NODE)) {
6180 trailing_comma = true;
6181 }
6182 }
6183 break;
6184 }
6185 case PM_PARAMETERS_NODE: {
6186 parameters_node = (pm_parameters_node_t *) scope_node->parameters;
6187 break;
6188 }
6189 case PM_NUMBERED_PARAMETERS_NODE: {
6190 uint32_t maximum = ((const pm_numbered_parameters_node_t *) scope_node->parameters)->maximum;
6191 body->param.lead_num = maximum;
6192 body->param.flags.ambiguous_param0 = maximum == 1;
6193 break;
6194 }
6195 case PM_IT_PARAMETERS_NODE:
6196 body->param.lead_num = 1;
6197 body->param.flags.ambiguous_param0 = true;
6198 break;
6199 default:
6200 rb_bug("Unexpected node type for parameters: %s", pm_node_type_to_str(PM_NODE_TYPE(scope_node->parameters)));
6201 }
6202 }
6203
6204 struct rb_iseq_param_keyword *keyword = NULL;
6205
6206 if (parameters_node) {
6207 optionals_list = &parameters_node->optionals;
6208 requireds_list = &parameters_node->requireds;
6209 keywords_list = &parameters_node->keywords;
6210 posts_list = &parameters_node->posts;
6211 }
6212 else if (scope_node->parameters && (PM_NODE_TYPE_P(scope_node->parameters, PM_NUMBERED_PARAMETERS_NODE) || PM_NODE_TYPE_P(scope_node->parameters, PM_IT_PARAMETERS_NODE))) {
6213 body->param.opt_num = 0;
6214 }
6215 else {
6216 body->param.lead_num = 0;
6217 body->param.opt_num = 0;
6218 }
6219
6220 //********STEP 1**********
6221 // Goal: calculate the table size for the locals, accounting for
6222 // hidden variables and multi target nodes
6223 size_t locals_size = locals->size;
6224
6225 // Index lookup table buffer size is only the number of the locals
6226 st_table *index_lookup_table = st_init_numtable();
6227
6228 int table_size = (int) locals_size;
6229
6230 // For nodes have a hidden iteration variable. We add that to the local
6231 // table size here.
6232 if (PM_NODE_TYPE_P(scope_node->ast_node, PM_FOR_NODE)) table_size++;
6233
6234 if (keywords_list && keywords_list->size) {
6235 table_size++;
6236 }
6237
6238 if (requireds_list) {
6239 for (size_t i = 0; i < requireds_list->size; i++) {
6240 // For each MultiTargetNode, we're going to have one
6241 // additional anonymous local not represented in the locals table
6242 // We want to account for this in our table size
6243 pm_node_t *required = requireds_list->nodes[i];
6244 if (PM_NODE_TYPE_P(required, PM_MULTI_TARGET_NODE)) {
6245 table_size++;
6246 }
6247 else if (PM_NODE_TYPE_P(required, PM_REQUIRED_PARAMETER_NODE)) {
6248 if (PM_NODE_FLAG_P(required, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6249 table_size++;
6250 }
6251 }
6252 }
6253 }
6254
6255 // If we have the `it` implicit local variable, we need to account for
6256 // it in the local table size.
6257 if (scope_node->parameters != NULL && PM_NODE_TYPE_P(scope_node->parameters, PM_IT_PARAMETERS_NODE)) {
6258 table_size++;
6259 }
6260
6261 // Ensure there is enough room in the local table for any
6262 // parameters that have been repeated
6263 // ex: def underscore_parameters(_, _ = 1, _ = 2); _; end
6264 // ^^^^^^^^^^^^
6265 if (optionals_list && optionals_list->size) {
6266 for (size_t i = 0; i < optionals_list->size; i++) {
6267 pm_node_t * node = optionals_list->nodes[i];
6268 if (PM_NODE_FLAG_P(node, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6269 table_size++;
6270 }
6271 }
6272 }
6273
6274 // If we have an anonymous "rest" node, we'll need to increase the local
6275 // table size to take it in to account.
6276 // def m(foo, *, bar)
6277 // ^
6278 if (parameters_node) {
6279 if (parameters_node->rest) {
6280 if (!(PM_NODE_TYPE_P(parameters_node->rest, PM_IMPLICIT_REST_NODE))) {
6281 if (!((const pm_rest_parameter_node_t *) parameters_node->rest)->name || PM_NODE_FLAG_P(parameters_node->rest, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6282 table_size++;
6283 }
6284 }
6285 }
6286
6287 // def foo(_, **_); _; end
6288 // ^^^
6289 if (parameters_node->keyword_rest) {
6290 // def foo(...); end
6291 // ^^^
6292 // When we have a `...` as the keyword_rest, it's a forwarding_parameter_node and
6293 // we need to leave space for 4 locals: *, **, &, ...
6294 if (PM_NODE_TYPE_P(parameters_node->keyword_rest, PM_FORWARDING_PARAMETER_NODE)) {
6295 // Only optimize specifically methods like this: `foo(...)`
6296 if (requireds_list->size == 0 && optionals_list->size == 0 && keywords_list->size == 0) {
6297 ISEQ_BODY(iseq)->param.flags.use_block = TRUE;
6298 ISEQ_BODY(iseq)->param.flags.forwardable = TRUE;
6299 table_size += 1;
6300 }
6301 else {
6302 table_size += 4;
6303 }
6304 }
6305 else {
6306 const pm_keyword_rest_parameter_node_t *kw_rest = (const pm_keyword_rest_parameter_node_t *) parameters_node->keyword_rest;
6307
6308 // If it's anonymous or repeated, then we need to allocate stack space
6309 if (!kw_rest->name || PM_NODE_FLAG_P(kw_rest, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6310 table_size++;
6311 }
6312 }
6313 }
6314 }
6315
6316 if (posts_list) {
6317 for (size_t i = 0; i < posts_list->size; i++) {
6318 // For each MultiTargetNode, we're going to have one
6319 // additional anonymous local not represented in the locals table
6320 // We want to account for this in our table size
6321 pm_node_t *required = posts_list->nodes[i];
6322 if (PM_NODE_TYPE_P(required, PM_MULTI_TARGET_NODE) || PM_NODE_FLAG_P(required, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6323 table_size++;
6324 }
6325 }
6326 }
6327
6328 if (keywords_list && keywords_list->size) {
6329 for (size_t i = 0; i < keywords_list->size; i++) {
6330 pm_node_t *keyword_parameter_node = keywords_list->nodes[i];
6331 if (PM_NODE_FLAG_P(keyword_parameter_node, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6332 table_size++;
6333 }
6334 }
6335 }
6336
6337 if (parameters_node && parameters_node->block) {
6338 const pm_block_parameter_node_t *block_node = (const pm_block_parameter_node_t *) parameters_node->block;
6339
6340 if (PM_NODE_FLAG_P(block_node, PM_PARAMETER_FLAGS_REPEATED_PARAMETER) || !block_node->name) {
6341 table_size++;
6342 }
6343 }
6344
6345 // We can create local_table_for_iseq with the correct size
6346 VALUE idtmp = 0;
6347 rb_ast_id_table_t *local_table_for_iseq = ALLOCV(idtmp, sizeof(rb_ast_id_table_t) + table_size * sizeof(ID));
6348 local_table_for_iseq->size = table_size;
6349
6350 //********END OF STEP 1**********
6351
6352 //********STEP 2**********
6353 // Goal: populate iv index table as well as local table, keeping the
6354 // layout of the local table consistent with the layout of the
6355 // stack when calling the method
6356 //
6357 // Do a first pass on all of the parameters, setting their values in
6358 // the local_table_for_iseq, _except_ for Multis who get a hidden
6359 // variable in this step, and will get their names inserted in step 3
6360
6361 // local_index is a cursor that keeps track of the current
6362 // index into local_table_for_iseq. The local table is actually a list,
6363 // and the order of that list must match the order of the items pushed
6364 // on the stack. We need to take in to account things pushed on the
6365 // stack that _might not have a name_ (for example array destructuring).
6366 // This index helps us know which item we're dealing with and also give
6367 // those anonymous items temporary names (as below)
6368 int local_index = 0;
6369
6370 // Here we figure out local table indices and insert them in to the
6371 // index lookup table and local tables.
6372 //
6373 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6374 // ^^^^^^^^^^^^^
6375 if (requireds_list && requireds_list->size) {
6376 for (size_t i = 0; i < requireds_list->size; i++, local_index++) {
6377 ID local;
6378
6379 // For each MultiTargetNode, we're going to have one additional
6380 // anonymous local not represented in the locals table. We want
6381 // to account for this in our table size.
6382 pm_node_t *required = requireds_list->nodes[i];
6383
6384 switch (PM_NODE_TYPE(required)) {
6385 case PM_MULTI_TARGET_NODE: {
6386 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6387 // ^^^^^^^^^^
6388 local = rb_make_temporary_id(local_index);
6389 local_table_for_iseq->ids[local_index] = local;
6390 break;
6391 }
6392 case PM_REQUIRED_PARAMETER_NODE: {
6393 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6394 // ^
6395 const pm_required_parameter_node_t *param = (const pm_required_parameter_node_t *) required;
6396
6397 if (PM_NODE_FLAG_P(required, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6398 ID local = pm_constant_id_lookup(scope_node, param->name);
6399 local_table_for_iseq->ids[local_index] = local;
6400 }
6401 else {
6402 pm_insert_local_index(param->name, local_index, index_lookup_table, local_table_for_iseq, scope_node);
6403 }
6404
6405 break;
6406 }
6407 default:
6408 rb_bug("Unsupported node in requireds in parameters %s", pm_node_type_to_str(PM_NODE_TYPE(required)));
6409 }
6410 }
6411
6412 body->param.lead_num = (int) requireds_list->size;
6413 body->param.flags.has_lead = true;
6414 }
6415
6416 if (scope_node->parameters != NULL && PM_NODE_TYPE_P(scope_node->parameters, PM_IT_PARAMETERS_NODE)) {
6417 local_table_for_iseq->ids[local_index++] = idItImplicit;
6418 }
6419
6420 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6421 // ^^^^^
6422 if (optionals_list && optionals_list->size) {
6423 body->param.opt_num = (int) optionals_list->size;
6424 body->param.flags.has_opt = true;
6425
6426 for (size_t i = 0; i < optionals_list->size; i++, local_index++) {
6427 pm_node_t * node = optionals_list->nodes[i];
6428 pm_constant_id_t name = ((const pm_optional_parameter_node_t *) node)->name;
6429
6430 if (PM_NODE_FLAG_P(node, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6431 ID local = pm_constant_id_lookup(scope_node, name);
6432 local_table_for_iseq->ids[local_index] = local;
6433 }
6434 else {
6435 pm_insert_local_index(name, local_index, index_lookup_table, local_table_for_iseq, scope_node);
6436 }
6437 }
6438 }
6439
6440 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6441 // ^^
6442 if (parameters_node && parameters_node->rest) {
6443 body->param.rest_start = local_index;
6444
6445 // If there's a trailing comma, we'll have an implicit rest node,
6446 // and we don't want it to impact the rest variables on param
6447 if (!(PM_NODE_TYPE_P(parameters_node->rest, PM_IMPLICIT_REST_NODE))) {
6448 body->param.flags.has_rest = true;
6449 RUBY_ASSERT(body->param.rest_start != -1);
6450
6451 pm_constant_id_t name = ((const pm_rest_parameter_node_t *) parameters_node->rest)->name;
6452
6453 if (name) {
6454 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6455 // ^^
6456 if (PM_NODE_FLAG_P(parameters_node->rest, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6457 ID local = pm_constant_id_lookup(scope_node, name);
6458 local_table_for_iseq->ids[local_index] = local;
6459 }
6460 else {
6461 pm_insert_local_index(name, local_index, index_lookup_table, local_table_for_iseq, scope_node);
6462 }
6463 }
6464 else {
6465 // def foo(a, (b, *c, d), e = 1, *, g, (h, *i, j), k:, l: 1, **m, &n)
6466 // ^
6467 body->param.flags.anon_rest = true;
6468 pm_insert_local_special(idMULT, local_index, index_lookup_table, local_table_for_iseq);
6469 }
6470
6471 local_index++;
6472 }
6473 }
6474
6475 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6476 // ^^^^^^^^^^^^^
6477 if (posts_list && posts_list->size) {
6478 body->param.post_num = (int) posts_list->size;
6479 body->param.post_start = local_index;
6480 body->param.flags.has_post = true;
6481
6482 for (size_t i = 0; i < posts_list->size; i++, local_index++) {
6483 ID local;
6484
6485 // For each MultiTargetNode, we're going to have one additional
6486 // anonymous local not represented in the locals table. We want
6487 // to account for this in our table size.
6488 const pm_node_t *post_node = posts_list->nodes[i];
6489
6490 switch (PM_NODE_TYPE(post_node)) {
6491 case PM_MULTI_TARGET_NODE: {
6492 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6493 // ^^^^^^^^^^
6494 local = rb_make_temporary_id(local_index);
6495 local_table_for_iseq->ids[local_index] = local;
6496 break;
6497 }
6498 case PM_REQUIRED_PARAMETER_NODE: {
6499 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6500 // ^
6501 const pm_required_parameter_node_t *param = (const pm_required_parameter_node_t *) post_node;
6502
6503 if (PM_NODE_FLAG_P(param, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6504 ID local = pm_constant_id_lookup(scope_node, param->name);
6505 local_table_for_iseq->ids[local_index] = local;
6506 }
6507 else {
6508 pm_insert_local_index(param->name, local_index, index_lookup_table, local_table_for_iseq, scope_node);
6509 }
6510 break;
6511 }
6512 default:
6513 rb_bug("Unsupported node in posts in parameters %s", pm_node_type_to_str(PM_NODE_TYPE(post_node)));
6514 }
6515 }
6516 }
6517
6518 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6519 // ^^^^^^^^
6520 // Keywords create an internal variable on the parse tree
6521 if (keywords_list && keywords_list->size) {
6522 if (keywords_list->size > VM_CALL_KW_LEN_MAX) {
6523 COMPILE_ERROR(iseq, node_location->line, "too many keyword parameters (%d, maximum is %d)",
6524 (int) keywords_list->size, (int) VM_CALL_KW_LEN_MAX);
6525 }
6526
6527 keyword = ZALLOC_N(struct rb_iseq_param_keyword, 1);
6528 keyword->num = (int) keywords_list->size;
6529
6530 const VALUE default_values = rb_ary_hidden_new(1);
6531 const VALUE complex_mark = rb_str_tmp_new(0);
6532
6533 for (size_t i = 0; i < keywords_list->size; i++) {
6534 pm_node_t *keyword_parameter_node = keywords_list->nodes[i];
6535 pm_constant_id_t name;
6536
6537 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6538 // ^^
6539 if (PM_NODE_TYPE_P(keyword_parameter_node, PM_REQUIRED_KEYWORD_PARAMETER_NODE)) {
6540 name = ((const pm_required_keyword_parameter_node_t *) keyword_parameter_node)->name;
6541 keyword->required_num++;
6542 ID local = pm_constant_id_lookup(scope_node, name);
6543
6544 if (PM_NODE_FLAG_P(keyword_parameter_node, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6545 local_table_for_iseq->ids[local_index] = local;
6546 }
6547 else {
6548 pm_insert_local_index(name, local_index, index_lookup_table, local_table_for_iseq, scope_node);
6549 }
6550 local_index++;
6551 }
6552 }
6553
6554 for (size_t i = 0; i < keywords_list->size; i++) {
6555 pm_node_t *keyword_parameter_node = keywords_list->nodes[i];
6556 pm_constant_id_t name;
6557
6558 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6559 // ^^^^
6560 if (PM_NODE_TYPE_P(keyword_parameter_node, PM_OPTIONAL_KEYWORD_PARAMETER_NODE)) {
6561 const pm_optional_keyword_parameter_node_t *cast = ((const pm_optional_keyword_parameter_node_t *) keyword_parameter_node);
6562
6563 pm_node_t *value = cast->value;
6564 name = cast->name;
6565
6566 if (PM_NODE_FLAG_P(value, PM_NODE_FLAG_STATIC_LITERAL) && !PM_CONTAINER_P(value)) {
6567 rb_ary_push(default_values, pm_static_literal_value(iseq, value, scope_node));
6568 }
6569 else {
6570 rb_ary_push(default_values, complex_mark);
6571 }
6572
6573 ID local = pm_constant_id_lookup(scope_node, name);
6574 if (PM_NODE_FLAG_P(keyword_parameter_node, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6575 local_table_for_iseq->ids[local_index] = local;
6576 }
6577 else {
6578 pm_insert_local_index(name, local_index, index_lookup_table, local_table_for_iseq, scope_node);
6579 }
6580 local_index++;
6581 }
6582
6583 }
6584
6585 if (RARRAY_LEN(default_values)) {
6586 VALUE *dvs = ALLOC_N(VALUE, RARRAY_LEN(default_values));
6587
6588 for (int i = 0; i < RARRAY_LEN(default_values); i++) {
6589 VALUE dv = RARRAY_AREF(default_values, i);
6590 if (dv == complex_mark) dv = Qundef;
6591 RB_OBJ_WRITE(iseq, &dvs[i], dv);
6592 }
6593
6594 keyword->default_values = dvs;
6595 }
6596
6597 // Hidden local for keyword arguments
6598 keyword->bits_start = local_index;
6599 ID local = rb_make_temporary_id(local_index);
6600 local_table_for_iseq->ids[local_index] = local;
6601 local_index++;
6602
6603 body->param.keyword = keyword;
6604 body->param.flags.has_kw = true;
6605 }
6606
6607 if (body->type == ISEQ_TYPE_BLOCK && local_index == 1 && requireds_list && requireds_list->size == 1 && !trailing_comma) {
6608 body->param.flags.ambiguous_param0 = true;
6609 }
6610
6611 if (parameters_node) {
6612 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6613 // ^^^
6614 if (parameters_node->keyword_rest) {
6615 switch (PM_NODE_TYPE(parameters_node->keyword_rest)) {
6616 case PM_NO_KEYWORDS_PARAMETER_NODE: {
6617 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **nil, &n)
6618 // ^^^^^
6619 body->param.flags.accepts_no_kwarg = true;
6620 break;
6621 }
6622 case PM_KEYWORD_REST_PARAMETER_NODE: {
6623 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6624 // ^^^
6625 const pm_keyword_rest_parameter_node_t *kw_rest_node = (const pm_keyword_rest_parameter_node_t *) parameters_node->keyword_rest;
6626 if (!body->param.flags.has_kw) {
6627 body->param.keyword = keyword = ZALLOC_N(struct rb_iseq_param_keyword, 1);
6628 }
6629
6630 keyword->rest_start = local_index;
6631 body->param.flags.has_kwrest = true;
6632
6633 pm_constant_id_t constant_id = kw_rest_node->name;
6634 if (constant_id) {
6635 if (PM_NODE_FLAG_P(kw_rest_node, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6636 ID local = pm_constant_id_lookup(scope_node, constant_id);
6637 local_table_for_iseq->ids[local_index] = local;
6638 }
6639 else {
6640 pm_insert_local_index(constant_id, local_index, index_lookup_table, local_table_for_iseq, scope_node);
6641 }
6642 }
6643 else {
6644 body->param.flags.anon_kwrest = true;
6645 pm_insert_local_special(idPow, local_index, index_lookup_table, local_table_for_iseq);
6646 }
6647
6648 local_index++;
6649 break;
6650 }
6651 case PM_FORWARDING_PARAMETER_NODE: {
6652 // def foo(...)
6653 // ^^^
6654 if (!ISEQ_BODY(iseq)->param.flags.forwardable) {
6655 // Add the anonymous *
6656 body->param.rest_start = local_index;
6657 body->param.flags.has_rest = true;
6658 body->param.flags.anon_rest = true;
6659 pm_insert_local_special(idMULT, local_index++, index_lookup_table, local_table_for_iseq);
6660
6661 // Add the anonymous **
6662 RUBY_ASSERT(!body->param.flags.has_kw);
6663 body->param.flags.has_kw = false;
6664 body->param.flags.has_kwrest = true;
6665 body->param.flags.anon_kwrest = true;
6666 body->param.keyword = keyword = ZALLOC_N(struct rb_iseq_param_keyword, 1);
6667 keyword->rest_start = local_index;
6668 pm_insert_local_special(idPow, local_index++, index_lookup_table, local_table_for_iseq);
6669
6670 // Add the anonymous &
6671 body->param.block_start = local_index;
6672 body->param.flags.has_block = true;
6673 pm_insert_local_special(idAnd, local_index++, index_lookup_table, local_table_for_iseq);
6674 }
6675
6676 // Add the ...
6677 pm_insert_local_special(idDot3, local_index++, index_lookup_table, local_table_for_iseq);
6678 break;
6679 }
6680 default:
6681 rb_bug("node type %s not expected as keyword_rest", pm_node_type_to_str(PM_NODE_TYPE(parameters_node->keyword_rest)));
6682 }
6683 }
6684
6685 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6686 // ^^
6687 if (parameters_node->block) {
6688 body->param.block_start = local_index;
6689 body->param.flags.has_block = true;
6690 iseq_set_use_block(iseq);
6691
6692 pm_constant_id_t name = ((const pm_block_parameter_node_t *) parameters_node->block)->name;
6693
6694 if (name) {
6695 if (PM_NODE_FLAG_P(parameters_node->block, PM_PARAMETER_FLAGS_REPEATED_PARAMETER)) {
6696 ID local = pm_constant_id_lookup(scope_node, name);
6697 local_table_for_iseq->ids[local_index] = local;
6698 }
6699 else {
6700 pm_insert_local_index(name, local_index, index_lookup_table, local_table_for_iseq, scope_node);
6701 }
6702 }
6703 else {
6704 pm_insert_local_special(idAnd, local_index, index_lookup_table, local_table_for_iseq);
6705 }
6706
6707 local_index++;
6708 }
6709 }
6710
6711 //********END OF STEP 2**********
6712 // The local table is now consistent with expected
6713 // stack layout
6714
6715 // If there's only one required element in the parameters
6716 // CRuby needs to recognize it as an ambiguous parameter
6717
6718 //********STEP 3**********
6719 // Goal: fill in the names of the parameters in MultiTargetNodes
6720 //
6721 // Go through requireds again to set the multis
6722
6723 if (requireds_list && requireds_list->size) {
6724 for (size_t i = 0; i < requireds_list->size; i++) {
6725 // For each MultiTargetNode, we're going to have one
6726 // additional anonymous local not represented in the locals table
6727 // We want to account for this in our table size
6728 const pm_node_t *required = requireds_list->nodes[i];
6729
6730 if (PM_NODE_TYPE_P(required, PM_MULTI_TARGET_NODE)) {
6731 local_index = pm_compile_destructured_param_locals((const pm_multi_target_node_t *) required, index_lookup_table, local_table_for_iseq, scope_node, local_index);
6732 }
6733 }
6734 }
6735
6736 // Go through posts again to set the multis
6737 if (posts_list && posts_list->size) {
6738 for (size_t i = 0; i < posts_list->size; i++) {
6739 // For each MultiTargetNode, we're going to have one
6740 // additional anonymous local not represented in the locals table
6741 // We want to account for this in our table size
6742 const pm_node_t *post = posts_list->nodes[i];
6743
6744 if (PM_NODE_TYPE_P(post, PM_MULTI_TARGET_NODE)) {
6745 local_index = pm_compile_destructured_param_locals((const pm_multi_target_node_t *) post, index_lookup_table, local_table_for_iseq, scope_node, local_index);
6746 }
6747 }
6748 }
6749
6750 // Set any anonymous locals for the for node
6751 if (PM_NODE_TYPE_P(scope_node->ast_node, PM_FOR_NODE)) {
6752 if (PM_NODE_TYPE_P(((const pm_for_node_t *) scope_node->ast_node)->index, PM_LOCAL_VARIABLE_TARGET_NODE)) {
6753 body->param.lead_num++;
6754 }
6755 else {
6756 body->param.rest_start = local_index;
6757 body->param.flags.has_rest = true;
6758 }
6759
6760 ID local = rb_make_temporary_id(local_index);
6761 local_table_for_iseq->ids[local_index] = local;
6762 local_index++;
6763 }
6764
6765 // Fill in any NumberedParameters, if they exist
6766 if (scope_node->parameters && PM_NODE_TYPE_P(scope_node->parameters, PM_NUMBERED_PARAMETERS_NODE)) {
6767 int maximum = ((const pm_numbered_parameters_node_t *) scope_node->parameters)->maximum;
6768 RUBY_ASSERT(0 < maximum && maximum <= 9);
6769 for (int i = 0; i < maximum; i++, local_index++) {
6770 const uint8_t param_name[] = { '_', '1' + i };
6771 pm_constant_id_t constant_id = pm_constant_pool_find(&scope_node->parser->constant_pool, param_name, 2);
6772 RUBY_ASSERT(constant_id && "parser should fill in any gaps in numbered parameters");
6773 pm_insert_local_index(constant_id, local_index, index_lookup_table, local_table_for_iseq, scope_node);
6774 }
6775 body->param.lead_num = maximum;
6776 body->param.flags.has_lead = true;
6777 }
6778
6779 // Fill in the anonymous `it` parameter, if it exists
6780 if (scope_node->parameters && PM_NODE_TYPE_P(scope_node->parameters, PM_IT_PARAMETERS_NODE)) {
6781 body->param.lead_num = 1;
6782 body->param.flags.has_lead = true;
6783 }
6784
6785 //********END OF STEP 3**********
6786
6787 //********STEP 4**********
6788 // Goal: fill in the method body locals
6789 // To be explicit, these are the non-parameter locals
6790 // We fill in the block_locals, if they exist
6791 // lambda { |x; y| y }
6792 // ^
6793 if (block_locals && block_locals->size) {
6794 for (size_t i = 0; i < block_locals->size; i++, local_index++) {
6795 pm_constant_id_t constant_id = ((const pm_block_local_variable_node_t *) block_locals->nodes[i])->name;
6796 pm_insert_local_index(constant_id, local_index, index_lookup_table, local_table_for_iseq, scope_node);
6797 }
6798 }
6799
6800 // Fill in any locals we missed
6801 if (scope_node->locals.size) {
6802 for (size_t i = 0; i < scope_node->locals.size; i++) {
6803 pm_constant_id_t constant_id = locals->ids[i];
6804 if (constant_id) {
6805 struct pm_local_table_insert_ctx ctx;
6806 ctx.scope_node = scope_node;
6807 ctx.local_table_for_iseq = local_table_for_iseq;
6808 ctx.local_index = local_index;
6809
6810 st_update(index_lookup_table, (st_data_t)constant_id, pm_local_table_insert_func, (st_data_t)&ctx);
6811
6812 local_index = ctx.local_index;
6813 }
6814 }
6815 }
6816
6817 //********END OF STEP 4**********
6818
6819 // We set the index_lookup_table on the scope node so we can
6820 // refer to the parameters correctly
6821 if (scope_node->index_lookup_table) {
6822 st_free_table(scope_node->index_lookup_table);
6823 }
6824 scope_node->index_lookup_table = index_lookup_table;
6825 iseq_calc_param_size(iseq);
6826
6827 if (ISEQ_BODY(iseq)->param.flags.forwardable) {
6828 // We're treating `...` as a parameter so that frame
6829 // pushing won't clobber it.
6830 ISEQ_BODY(iseq)->param.size += 1;
6831 }
6832
6833 // FIXME: args?
6834 iseq_set_local_table(iseq, local_table_for_iseq, 0);
6835 iseq_set_parameters_lvar_state(iseq);
6836
6837 scope_node->local_table_for_iseq_size = local_table_for_iseq->size;
6838
6839 if (keyword != NULL) {
6840 size_t keyword_start_index = keyword->bits_start - keyword->num;
6841 keyword->table = (ID *)&ISEQ_BODY(iseq)->local_table[keyword_start_index];
6842 }
6843
6844 //********STEP 5************
6845 // Goal: compile anything that needed to be compiled
6846 if (optionals_list && optionals_list->size) {
6847 LABEL **opt_table = (LABEL **) ALLOC_N(VALUE, optionals_list->size + 1);
6848 LABEL *label;
6849
6850 // TODO: Should we make an api for NEW_LABEL where you can pass
6851 // a pointer to the label it should fill out? We already
6852 // have a list of labels allocated above so it seems wasteful
6853 // to do the copies.
6854 for (size_t i = 0; i < optionals_list->size; i++) {
6855 label = NEW_LABEL(location.line);
6856 opt_table[i] = label;
6857 PUSH_LABEL(ret, label);
6858 pm_node_t *optional_node = optionals_list->nodes[i];
6859 PM_COMPILE_NOT_POPPED(optional_node);
6860 }
6861
6862 // Set the last label
6863 label = NEW_LABEL(location.line);
6864 opt_table[optionals_list->size] = label;
6865 PUSH_LABEL(ret, label);
6866
6867 body->param.opt_table = (const VALUE *) opt_table;
6868 }
6869
6870 if (keywords_list && keywords_list->size) {
6871 size_t optional_index = 0;
6872 for (size_t i = 0; i < keywords_list->size; i++) {
6873 pm_node_t *keyword_parameter_node = keywords_list->nodes[i];
6874 pm_constant_id_t name;
6875
6876 switch (PM_NODE_TYPE(keyword_parameter_node)) {
6877 case PM_OPTIONAL_KEYWORD_PARAMETER_NODE: {
6878 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6879 // ^^^^
6880 const pm_optional_keyword_parameter_node_t *cast = ((const pm_optional_keyword_parameter_node_t *) keyword_parameter_node);
6881
6882 pm_node_t *value = cast->value;
6883 name = cast->name;
6884
6885 if (!PM_NODE_FLAG_P(value, PM_NODE_FLAG_STATIC_LITERAL) || PM_CONTAINER_P(value)) {
6886 LABEL *end_label = NEW_LABEL(location.line);
6887
6888 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, name, 0);
6889 int kw_bits_idx = table_size - body->param.keyword->bits_start;
6890 PUSH_INSN2(ret, location, checkkeyword, INT2FIX(kw_bits_idx + VM_ENV_DATA_SIZE - 1), INT2FIX(optional_index));
6891 PUSH_INSNL(ret, location, branchif, end_label);
6892 PM_COMPILE(value);
6893 PUSH_SETLOCAL(ret, location, index.index, index.level);
6894 PUSH_LABEL(ret, end_label);
6895 }
6896 optional_index++;
6897 break;
6898 }
6899 case PM_REQUIRED_KEYWORD_PARAMETER_NODE:
6900 // def foo(a, (b, *c, d), e = 1, *f, g, (h, *i, j), k:, l: 1, **m, &n)
6901 // ^^
6902 break;
6903 default:
6904 rb_bug("Unexpected keyword parameter node type %s", pm_node_type_to_str(PM_NODE_TYPE(keyword_parameter_node)));
6905 }
6906 }
6907 }
6908
6909 if (requireds_list && requireds_list->size) {
6910 for (size_t i = 0; i < requireds_list->size; i++) {
6911 // For each MultiTargetNode, we're going to have one additional
6912 // anonymous local not represented in the locals table. We want
6913 // to account for this in our table size.
6914 const pm_node_t *required = requireds_list->nodes[i];
6915
6916 if (PM_NODE_TYPE_P(required, PM_MULTI_TARGET_NODE)) {
6917 PUSH_GETLOCAL(ret, location, table_size - (int)i, 0);
6918 pm_compile_destructured_param_writes(iseq, (const pm_multi_target_node_t *) required, ret, scope_node);
6919 }
6920 }
6921 }
6922
6923 if (posts_list && posts_list->size) {
6924 for (size_t i = 0; i < posts_list->size; i++) {
6925 // For each MultiTargetNode, we're going to have one additional
6926 // anonymous local not represented in the locals table. We want
6927 // to account for this in our table size.
6928 const pm_node_t *post = posts_list->nodes[i];
6929
6930 if (PM_NODE_TYPE_P(post, PM_MULTI_TARGET_NODE)) {
6931 PUSH_GETLOCAL(ret, location, table_size - body->param.post_start - (int) i, 0);
6932 pm_compile_destructured_param_writes(iseq, (const pm_multi_target_node_t *) post, ret, scope_node);
6933 }
6934 }
6935 }
6936
6937 switch (body->type) {
6938 case ISEQ_TYPE_PLAIN: {
6939 RUBY_ASSERT(PM_NODE_TYPE_P(scope_node->ast_node, PM_INTERPOLATED_REGULAR_EXPRESSION_NODE));
6940
6941 const pm_interpolated_regular_expression_node_t *cast = (const pm_interpolated_regular_expression_node_t *) scope_node->ast_node;
6942 pm_compile_regexp_dynamic(iseq, (const pm_node_t *) cast, &cast->parts, &location, ret, popped, scope_node);
6943
6944 break;
6945 }
6946 case ISEQ_TYPE_BLOCK: {
6947 LABEL *start = ISEQ_COMPILE_DATA(iseq)->start_label = NEW_LABEL(0);
6948 LABEL *end = ISEQ_COMPILE_DATA(iseq)->end_label = NEW_LABEL(0);
6949 const pm_node_location_t block_location = { .line = body->location.first_lineno, .node_id = scope_node->ast_node->node_id };
6950
6951 start->rescued = LABEL_RESCUE_BEG;
6952 end->rescued = LABEL_RESCUE_END;
6953
6954 // For nodes automatically assign the iteration variable to whatever
6955 // index variable. We need to handle that write here because it has
6956 // to happen in the context of the block. Note that this happens
6957 // before the B_CALL tracepoint event.
6958 if (PM_NODE_TYPE_P(scope_node->ast_node, PM_FOR_NODE)) {
6959 pm_compile_for_node_index(iseq, ((const pm_for_node_t *) scope_node->ast_node)->index, ret, scope_node);
6960 }
6961
6962 PUSH_TRACE(ret, RUBY_EVENT_B_CALL);
6963 PUSH_INSN(ret, block_location, nop);
6964 PUSH_LABEL(ret, start);
6965
6966 if (scope_node->body != NULL) {
6967 switch (PM_NODE_TYPE(scope_node->ast_node)) {
6968 case PM_POST_EXECUTION_NODE: {
6969 const pm_post_execution_node_t *cast = (const pm_post_execution_node_t *) scope_node->ast_node;
6970 PUSH_INSN1(ret, block_location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
6971
6972 // We create another ScopeNode from the statements within the PostExecutionNode
6973 pm_scope_node_t next_scope_node;
6974 pm_scope_node_init((const pm_node_t *) cast->statements, &next_scope_node, scope_node);
6975
6976 const rb_iseq_t *block = NEW_CHILD_ISEQ(&next_scope_node, make_name_for_block(body->parent_iseq), ISEQ_TYPE_BLOCK, location.line);
6977 pm_scope_node_destroy(&next_scope_node);
6978
6979 PUSH_CALL_WITH_BLOCK(ret, block_location, id_core_set_postexe, INT2FIX(0), block);
6980 break;
6981 }
6982 case PM_INTERPOLATED_REGULAR_EXPRESSION_NODE: {
6983 const pm_interpolated_regular_expression_node_t *cast = (const pm_interpolated_regular_expression_node_t *) scope_node->ast_node;
6984 pm_compile_regexp_dynamic(iseq, (const pm_node_t *) cast, &cast->parts, &location, ret, popped, scope_node);
6985 break;
6986 }
6987 default:
6988 pm_compile_node(iseq, scope_node->body, ret, popped, scope_node);
6989 break;
6990 }
6991 }
6992 else {
6993 PUSH_INSN(ret, block_location, putnil);
6994 }
6995
6996 PUSH_LABEL(ret, end);
6997 PUSH_TRACE(ret, RUBY_EVENT_B_RETURN);
6998 ISEQ_COMPILE_DATA(iseq)->last_line = body->location.code_location.end_pos.lineno;
6999
7000 /* wide range catch handler must put at last */
7001 PUSH_CATCH_ENTRY(CATCH_TYPE_REDO, start, end, NULL, start);
7002 PUSH_CATCH_ENTRY(CATCH_TYPE_NEXT, start, end, NULL, end);
7003 break;
7004 }
7005 case ISEQ_TYPE_ENSURE: {
7006 const pm_node_location_t statements_location = (scope_node->body != NULL ? PM_NODE_START_LOCATION(scope_node->parser, scope_node->body) : location);
7007 iseq_set_exception_local_table(iseq);
7008
7009 if (scope_node->body != NULL) {
7010 PM_COMPILE_POPPED((const pm_node_t *) scope_node->body);
7011 }
7012
7013 PUSH_GETLOCAL(ret, statements_location, 1, 0);
7014 PUSH_INSN1(ret, statements_location, throw, INT2FIX(0));
7015 return;
7016 }
7017 case ISEQ_TYPE_METHOD: {
7018 ISEQ_COMPILE_DATA(iseq)->root_node = (const void *) scope_node->body;
7019 PUSH_TRACE(ret, RUBY_EVENT_CALL);
7020
7021 if (scope_node->body) {
7022 PM_COMPILE((const pm_node_t *) scope_node->body);
7023 }
7024 else {
7025 PUSH_INSN(ret, location, putnil);
7026 }
7027
7028 ISEQ_COMPILE_DATA(iseq)->root_node = (const void *) scope_node->body;
7029 PUSH_TRACE(ret, RUBY_EVENT_RETURN);
7030
7031 ISEQ_COMPILE_DATA(iseq)->last_line = body->location.code_location.end_pos.lineno;
7032 break;
7033 }
7034 case ISEQ_TYPE_RESCUE: {
7035 iseq_set_exception_local_table(iseq);
7036 if (PM_NODE_TYPE_P(scope_node->ast_node, PM_RESCUE_MODIFIER_NODE)) {
7037 LABEL *lab = NEW_LABEL(location.line);
7038 LABEL *rescue_end = NEW_LABEL(location.line);
7039 PUSH_GETLOCAL(ret, location, LVAR_ERRINFO, 0);
7040 PUSH_INSN1(ret, location, putobject, rb_eStandardError);
7041 PUSH_INSN1(ret, location, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE));
7042 PUSH_INSNL(ret, location, branchif, lab);
7043 PUSH_INSNL(ret, location, jump, rescue_end);
7044 PUSH_LABEL(ret, lab);
7045 PUSH_TRACE(ret, RUBY_EVENT_RESCUE);
7046 PM_COMPILE((const pm_node_t *) scope_node->body);
7047 PUSH_INSN(ret, location, leave);
7048 PUSH_LABEL(ret, rescue_end);
7049 PUSH_GETLOCAL(ret, location, LVAR_ERRINFO, 0);
7050 }
7051 else {
7052 PM_COMPILE((const pm_node_t *) scope_node->ast_node);
7053 }
7054 PUSH_INSN1(ret, location, throw, INT2FIX(0));
7055
7056 return;
7057 }
7058 default:
7059 if (scope_node->body) {
7060 PM_COMPILE((const pm_node_t *) scope_node->body);
7061 }
7062 else {
7063 PUSH_INSN(ret, location, putnil);
7064 }
7065 break;
7066 }
7067
7068 if (PM_NODE_TYPE_P(scope_node->ast_node, PM_CLASS_NODE) || PM_NODE_TYPE_P(scope_node->ast_node, PM_MODULE_NODE)) {
7069 const pm_node_location_t end_location = PM_NODE_END_LOCATION(scope_node->parser, scope_node->ast_node);
7070 PUSH_TRACE(ret, RUBY_EVENT_END);
7071 ISEQ_COMPILE_DATA(iseq)->last_line = end_location.line;
7072 }
7073
7074 if (!PM_NODE_TYPE_P(scope_node->ast_node, PM_ENSURE_NODE)) {
7075 const pm_node_location_t location = { .line = ISEQ_COMPILE_DATA(iseq)->last_line, .node_id = scope_node->ast_node->node_id };
7076 PUSH_INSN(ret, location, leave);
7077 }
7078}
7079
7080static inline void
7081pm_compile_alias_global_variable_node(rb_iseq_t *iseq, const pm_alias_global_variable_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
7082{
7083 // alias $foo $bar
7084 // ^^^^^^^^^^^^^^^
7085 PUSH_INSN1(ret, *location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7086
7087 {
7088 const pm_location_t *name_loc = &node->new_name->location;
7089 VALUE operand = ID2SYM(rb_intern3((const char *) name_loc->start, name_loc->end - name_loc->start, scope_node->encoding));
7090 PUSH_INSN1(ret, *location, putobject, operand);
7091 }
7092
7093 {
7094 const pm_location_t *name_loc = &node->old_name->location;
7095 VALUE operand = ID2SYM(rb_intern3((const char *) name_loc->start, name_loc->end - name_loc->start, scope_node->encoding));
7096 PUSH_INSN1(ret, *location, putobject, operand);
7097 }
7098
7099 PUSH_SEND(ret, *location, id_core_set_variable_alias, INT2FIX(2));
7100 if (popped) PUSH_INSN(ret, *location, pop);
7101}
7102
7103static inline void
7104pm_compile_alias_method_node(rb_iseq_t *iseq, const pm_alias_method_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
7105{
7106 PUSH_INSN1(ret, *location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7107 PUSH_INSN1(ret, *location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CBASE));
7108 PM_COMPILE_NOT_POPPED(node->new_name);
7109 PM_COMPILE_NOT_POPPED(node->old_name);
7110
7111 PUSH_SEND(ret, *location, id_core_set_method_alias, INT2FIX(3));
7112 if (popped) PUSH_INSN(ret, *location, pop);
7113}
7114
7115static inline void
7116pm_compile_and_node(rb_iseq_t *iseq, const pm_and_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
7117{
7118 LABEL *end_label = NEW_LABEL(location->line);
7119
7120 PM_COMPILE_NOT_POPPED(node->left);
7121 if (!popped) PUSH_INSN(ret, *location, dup);
7122 PUSH_INSNL(ret, *location, branchunless, end_label);
7123
7124 if (!popped) PUSH_INSN(ret, *location, pop);
7125 PM_COMPILE(node->right);
7126 PUSH_LABEL(ret, end_label);
7127}
7128
7129static inline void
7130pm_compile_array_node(rb_iseq_t *iseq, const pm_node_t *node, const pm_node_list_t *elements, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
7131{
7132 // If every node in the array is static, then we can compile the entire
7133 // array now instead of later.
7134 if (PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL)) {
7135 // We're only going to compile this node if it's not popped. If it
7136 // is popped, then we know we don't need to do anything since it's
7137 // statically known.
7138 if (!popped) {
7139 if (elements->size) {
7140 VALUE value = pm_static_literal_value(iseq, node, scope_node);
7141 RB_OBJ_SET_FROZEN_SHAREABLE(value);
7142 PUSH_INSN1(ret, *location, duparray, value);
7143 }
7144 else {
7145 PUSH_INSN1(ret, *location, newarray, INT2FIX(0));
7146 }
7147 }
7148 return;
7149 }
7150
7151 // Here since we know there are possible side-effects inside the
7152 // array contents, we're going to build it entirely at runtime.
7153 // We'll do this by pushing all of the elements onto the stack and
7154 // then combining them with newarray.
7155 //
7156 // If this array is popped, then this serves only to ensure we enact
7157 // all side-effects (like method calls) that are contained within
7158 // the array contents.
7159 //
7160 // We treat all sequences of non-splat elements as their
7161 // own arrays, followed by a newarray, and then continually
7162 // concat the arrays with the SplatNode nodes.
7163 const int max_new_array_size = 0x100;
7164 const unsigned int min_tmp_array_size = 0x40;
7165
7166 int new_array_size = 0;
7167 bool first_chunk = true;
7168
7169 // This is an optimization wherein we keep track of whether or not
7170 // the previous element was a static literal. If it was, then we do
7171 // not attempt to check if we have a subarray that can be optimized.
7172 // If it was not, then we do check.
7173 bool static_literal = false;
7174
7175 // Either create a new array, or push to the existing array.
7176#define FLUSH_CHUNK \
7177 if (new_array_size) { \
7178 if (first_chunk) PUSH_INSN1(ret, *location, newarray, INT2FIX(new_array_size)); \
7179 else PUSH_INSN1(ret, *location, pushtoarray, INT2FIX(new_array_size)); \
7180 first_chunk = false; \
7181 new_array_size = 0; \
7182 }
7183
7184 for (size_t index = 0; index < elements->size; index++) {
7185 const pm_node_t *element = elements->nodes[index];
7186
7187 if (PM_NODE_TYPE_P(element, PM_SPLAT_NODE)) {
7188 FLUSH_CHUNK;
7189
7190 const pm_splat_node_t *splat_element = (const pm_splat_node_t *) element;
7191 if (splat_element->expression) {
7192 PM_COMPILE_NOT_POPPED(splat_element->expression);
7193 }
7194 else {
7195 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, PM_CONSTANT_MULT, 0);
7196 PUSH_GETLOCAL(ret, *location, index.index, index.level);
7197 }
7198
7199 if (first_chunk) {
7200 // If this is the first element of the array then we
7201 // need to splatarray the elements into the list.
7202 PUSH_INSN1(ret, *location, splatarray, Qtrue);
7203 first_chunk = false;
7204 }
7205 else {
7206 PUSH_INSN(ret, *location, concattoarray);
7207 }
7208
7209 static_literal = false;
7210 }
7211 else if (PM_NODE_TYPE_P(element, PM_KEYWORD_HASH_NODE)) {
7212 if (new_array_size == 0 && first_chunk) {
7213 PUSH_INSN1(ret, *location, newarray, INT2FIX(0));
7214 first_chunk = false;
7215 }
7216 else {
7217 FLUSH_CHUNK;
7218 }
7219
7220 // If we get here, then this is the last element of the
7221 // array/arguments, because it cannot be followed by
7222 // anything else without a syntax error. This looks like:
7223 //
7224 // [foo, bar, baz: qux]
7225 // ^^^^^^^^
7226 //
7227 // [foo, bar, **baz]
7228 // ^^^^^
7229 //
7230 const pm_keyword_hash_node_t *keyword_hash = (const pm_keyword_hash_node_t *) element;
7231 pm_compile_hash_elements(iseq, element, &keyword_hash->elements, 0, Qundef, false, ret, scope_node);
7232
7233 // This boolean controls the manner in which we push the
7234 // hash onto the array. If it's all keyword splats, then we
7235 // can use the very specialized pushtoarraykwsplat
7236 // instruction to check if it's empty before we push it.
7237 size_t splats = 0;
7238 while (splats < keyword_hash->elements.size && PM_NODE_TYPE_P(keyword_hash->elements.nodes[splats], PM_ASSOC_SPLAT_NODE)) splats++;
7239
7240 if (keyword_hash->elements.size == splats) {
7241 PUSH_INSN(ret, *location, pushtoarraykwsplat);
7242 }
7243 else {
7244 new_array_size++;
7245 }
7246 }
7247 else if (
7248 PM_NODE_FLAG_P(element, PM_NODE_FLAG_STATIC_LITERAL) &&
7249 !PM_CONTAINER_P(element) &&
7250 !static_literal &&
7251 ((index + min_tmp_array_size) < elements->size)
7252 ) {
7253 // If we have a static literal, then there's the potential
7254 // to group a bunch of them together with a literal array
7255 // and then concat them together.
7256 size_t right_index = index + 1;
7257 while (
7258 right_index < elements->size &&
7259 PM_NODE_FLAG_P(elements->nodes[right_index], PM_NODE_FLAG_STATIC_LITERAL) &&
7260 !PM_CONTAINER_P(elements->nodes[right_index])
7261 ) right_index++;
7262
7263 size_t tmp_array_size = right_index - index;
7264 if (tmp_array_size >= min_tmp_array_size) {
7265 VALUE tmp_array = rb_ary_hidden_new(tmp_array_size);
7266
7267 // Create the temporary array.
7268 for (; tmp_array_size; tmp_array_size--)
7269 rb_ary_push(tmp_array, pm_static_literal_value(iseq, elements->nodes[index++], scope_node));
7270
7271 index--; // about to be incremented by for loop
7272 RB_OBJ_SET_FROZEN_SHAREABLE(tmp_array);
7273
7274 // Emit the optimized code.
7275 FLUSH_CHUNK;
7276 if (first_chunk) {
7277 PUSH_INSN1(ret, *location, duparray, tmp_array);
7278 first_chunk = false;
7279 }
7280 else {
7281 PUSH_INSN1(ret, *location, putobject, tmp_array);
7282 PUSH_INSN(ret, *location, concattoarray);
7283 }
7284 }
7285 else {
7286 PM_COMPILE_NOT_POPPED(element);
7287 if (++new_array_size >= max_new_array_size) FLUSH_CHUNK;
7288 static_literal = true;
7289 }
7290 } else {
7291 PM_COMPILE_NOT_POPPED(element);
7292 if (++new_array_size >= max_new_array_size) FLUSH_CHUNK;
7293 static_literal = false;
7294 }
7295 }
7296
7297 FLUSH_CHUNK;
7298 if (popped) PUSH_INSN(ret, *location, pop);
7299
7300#undef FLUSH_CHUNK
7301}
7302
7303static inline void
7304pm_compile_break_node(rb_iseq_t *iseq, const pm_break_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
7305{
7306 unsigned long throw_flag = 0;
7307
7308 if (ISEQ_COMPILE_DATA(iseq)->redo_label != 0 && can_add_ensure_iseq(iseq)) {
7309 /* while/until */
7310 LABEL *splabel = NEW_LABEL(0);
7311 PUSH_LABEL(ret, splabel);
7312 PUSH_ADJUST(ret, *location, ISEQ_COMPILE_DATA(iseq)->redo_label);
7313
7314 if (node->arguments != NULL) {
7315 PM_COMPILE_NOT_POPPED((const pm_node_t *) node->arguments);
7316 }
7317 else {
7318 PUSH_INSN(ret, *location, putnil);
7319 }
7320
7321 pm_add_ensure_iseq(ret, iseq, 0, scope_node);
7322 PUSH_INSNL(ret, *location, jump, ISEQ_COMPILE_DATA(iseq)->end_label);
7323 PUSH_ADJUST_RESTORE(ret, splabel);
7324 if (!popped) PUSH_INSN(ret, *location, putnil);
7325 }
7326 else {
7327 const rb_iseq_t *ip = iseq;
7328
7329 while (ip) {
7330 if (!ISEQ_COMPILE_DATA(ip)) {
7331 ip = 0;
7332 break;
7333 }
7334
7335 if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) {
7336 throw_flag = VM_THROW_NO_ESCAPE_FLAG;
7337 }
7338 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) {
7339 throw_flag = 0;
7340 }
7341 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) {
7342 COMPILE_ERROR(iseq, location->line, "Invalid break");
7343 return;
7344 }
7345 else {
7346 ip = ISEQ_BODY(ip)->parent_iseq;
7347 continue;
7348 }
7349
7350 /* escape from block */
7351 if (node->arguments != NULL) {
7352 PM_COMPILE_NOT_POPPED((const pm_node_t *) node->arguments);
7353 }
7354 else {
7355 PUSH_INSN(ret, *location, putnil);
7356 }
7357
7358 PUSH_INSN1(ret, *location, throw, INT2FIX(throw_flag | TAG_BREAK));
7359 if (popped) PUSH_INSN(ret, *location, pop);
7360
7361 return;
7362 }
7363
7364 COMPILE_ERROR(iseq, location->line, "Invalid break");
7365 }
7366}
7367
7368static inline void
7369pm_compile_call_node(rb_iseq_t *iseq, const pm_call_node_t *node, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
7370{
7371 ID method_id = pm_constant_id_lookup(scope_node, node->name);
7372
7373 const pm_location_t *message_loc = &node->message_loc;
7374 if (message_loc->start == NULL) message_loc = &node->base.location;
7375
7376 const pm_node_location_t location = PM_LOCATION_START_LOCATION(scope_node->parser, message_loc, node->base.node_id);
7377 const char *builtin_func;
7378
7379 if (UNLIKELY(iseq_has_builtin_function_table(iseq)) && (builtin_func = pm_iseq_builtin_function_name(scope_node, node->receiver, method_id)) != NULL) {
7380 pm_compile_builtin_function_call(iseq, ret, scope_node, node, &location, popped, ISEQ_COMPILE_DATA(iseq)->current_block, builtin_func);
7381 return;
7382 }
7383
7384 LABEL *start = NEW_LABEL(location.line);
7385 if (node->block) PUSH_LABEL(ret, start);
7386
7387 switch (method_id) {
7388 case idUMinus: {
7389 if (pm_opt_str_freeze_p(iseq, node)) {
7390 VALUE value = parse_static_literal_string(iseq, scope_node, node->receiver, &((const pm_string_node_t * ) node->receiver)->unescaped);
7391 const struct rb_callinfo *callinfo = new_callinfo(iseq, idUMinus, 0, 0, NULL, FALSE);
7392 PUSH_INSN2(ret, location, opt_str_uminus, value, callinfo);
7393 if (popped) PUSH_INSN(ret, location, pop);
7394 return;
7395 }
7396 break;
7397 }
7398 case idFreeze: {
7399 if (pm_opt_str_freeze_p(iseq, node)) {
7400 VALUE value = parse_static_literal_string(iseq, scope_node, node->receiver, &((const pm_string_node_t * ) node->receiver)->unescaped);
7401 const struct rb_callinfo *callinfo = new_callinfo(iseq, idFreeze, 0, 0, NULL, FALSE);
7402 PUSH_INSN2(ret, location, opt_str_freeze, value, callinfo);
7403 if (popped) PUSH_INSN(ret, location, pop);
7404 return;
7405 }
7406 break;
7407 }
7408 }
7409
7410 if (PM_NODE_FLAG_P(node, PM_CALL_NODE_FLAGS_ATTRIBUTE_WRITE) && !popped) {
7411 PUSH_INSN(ret, location, putnil);
7412 }
7413
7414 if (node->receiver == NULL) {
7415 PUSH_INSN(ret, location, putself);
7416 }
7417 else {
7418 if (method_id == idCall && PM_NODE_TYPE_P(node->receiver, PM_LOCAL_VARIABLE_READ_NODE)) {
7419 const pm_local_variable_read_node_t *read_node_cast = (const pm_local_variable_read_node_t *) node->receiver;
7420 uint32_t node_id = node->receiver->node_id;
7421 int idx, level;
7422
7423 if (iseq_block_param_id_p(iseq, pm_constant_id_lookup(scope_node, read_node_cast->name), &idx, &level)) {
7424 ADD_ELEM(ret, (LINK_ELEMENT *) new_insn_body(iseq, location.line, node_id, BIN(getblockparamproxy), 2, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level)));
7425 }
7426 else {
7427 PM_COMPILE_NOT_POPPED(node->receiver);
7428 }
7429 }
7430 else {
7431 PM_COMPILE_NOT_POPPED(node->receiver);
7432 }
7433 }
7434
7435 pm_compile_call(iseq, node, ret, popped, scope_node, method_id, start);
7436 return;
7437}
7438
7439static inline void
7440pm_compile_call_operator_write_node(rb_iseq_t *iseq, const pm_call_operator_write_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
7441{
7442 int flag = 0;
7443
7444 if (PM_NODE_FLAG_P(node, PM_CALL_NODE_FLAGS_IGNORE_VISIBILITY)) {
7445 flag = VM_CALL_FCALL;
7446 }
7447
7448 PM_COMPILE_NOT_POPPED(node->receiver);
7449
7450 LABEL *safe_label = NULL;
7451 if (PM_NODE_FLAG_P(node, PM_CALL_NODE_FLAGS_SAFE_NAVIGATION)) {
7452 safe_label = NEW_LABEL(location->line);
7453 PUSH_INSN(ret, *location, dup);
7454 PUSH_INSNL(ret, *location, branchnil, safe_label);
7455 }
7456
7457 PUSH_INSN(ret, *location, dup);
7458
7459 ID id_read_name = pm_constant_id_lookup(scope_node, node->read_name);
7460 PUSH_SEND_WITH_FLAG(ret, *location, id_read_name, INT2FIX(0), INT2FIX(flag));
7461
7462 PM_COMPILE_NOT_POPPED(node->value);
7463 ID id_operator = pm_constant_id_lookup(scope_node, node->binary_operator);
7464 PUSH_SEND(ret, *location, id_operator, INT2FIX(1));
7465
7466 if (!popped) {
7467 PUSH_INSN(ret, *location, swap);
7468 PUSH_INSN1(ret, *location, topn, INT2FIX(1));
7469 }
7470
7471 ID id_write_name = pm_constant_id_lookup(scope_node, node->write_name);
7472 PUSH_SEND_WITH_FLAG(ret, *location, id_write_name, INT2FIX(1), INT2FIX(flag));
7473
7474 if (safe_label != NULL && popped) PUSH_LABEL(ret, safe_label);
7475 PUSH_INSN(ret, *location, pop);
7476 if (safe_label != NULL && !popped) PUSH_LABEL(ret, safe_label);
7477}
7478
7495static VALUE
7496pm_compile_case_node_dispatch(rb_iseq_t *iseq, VALUE dispatch, const pm_node_t *node, LABEL *label, const pm_scope_node_t *scope_node)
7497{
7498 VALUE key = Qundef;
7499 switch (PM_NODE_TYPE(node)) {
7500 case PM_FLOAT_NODE: {
7501 key = pm_static_literal_value(iseq, node, scope_node);
7502 double intptr;
7503
7504 if (modf(RFLOAT_VALUE(key), &intptr) == 0.0) {
7505 key = (FIXABLE(intptr) ? LONG2FIX((long) intptr) : rb_dbl2big(intptr));
7506 }
7507
7508 break;
7509 }
7510 case PM_FALSE_NODE:
7511 case PM_INTEGER_NODE:
7512 case PM_NIL_NODE:
7513 case PM_SOURCE_FILE_NODE:
7514 case PM_SOURCE_LINE_NODE:
7515 case PM_SYMBOL_NODE:
7516 case PM_TRUE_NODE:
7517 key = pm_static_literal_value(iseq, node, scope_node);
7518 break;
7519 case PM_STRING_NODE: {
7520 const pm_string_node_t *cast = (const pm_string_node_t *) node;
7521 key = parse_static_literal_string(iseq, scope_node, node, &cast->unescaped);
7522 break;
7523 }
7524 default:
7525 return Qundef;
7526 }
7527
7528 if (NIL_P(rb_hash_lookup(dispatch, key))) {
7529 rb_hash_aset(dispatch, key, ((VALUE) label) | 1);
7530 }
7531 return dispatch;
7532}
7533
7537static inline void
7538pm_compile_case_node(rb_iseq_t *iseq, const pm_case_node_t *cast, const pm_node_location_t *node_location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
7539{
7540 const pm_parser_t *parser = scope_node->parser;
7541 const pm_node_location_t location = *node_location;
7542 const pm_node_list_t *conditions = &cast->conditions;
7543
7544 // This is the anchor that we will compile the conditions of the various
7545 // `when` nodes into. If a match is found, they will need to jump into
7546 // the body_seq anchor to the correct spot.
7547 DECL_ANCHOR(cond_seq);
7548
7549 // This is the anchor that we will compile the bodies of the various
7550 // `when` nodes into. We'll make sure that the clauses that are compiled
7551 // jump into the correct spots within this anchor.
7552 DECL_ANCHOR(body_seq);
7553
7554 // This is the label where all of the when clauses will jump to if they
7555 // have matched and are done executing their bodies.
7556 LABEL *end_label = NEW_LABEL(location.line);
7557
7558 // If we have a predicate on this case statement, then it's going to
7559 // compare all of the various when clauses to the predicate. If we
7560 // don't, then it's basically an if-elsif-else chain.
7561 if (cast->predicate == NULL) {
7562 // Establish branch coverage for the case node.
7563 VALUE branches = Qfalse;
7564 rb_code_location_t case_location = { 0 };
7565 int branch_id = 0;
7566
7567 if (PM_BRANCH_COVERAGE_P(iseq)) {
7568 case_location = pm_code_location(scope_node, (const pm_node_t *) cast);
7569 branches = decl_branch_base(iseq, PTR2NUM(cast), &case_location, "case");
7570 }
7571
7572 // Loop through each clauses in the case node and compile each of
7573 // the conditions within them into cond_seq. If they match, they
7574 // should jump into their respective bodies in body_seq.
7575 for (size_t clause_index = 0; clause_index < conditions->size; clause_index++) {
7576 const pm_when_node_t *clause = (const pm_when_node_t *) conditions->nodes[clause_index];
7577 const pm_node_list_t *conditions = &clause->conditions;
7578
7579 int clause_lineno = pm_node_line_number(parser, (const pm_node_t *) clause);
7580 LABEL *label = NEW_LABEL(clause_lineno);
7581 PUSH_LABEL(body_seq, label);
7582
7583 // Establish branch coverage for the when clause.
7584 if (PM_BRANCH_COVERAGE_P(iseq)) {
7585 rb_code_location_t branch_location = pm_code_location(scope_node, clause->statements != NULL ? ((const pm_node_t *) clause->statements) : ((const pm_node_t *) clause));
7586 add_trace_branch_coverage(iseq, body_seq, &branch_location, branch_location.beg_pos.column, branch_id++, "when", branches);
7587 }
7588
7589 if (clause->statements != NULL) {
7590 pm_compile_node(iseq, (const pm_node_t *) clause->statements, body_seq, popped, scope_node);
7591 }
7592 else if (!popped) {
7593 PUSH_SYNTHETIC_PUTNIL(body_seq, iseq);
7594 }
7595
7596 PUSH_INSNL(body_seq, location, jump, end_label);
7597
7598 // Compile each of the conditions for the when clause into the
7599 // cond_seq. Each one should have a unique condition and should
7600 // jump to the subsequent one if it doesn't match.
7601 for (size_t condition_index = 0; condition_index < conditions->size; condition_index++) {
7602 const pm_node_t *condition = conditions->nodes[condition_index];
7603
7604 if (PM_NODE_TYPE_P(condition, PM_SPLAT_NODE)) {
7605 pm_node_location_t cond_location = PM_NODE_START_LOCATION(parser, condition);
7606 PUSH_INSN(cond_seq, cond_location, putnil);
7607 pm_compile_node(iseq, condition, cond_seq, false, scope_node);
7608 PUSH_INSN1(cond_seq, cond_location, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_WHEN | VM_CHECKMATCH_ARRAY));
7609 PUSH_INSNL(cond_seq, cond_location, branchif, label);
7610 }
7611 else {
7612 LABEL *next_label = NEW_LABEL(pm_node_line_number(parser, condition));
7613 pm_compile_branch_condition(iseq, cond_seq, condition, label, next_label, scope_node);
7614 PUSH_LABEL(cond_seq, next_label);
7615 }
7616 }
7617 }
7618
7619 // Establish branch coverage for the else clause (implicit or
7620 // explicit).
7621 if (PM_BRANCH_COVERAGE_P(iseq)) {
7622 rb_code_location_t branch_location;
7623
7624 if (cast->else_clause == NULL) {
7625 branch_location = case_location;
7626 } else if (cast->else_clause->statements == NULL) {
7627 branch_location = pm_code_location(scope_node, (const pm_node_t *) cast->else_clause);
7628 } else {
7629 branch_location = pm_code_location(scope_node, (const pm_node_t *) cast->else_clause->statements);
7630 }
7631
7632 add_trace_branch_coverage(iseq, cond_seq, &branch_location, branch_location.beg_pos.column, branch_id, "else", branches);
7633 }
7634
7635 // Compile the else clause if there is one.
7636 if (cast->else_clause != NULL) {
7637 pm_compile_node(iseq, (const pm_node_t *) cast->else_clause, cond_seq, popped, scope_node);
7638 }
7639 else if (!popped) {
7640 PUSH_SYNTHETIC_PUTNIL(cond_seq, iseq);
7641 }
7642
7643 // Finally, jump to the end label if none of the other conditions
7644 // have matched.
7645 PUSH_INSNL(cond_seq, location, jump, end_label);
7646 PUSH_SEQ(ret, cond_seq);
7647 }
7648 else {
7649 // Establish branch coverage for the case node.
7650 VALUE branches = Qfalse;
7651 rb_code_location_t case_location = { 0 };
7652 int branch_id = 0;
7653
7654 if (PM_BRANCH_COVERAGE_P(iseq)) {
7655 case_location = pm_code_location(scope_node, (const pm_node_t *) cast);
7656 branches = decl_branch_base(iseq, PTR2NUM(cast), &case_location, "case");
7657 }
7658
7659 // This is the label where everything will fall into if none of the
7660 // conditions matched.
7661 LABEL *else_label = NEW_LABEL(location.line);
7662
7663 // It's possible for us to speed up the case node by using a
7664 // dispatch hash. This is a hash that maps the conditions of the
7665 // various when clauses to the labels of their bodies. If we can
7666 // compile the conditions into a hash key, then we can use a hash
7667 // lookup to jump directly to the correct when clause body.
7668 VALUE dispatch = Qundef;
7669 if (ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction) {
7670 dispatch = rb_hash_new();
7671 RHASH_TBL_RAW(dispatch)->type = &cdhash_type;
7672 }
7673
7674 // We're going to loop through each of the conditions in the case
7675 // node and compile each of their contents into both the cond_seq
7676 // and the body_seq. Each condition will use its own label to jump
7677 // from its conditions into its body.
7678 //
7679 // Note that none of the code in the loop below should be adding
7680 // anything to ret, as we're going to be laying out the entire case
7681 // node instructions later.
7682 for (size_t clause_index = 0; clause_index < conditions->size; clause_index++) {
7683 const pm_when_node_t *clause = (const pm_when_node_t *) conditions->nodes[clause_index];
7684 pm_node_location_t clause_location = PM_NODE_START_LOCATION(parser, (const pm_node_t *) clause);
7685
7686 const pm_node_list_t *conditions = &clause->conditions;
7687 LABEL *label = NEW_LABEL(clause_location.line);
7688
7689 // Compile each of the conditions for the when clause into the
7690 // cond_seq. Each one should have a unique comparison that then
7691 // jumps into the body if it matches.
7692 for (size_t condition_index = 0; condition_index < conditions->size; condition_index++) {
7693 const pm_node_t *condition = conditions->nodes[condition_index];
7694 const pm_node_location_t condition_location = PM_NODE_START_LOCATION(parser, condition);
7695
7696 // If we haven't already abandoned the optimization, then
7697 // we're going to try to compile the condition into the
7698 // dispatch hash.
7699 if (dispatch != Qundef) {
7700 dispatch = pm_compile_case_node_dispatch(iseq, dispatch, condition, label, scope_node);
7701 }
7702
7703 if (PM_NODE_TYPE_P(condition, PM_SPLAT_NODE)) {
7704 PUSH_INSN(cond_seq, condition_location, dup);
7705 pm_compile_node(iseq, condition, cond_seq, false, scope_node);
7706 PUSH_INSN1(cond_seq, condition_location, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE | VM_CHECKMATCH_ARRAY));
7707 }
7708 else {
7709 if (PM_NODE_TYPE_P(condition, PM_STRING_NODE)) {
7710 const pm_string_node_t *string = (const pm_string_node_t *) condition;
7711 VALUE value = parse_static_literal_string(iseq, scope_node, condition, &string->unescaped);
7712 PUSH_INSN1(cond_seq, condition_location, putobject, value);
7713 }
7714 else {
7715 pm_compile_node(iseq, condition, cond_seq, false, scope_node);
7716 }
7717
7718 PUSH_INSN1(cond_seq, condition_location, topn, INT2FIX(1));
7719 PUSH_SEND_WITH_FLAG(cond_seq, condition_location, idEqq, INT2NUM(1), INT2FIX(VM_CALL_FCALL | VM_CALL_ARGS_SIMPLE));
7720 }
7721
7722 PUSH_INSNL(cond_seq, condition_location, branchif, label);
7723 }
7724
7725 // Now, add the label to the body and compile the body of the
7726 // when clause. This involves popping the predicate, compiling
7727 // the statements to be executed, and then compiling a jump to
7728 // the end of the case node.
7729 PUSH_LABEL(body_seq, label);
7730 PUSH_INSN(body_seq, clause_location, pop);
7731
7732 // Establish branch coverage for the when clause.
7733 if (PM_BRANCH_COVERAGE_P(iseq)) {
7734 rb_code_location_t branch_location = pm_code_location(scope_node, clause->statements != NULL ? ((const pm_node_t *) clause->statements) : ((const pm_node_t *) clause));
7735 add_trace_branch_coverage(iseq, body_seq, &branch_location, branch_location.beg_pos.column, branch_id++, "when", branches);
7736 }
7737
7738 if (clause->statements != NULL) {
7739 pm_compile_node(iseq, (const pm_node_t *) clause->statements, body_seq, popped, scope_node);
7740 }
7741 else if (!popped) {
7742 PUSH_SYNTHETIC_PUTNIL(body_seq, iseq);
7743 }
7744
7745 PUSH_INSNL(body_seq, clause_location, jump, end_label);
7746 }
7747
7748 // Now that we have compiled the conditions and the bodies of the
7749 // various when clauses, we can compile the predicate, lay out the
7750 // conditions, compile the fallback subsequent if there is one, and
7751 // finally put in the bodies of the when clauses.
7752 PM_COMPILE_NOT_POPPED(cast->predicate);
7753
7754 // If we have a dispatch hash, then we'll use it here to create the
7755 // optimization.
7756 if (dispatch != Qundef) {
7757 PUSH_INSN(ret, location, dup);
7758 RB_OBJ_SET_SHAREABLE(dispatch); // it is special that the hash is shareable but not frozen, because compile.c modify them. This Hahs instance is not accessible so it is safe to leave it.
7759 PUSH_INSN2(ret, location, opt_case_dispatch, dispatch, else_label);
7760 LABEL_REF(else_label);
7761 }
7762
7763 PUSH_SEQ(ret, cond_seq);
7764
7765 // Compile either the explicit else clause or an implicit else
7766 // clause.
7767 PUSH_LABEL(ret, else_label);
7768
7769 if (cast->else_clause != NULL) {
7770 pm_node_location_t else_location = PM_NODE_START_LOCATION(parser, cast->else_clause->statements != NULL ? ((const pm_node_t *) cast->else_clause->statements) : ((const pm_node_t *) cast->else_clause));
7771 PUSH_INSN(ret, else_location, pop);
7772
7773 // Establish branch coverage for the else clause.
7774 if (PM_BRANCH_COVERAGE_P(iseq)) {
7775 rb_code_location_t branch_location = pm_code_location(scope_node, cast->else_clause->statements != NULL ? ((const pm_node_t *) cast->else_clause->statements) : ((const pm_node_t *) cast->else_clause));
7776 add_trace_branch_coverage(iseq, ret, &branch_location, branch_location.beg_pos.column, branch_id, "else", branches);
7777 }
7778
7779 PM_COMPILE((const pm_node_t *) cast->else_clause);
7780 PUSH_INSNL(ret, else_location, jump, end_label);
7781 }
7782 else {
7783 PUSH_INSN(ret, location, pop);
7784
7785 // Establish branch coverage for the implicit else clause.
7786 if (PM_BRANCH_COVERAGE_P(iseq)) {
7787 add_trace_branch_coverage(iseq, ret, &case_location, case_location.beg_pos.column, branch_id, "else", branches);
7788 }
7789
7790 if (!popped) PUSH_INSN(ret, location, putnil);
7791 PUSH_INSNL(ret, location, jump, end_label);
7792 }
7793 }
7794
7795 PUSH_SEQ(ret, body_seq);
7796 PUSH_LABEL(ret, end_label);
7797}
7798
7799static inline void
7800pm_compile_case_match_node(rb_iseq_t *iseq, const pm_case_match_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
7801{
7802 // This is the anchor that we will compile the bodies of the various
7803 // `in` nodes into. We'll make sure that the patterns that are compiled
7804 // jump into the correct spots within this anchor.
7805 DECL_ANCHOR(body_seq);
7806
7807 // This is the anchor that we will compile the patterns of the various
7808 // `in` nodes into. If a match is found, they will need to jump into the
7809 // body_seq anchor to the correct spot.
7810 DECL_ANCHOR(cond_seq);
7811
7812 // This label is used to indicate the end of the entire node. It is
7813 // jumped to after the entire stack is cleaned up.
7814 LABEL *end_label = NEW_LABEL(location->line);
7815
7816 // This label is used as the fallback for the case match. If no match is
7817 // found, then we jump to this label. This is either an `else` clause or
7818 // an error handler.
7819 LABEL *else_label = NEW_LABEL(location->line);
7820
7821 // We're going to use this to uniquely identify each branch so that we
7822 // can track coverage information.
7823 rb_code_location_t case_location = { 0 };
7824 VALUE branches = Qfalse;
7825 int branch_id = 0;
7826
7827 if (PM_BRANCH_COVERAGE_P(iseq)) {
7828 case_location = pm_code_location(scope_node, (const pm_node_t *) node);
7829 branches = decl_branch_base(iseq, PTR2NUM(node), &case_location, "case");
7830 }
7831
7832 // If there is only one pattern, then the behavior changes a bit. It
7833 // effectively gets treated as a match required node (this is how it is
7834 // represented in the other parser).
7835 bool in_single_pattern = node->else_clause == NULL && node->conditions.size == 1;
7836
7837 // First, we're going to push a bunch of stuff onto the stack that is
7838 // going to serve as our scratch space.
7839 if (in_single_pattern) {
7840 PUSH_INSN(ret, *location, putnil); // key error key
7841 PUSH_INSN(ret, *location, putnil); // key error matchee
7842 PUSH_INSN1(ret, *location, putobject, Qfalse); // key error?
7843 PUSH_INSN(ret, *location, putnil); // error string
7844 }
7845
7846 // Now we're going to compile the value to match against.
7847 PUSH_INSN(ret, *location, putnil); // deconstruct cache
7848 PM_COMPILE_NOT_POPPED(node->predicate);
7849
7850 // Next, we'll loop through every in clause and compile its body into
7851 // the body_seq anchor and its pattern into the cond_seq anchor. We'll
7852 // make sure the pattern knows how to jump correctly into the body if it
7853 // finds a match.
7854 for (size_t index = 0; index < node->conditions.size; index++) {
7855 const pm_node_t *condition = node->conditions.nodes[index];
7856 RUBY_ASSERT(PM_NODE_TYPE_P(condition, PM_IN_NODE));
7857
7858 const pm_in_node_t *in_node = (const pm_in_node_t *) condition;
7859 const pm_node_location_t in_location = PM_NODE_START_LOCATION(scope_node->parser, in_node);
7860 const pm_node_location_t pattern_location = PM_NODE_START_LOCATION(scope_node->parser, in_node->pattern);
7861
7862 if (branch_id) {
7863 PUSH_INSN(body_seq, in_location, putnil);
7864 }
7865
7866 LABEL *body_label = NEW_LABEL(in_location.line);
7867 PUSH_LABEL(body_seq, body_label);
7868 PUSH_INSN1(body_seq, in_location, adjuststack, INT2FIX(in_single_pattern ? 6 : 2));
7869
7870 // Establish branch coverage for the in clause.
7871 if (PM_BRANCH_COVERAGE_P(iseq)) {
7872 rb_code_location_t branch_location = pm_code_location(scope_node, in_node->statements != NULL ? ((const pm_node_t *) in_node->statements) : ((const pm_node_t *) in_node));
7873 add_trace_branch_coverage(iseq, body_seq, &branch_location, branch_location.beg_pos.column, branch_id++, "in", branches);
7874 }
7875
7876 if (in_node->statements != NULL) {
7877 PM_COMPILE_INTO_ANCHOR(body_seq, (const pm_node_t *) in_node->statements);
7878 }
7879 else if (!popped) {
7880 PUSH_SYNTHETIC_PUTNIL(body_seq, iseq);
7881 }
7882
7883 PUSH_INSNL(body_seq, in_location, jump, end_label);
7884 LABEL *next_pattern_label = NEW_LABEL(pattern_location.line);
7885
7886 PUSH_INSN(cond_seq, pattern_location, dup);
7887 pm_compile_pattern(iseq, scope_node, in_node->pattern, cond_seq, body_label, next_pattern_label, in_single_pattern, true, 2);
7888 PUSH_LABEL(cond_seq, next_pattern_label);
7889 LABEL_UNREMOVABLE(next_pattern_label);
7890 }
7891
7892 if (node->else_clause != NULL) {
7893 // If we have an `else` clause, then this becomes our fallback (and
7894 // there is no need to compile in code to potentially raise an
7895 // error).
7896 const pm_else_node_t *else_node = node->else_clause;
7897
7898 PUSH_LABEL(cond_seq, else_label);
7899 PUSH_INSN(cond_seq, *location, pop);
7900 PUSH_INSN(cond_seq, *location, pop);
7901
7902 // Establish branch coverage for the else clause.
7903 if (PM_BRANCH_COVERAGE_P(iseq)) {
7904 rb_code_location_t branch_location = pm_code_location(scope_node, else_node->statements != NULL ? ((const pm_node_t *) else_node->statements) : ((const pm_node_t *) else_node));
7905 add_trace_branch_coverage(iseq, cond_seq, &branch_location, branch_location.beg_pos.column, branch_id, "else", branches);
7906 }
7907
7908 PM_COMPILE_INTO_ANCHOR(cond_seq, (const pm_node_t *) else_node);
7909 PUSH_INSNL(cond_seq, *location, jump, end_label);
7910 PUSH_INSN(cond_seq, *location, putnil);
7911 if (popped) PUSH_INSN(cond_seq, *location, putnil);
7912 }
7913 else {
7914 // Otherwise, if we do not have an `else` clause, we will compile in
7915 // the code to handle raising an appropriate error.
7916 PUSH_LABEL(cond_seq, else_label);
7917
7918 // Establish branch coverage for the implicit else clause.
7919 add_trace_branch_coverage(iseq, cond_seq, &case_location, case_location.beg_pos.column, branch_id, "else", branches);
7920
7921 if (in_single_pattern) {
7922 pm_compile_pattern_error_handler(iseq, scope_node, (const pm_node_t *) node, cond_seq, end_label, popped);
7923 }
7924 else {
7925 PUSH_INSN1(cond_seq, *location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7926 PUSH_INSN1(cond_seq, *location, putobject, rb_eNoMatchingPatternError);
7927 PUSH_INSN1(cond_seq, *location, topn, INT2FIX(2));
7928 PUSH_SEND(cond_seq, *location, id_core_raise, INT2FIX(2));
7929
7930 PUSH_INSN1(cond_seq, *location, adjuststack, INT2FIX(3));
7931 if (!popped) PUSH_INSN(cond_seq, *location, putnil);
7932 PUSH_INSNL(cond_seq, *location, jump, end_label);
7933 PUSH_INSN1(cond_seq, *location, dupn, INT2FIX(1));
7934 if (popped) PUSH_INSN(cond_seq, *location, putnil);
7935 }
7936 }
7937
7938 // At the end of all of this compilation, we will add the code for the
7939 // conditions first, then the various bodies, then mark the end of the
7940 // entire sequence with the end label.
7941 PUSH_SEQ(ret, cond_seq);
7942 PUSH_SEQ(ret, body_seq);
7943 PUSH_LABEL(ret, end_label);
7944}
7945
7946static inline void
7947pm_compile_forwarding_super_node(rb_iseq_t *iseq, const pm_forwarding_super_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
7948{
7949 const rb_iseq_t *block = NULL;
7950 const rb_iseq_t *previous_block = NULL;
7951 LABEL *retry_label = NULL;
7952 LABEL *retry_end_l = NULL;
7953
7954 if (node->block != NULL) {
7955 previous_block = ISEQ_COMPILE_DATA(iseq)->current_block;
7956 ISEQ_COMPILE_DATA(iseq)->current_block = NULL;
7957
7958 retry_label = NEW_LABEL(location->line);
7959 retry_end_l = NEW_LABEL(location->line);
7960
7961 PUSH_LABEL(ret, retry_label);
7962 }
7963 else {
7964 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
7965 }
7966
7967 PUSH_INSN(ret, *location, putself);
7968 int flag = VM_CALL_ZSUPER | VM_CALL_SUPER | VM_CALL_FCALL;
7969
7970 if (node->block != NULL) {
7971 pm_scope_node_t next_scope_node;
7972 pm_scope_node_init((const pm_node_t *) node->block, &next_scope_node, scope_node);
7973
7974 ISEQ_COMPILE_DATA(iseq)->current_block = block = NEW_CHILD_ISEQ(&next_scope_node, make_name_for_block(iseq), ISEQ_TYPE_BLOCK, location->line);
7975 pm_scope_node_destroy(&next_scope_node);
7976 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE) block);
7977 }
7978
7979 DECL_ANCHOR(args);
7980
7981 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
7982 const rb_iseq_t *local_iseq = body->local_iseq;
7983 const struct rb_iseq_constant_body *const local_body = ISEQ_BODY(local_iseq);
7984
7985 int argc = 0;
7986 int depth = get_lvar_level(iseq);
7987
7988 if (ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->param.flags.forwardable) {
7989 flag |= VM_CALL_FORWARDING;
7990 pm_local_index_t mult_local = pm_lookup_local_index(iseq, scope_node, PM_CONSTANT_DOT3, 0);
7991 PUSH_GETLOCAL(ret, *location, mult_local.index, mult_local.level);
7992
7993 const struct rb_callinfo *callinfo = new_callinfo(iseq, 0, 0, flag, NULL, block != NULL);
7994 PUSH_INSN2(ret, *location, invokesuperforward, callinfo, block);
7995
7996 if (popped) PUSH_INSN(ret, *location, pop);
7997 if (node->block) {
7998 ISEQ_COMPILE_DATA(iseq)->current_block = previous_block;
7999 }
8000 return;
8001 }
8002
8003 if (local_body->param.flags.has_lead) {
8004 /* required arguments */
8005 for (int i = 0; i < local_body->param.lead_num; i++) {
8006 int idx = local_body->local_table_size - i;
8007 PUSH_GETLOCAL(args, *location, idx, depth);
8008 }
8009 argc += local_body->param.lead_num;
8010 }
8011
8012 if (local_body->param.flags.has_opt) {
8013 /* optional arguments */
8014 for (int j = 0; j < local_body->param.opt_num; j++) {
8015 int idx = local_body->local_table_size - (argc + j);
8016 PUSH_GETLOCAL(args, *location, idx, depth);
8017 }
8018 argc += local_body->param.opt_num;
8019 }
8020
8021 if (local_body->param.flags.has_rest) {
8022 /* rest argument */
8023 int idx = local_body->local_table_size - local_body->param.rest_start;
8024 PUSH_GETLOCAL(args, *location, idx, depth);
8025 PUSH_INSN1(args, *location, splatarray, Qfalse);
8026
8027 argc = local_body->param.rest_start + 1;
8028 flag |= VM_CALL_ARGS_SPLAT;
8029 }
8030
8031 if (local_body->param.flags.has_post) {
8032 /* post arguments */
8033 int post_len = local_body->param.post_num;
8034 int post_start = local_body->param.post_start;
8035
8036 int j = 0;
8037 for (; j < post_len; j++) {
8038 int idx = local_body->local_table_size - (post_start + j);
8039 PUSH_GETLOCAL(args, *location, idx, depth);
8040 }
8041
8042 if (local_body->param.flags.has_rest) {
8043 // argc remains unchanged from rest branch
8044 PUSH_INSN1(args, *location, newarray, INT2FIX(j));
8045 PUSH_INSN(args, *location, concatarray);
8046 }
8047 else {
8048 argc = post_len + post_start;
8049 }
8050 }
8051
8052 const struct rb_iseq_param_keyword *const local_keyword = local_body->param.keyword;
8053 if (local_body->param.flags.has_kw) {
8054 int local_size = local_body->local_table_size;
8055 argc++;
8056
8057 PUSH_INSN1(args, *location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8058
8059 if (local_body->param.flags.has_kwrest) {
8060 int idx = local_body->local_table_size - local_keyword->rest_start;
8061 PUSH_GETLOCAL(args, *location, idx, depth);
8062 RUBY_ASSERT(local_keyword->num > 0);
8063 PUSH_SEND(args, *location, rb_intern("dup"), INT2FIX(0));
8064 }
8065 else {
8066 PUSH_INSN1(args, *location, newhash, INT2FIX(0));
8067 }
8068 int i = 0;
8069 for (; i < local_keyword->num; ++i) {
8070 ID id = local_keyword->table[i];
8071 int idx = local_size - get_local_var_idx(local_iseq, id);
8072
8073 {
8074 VALUE operand = ID2SYM(id);
8075 PUSH_INSN1(args, *location, putobject, operand);
8076 }
8077
8078 PUSH_GETLOCAL(args, *location, idx, depth);
8079 }
8080
8081 PUSH_SEND(args, *location, id_core_hash_merge_ptr, INT2FIX(i * 2 + 1));
8082 flag |= VM_CALL_KW_SPLAT| VM_CALL_KW_SPLAT_MUT;
8083 }
8084 else if (local_body->param.flags.has_kwrest) {
8085 int idx = local_body->local_table_size - local_keyword->rest_start;
8086 PUSH_GETLOCAL(args, *location, idx, depth);
8087 argc++;
8088 flag |= VM_CALL_KW_SPLAT;
8089 }
8090
8091 PUSH_SEQ(ret, args);
8092
8093 {
8094 const struct rb_callinfo *callinfo = new_callinfo(iseq, 0, argc, flag, NULL, block != NULL);
8095 PUSH_INSN2(ret, *location, invokesuper, callinfo, block);
8096 }
8097
8098 if (node->block != NULL) {
8099 pm_compile_retry_end_label(iseq, ret, retry_end_l);
8100 PUSH_CATCH_ENTRY(CATCH_TYPE_BREAK, retry_label, retry_end_l, block, retry_end_l);
8101 ISEQ_COMPILE_DATA(iseq)->current_block = previous_block;
8102 }
8103
8104 if (popped) PUSH_INSN(ret, *location, pop);
8105}
8106
8107static inline void
8108pm_compile_match_required_node(rb_iseq_t *iseq, const pm_match_required_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
8109{
8110 LABEL *matched_label = NEW_LABEL(location->line);
8111 LABEL *unmatched_label = NEW_LABEL(location->line);
8112 LABEL *done_label = NEW_LABEL(location->line);
8113
8114 // First, we're going to push a bunch of stuff onto the stack that is
8115 // going to serve as our scratch space.
8116 PUSH_INSN(ret, *location, putnil); // key error key
8117 PUSH_INSN(ret, *location, putnil); // key error matchee
8118 PUSH_INSN1(ret, *location, putobject, Qfalse); // key error?
8119 PUSH_INSN(ret, *location, putnil); // error string
8120 PUSH_INSN(ret, *location, putnil); // deconstruct cache
8121
8122 // Next we're going to compile the value expression such that it's on
8123 // the stack.
8124 PM_COMPILE_NOT_POPPED(node->value);
8125
8126 // Here we'll dup it so that it can be used for comparison, but also be
8127 // used for error handling.
8128 PUSH_INSN(ret, *location, dup);
8129
8130 // Next we'll compile the pattern. We indicate to the pm_compile_pattern
8131 // function that this is the only pattern that will be matched against
8132 // through the in_single_pattern parameter. We also indicate that the
8133 // value to compare against is 2 slots from the top of the stack (the
8134 // base_index parameter).
8135 pm_compile_pattern(iseq, scope_node, node->pattern, ret, matched_label, unmatched_label, true, true, 2);
8136
8137 // If the pattern did not match the value, then we're going to compile
8138 // in our error handler code. This will determine which error to raise
8139 // and raise it.
8140 PUSH_LABEL(ret, unmatched_label);
8141 pm_compile_pattern_error_handler(iseq, scope_node, (const pm_node_t *) node, ret, done_label, popped);
8142
8143 // If the pattern did match, we'll clean up the values we've pushed onto
8144 // the stack and then push nil onto the stack if it's not popped.
8145 PUSH_LABEL(ret, matched_label);
8146 PUSH_INSN1(ret, *location, adjuststack, INT2FIX(6));
8147 if (!popped) PUSH_INSN(ret, *location, putnil);
8148 PUSH_INSNL(ret, *location, jump, done_label);
8149
8150 PUSH_LABEL(ret, done_label);
8151}
8152
8153static inline void
8154pm_compile_match_write_node(rb_iseq_t *iseq, const pm_match_write_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
8155{
8156 LABEL *fail_label = NEW_LABEL(location->line);
8157 LABEL *end_label = NEW_LABEL(location->line);
8158
8159 // First, we'll compile the call so that all of its instructions are
8160 // present. Then we'll compile all of the local variable targets.
8161 PM_COMPILE_NOT_POPPED((const pm_node_t *) node->call);
8162
8163 // Now, check if the match was successful. If it was, then we'll
8164 // continue on and assign local variables. Otherwise we'll skip over the
8165 // assignment code.
8166 {
8167 VALUE operand = rb_id2sym(idBACKREF);
8168 PUSH_INSN1(ret, *location, getglobal, operand);
8169 }
8170
8171 PUSH_INSN(ret, *location, dup);
8172 PUSH_INSNL(ret, *location, branchunless, fail_label);
8173
8174 // If there's only a single local variable target, we can skip some of
8175 // the bookkeeping, so we'll put a special branch here.
8176 size_t targets_count = node->targets.size;
8177
8178 if (targets_count == 1) {
8179 const pm_node_t *target = node->targets.nodes[0];
8180 RUBY_ASSERT(PM_NODE_TYPE_P(target, PM_LOCAL_VARIABLE_TARGET_NODE));
8181
8182 const pm_local_variable_target_node_t *local_target = (const pm_local_variable_target_node_t *) target;
8183 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, local_target->name, local_target->depth);
8184
8185 {
8186 VALUE operand = rb_id2sym(pm_constant_id_lookup(scope_node, local_target->name));
8187 PUSH_INSN1(ret, *location, putobject, operand);
8188 }
8189
8190 PUSH_SEND(ret, *location, idAREF, INT2FIX(1));
8191 PUSH_LABEL(ret, fail_label);
8192 PUSH_SETLOCAL(ret, *location, index.index, index.level);
8193 if (popped) PUSH_INSN(ret, *location, pop);
8194 return;
8195 }
8196
8197 DECL_ANCHOR(fail_anchor);
8198
8199 // Otherwise there is more than one local variable target, so we'll need
8200 // to do some bookkeeping.
8201 for (size_t targets_index = 0; targets_index < targets_count; targets_index++) {
8202 const pm_node_t *target = node->targets.nodes[targets_index];
8203 RUBY_ASSERT(PM_NODE_TYPE_P(target, PM_LOCAL_VARIABLE_TARGET_NODE));
8204
8205 const pm_local_variable_target_node_t *local_target = (const pm_local_variable_target_node_t *) target;
8206 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, local_target->name, local_target->depth);
8207
8208 if (((size_t) targets_index) < (targets_count - 1)) {
8209 PUSH_INSN(ret, *location, dup);
8210 }
8211
8212 {
8213 VALUE operand = rb_id2sym(pm_constant_id_lookup(scope_node, local_target->name));
8214 PUSH_INSN1(ret, *location, putobject, operand);
8215 }
8216
8217 PUSH_SEND(ret, *location, idAREF, INT2FIX(1));
8218 PUSH_SETLOCAL(ret, *location, index.index, index.level);
8219
8220 PUSH_INSN(fail_anchor, *location, putnil);
8221 PUSH_SETLOCAL(fail_anchor, *location, index.index, index.level);
8222 }
8223
8224 // Since we matched successfully, now we'll jump to the end.
8225 PUSH_INSNL(ret, *location, jump, end_label);
8226
8227 // In the case that the match failed, we'll loop through each local
8228 // variable target and set all of them to `nil`.
8229 PUSH_LABEL(ret, fail_label);
8230 PUSH_INSN(ret, *location, pop);
8231 PUSH_SEQ(ret, fail_anchor);
8232
8233 // Finally, we can push the end label for either case.
8234 PUSH_LABEL(ret, end_label);
8235 if (popped) PUSH_INSN(ret, *location, pop);
8236}
8237
8238static inline void
8239pm_compile_next_node(rb_iseq_t *iseq, const pm_next_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
8240{
8241 if (ISEQ_COMPILE_DATA(iseq)->redo_label != 0 && can_add_ensure_iseq(iseq)) {
8242 LABEL *splabel = NEW_LABEL(0);
8243 PUSH_LABEL(ret, splabel);
8244
8245 if (node->arguments) {
8246 PM_COMPILE_NOT_POPPED((const pm_node_t *) node->arguments);
8247 }
8248 else {
8249 PUSH_INSN(ret, *location, putnil);
8250 }
8251 pm_add_ensure_iseq(ret, iseq, 0, scope_node);
8252
8253 PUSH_ADJUST(ret, *location, ISEQ_COMPILE_DATA(iseq)->redo_label);
8254 PUSH_INSNL(ret, *location, jump, ISEQ_COMPILE_DATA(iseq)->start_label);
8255
8256 PUSH_ADJUST_RESTORE(ret, splabel);
8257 if (!popped) PUSH_INSN(ret, *location, putnil);
8258 }
8259 else if (ISEQ_COMPILE_DATA(iseq)->end_label && can_add_ensure_iseq(iseq)) {
8260 LABEL *splabel = NEW_LABEL(0);
8261
8262 PUSH_LABEL(ret, splabel);
8263 PUSH_ADJUST(ret, *location, ISEQ_COMPILE_DATA(iseq)->start_label);
8264
8265 if (node->arguments != NULL) {
8266 PM_COMPILE_NOT_POPPED((const pm_node_t *) node->arguments);
8267 }
8268 else {
8269 PUSH_INSN(ret, *location, putnil);
8270 }
8271
8272 pm_add_ensure_iseq(ret, iseq, 0, scope_node);
8273 PUSH_INSNL(ret, *location, jump, ISEQ_COMPILE_DATA(iseq)->end_label);
8274 PUSH_ADJUST_RESTORE(ret, splabel);
8275 splabel->unremovable = FALSE;
8276
8277 if (!popped) PUSH_INSN(ret, *location, putnil);
8278 }
8279 else {
8280 const rb_iseq_t *ip = iseq;
8281 unsigned long throw_flag = 0;
8282
8283 while (ip) {
8284 if (!ISEQ_COMPILE_DATA(ip)) {
8285 ip = 0;
8286 break;
8287 }
8288
8289 throw_flag = VM_THROW_NO_ESCAPE_FLAG;
8290 if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) {
8291 /* while loop */
8292 break;
8293 }
8294 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) {
8295 break;
8296 }
8297 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) {
8298 COMPILE_ERROR(iseq, location->line, "Invalid next");
8299 return;
8300 }
8301
8302 ip = ISEQ_BODY(ip)->parent_iseq;
8303 }
8304
8305 if (ip != 0) {
8306 if (node->arguments) {
8307 PM_COMPILE_NOT_POPPED((const pm_node_t *) node->arguments);
8308 }
8309 else {
8310 PUSH_INSN(ret, *location, putnil);
8311 }
8312
8313 PUSH_INSN1(ret, *location, throw, INT2FIX(throw_flag | TAG_NEXT));
8314 if (popped) PUSH_INSN(ret, *location, pop);
8315 }
8316 else {
8317 COMPILE_ERROR(iseq, location->line, "Invalid next");
8318 }
8319 }
8320}
8321
8322static inline void
8323pm_compile_redo_node(rb_iseq_t *iseq, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
8324{
8325 if (ISEQ_COMPILE_DATA(iseq)->redo_label && can_add_ensure_iseq(iseq)) {
8326 LABEL *splabel = NEW_LABEL(0);
8327
8328 PUSH_LABEL(ret, splabel);
8329 PUSH_ADJUST(ret, *location, ISEQ_COMPILE_DATA(iseq)->redo_label);
8330 pm_add_ensure_iseq(ret, iseq, 0, scope_node);
8331
8332 PUSH_INSNL(ret, *location, jump, ISEQ_COMPILE_DATA(iseq)->redo_label);
8333 PUSH_ADJUST_RESTORE(ret, splabel);
8334 if (!popped) PUSH_INSN(ret, *location, putnil);
8335 }
8336 else if (ISEQ_BODY(iseq)->type != ISEQ_TYPE_EVAL && ISEQ_COMPILE_DATA(iseq)->start_label && can_add_ensure_iseq(iseq)) {
8337 LABEL *splabel = NEW_LABEL(0);
8338
8339 PUSH_LABEL(ret, splabel);
8340 pm_add_ensure_iseq(ret, iseq, 0, scope_node);
8341 PUSH_ADJUST(ret, *location, ISEQ_COMPILE_DATA(iseq)->start_label);
8342
8343 PUSH_INSNL(ret, *location, jump, ISEQ_COMPILE_DATA(iseq)->start_label);
8344 PUSH_ADJUST_RESTORE(ret, splabel);
8345 if (!popped) PUSH_INSN(ret, *location, putnil);
8346 }
8347 else {
8348 const rb_iseq_t *ip = iseq;
8349
8350 while (ip) {
8351 if (!ISEQ_COMPILE_DATA(ip)) {
8352 ip = 0;
8353 break;
8354 }
8355
8356 if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) {
8357 break;
8358 }
8359 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) {
8360 break;
8361 }
8362 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) {
8363 COMPILE_ERROR(iseq, location->line, "Invalid redo");
8364 return;
8365 }
8366
8367 ip = ISEQ_BODY(ip)->parent_iseq;
8368 }
8369
8370 if (ip != 0) {
8371 PUSH_INSN(ret, *location, putnil);
8372 PUSH_INSN1(ret, *location, throw, INT2FIX(VM_THROW_NO_ESCAPE_FLAG | TAG_REDO));
8373 if (popped) PUSH_INSN(ret, *location, pop);
8374 }
8375 else {
8376 COMPILE_ERROR(iseq, location->line, "Invalid redo");
8377 }
8378 }
8379}
8380
8381static inline void
8382pm_compile_rescue_node(rb_iseq_t *iseq, const pm_rescue_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
8383{
8384 iseq_set_exception_local_table(iseq);
8385
8386 // First, establish the labels that we need to be able to jump to within
8387 // this compilation block.
8388 LABEL *exception_match_label = NEW_LABEL(location->line);
8389 LABEL *rescue_end_label = NEW_LABEL(location->line);
8390
8391 // Next, compile each of the exceptions that we're going to be
8392 // handling. For each one, we'll add instructions to check if the
8393 // exception matches the raised one, and if it does then jump to the
8394 // exception_match_label label. Otherwise it will fall through to the
8395 // subsequent check. If there are no exceptions, we'll only check
8396 // StandardError.
8397 const pm_node_list_t *exceptions = &node->exceptions;
8398
8399 if (exceptions->size > 0) {
8400 for (size_t index = 0; index < exceptions->size; index++) {
8401 PUSH_GETLOCAL(ret, *location, LVAR_ERRINFO, 0);
8402 PM_COMPILE(exceptions->nodes[index]);
8403 int checkmatch_flags = VM_CHECKMATCH_TYPE_RESCUE;
8404 if (PM_NODE_TYPE_P(exceptions->nodes[index], PM_SPLAT_NODE)) {
8405 checkmatch_flags |= VM_CHECKMATCH_ARRAY;
8406 }
8407 PUSH_INSN1(ret, *location, checkmatch, INT2FIX(checkmatch_flags));
8408 PUSH_INSNL(ret, *location, branchif, exception_match_label);
8409 }
8410 }
8411 else {
8412 PUSH_GETLOCAL(ret, *location, LVAR_ERRINFO, 0);
8413 PUSH_INSN1(ret, *location, putobject, rb_eStandardError);
8414 PUSH_INSN1(ret, *location, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE));
8415 PUSH_INSNL(ret, *location, branchif, exception_match_label);
8416 }
8417
8418 // If none of the exceptions that we are matching against matched, then
8419 // we'll jump straight to the rescue_end_label label.
8420 PUSH_INSNL(ret, *location, jump, rescue_end_label);
8421
8422 // Here we have the exception_match_label, which is where the
8423 // control-flow goes in the case that one of the exceptions matched.
8424 // Here we will compile the instructions to handle the exception.
8425 PUSH_LABEL(ret, exception_match_label);
8426 PUSH_TRACE(ret, RUBY_EVENT_RESCUE);
8427
8428 // If we have a reference to the exception, then we'll compile the write
8429 // into the instruction sequence. This can look quite different
8430 // depending on the kind of write being performed.
8431 if (node->reference) {
8432 DECL_ANCHOR(writes);
8433 DECL_ANCHOR(cleanup);
8434
8435 pm_compile_target_node(iseq, node->reference, ret, writes, cleanup, scope_node, NULL);
8436 PUSH_GETLOCAL(ret, *location, LVAR_ERRINFO, 0);
8437
8438 PUSH_SEQ(ret, writes);
8439 PUSH_SEQ(ret, cleanup);
8440 }
8441
8442 // If we have statements to execute, we'll compile them here. Otherwise
8443 // we'll push nil onto the stack.
8444 if (node->statements != NULL) {
8445 // We'll temporarily remove the end_label location from the iseq
8446 // when compiling the statements so that next/redo statements
8447 // inside the body will throw to the correct place instead of
8448 // jumping straight to the end of this iseq
8449 LABEL *prev_end = ISEQ_COMPILE_DATA(iseq)->end_label;
8450 ISEQ_COMPILE_DATA(iseq)->end_label = NULL;
8451
8452 PM_COMPILE((const pm_node_t *) node->statements);
8453
8454 // Now restore the end_label
8455 ISEQ_COMPILE_DATA(iseq)->end_label = prev_end;
8456 }
8457 else {
8458 PUSH_INSN(ret, *location, putnil);
8459 }
8460
8461 PUSH_INSN(ret, *location, leave);
8462
8463 // Here we'll insert the rescue_end_label label, which is jumped to if
8464 // none of the exceptions matched. It will cause the control-flow to
8465 // either jump to the next rescue clause or it will fall through to the
8466 // subsequent instruction returning the raised error.
8467 PUSH_LABEL(ret, rescue_end_label);
8468 if (node->subsequent != NULL) {
8469 PM_COMPILE((const pm_node_t *) node->subsequent);
8470 }
8471 else {
8472 PUSH_GETLOCAL(ret, *location, 1, 0);
8473 }
8474}
8475
8476static inline void
8477pm_compile_return_node(rb_iseq_t *iseq, const pm_return_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
8478{
8479 const pm_arguments_node_t *arguments = node->arguments;
8480 enum rb_iseq_type type = ISEQ_BODY(iseq)->type;
8481 LABEL *splabel = 0;
8482
8483 const rb_iseq_t *parent_iseq = iseq;
8484 enum rb_iseq_type parent_type = ISEQ_BODY(parent_iseq)->type;
8485 while (parent_type == ISEQ_TYPE_RESCUE || parent_type == ISEQ_TYPE_ENSURE) {
8486 if (!(parent_iseq = ISEQ_BODY(parent_iseq)->parent_iseq)) break;
8487 parent_type = ISEQ_BODY(parent_iseq)->type;
8488 }
8489
8490 switch (parent_type) {
8491 case ISEQ_TYPE_TOP:
8492 case ISEQ_TYPE_MAIN:
8493 if (arguments) {
8494 rb_warn("argument of top-level return is ignored");
8495 }
8496 if (parent_iseq == iseq) {
8497 type = ISEQ_TYPE_METHOD;
8498 }
8499 break;
8500 default:
8501 break;
8502 }
8503
8504 if (type == ISEQ_TYPE_METHOD) {
8505 splabel = NEW_LABEL(0);
8506 PUSH_LABEL(ret, splabel);
8507 PUSH_ADJUST(ret, *location, 0);
8508 }
8509
8510 if (arguments != NULL) {
8511 PM_COMPILE_NOT_POPPED((const pm_node_t *) arguments);
8512 }
8513 else {
8514 PUSH_INSN(ret, *location, putnil);
8515 }
8516
8517 if (type == ISEQ_TYPE_METHOD && can_add_ensure_iseq(iseq)) {
8518 pm_add_ensure_iseq(ret, iseq, 1, scope_node);
8519 PUSH_TRACE(ret, RUBY_EVENT_RETURN);
8520 PUSH_INSN(ret, *location, leave);
8521 PUSH_ADJUST_RESTORE(ret, splabel);
8522 if (!popped) PUSH_INSN(ret, *location, putnil);
8523 }
8524 else {
8525 PUSH_INSN1(ret, *location, throw, INT2FIX(TAG_RETURN));
8526 if (popped) PUSH_INSN(ret, *location, pop);
8527 }
8528}
8529
8530static inline void
8531pm_compile_super_node(rb_iseq_t *iseq, const pm_super_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
8532{
8533 DECL_ANCHOR(args);
8534
8535 LABEL *retry_label = NEW_LABEL(location->line);
8536 LABEL *retry_end_l = NEW_LABEL(location->line);
8537
8538 const rb_iseq_t *previous_block = ISEQ_COMPILE_DATA(iseq)->current_block;
8539 const rb_iseq_t *current_block;
8540 ISEQ_COMPILE_DATA(iseq)->current_block = current_block = NULL;
8541
8542 PUSH_LABEL(ret, retry_label);
8543 PUSH_INSN(ret, *location, putself);
8544
8545 int flags = 0;
8546 struct rb_callinfo_kwarg *keywords = NULL;
8547 int argc = pm_setup_args(node->arguments, node->block, &flags, &keywords, iseq, ret, scope_node, location);
8548 bool is_forwardable = (node->arguments != NULL) && PM_NODE_FLAG_P(node->arguments, PM_ARGUMENTS_NODE_FLAGS_CONTAINS_FORWARDING);
8549 flags |= VM_CALL_SUPER | VM_CALL_FCALL;
8550
8551 if (node->block && PM_NODE_TYPE_P(node->block, PM_BLOCK_NODE)) {
8552 pm_scope_node_t next_scope_node;
8553 pm_scope_node_init(node->block, &next_scope_node, scope_node);
8554
8555 ISEQ_COMPILE_DATA(iseq)->current_block = current_block = NEW_CHILD_ISEQ(&next_scope_node, make_name_for_block(iseq), ISEQ_TYPE_BLOCK, location->line);
8556 pm_scope_node_destroy(&next_scope_node);
8557 }
8558
8559 if (!node->block) {
8560 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
8561 }
8562
8563 if ((flags & VM_CALL_ARGS_BLOCKARG) && (flags & VM_CALL_KW_SPLAT) && !(flags & VM_CALL_KW_SPLAT_MUT)) {
8564 PUSH_INSN(args, *location, splatkw);
8565 }
8566
8567 PUSH_SEQ(ret, args);
8568 if (is_forwardable && ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->param.flags.forwardable) {
8569 flags |= VM_CALL_FORWARDING;
8570
8571 {
8572 const struct rb_callinfo *callinfo = new_callinfo(iseq, 0, argc, flags, keywords, current_block != NULL);
8573 PUSH_INSN2(ret, *location, invokesuperforward, callinfo, current_block);
8574 }
8575 }
8576 else {
8577 {
8578 const struct rb_callinfo *callinfo = new_callinfo(iseq, 0, argc, flags, keywords, current_block != NULL);
8579 PUSH_INSN2(ret, *location, invokesuper, callinfo, current_block);
8580 }
8581
8582 }
8583
8584 pm_compile_retry_end_label(iseq, ret, retry_end_l);
8585
8586 if (popped) PUSH_INSN(ret, *location, pop);
8587 ISEQ_COMPILE_DATA(iseq)->current_block = previous_block;
8588 PUSH_CATCH_ENTRY(CATCH_TYPE_BREAK, retry_label, retry_end_l, current_block, retry_end_l);
8589}
8590
8591static inline void
8592pm_compile_yield_node(rb_iseq_t *iseq, const pm_yield_node_t *node, const pm_node_location_t *location, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
8593{
8594 switch (ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->type) {
8595 case ISEQ_TYPE_TOP:
8596 case ISEQ_TYPE_MAIN:
8597 case ISEQ_TYPE_CLASS:
8598 COMPILE_ERROR(iseq, location->line, "Invalid yield");
8599 return;
8600 default: /* valid */;
8601 }
8602
8603 int argc = 0;
8604 int flags = 0;
8605 struct rb_callinfo_kwarg *keywords = NULL;
8606
8607 if (node->arguments) {
8608 argc = pm_setup_args(node->arguments, NULL, &flags, &keywords, iseq, ret, scope_node, location);
8609 }
8610
8611 const struct rb_callinfo *callinfo = new_callinfo(iseq, 0, argc, flags, keywords, FALSE);
8612 PUSH_INSN1(ret, *location, invokeblock, callinfo);
8613
8614 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
8615 if (popped) PUSH_INSN(ret, *location, pop);
8616
8617 int level = 0;
8618 for (const rb_iseq_t *tmp_iseq = iseq; tmp_iseq != ISEQ_BODY(iseq)->local_iseq; level++) {
8619 tmp_iseq = ISEQ_BODY(tmp_iseq)->parent_iseq;
8620 }
8621
8622 if (level > 0) access_outer_variables(iseq, level, rb_intern("yield"), true);
8623}
8624
8635static void
8636pm_compile_node(rb_iseq_t *iseq, const pm_node_t *node, LINK_ANCHOR *const ret, bool popped, pm_scope_node_t *scope_node)
8637{
8638 const pm_parser_t *parser = scope_node->parser;
8639 const pm_node_location_t location = PM_NODE_START_LOCATION(parser, node);
8640 int lineno = (int) location.line;
8641
8642 if (PM_NODE_TYPE_P(node, PM_BEGIN_NODE) && (((const pm_begin_node_t *) node)->statements == NULL) && (((const pm_begin_node_t *) node)->rescue_clause != NULL)) {
8643 // If this node is a begin node and it has empty statements and also
8644 // has a rescue clause, then the other parser considers it as
8645 // starting on the same line as the rescue, as opposed to the
8646 // location of the begin keyword. We replicate that behavior here.
8647 lineno = (int) PM_NODE_START_LINE_COLUMN(parser, ((const pm_begin_node_t *) node)->rescue_clause).line;
8648 }
8649
8650 if (PM_NODE_FLAG_P(node, PM_NODE_FLAG_NEWLINE) && ISEQ_COMPILE_DATA(iseq)->last_line != lineno) {
8651 // If this node has the newline flag set and it is on a new line
8652 // from the previous nodes that have been compiled for this ISEQ,
8653 // then we need to emit a newline event.
8654 int event = RUBY_EVENT_LINE;
8655
8656 ISEQ_COMPILE_DATA(iseq)->last_line = lineno;
8657 if (lineno > 0 && ISEQ_COVERAGE(iseq) && ISEQ_LINE_COVERAGE(iseq)) {
8658 event |= RUBY_EVENT_COVERAGE_LINE;
8659 }
8660 PUSH_TRACE(ret, event);
8661 }
8662
8663 switch (PM_NODE_TYPE(node)) {
8664 case PM_ALIAS_GLOBAL_VARIABLE_NODE:
8665 // alias $foo $bar
8666 // ^^^^^^^^^^^^^^^
8667 pm_compile_alias_global_variable_node(iseq, (const pm_alias_global_variable_node_t *) node, &location, ret, popped, scope_node);
8668 return;
8669 case PM_ALIAS_METHOD_NODE:
8670 // alias foo bar
8671 // ^^^^^^^^^^^^^
8672 pm_compile_alias_method_node(iseq, (const pm_alias_method_node_t *) node, &location, ret, popped, scope_node);
8673 return;
8674 case PM_AND_NODE:
8675 // a and b
8676 // ^^^^^^^
8677 pm_compile_and_node(iseq, (const pm_and_node_t *) node, &location, ret, popped, scope_node);
8678 return;
8679 case PM_ARGUMENTS_NODE: {
8680 // break foo
8681 // ^^^
8682 //
8683 // These are ArgumentsNodes that are not compiled directly by their
8684 // parent call nodes, used in the cases of NextNodes, ReturnNodes, and
8685 // BreakNodes. They can create an array like ArrayNode.
8686 const pm_arguments_node_t *cast = (const pm_arguments_node_t *) node;
8687 const pm_node_list_t *elements = &cast->arguments;
8688
8689 if (elements->size == 1) {
8690 // If we are only returning a single element through one of the jump
8691 // nodes, then we will only compile that node directly.
8692 PM_COMPILE(elements->nodes[0]);
8693 }
8694 else {
8695 pm_compile_array_node(iseq, (const pm_node_t *) cast, elements, &location, ret, popped, scope_node);
8696 }
8697 return;
8698 }
8699 case PM_ARRAY_NODE: {
8700 // [foo, bar, baz]
8701 // ^^^^^^^^^^^^^^^
8702 const pm_array_node_t *cast = (const pm_array_node_t *) node;
8703 pm_compile_array_node(iseq, (const pm_node_t *) cast, &cast->elements, &location, ret, popped, scope_node);
8704 return;
8705 }
8706 case PM_ASSOC_NODE: {
8707 // { foo: 1 }
8708 // ^^^^^^
8709 //
8710 // foo(bar: 1)
8711 // ^^^^^^
8712 const pm_assoc_node_t *cast = (const pm_assoc_node_t *) node;
8713
8714 PM_COMPILE(cast->key);
8715 PM_COMPILE(cast->value);
8716
8717 return;
8718 }
8719 case PM_ASSOC_SPLAT_NODE: {
8720 // { **foo }
8721 // ^^^^^
8722 //
8723 // def foo(**); bar(**); end
8724 // ^^
8725 const pm_assoc_splat_node_t *cast = (const pm_assoc_splat_node_t *) node;
8726
8727 if (cast->value != NULL) {
8728 PM_COMPILE(cast->value);
8729 }
8730 else if (!popped) {
8731 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, PM_CONSTANT_POW, 0);
8732 PUSH_GETLOCAL(ret, location, index.index, index.level);
8733 }
8734
8735 return;
8736 }
8737 case PM_BACK_REFERENCE_READ_NODE: {
8738 // $+
8739 // ^^
8740 if (!popped) {
8741 const pm_back_reference_read_node_t *cast = (const pm_back_reference_read_node_t *) node;
8742 VALUE backref = pm_compile_back_reference_ref(cast);
8743
8744 PUSH_INSN2(ret, location, getspecial, INT2FIX(1), backref);
8745 }
8746 return;
8747 }
8748 case PM_BEGIN_NODE: {
8749 // begin end
8750 // ^^^^^^^^^
8751 const pm_begin_node_t *cast = (const pm_begin_node_t *) node;
8752
8753 if (cast->ensure_clause) {
8754 // Compiling the ensure clause will compile the rescue clause (if
8755 // there is one), which will compile the begin statements.
8756 pm_compile_ensure(iseq, cast, &location, ret, popped, scope_node);
8757 }
8758 else if (cast->rescue_clause) {
8759 // Compiling rescue will compile begin statements (if applicable).
8760 pm_compile_rescue(iseq, cast, &location, ret, popped, scope_node);
8761 }
8762 else {
8763 // If there is neither ensure or rescue, the just compile the
8764 // statements.
8765 if (cast->statements != NULL) {
8766 PM_COMPILE((const pm_node_t *) cast->statements);
8767 }
8768 else if (!popped) {
8769 PUSH_SYNTHETIC_PUTNIL(ret, iseq);
8770 }
8771 }
8772 return;
8773 }
8774 case PM_BLOCK_ARGUMENT_NODE: {
8775 // foo(&bar)
8776 // ^^^^
8777 const pm_block_argument_node_t *cast = (const pm_block_argument_node_t *) node;
8778
8779 if (cast->expression != NULL) {
8780 PM_COMPILE(cast->expression);
8781 }
8782 else {
8783 // If there's no expression, this must be block forwarding.
8784 pm_local_index_t local_index = pm_lookup_local_index(iseq, scope_node, PM_CONSTANT_AND, 0);
8785 PUSH_INSN2(ret, location, getblockparamproxy, INT2FIX(local_index.index + VM_ENV_DATA_SIZE - 1), INT2FIX(local_index.level));
8786 }
8787 return;
8788 }
8789 case PM_BREAK_NODE:
8790 // break
8791 // ^^^^^
8792 //
8793 // break foo
8794 // ^^^^^^^^^
8795 pm_compile_break_node(iseq, (const pm_break_node_t *) node, &location, ret, popped, scope_node);
8796 return;
8797 case PM_CALL_NODE:
8798 // foo
8799 // ^^^
8800 //
8801 // foo.bar
8802 // ^^^^^^^
8803 //
8804 // foo.bar() {}
8805 // ^^^^^^^^^^^^
8806 pm_compile_call_node(iseq, (const pm_call_node_t *) node, ret, popped, scope_node);
8807 return;
8808 case PM_CALL_AND_WRITE_NODE: {
8809 // foo.bar &&= baz
8810 // ^^^^^^^^^^^^^^^
8811 const pm_call_and_write_node_t *cast = (const pm_call_and_write_node_t *) node;
8812 pm_compile_call_and_or_write_node(iseq, true, cast->receiver, cast->value, cast->write_name, cast->read_name, PM_NODE_FLAG_P(cast, PM_CALL_NODE_FLAGS_SAFE_NAVIGATION), &location, ret, popped, scope_node);
8813 return;
8814 }
8815 case PM_CALL_OR_WRITE_NODE: {
8816 // foo.bar ||= baz
8817 // ^^^^^^^^^^^^^^^
8818 const pm_call_or_write_node_t *cast = (const pm_call_or_write_node_t *) node;
8819 pm_compile_call_and_or_write_node(iseq, false, cast->receiver, cast->value, cast->write_name, cast->read_name, PM_NODE_FLAG_P(cast, PM_CALL_NODE_FLAGS_SAFE_NAVIGATION), &location, ret, popped, scope_node);
8820 return;
8821 }
8822 case PM_CALL_OPERATOR_WRITE_NODE:
8823 // foo.bar += baz
8824 // ^^^^^^^^^^^^^^^
8825 //
8826 // Call operator writes occur when you have a call node on the left-hand
8827 // side of a write operator that is not `=`. As an example,
8828 // `foo.bar *= 1`. This breaks down to caching the receiver on the
8829 // stack and then performing three method calls, one to read the value,
8830 // one to compute the result, and one to write the result back to the
8831 // receiver.
8832 pm_compile_call_operator_write_node(iseq, (const pm_call_operator_write_node_t *) node, &location, ret, popped, scope_node);
8833 return;
8834 case PM_CASE_NODE:
8835 // case foo; when bar; end
8836 // ^^^^^^^^^^^^^^^^^^^^^^^
8837 pm_compile_case_node(iseq, (const pm_case_node_t *) node, &location, ret, popped, scope_node);
8838 return;
8839 case PM_CASE_MATCH_NODE:
8840 // case foo; in bar; end
8841 // ^^^^^^^^^^^^^^^^^^^^^
8842 //
8843 // If you use the `case` keyword to create a case match node, it will
8844 // match against all of the `in` clauses until it finds one that
8845 // matches. If it doesn't find one, it can optionally fall back to an
8846 // `else` clause. If none is present and a match wasn't found, it will
8847 // raise an appropriate error.
8848 pm_compile_case_match_node(iseq, (const pm_case_match_node_t *) node, &location, ret, popped, scope_node);
8849 return;
8850 case PM_CLASS_NODE: {
8851 // class Foo; end
8852 // ^^^^^^^^^^^^^^
8853 const pm_class_node_t *cast = (const pm_class_node_t *) node;
8854
8855 ID class_id = pm_constant_id_lookup(scope_node, cast->name);
8856 VALUE class_name = rb_str_freeze(rb_sprintf("<class:%"PRIsVALUE">", rb_id2str(class_id)));
8857
8858 pm_scope_node_t next_scope_node;
8859 pm_scope_node_init((const pm_node_t *) cast, &next_scope_node, scope_node);
8860
8861 const rb_iseq_t *class_iseq = NEW_CHILD_ISEQ(&next_scope_node, class_name, ISEQ_TYPE_CLASS, location.line);
8862 pm_scope_node_destroy(&next_scope_node);
8863
8864 // TODO: Once we merge constant path nodes correctly, fix this flag
8865 const int flags = VM_DEFINECLASS_TYPE_CLASS |
8866 (cast->superclass ? VM_DEFINECLASS_FLAG_HAS_SUPERCLASS : 0) |
8867 pm_compile_class_path(iseq, cast->constant_path, &location, ret, false, scope_node);
8868
8869 if (cast->superclass) {
8870 PM_COMPILE_NOT_POPPED(cast->superclass);
8871 }
8872 else {
8873 PUSH_INSN(ret, location, putnil);
8874 }
8875
8876 {
8877 VALUE operand = ID2SYM(class_id);
8878 PUSH_INSN3(ret, location, defineclass, operand, class_iseq, INT2FIX(flags));
8879 }
8880 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)class_iseq);
8881
8882 if (popped) PUSH_INSN(ret, location, pop);
8883 return;
8884 }
8885 case PM_CLASS_VARIABLE_AND_WRITE_NODE: {
8886 // @@foo &&= bar
8887 // ^^^^^^^^^^^^^
8888 const pm_class_variable_and_write_node_t *cast = (const pm_class_variable_and_write_node_t *) node;
8889 LABEL *end_label = NEW_LABEL(location.line);
8890
8891 ID name_id = pm_constant_id_lookup(scope_node, cast->name);
8892 VALUE name = ID2SYM(name_id);
8893
8894 PUSH_INSN2(ret, location, getclassvariable, name, get_cvar_ic_value(iseq, name_id));
8895 if (!popped) PUSH_INSN(ret, location, dup);
8896
8897 PUSH_INSNL(ret, location, branchunless, end_label);
8898 if (!popped) PUSH_INSN(ret, location, pop);
8899
8900 PM_COMPILE_NOT_POPPED(cast->value);
8901 if (!popped) PUSH_INSN(ret, location, dup);
8902
8903 PUSH_INSN2(ret, location, setclassvariable, name, get_cvar_ic_value(iseq, name_id));
8904 PUSH_LABEL(ret, end_label);
8905
8906 return;
8907 }
8908 case PM_CLASS_VARIABLE_OPERATOR_WRITE_NODE: {
8909 // @@foo += bar
8910 // ^^^^^^^^^^^^
8911 const pm_class_variable_operator_write_node_t *cast = (const pm_class_variable_operator_write_node_t *) node;
8912
8913 ID name_id = pm_constant_id_lookup(scope_node, cast->name);
8914 VALUE name = ID2SYM(name_id);
8915
8916 PUSH_INSN2(ret, location, getclassvariable, name, get_cvar_ic_value(iseq, name_id));
8917 PM_COMPILE_NOT_POPPED(cast->value);
8918
8919 ID method_id = pm_constant_id_lookup(scope_node, cast->binary_operator);
8920 int flags = VM_CALL_ARGS_SIMPLE;
8921 PUSH_SEND_WITH_FLAG(ret, location, method_id, INT2NUM(1), INT2FIX(flags));
8922
8923 if (!popped) PUSH_INSN(ret, location, dup);
8924 PUSH_INSN2(ret, location, setclassvariable, name, get_cvar_ic_value(iseq, name_id));
8925
8926 return;
8927 }
8928 case PM_CLASS_VARIABLE_OR_WRITE_NODE: {
8929 // @@foo ||= bar
8930 // ^^^^^^^^^^^^^
8931 const pm_class_variable_or_write_node_t *cast = (const pm_class_variable_or_write_node_t *) node;
8932 LABEL *end_label = NEW_LABEL(location.line);
8933 LABEL *start_label = NEW_LABEL(location.line);
8934
8935 ID name_id = pm_constant_id_lookup(scope_node, cast->name);
8936 VALUE name = ID2SYM(name_id);
8937
8938 PUSH_INSN(ret, location, putnil);
8939 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_CVAR), name, Qtrue);
8940 PUSH_INSNL(ret, location, branchunless, start_label);
8941
8942 PUSH_INSN2(ret, location, getclassvariable, name, get_cvar_ic_value(iseq, name_id));
8943 if (!popped) PUSH_INSN(ret, location, dup);
8944
8945 PUSH_INSNL(ret, location, branchif, end_label);
8946 if (!popped) PUSH_INSN(ret, location, pop);
8947
8948 PUSH_LABEL(ret, start_label);
8949 PM_COMPILE_NOT_POPPED(cast->value);
8950 if (!popped) PUSH_INSN(ret, location, dup);
8951
8952 PUSH_INSN2(ret, location, setclassvariable, name, get_cvar_ic_value(iseq, name_id));
8953 PUSH_LABEL(ret, end_label);
8954
8955 return;
8956 }
8957 case PM_CLASS_VARIABLE_READ_NODE: {
8958 // @@foo
8959 // ^^^^^
8960 if (!popped) {
8961 const pm_class_variable_read_node_t *cast = (const pm_class_variable_read_node_t *) node;
8962 ID name = pm_constant_id_lookup(scope_node, cast->name);
8963 PUSH_INSN2(ret, location, getclassvariable, ID2SYM(name), get_cvar_ic_value(iseq, name));
8964 }
8965 return;
8966 }
8967 case PM_CLASS_VARIABLE_WRITE_NODE: {
8968 // @@foo = 1
8969 // ^^^^^^^^^
8970 const pm_class_variable_write_node_t *cast = (const pm_class_variable_write_node_t *) node;
8971 PM_COMPILE_NOT_POPPED(cast->value);
8972 if (!popped) PUSH_INSN(ret, location, dup);
8973
8974 ID name = pm_constant_id_lookup(scope_node, cast->name);
8975 PUSH_INSN2(ret, location, setclassvariable, ID2SYM(name), get_cvar_ic_value(iseq, name));
8976
8977 return;
8978 }
8979 case PM_CONSTANT_PATH_NODE: {
8980 // Foo::Bar
8981 // ^^^^^^^^
8982 VALUE parts;
8983
8984 if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache && ((parts = pm_constant_path_parts(node, scope_node)) != Qnil)) {
8985 ISEQ_BODY(iseq)->ic_size++;
8986 RB_OBJ_SET_SHAREABLE(parts);
8987 PUSH_INSN1(ret, location, opt_getconstant_path, parts);
8988 }
8989 else {
8990 DECL_ANCHOR(prefix);
8991 DECL_ANCHOR(body);
8992
8993 pm_compile_constant_path(iseq, node, prefix, body, popped, scope_node);
8994 if (LIST_INSN_SIZE_ZERO(prefix)) {
8995 PUSH_INSN(ret, location, putnil);
8996 }
8997 else {
8998 PUSH_SEQ(ret, prefix);
8999 }
9000
9001 PUSH_SEQ(ret, body);
9002 }
9003
9004 if (popped) PUSH_INSN(ret, location, pop);
9005 return;
9006 }
9007 case PM_CONSTANT_PATH_AND_WRITE_NODE: {
9008 // Foo::Bar &&= baz
9009 // ^^^^^^^^^^^^^^^^
9010 const pm_constant_path_and_write_node_t *cast = (const pm_constant_path_and_write_node_t *) node;
9011 pm_compile_constant_path_and_write_node(iseq, cast, 0, &location, ret, popped, scope_node);
9012 return;
9013 }
9014 case PM_CONSTANT_PATH_OR_WRITE_NODE: {
9015 // Foo::Bar ||= baz
9016 // ^^^^^^^^^^^^^^^^
9017 const pm_constant_path_or_write_node_t *cast = (const pm_constant_path_or_write_node_t *) node;
9018 pm_compile_constant_path_or_write_node(iseq, cast, 0, &location, ret, popped, scope_node);
9019 return;
9020 }
9021 case PM_CONSTANT_PATH_OPERATOR_WRITE_NODE: {
9022 // Foo::Bar += baz
9023 // ^^^^^^^^^^^^^^^
9024 const pm_constant_path_operator_write_node_t *cast = (const pm_constant_path_operator_write_node_t *) node;
9025 pm_compile_constant_path_operator_write_node(iseq, cast, 0, &location, ret, popped, scope_node);
9026 return;
9027 }
9028 case PM_CONSTANT_PATH_WRITE_NODE: {
9029 // Foo::Bar = 1
9030 // ^^^^^^^^^^^^
9031 const pm_constant_path_write_node_t *cast = (const pm_constant_path_write_node_t *) node;
9032 pm_compile_constant_path_write_node(iseq, cast, 0, &location, ret, popped, scope_node);
9033 return;
9034 }
9035 case PM_CONSTANT_READ_NODE: {
9036 // Foo
9037 // ^^^
9038 const pm_constant_read_node_t *cast = (const pm_constant_read_node_t *) node;
9039 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, cast->name));
9040
9041 pm_compile_constant_read(iseq, name, &cast->base.location, location.node_id, ret, scope_node);
9042 if (popped) PUSH_INSN(ret, location, pop);
9043
9044 return;
9045 }
9046 case PM_CONSTANT_AND_WRITE_NODE: {
9047 // Foo &&= bar
9048 // ^^^^^^^^^^^
9049 const pm_constant_and_write_node_t *cast = (const pm_constant_and_write_node_t *) node;
9050 pm_compile_constant_and_write_node(iseq, cast, 0, &location, ret, popped, scope_node);
9051 return;
9052 }
9053 case PM_CONSTANT_OR_WRITE_NODE: {
9054 // Foo ||= bar
9055 // ^^^^^^^^^^^
9056 const pm_constant_or_write_node_t *cast = (const pm_constant_or_write_node_t *) node;
9057 pm_compile_constant_or_write_node(iseq, cast, 0, &location, ret, popped, scope_node);
9058 return;
9059 }
9060 case PM_CONSTANT_OPERATOR_WRITE_NODE: {
9061 // Foo += bar
9062 // ^^^^^^^^^^
9063 const pm_constant_operator_write_node_t *cast = (const pm_constant_operator_write_node_t *) node;
9064 pm_compile_constant_operator_write_node(iseq, cast, 0, &location, ret, popped, scope_node);
9065 return;
9066 }
9067 case PM_CONSTANT_WRITE_NODE: {
9068 // Foo = 1
9069 // ^^^^^^^
9070 const pm_constant_write_node_t *cast = (const pm_constant_write_node_t *) node;
9071 pm_compile_constant_write_node(iseq, cast, 0, &location, ret, popped, scope_node);
9072 return;
9073 }
9074 case PM_DEF_NODE: {
9075 // def foo; end
9076 // ^^^^^^^^^^^^
9077 //
9078 // def self.foo; end
9079 // ^^^^^^^^^^^^^^^^^
9080 const pm_def_node_t *cast = (const pm_def_node_t *) node;
9081 ID method_name = pm_constant_id_lookup(scope_node, cast->name);
9082
9083 pm_scope_node_t next_scope_node;
9084 pm_scope_node_init((const pm_node_t *) cast, &next_scope_node, scope_node);
9085
9086 rb_iseq_t *method_iseq = NEW_ISEQ(&next_scope_node, rb_id2str(method_name), ISEQ_TYPE_METHOD, location.line);
9087 pm_scope_node_destroy(&next_scope_node);
9088
9089 if (cast->receiver) {
9090 PM_COMPILE_NOT_POPPED(cast->receiver);
9091 PUSH_INSN2(ret, location, definesmethod, ID2SYM(method_name), method_iseq);
9092 }
9093 else {
9094 PUSH_INSN2(ret, location, definemethod, ID2SYM(method_name), method_iseq);
9095 }
9096 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE) method_iseq);
9097
9098 if (!popped) {
9099 PUSH_INSN1(ret, location, putobject, ID2SYM(method_name));
9100 }
9101
9102 return;
9103 }
9104 case PM_DEFINED_NODE: {
9105 // defined?(a)
9106 // ^^^^^^^^^^^
9107 const pm_defined_node_t *cast = (const pm_defined_node_t *) node;
9108 pm_compile_defined_expr(iseq, cast->value, &location, ret, popped, scope_node, false);
9109 return;
9110 }
9111 case PM_EMBEDDED_STATEMENTS_NODE: {
9112 // "foo #{bar}"
9113 // ^^^^^^
9114 const pm_embedded_statements_node_t *cast = (const pm_embedded_statements_node_t *) node;
9115
9116 if (cast->statements != NULL) {
9117 PM_COMPILE((const pm_node_t *) (cast->statements));
9118 }
9119 else {
9120 PUSH_SYNTHETIC_PUTNIL(ret, iseq);
9121 }
9122
9123 if (popped) PUSH_INSN(ret, location, pop);
9124 return;
9125 }
9126 case PM_EMBEDDED_VARIABLE_NODE: {
9127 // "foo #@bar"
9128 // ^^^^^
9129 const pm_embedded_variable_node_t *cast = (const pm_embedded_variable_node_t *) node;
9130 PM_COMPILE(cast->variable);
9131 return;
9132 }
9133 case PM_FALSE_NODE: {
9134 // false
9135 // ^^^^^
9136 if (!popped) {
9137 PUSH_INSN1(ret, location, putobject, Qfalse);
9138 }
9139 return;
9140 }
9141 case PM_ENSURE_NODE: {
9142 const pm_ensure_node_t *cast = (const pm_ensure_node_t *) node;
9143
9144 if (cast->statements != NULL) {
9145 PM_COMPILE((const pm_node_t *) cast->statements);
9146 }
9147
9148 return;
9149 }
9150 case PM_ELSE_NODE: {
9151 // if foo then bar else baz end
9152 // ^^^^^^^^^^^^
9153 const pm_else_node_t *cast = (const pm_else_node_t *) node;
9154
9155 if (cast->statements != NULL) {
9156 PM_COMPILE((const pm_node_t *) cast->statements);
9157 }
9158 else if (!popped) {
9159 PUSH_SYNTHETIC_PUTNIL(ret, iseq);
9160 }
9161
9162 return;
9163 }
9164 case PM_FLIP_FLOP_NODE: {
9165 // if foo .. bar; end
9166 // ^^^^^^^^^^
9167 const pm_flip_flop_node_t *cast = (const pm_flip_flop_node_t *) node;
9168
9169 LABEL *final_label = NEW_LABEL(location.line);
9170 LABEL *then_label = NEW_LABEL(location.line);
9171 LABEL *else_label = NEW_LABEL(location.line);
9172
9173 pm_compile_flip_flop(cast, else_label, then_label, iseq, location.line, ret, popped, scope_node);
9174
9175 PUSH_LABEL(ret, then_label);
9176 PUSH_INSN1(ret, location, putobject, Qtrue);
9177 PUSH_INSNL(ret, location, jump, final_label);
9178 PUSH_LABEL(ret, else_label);
9179 PUSH_INSN1(ret, location, putobject, Qfalse);
9180 PUSH_LABEL(ret, final_label);
9181
9182 return;
9183 }
9184 case PM_FLOAT_NODE: {
9185 // 1.0
9186 // ^^^
9187 if (!popped) {
9188 VALUE operand = parse_float((const pm_float_node_t *) node);
9189 PUSH_INSN1(ret, location, putobject, operand);
9190 }
9191 return;
9192 }
9193 case PM_FOR_NODE: {
9194 // for foo in bar do end
9195 // ^^^^^^^^^^^^^^^^^^^^^
9196 const pm_for_node_t *cast = (const pm_for_node_t *) node;
9197
9198 LABEL *retry_label = NEW_LABEL(location.line);
9199 LABEL *retry_end_l = NEW_LABEL(location.line);
9200
9201 // First, compile the collection that we're going to be iterating over.
9202 PUSH_LABEL(ret, retry_label);
9203 PM_COMPILE_NOT_POPPED(cast->collection);
9204
9205 // Next, create the new scope that is going to contain the block that
9206 // will be passed to the each method.
9207 pm_scope_node_t next_scope_node;
9208 pm_scope_node_init((const pm_node_t *) cast, &next_scope_node, scope_node);
9209
9210 const rb_iseq_t *child_iseq = NEW_CHILD_ISEQ(&next_scope_node, make_name_for_block(iseq), ISEQ_TYPE_BLOCK, location.line);
9211 pm_scope_node_destroy(&next_scope_node);
9212
9213 const rb_iseq_t *prev_block = ISEQ_COMPILE_DATA(iseq)->current_block;
9214 ISEQ_COMPILE_DATA(iseq)->current_block = child_iseq;
9215
9216 // Now, create the method call to each that will be used to iterate over
9217 // the collection, and pass the newly created iseq as the block.
9218 PUSH_SEND_WITH_BLOCK(ret, location, idEach, INT2FIX(0), child_iseq);
9219 pm_compile_retry_end_label(iseq, ret, retry_end_l);
9220
9221 if (popped) PUSH_INSN(ret, location, pop);
9222 ISEQ_COMPILE_DATA(iseq)->current_block = prev_block;
9223 PUSH_CATCH_ENTRY(CATCH_TYPE_BREAK, retry_label, retry_end_l, child_iseq, retry_end_l);
9224 return;
9225 }
9226 case PM_FORWARDING_ARGUMENTS_NODE:
9227 rb_bug("Cannot compile a ForwardingArgumentsNode directly\n");
9228 return;
9229 case PM_FORWARDING_SUPER_NODE:
9230 // super
9231 // ^^^^^
9232 //
9233 // super {}
9234 // ^^^^^^^^
9235 pm_compile_forwarding_super_node(iseq, (const pm_forwarding_super_node_t *) node, &location, ret, popped, scope_node);
9236 return;
9237 case PM_GLOBAL_VARIABLE_AND_WRITE_NODE: {
9238 // $foo &&= bar
9239 // ^^^^^^^^^^^^
9240 const pm_global_variable_and_write_node_t *cast = (const pm_global_variable_and_write_node_t *) node;
9241 LABEL *end_label = NEW_LABEL(location.line);
9242
9243 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, cast->name));
9244 PUSH_INSN1(ret, location, getglobal, name);
9245 if (!popped) PUSH_INSN(ret, location, dup);
9246
9247 PUSH_INSNL(ret, location, branchunless, end_label);
9248 if (!popped) PUSH_INSN(ret, location, pop);
9249
9250 PM_COMPILE_NOT_POPPED(cast->value);
9251 if (!popped) PUSH_INSN(ret, location, dup);
9252
9253 PUSH_INSN1(ret, location, setglobal, name);
9254 PUSH_LABEL(ret, end_label);
9255
9256 return;
9257 }
9258 case PM_GLOBAL_VARIABLE_OPERATOR_WRITE_NODE: {
9259 // $foo += bar
9260 // ^^^^^^^^^^^
9261 const pm_global_variable_operator_write_node_t *cast = (const pm_global_variable_operator_write_node_t *) node;
9262
9263 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, cast->name));
9264 PUSH_INSN1(ret, location, getglobal, name);
9265 PM_COMPILE_NOT_POPPED(cast->value);
9266
9267 ID method_id = pm_constant_id_lookup(scope_node, cast->binary_operator);
9268 int flags = VM_CALL_ARGS_SIMPLE;
9269 PUSH_SEND_WITH_FLAG(ret, location, method_id, INT2NUM(1), INT2FIX(flags));
9270
9271 if (!popped) PUSH_INSN(ret, location, dup);
9272 PUSH_INSN1(ret, location, setglobal, name);
9273
9274 return;
9275 }
9276 case PM_GLOBAL_VARIABLE_OR_WRITE_NODE: {
9277 // $foo ||= bar
9278 // ^^^^^^^^^^^^
9279 const pm_global_variable_or_write_node_t *cast = (const pm_global_variable_or_write_node_t *) node;
9280 LABEL *set_label = NEW_LABEL(location.line);
9281 LABEL *end_label = NEW_LABEL(location.line);
9282
9283 PUSH_INSN(ret, location, putnil);
9284 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, cast->name));
9285
9286 PUSH_INSN3(ret, location, defined, INT2FIX(DEFINED_GVAR), name, Qtrue);
9287 PUSH_INSNL(ret, location, branchunless, set_label);
9288
9289 PUSH_INSN1(ret, location, getglobal, name);
9290 if (!popped) PUSH_INSN(ret, location, dup);
9291
9292 PUSH_INSNL(ret, location, branchif, end_label);
9293 if (!popped) PUSH_INSN(ret, location, pop);
9294
9295 PUSH_LABEL(ret, set_label);
9296 PM_COMPILE_NOT_POPPED(cast->value);
9297 if (!popped) PUSH_INSN(ret, location, dup);
9298
9299 PUSH_INSN1(ret, location, setglobal, name);
9300 PUSH_LABEL(ret, end_label);
9301
9302 return;
9303 }
9304 case PM_GLOBAL_VARIABLE_READ_NODE: {
9305 // $foo
9306 // ^^^^
9307 const pm_global_variable_read_node_t *cast = (const pm_global_variable_read_node_t *) node;
9308 VALUE name = ID2SYM(pm_constant_id_lookup(scope_node, cast->name));
9309
9310 PUSH_INSN1(ret, location, getglobal, name);
9311 if (popped) PUSH_INSN(ret, location, pop);
9312
9313 return;
9314 }
9315 case PM_GLOBAL_VARIABLE_WRITE_NODE: {
9316 // $foo = 1
9317 // ^^^^^^^^
9318 const pm_global_variable_write_node_t *cast = (const pm_global_variable_write_node_t *) node;
9319 PM_COMPILE_NOT_POPPED(cast->value);
9320 if (!popped) PUSH_INSN(ret, location, dup);
9321
9322 ID name = pm_constant_id_lookup(scope_node, cast->name);
9323 PUSH_INSN1(ret, location, setglobal, ID2SYM(name));
9324
9325 return;
9326 }
9327 case PM_HASH_NODE: {
9328 // {}
9329 // ^^
9330 //
9331 // If every node in the hash is static, then we can compile the entire
9332 // hash now instead of later.
9333 if (PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL)) {
9334 // We're only going to compile this node if it's not popped. If it
9335 // is popped, then we know we don't need to do anything since it's
9336 // statically known.
9337 if (!popped) {
9338 const pm_hash_node_t *cast = (const pm_hash_node_t *) node;
9339
9340 if (cast->elements.size == 0) {
9341 PUSH_INSN1(ret, location, newhash, INT2FIX(0));
9342 }
9343 else {
9344 VALUE value = pm_static_literal_value(iseq, node, scope_node);
9345 PUSH_INSN1(ret, location, duphash, value);
9346 RB_OBJ_WRITTEN(iseq, Qundef, value);
9347 }
9348 }
9349 }
9350 else {
9351 // Here since we know there are possible side-effects inside the
9352 // hash contents, we're going to build it entirely at runtime. We'll
9353 // do this by pushing all of the key-value pairs onto the stack and
9354 // then combining them with newhash.
9355 //
9356 // If this hash is popped, then this serves only to ensure we enact
9357 // all side-effects (like method calls) that are contained within
9358 // the hash contents.
9359 const pm_hash_node_t *cast = (const pm_hash_node_t *) node;
9360 const pm_node_list_t *elements = &cast->elements;
9361
9362 if (popped) {
9363 // If this hash is popped, then we can iterate through each
9364 // element and compile it. The result of each compilation will
9365 // only include the side effects of the element itself.
9366 for (size_t index = 0; index < elements->size; index++) {
9367 PM_COMPILE_POPPED(elements->nodes[index]);
9368 }
9369 }
9370 else {
9371 pm_compile_hash_elements(iseq, node, elements, 0, Qundef, false, ret, scope_node);
9372 }
9373 }
9374
9375 return;
9376 }
9377 case PM_IF_NODE: {
9378 // if foo then bar end
9379 // ^^^^^^^^^^^^^^^^^^^
9380 //
9381 // bar if foo
9382 // ^^^^^^^^^^
9383 //
9384 // foo ? bar : baz
9385 // ^^^^^^^^^^^^^^^
9386 const pm_if_node_t *cast = (const pm_if_node_t *) node;
9387 pm_compile_conditional(iseq, &location, PM_IF_NODE, (const pm_node_t *) cast, cast->statements, cast->subsequent, cast->predicate, ret, popped, scope_node);
9388 return;
9389 }
9390 case PM_IMAGINARY_NODE: {
9391 // 1i
9392 // ^^
9393 if (!popped) {
9394 VALUE operand = parse_imaginary((const pm_imaginary_node_t *) node);
9395 PUSH_INSN1(ret, location, putobject, operand);
9396 }
9397 return;
9398 }
9399 case PM_IMPLICIT_NODE: {
9400 // Implicit nodes mark places in the syntax tree where explicit syntax
9401 // was omitted, but implied. For example,
9402 //
9403 // { foo: }
9404 //
9405 // In this case a method call/local variable read is implied by virtue
9406 // of the missing value. To compile these nodes, we simply compile the
9407 // value that is implied, which is helpfully supplied by the parser.
9408 const pm_implicit_node_t *cast = (const pm_implicit_node_t *) node;
9409 PM_COMPILE(cast->value);
9410 return;
9411 }
9412 case PM_IN_NODE: {
9413 // In nodes are handled by the case match node directly, so we should
9414 // never end up hitting them through this path.
9415 rb_bug("Should not ever enter an in node directly");
9416 return;
9417 }
9418 case PM_INDEX_OPERATOR_WRITE_NODE: {
9419 // foo[bar] += baz
9420 // ^^^^^^^^^^^^^^^
9421 const pm_index_operator_write_node_t *cast = (const pm_index_operator_write_node_t *) node;
9422 pm_compile_index_operator_write_node(iseq, cast, &location, ret, popped, scope_node);
9423 return;
9424 }
9425 case PM_INDEX_AND_WRITE_NODE: {
9426 // foo[bar] &&= baz
9427 // ^^^^^^^^^^^^^^^^
9428 const pm_index_and_write_node_t *cast = (const pm_index_and_write_node_t *) node;
9429 pm_compile_index_control_flow_write_node(iseq, node, cast->receiver, cast->arguments, cast->block, cast->value, &location, ret, popped, scope_node);
9430 return;
9431 }
9432 case PM_INDEX_OR_WRITE_NODE: {
9433 // foo[bar] ||= baz
9434 // ^^^^^^^^^^^^^^^^
9435 const pm_index_or_write_node_t *cast = (const pm_index_or_write_node_t *) node;
9436 pm_compile_index_control_flow_write_node(iseq, node, cast->receiver, cast->arguments, cast->block, cast->value, &location, ret, popped, scope_node);
9437 return;
9438 }
9439 case PM_INSTANCE_VARIABLE_AND_WRITE_NODE: {
9440 // @foo &&= bar
9441 // ^^^^^^^^^^^^
9442 const pm_instance_variable_and_write_node_t *cast = (const pm_instance_variable_and_write_node_t *) node;
9443 LABEL *end_label = NEW_LABEL(location.line);
9444
9445 ID name_id = pm_constant_id_lookup(scope_node, cast->name);
9446 VALUE name = ID2SYM(name_id);
9447
9448 PUSH_INSN2(ret, location, getinstancevariable, name, get_ivar_ic_value(iseq, name_id));
9449 if (!popped) PUSH_INSN(ret, location, dup);
9450
9451 PUSH_INSNL(ret, location, branchunless, end_label);
9452 if (!popped) PUSH_INSN(ret, location, pop);
9453
9454 PM_COMPILE_NOT_POPPED(cast->value);
9455 if (!popped) PUSH_INSN(ret, location, dup);
9456
9457 PUSH_INSN2(ret, location, setinstancevariable, name, get_ivar_ic_value(iseq, name_id));
9458 PUSH_LABEL(ret, end_label);
9459
9460 return;
9461 }
9462 case PM_INSTANCE_VARIABLE_OPERATOR_WRITE_NODE: {
9463 // @foo += bar
9464 // ^^^^^^^^^^^
9465 const pm_instance_variable_operator_write_node_t *cast = (const pm_instance_variable_operator_write_node_t *) node;
9466
9467 ID name_id = pm_constant_id_lookup(scope_node, cast->name);
9468 VALUE name = ID2SYM(name_id);
9469
9470 PUSH_INSN2(ret, location, getinstancevariable, name, get_ivar_ic_value(iseq, name_id));
9471 PM_COMPILE_NOT_POPPED(cast->value);
9472
9473 ID method_id = pm_constant_id_lookup(scope_node, cast->binary_operator);
9474 int flags = VM_CALL_ARGS_SIMPLE;
9475 PUSH_SEND_WITH_FLAG(ret, location, method_id, INT2NUM(1), INT2FIX(flags));
9476
9477 if (!popped) PUSH_INSN(ret, location, dup);
9478 PUSH_INSN2(ret, location, setinstancevariable, name, get_ivar_ic_value(iseq, name_id));
9479
9480 return;
9481 }
9482 case PM_INSTANCE_VARIABLE_OR_WRITE_NODE: {
9483 // @foo ||= bar
9484 // ^^^^^^^^^^^^
9485 const pm_instance_variable_or_write_node_t *cast = (const pm_instance_variable_or_write_node_t *) node;
9486 LABEL *end_label = NEW_LABEL(location.line);
9487
9488 ID name_id = pm_constant_id_lookup(scope_node, cast->name);
9489 VALUE name = ID2SYM(name_id);
9490
9491 PUSH_INSN2(ret, location, getinstancevariable, name, get_ivar_ic_value(iseq, name_id));
9492 if (!popped) PUSH_INSN(ret, location, dup);
9493
9494 PUSH_INSNL(ret, location, branchif, end_label);
9495 if (!popped) PUSH_INSN(ret, location, pop);
9496
9497 PM_COMPILE_NOT_POPPED(cast->value);
9498 if (!popped) PUSH_INSN(ret, location, dup);
9499
9500 PUSH_INSN2(ret, location, setinstancevariable, name, get_ivar_ic_value(iseq, name_id));
9501 PUSH_LABEL(ret, end_label);
9502
9503 return;
9504 }
9505 case PM_INSTANCE_VARIABLE_READ_NODE: {
9506 // @foo
9507 // ^^^^
9508 if (!popped) {
9509 const pm_instance_variable_read_node_t *cast = (const pm_instance_variable_read_node_t *) node;
9510 ID name = pm_constant_id_lookup(scope_node, cast->name);
9511 PUSH_INSN2(ret, location, getinstancevariable, ID2SYM(name), get_ivar_ic_value(iseq, name));
9512 }
9513 return;
9514 }
9515 case PM_INSTANCE_VARIABLE_WRITE_NODE: {
9516 // @foo = 1
9517 // ^^^^^^^^
9518 const pm_instance_variable_write_node_t *cast = (const pm_instance_variable_write_node_t *) node;
9519 PM_COMPILE_NOT_POPPED(cast->value);
9520 if (!popped) PUSH_INSN(ret, location, dup);
9521
9522 ID name = pm_constant_id_lookup(scope_node, cast->name);
9523 PUSH_INSN2(ret, location, setinstancevariable, ID2SYM(name), get_ivar_ic_value(iseq, name));
9524
9525 return;
9526 }
9527 case PM_INTEGER_NODE: {
9528 // 1
9529 // ^
9530 if (!popped) {
9531 VALUE operand = parse_integer((const pm_integer_node_t *) node);
9532 PUSH_INSN1(ret, location, putobject, operand);
9533 }
9534 return;
9535 }
9536 case PM_INTERPOLATED_MATCH_LAST_LINE_NODE: {
9537 // if /foo #{bar}/ then end
9538 // ^^^^^^^^^^^^
9539 if (PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL)) {
9540 if (!popped) {
9541 VALUE regexp = pm_static_literal_value(iseq, node, scope_node);
9542 PUSH_INSN1(ret, location, putobject, regexp);
9543 }
9544 }
9545 else {
9546 pm_compile_regexp_dynamic(iseq, node, &((const pm_interpolated_match_last_line_node_t *) node)->parts, &location, ret, popped, scope_node);
9547 }
9548
9549 PUSH_INSN1(ret, location, getglobal, rb_id2sym(idLASTLINE));
9550 PUSH_SEND(ret, location, idEqTilde, INT2NUM(1));
9551 if (popped) PUSH_INSN(ret, location, pop);
9552
9553 return;
9554 }
9555 case PM_INTERPOLATED_REGULAR_EXPRESSION_NODE: {
9556 // /foo #{bar}/
9557 // ^^^^^^^^^^^^
9558 if (PM_NODE_FLAG_P(node, PM_REGULAR_EXPRESSION_FLAGS_ONCE)) {
9559 const rb_iseq_t *prevblock = ISEQ_COMPILE_DATA(iseq)->current_block;
9560 const rb_iseq_t *block_iseq = NULL;
9561 int ise_index = ISEQ_BODY(iseq)->ise_size++;
9562
9563 pm_scope_node_t next_scope_node;
9564 pm_scope_node_init(node, &next_scope_node, scope_node);
9565
9566 block_iseq = NEW_CHILD_ISEQ(&next_scope_node, make_name_for_block(iseq), ISEQ_TYPE_PLAIN, location.line);
9567 pm_scope_node_destroy(&next_scope_node);
9568
9569 ISEQ_COMPILE_DATA(iseq)->current_block = block_iseq;
9570 PUSH_INSN2(ret, location, once, block_iseq, INT2FIX(ise_index));
9571 ISEQ_COMPILE_DATA(iseq)->current_block = prevblock;
9572
9573 if (popped) PUSH_INSN(ret, location, pop);
9574 return;
9575 }
9576
9577 if (PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL)) {
9578 if (!popped) {
9579 VALUE regexp = pm_static_literal_value(iseq, node, scope_node);
9580 PUSH_INSN1(ret, location, putobject, regexp);
9581 }
9582 }
9583 else {
9584 pm_compile_regexp_dynamic(iseq, node, &((const pm_interpolated_regular_expression_node_t *) node)->parts, &location, ret, popped, scope_node);
9585 if (popped) PUSH_INSN(ret, location, pop);
9586 }
9587
9588 return;
9589 }
9590 case PM_INTERPOLATED_STRING_NODE: {
9591 // "foo #{bar}"
9592 // ^^^^^^^^^^^^
9593 if (PM_NODE_FLAG_P(node, PM_NODE_FLAG_STATIC_LITERAL)) {
9594 if (!popped) {
9595 VALUE string = pm_static_literal_value(iseq, node, scope_node);
9596
9597 if (PM_NODE_FLAG_P(node, PM_INTERPOLATED_STRING_NODE_FLAGS_FROZEN)) {
9598 PUSH_INSN1(ret, location, putobject, string);
9599 }
9600 else if (PM_NODE_FLAG_P(node, PM_INTERPOLATED_STRING_NODE_FLAGS_MUTABLE)) {
9601 PUSH_INSN1(ret, location, putstring, string);
9602 }
9603 else {
9604 PUSH_INSN1(ret, location, putchilledstring, string);
9605 }
9606 }
9607 }
9608 else {
9609 const pm_interpolated_string_node_t *cast = (const pm_interpolated_string_node_t *) node;
9610 int length = pm_interpolated_node_compile(iseq, &cast->parts, &location, ret, popped, scope_node, NULL, NULL, PM_NODE_FLAG_P(cast, PM_INTERPOLATED_STRING_NODE_FLAGS_MUTABLE), PM_NODE_FLAG_P(cast, PM_INTERPOLATED_STRING_NODE_FLAGS_FROZEN));
9611 if (length > 1) PUSH_INSN1(ret, location, concatstrings, INT2FIX(length));
9612 if (popped) PUSH_INSN(ret, location, pop);
9613 }
9614
9615 return;
9616 }
9617 case PM_INTERPOLATED_SYMBOL_NODE: {
9618 // :"foo #{bar}"
9619 // ^^^^^^^^^^^^^
9620 const pm_interpolated_symbol_node_t *cast = (const pm_interpolated_symbol_node_t *) node;
9621 int length = pm_interpolated_node_compile(iseq, &cast->parts, &location, ret, popped, scope_node, NULL, NULL, false, false);
9622
9623 if (length > 1) {
9624 PUSH_INSN1(ret, location, concatstrings, INT2FIX(length));
9625 }
9626
9627 if (!popped) {
9628 PUSH_INSN(ret, location, intern);
9629 }
9630 else {
9631 PUSH_INSN(ret, location, pop);
9632 }
9633
9634 return;
9635 }
9636 case PM_INTERPOLATED_X_STRING_NODE: {
9637 // `foo #{bar}`
9638 // ^^^^^^^^^^^^
9639 const pm_interpolated_x_string_node_t *cast = (const pm_interpolated_x_string_node_t *) node;
9640
9641 PUSH_INSN(ret, location, putself);
9642
9643 int length = pm_interpolated_node_compile(iseq, &cast->parts, &location, ret, false, scope_node, NULL, NULL, false, false);
9644 if (length > 1) PUSH_INSN1(ret, location, concatstrings, INT2FIX(length));
9645
9646 PUSH_SEND_WITH_FLAG(ret, location, idBackquote, INT2NUM(1), INT2FIX(VM_CALL_FCALL | VM_CALL_ARGS_SIMPLE));
9647 if (popped) PUSH_INSN(ret, location, pop);
9648
9649 return;
9650 }
9651 case PM_IT_LOCAL_VARIABLE_READ_NODE: {
9652 // -> { it }
9653 // ^^
9654 if (!popped) {
9655 pm_scope_node_t *current_scope_node = scope_node;
9656 int level = 0;
9657
9658 while (current_scope_node) {
9659 if (current_scope_node->parameters && PM_NODE_TYPE_P(current_scope_node->parameters, PM_IT_PARAMETERS_NODE)) {
9660 PUSH_GETLOCAL(ret, location, current_scope_node->local_table_for_iseq_size, level);
9661 return;
9662 }
9663
9664 current_scope_node = current_scope_node->previous;
9665 level++;
9666 }
9667 rb_bug("Local `it` does not exist");
9668 }
9669
9670 return;
9671 }
9672 case PM_KEYWORD_HASH_NODE: {
9673 // foo(bar: baz)
9674 // ^^^^^^^^
9675 const pm_keyword_hash_node_t *cast = (const pm_keyword_hash_node_t *) node;
9676 const pm_node_list_t *elements = &cast->elements;
9677
9678 const pm_node_t *element;
9679 PM_NODE_LIST_FOREACH(elements, index, element) {
9680 PM_COMPILE(element);
9681 }
9682
9683 if (!popped) PUSH_INSN1(ret, location, newhash, INT2FIX(elements->size * 2));
9684 return;
9685 }
9686 case PM_LAMBDA_NODE: {
9687 // -> {}
9688 // ^^^^^
9689 const pm_lambda_node_t *cast = (const pm_lambda_node_t *) node;
9690
9691 pm_scope_node_t next_scope_node;
9692 pm_scope_node_init(node, &next_scope_node, scope_node);
9693
9694 int opening_lineno = pm_location_line_number(parser, &cast->opening_loc);
9695 const rb_iseq_t *block = NEW_CHILD_ISEQ(&next_scope_node, make_name_for_block(iseq), ISEQ_TYPE_BLOCK, opening_lineno);
9696 pm_scope_node_destroy(&next_scope_node);
9697
9698 VALUE argc = INT2FIX(0);
9699 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
9700 PUSH_CALL_WITH_BLOCK(ret, location, idLambda, argc, block);
9701 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE) block);
9702
9703 if (popped) PUSH_INSN(ret, location, pop);
9704 return;
9705 }
9706 case PM_LOCAL_VARIABLE_AND_WRITE_NODE: {
9707 // foo &&= bar
9708 // ^^^^^^^^^^^
9709 const pm_local_variable_and_write_node_t *cast = (const pm_local_variable_and_write_node_t *) node;
9710 LABEL *end_label = NEW_LABEL(location.line);
9711
9712 pm_local_index_t local_index = pm_lookup_local_index(iseq, scope_node, cast->name, cast->depth);
9713 PUSH_GETLOCAL(ret, location, local_index.index, local_index.level);
9714 if (!popped) PUSH_INSN(ret, location, dup);
9715
9716 PUSH_INSNL(ret, location, branchunless, end_label);
9717 if (!popped) PUSH_INSN(ret, location, pop);
9718
9719 PM_COMPILE_NOT_POPPED(cast->value);
9720 if (!popped) PUSH_INSN(ret, location, dup);
9721
9722 PUSH_SETLOCAL(ret, location, local_index.index, local_index.level);
9723 PUSH_LABEL(ret, end_label);
9724
9725 return;
9726 }
9727 case PM_LOCAL_VARIABLE_OPERATOR_WRITE_NODE: {
9728 // foo += bar
9729 // ^^^^^^^^^^
9730 const pm_local_variable_operator_write_node_t *cast = (const pm_local_variable_operator_write_node_t *) node;
9731
9732 pm_local_index_t local_index = pm_lookup_local_index(iseq, scope_node, cast->name, cast->depth);
9733 PUSH_GETLOCAL(ret, location, local_index.index, local_index.level);
9734
9735 PM_COMPILE_NOT_POPPED(cast->value);
9736
9737 ID method_id = pm_constant_id_lookup(scope_node, cast->binary_operator);
9738 PUSH_SEND_WITH_FLAG(ret, location, method_id, INT2NUM(1), INT2FIX(VM_CALL_ARGS_SIMPLE));
9739
9740 if (!popped) PUSH_INSN(ret, location, dup);
9741 PUSH_SETLOCAL(ret, location, local_index.index, local_index.level);
9742
9743 return;
9744 }
9745 case PM_LOCAL_VARIABLE_OR_WRITE_NODE: {
9746 // foo ||= bar
9747 // ^^^^^^^^^^^
9748 const pm_local_variable_or_write_node_t *cast = (const pm_local_variable_or_write_node_t *) node;
9749
9750 LABEL *set_label = NEW_LABEL(location.line);
9751 LABEL *end_label = NEW_LABEL(location.line);
9752
9753 PUSH_INSN1(ret, location, putobject, Qtrue);
9754 PUSH_INSNL(ret, location, branchunless, set_label);
9755
9756 pm_local_index_t local_index = pm_lookup_local_index(iseq, scope_node, cast->name, cast->depth);
9757 PUSH_GETLOCAL(ret, location, local_index.index, local_index.level);
9758 if (!popped) PUSH_INSN(ret, location, dup);
9759
9760 PUSH_INSNL(ret, location, branchif, end_label);
9761 if (!popped) PUSH_INSN(ret, location, pop);
9762
9763 PUSH_LABEL(ret, set_label);
9764 PM_COMPILE_NOT_POPPED(cast->value);
9765 if (!popped) PUSH_INSN(ret, location, dup);
9766
9767 PUSH_SETLOCAL(ret, location, local_index.index, local_index.level);
9768 PUSH_LABEL(ret, end_label);
9769
9770 return;
9771 }
9772 case PM_LOCAL_VARIABLE_READ_NODE: {
9773 // foo
9774 // ^^^
9775 if (!popped) {
9776 const pm_local_variable_read_node_t *cast = (const pm_local_variable_read_node_t *) node;
9777 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, cast->name, cast->depth);
9778 PUSH_GETLOCAL(ret, location, index.index, index.level);
9779 }
9780
9781 return;
9782 }
9783 case PM_LOCAL_VARIABLE_WRITE_NODE: {
9784 // foo = 1
9785 // ^^^^^^^
9786 const pm_local_variable_write_node_t *cast = (const pm_local_variable_write_node_t *) node;
9787 PM_COMPILE_NOT_POPPED(cast->value);
9788 if (!popped) PUSH_INSN(ret, location, dup);
9789
9790 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, cast->name, cast->depth);
9791 PUSH_SETLOCAL(ret, location, index.index, index.level);
9792 return;
9793 }
9794 case PM_MATCH_LAST_LINE_NODE: {
9795 // if /foo/ then end
9796 // ^^^^^
9797 VALUE regexp = pm_static_literal_value(iseq, node, scope_node);
9798
9799 PUSH_INSN1(ret, location, putobject, regexp);
9800 PUSH_INSN2(ret, location, getspecial, INT2FIX(0), INT2FIX(0));
9801 PUSH_SEND(ret, location, idEqTilde, INT2NUM(1));
9802 if (popped) PUSH_INSN(ret, location, pop);
9803
9804 return;
9805 }
9806 case PM_MATCH_PREDICATE_NODE: {
9807 // foo in bar
9808 // ^^^^^^^^^^
9809 const pm_match_predicate_node_t *cast = (const pm_match_predicate_node_t *) node;
9810
9811 // First, allocate some stack space for the cached return value of any
9812 // calls to #deconstruct.
9813 PUSH_INSN(ret, location, putnil);
9814
9815 // Next, compile the expression that we're going to match against.
9816 PM_COMPILE_NOT_POPPED(cast->value);
9817 PUSH_INSN(ret, location, dup);
9818
9819 // Now compile the pattern that is going to be used to match against the
9820 // expression.
9821 LABEL *matched_label = NEW_LABEL(location.line);
9822 LABEL *unmatched_label = NEW_LABEL(location.line);
9823 LABEL *done_label = NEW_LABEL(location.line);
9824 pm_compile_pattern(iseq, scope_node, cast->pattern, ret, matched_label, unmatched_label, false, true, 2);
9825
9826 // If the pattern did not match, then compile the necessary instructions
9827 // to handle pushing false onto the stack, then jump to the end.
9828 PUSH_LABEL(ret, unmatched_label);
9829 PUSH_INSN(ret, location, pop);
9830 PUSH_INSN(ret, location, pop);
9831
9832 if (!popped) PUSH_INSN1(ret, location, putobject, Qfalse);
9833 PUSH_INSNL(ret, location, jump, done_label);
9834 PUSH_INSN(ret, location, putnil);
9835
9836 // If the pattern did match, then compile the necessary instructions to
9837 // handle pushing true onto the stack, then jump to the end.
9838 PUSH_LABEL(ret, matched_label);
9839 PUSH_INSN1(ret, location, adjuststack, INT2FIX(2));
9840 if (!popped) PUSH_INSN1(ret, location, putobject, Qtrue);
9841 PUSH_INSNL(ret, location, jump, done_label);
9842
9843 PUSH_LABEL(ret, done_label);
9844 return;
9845 }
9846 case PM_MATCH_REQUIRED_NODE:
9847 // foo => bar
9848 // ^^^^^^^^^^
9849 //
9850 // A match required node represents pattern matching against a single
9851 // pattern using the => operator. For example,
9852 //
9853 // foo => bar
9854 //
9855 // This is somewhat analogous to compiling a case match statement with a
9856 // single pattern. In both cases, if the pattern fails it should
9857 // immediately raise an error.
9858 pm_compile_match_required_node(iseq, (const pm_match_required_node_t *) node, &location, ret, popped, scope_node);
9859 return;
9860 case PM_MATCH_WRITE_NODE:
9861 // /(?<foo>foo)/ =~ bar
9862 // ^^^^^^^^^^^^^^^^^^^^
9863 //
9864 // Match write nodes are specialized call nodes that have a regular
9865 // expression with valid named capture groups on the left, the =~
9866 // operator, and some value on the right. The nodes themselves simply
9867 // wrap the call with the local variable targets that will be written
9868 // when the call is executed.
9869 pm_compile_match_write_node(iseq, (const pm_match_write_node_t *) node, &location, ret, popped, scope_node);
9870 return;
9871 case PM_MISSING_NODE:
9872 rb_bug("A pm_missing_node_t should not exist in prism's AST.");
9873 return;
9874 case PM_MODULE_NODE: {
9875 // module Foo; end
9876 // ^^^^^^^^^^^^^^^
9877 const pm_module_node_t *cast = (const pm_module_node_t *) node;
9878
9879 ID module_id = pm_constant_id_lookup(scope_node, cast->name);
9880 VALUE module_name = rb_str_freeze(rb_sprintf("<module:%"PRIsVALUE">", rb_id2str(module_id)));
9881
9882 pm_scope_node_t next_scope_node;
9883 pm_scope_node_init((const pm_node_t *) cast, &next_scope_node, scope_node);
9884
9885 const rb_iseq_t *module_iseq = NEW_CHILD_ISEQ(&next_scope_node, module_name, ISEQ_TYPE_CLASS, location.line);
9886 pm_scope_node_destroy(&next_scope_node);
9887
9888 const int flags = VM_DEFINECLASS_TYPE_MODULE | pm_compile_class_path(iseq, cast->constant_path, &location, ret, false, scope_node);
9889 PUSH_INSN(ret, location, putnil);
9890 PUSH_INSN3(ret, location, defineclass, ID2SYM(module_id), module_iseq, INT2FIX(flags));
9891 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE) module_iseq);
9892
9893 if (popped) PUSH_INSN(ret, location, pop);
9894 return;
9895 }
9896 case PM_REQUIRED_PARAMETER_NODE: {
9897 // def foo(bar); end
9898 // ^^^
9899 const pm_required_parameter_node_t *cast = (const pm_required_parameter_node_t *) node;
9900 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, cast->name, 0);
9901
9902 PUSH_SETLOCAL(ret, location, index.index, index.level);
9903 return;
9904 }
9905 case PM_MULTI_WRITE_NODE: {
9906 // foo, bar = baz
9907 // ^^^^^^^^^^^^^^
9908 //
9909 // A multi write node represents writing to multiple values using an =
9910 // operator. Importantly these nodes are only parsed when the left-hand
9911 // side of the operator has multiple targets. The right-hand side of the
9912 // operator having multiple targets represents an implicit array
9913 // instead.
9914 const pm_multi_write_node_t *cast = (const pm_multi_write_node_t *) node;
9915
9916 DECL_ANCHOR(writes);
9917 DECL_ANCHOR(cleanup);
9918
9919 pm_multi_target_state_t state = { 0 };
9920 state.position = popped ? 0 : 1;
9921 pm_compile_multi_target_node(iseq, node, ret, writes, cleanup, scope_node, &state);
9922
9923 PM_COMPILE_NOT_POPPED(cast->value);
9924 if (!popped) PUSH_INSN(ret, location, dup);
9925
9926 PUSH_SEQ(ret, writes);
9927 if (!popped && state.stack_size >= 1) {
9928 // Make sure the value on the right-hand side of the = operator is
9929 // being returned before we pop the parent expressions.
9930 PUSH_INSN1(ret, location, setn, INT2FIX(state.stack_size));
9931 }
9932
9933 // Now, we need to go back and modify the topn instructions in order to
9934 // ensure they can correctly retrieve the parent expressions.
9935 pm_multi_target_state_update(&state);
9936
9937 PUSH_SEQ(ret, cleanup);
9938 return;
9939 }
9940 case PM_NEXT_NODE:
9941 // next
9942 // ^^^^
9943 //
9944 // next foo
9945 // ^^^^^^^^
9946 pm_compile_next_node(iseq, (const pm_next_node_t *) node, &location, ret, popped, scope_node);
9947 return;
9948 case PM_NIL_NODE: {
9949 // nil
9950 // ^^^
9951 if (!popped) {
9952 PUSH_INSN(ret, location, putnil);
9953 }
9954
9955 return;
9956 }
9957 case PM_NO_KEYWORDS_PARAMETER_NODE: {
9958 // def foo(**nil); end
9959 // ^^^^^
9960 ISEQ_BODY(iseq)->param.flags.accepts_no_kwarg = TRUE;
9961 return;
9962 }
9963 case PM_NUMBERED_REFERENCE_READ_NODE: {
9964 // $1
9965 // ^^
9966 if (!popped) {
9967 const pm_numbered_reference_read_node_t *cast = (const pm_numbered_reference_read_node_t *) node;
9968
9969 if (cast->number != 0) {
9970 VALUE ref = pm_compile_numbered_reference_ref(cast);
9971 PUSH_INSN2(ret, location, getspecial, INT2FIX(1), ref);
9972 }
9973 else {
9974 PUSH_INSN(ret, location, putnil);
9975 }
9976 }
9977
9978 return;
9979 }
9980 case PM_OR_NODE: {
9981 // a or b
9982 // ^^^^^^
9983 const pm_or_node_t *cast = (const pm_or_node_t *) node;
9984
9985 LABEL *end_label = NEW_LABEL(location.line);
9986 PM_COMPILE_NOT_POPPED(cast->left);
9987
9988 if (!popped) PUSH_INSN(ret, location, dup);
9989 PUSH_INSNL(ret, location, branchif, end_label);
9990
9991 if (!popped) PUSH_INSN(ret, location, pop);
9992 PM_COMPILE(cast->right);
9993 PUSH_LABEL(ret, end_label);
9994
9995 return;
9996 }
9997 case PM_OPTIONAL_PARAMETER_NODE: {
9998 // def foo(bar = 1); end
9999 // ^^^^^^^
10000 const pm_optional_parameter_node_t *cast = (const pm_optional_parameter_node_t *) node;
10001 PM_COMPILE_NOT_POPPED(cast->value);
10002
10003 pm_local_index_t index = pm_lookup_local_index(iseq, scope_node, cast->name, 0);
10004 PUSH_SETLOCAL(ret, location, index.index, index.level);
10005
10006 return;
10007 }
10008 case PM_PARENTHESES_NODE: {
10009 // ()
10010 // ^^
10011 //
10012 // (1)
10013 // ^^^
10014 const pm_parentheses_node_t *cast = (const pm_parentheses_node_t *) node;
10015
10016 if (cast->body != NULL) {
10017 PM_COMPILE(cast->body);
10018 }
10019 else if (!popped) {
10020 PUSH_INSN(ret, location, putnil);
10021 }
10022
10023 return;
10024 }
10025 case PM_PRE_EXECUTION_NODE: {
10026 // BEGIN {}
10027 // ^^^^^^^^
10028 const pm_pre_execution_node_t *cast = (const pm_pre_execution_node_t *) node;
10029
10030 LINK_ANCHOR *outer_pre = scope_node->pre_execution_anchor;
10031 RUBY_ASSERT(outer_pre != NULL);
10032
10033 // BEGIN{} nodes can be nested, so here we're going to do the same thing
10034 // that we did for the top-level compilation where we create two
10035 // anchors and then join them in the correct order into the resulting
10036 // anchor.
10037 DECL_ANCHOR(inner_pre);
10038 scope_node->pre_execution_anchor = inner_pre;
10039
10040 DECL_ANCHOR(inner_body);
10041
10042 if (cast->statements != NULL) {
10043 const pm_node_list_t *body = &cast->statements->body;
10044
10045 for (size_t index = 0; index < body->size; index++) {
10046 pm_compile_node(iseq, body->nodes[index], inner_body, true, scope_node);
10047 }
10048 }
10049
10050 if (!popped) {
10051 PUSH_INSN(inner_body, location, putnil);
10052 }
10053
10054 // Now that everything has been compiled, join both anchors together
10055 // into the correct outer pre execution anchor, and reset the value so
10056 // that subsequent BEGIN{} nodes can be compiled correctly.
10057 PUSH_SEQ(outer_pre, inner_pre);
10058 PUSH_SEQ(outer_pre, inner_body);
10059 scope_node->pre_execution_anchor = outer_pre;
10060
10061 return;
10062 }
10063 case PM_POST_EXECUTION_NODE: {
10064 // END {}
10065 // ^^^^^^
10066 const rb_iseq_t *child_iseq;
10067 const rb_iseq_t *prevblock = ISEQ_COMPILE_DATA(iseq)->current_block;
10068
10069 pm_scope_node_t next_scope_node;
10070 pm_scope_node_init(node, &next_scope_node, scope_node);
10071 child_iseq = NEW_CHILD_ISEQ(&next_scope_node, make_name_for_block(iseq), ISEQ_TYPE_BLOCK, lineno);
10072 pm_scope_node_destroy(&next_scope_node);
10073
10074 ISEQ_COMPILE_DATA(iseq)->current_block = child_iseq;
10075
10076 int is_index = ISEQ_BODY(iseq)->ise_size++;
10077 PUSH_INSN2(ret, location, once, child_iseq, INT2FIX(is_index));
10078 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE) child_iseq);
10079 if (popped) PUSH_INSN(ret, location, pop);
10080
10081 ISEQ_COMPILE_DATA(iseq)->current_block = prevblock;
10082
10083 return;
10084 }
10085 case PM_RANGE_NODE: {
10086 // 0..5
10087 // ^^^^
10088 const pm_range_node_t *cast = (const pm_range_node_t *) node;
10089 bool exclude_end = PM_NODE_FLAG_P(cast, PM_RANGE_FLAGS_EXCLUDE_END);
10090
10091 if (pm_optimizable_range_item_p(cast->left) && pm_optimizable_range_item_p(cast->right)) {
10092 if (!popped) {
10093 const pm_node_t *left = cast->left;
10094 const pm_node_t *right = cast->right;
10095
10096 VALUE val = rb_range_new(
10097 (left && PM_NODE_TYPE_P(left, PM_INTEGER_NODE)) ? parse_integer((const pm_integer_node_t *) left) : Qnil,
10098 (right && PM_NODE_TYPE_P(right, PM_INTEGER_NODE)) ? parse_integer((const pm_integer_node_t *) right) : Qnil,
10099 exclude_end
10100 );
10101
10102 RB_OBJ_SET_SHAREABLE(val);
10103 PUSH_INSN1(ret, location, putobject, val);
10104 }
10105 }
10106 else {
10107 if (cast->left != NULL) {
10108 PM_COMPILE(cast->left);
10109 }
10110 else if (!popped) {
10111 PUSH_INSN(ret, location, putnil);
10112 }
10113
10114 if (cast->right != NULL) {
10115 PM_COMPILE(cast->right);
10116 }
10117 else if (!popped) {
10118 PUSH_INSN(ret, location, putnil);
10119 }
10120
10121 if (!popped) {
10122 PUSH_INSN1(ret, location, newrange, INT2FIX(exclude_end ? 1 : 0));
10123 }
10124 }
10125 return;
10126 }
10127 case PM_RATIONAL_NODE: {
10128 // 1r
10129 // ^^
10130 if (!popped) {
10131 PUSH_INSN1(ret, location, putobject, parse_rational((const pm_rational_node_t *) node));
10132 }
10133 return;
10134 }
10135 case PM_REDO_NODE:
10136 // redo
10137 // ^^^^
10138 pm_compile_redo_node(iseq, &location, ret, popped, scope_node);
10139 return;
10140 case PM_REGULAR_EXPRESSION_NODE: {
10141 // /foo/
10142 // ^^^^^
10143 if (!popped) {
10144 VALUE regexp = pm_static_literal_value(iseq, node, scope_node);
10145 PUSH_INSN1(ret, location, putobject, regexp);
10146 }
10147 return;
10148 }
10149 case PM_RESCUE_NODE:
10150 // begin; rescue; end
10151 // ^^^^^^^
10152 pm_compile_rescue_node(iseq, (const pm_rescue_node_t *) node, &location, ret, popped, scope_node);
10153 return;
10154 case PM_RESCUE_MODIFIER_NODE: {
10155 // foo rescue bar
10156 // ^^^^^^^^^^^^^^
10157 const pm_rescue_modifier_node_t *cast = (const pm_rescue_modifier_node_t *) node;
10158
10159 pm_scope_node_t rescue_scope_node;
10160 pm_scope_node_init((const pm_node_t *) cast, &rescue_scope_node, scope_node);
10161
10162 rb_iseq_t *rescue_iseq = NEW_CHILD_ISEQ(
10163 &rescue_scope_node,
10164 rb_str_concat(rb_str_new2("rescue in "), ISEQ_BODY(iseq)->location.label),
10165 ISEQ_TYPE_RESCUE,
10166 pm_node_line_number(parser, cast->rescue_expression)
10167 );
10168
10169 pm_scope_node_destroy(&rescue_scope_node);
10170
10171 LABEL *lstart = NEW_LABEL(location.line);
10172 LABEL *lend = NEW_LABEL(location.line);
10173 LABEL *lcont = NEW_LABEL(location.line);
10174
10175 lstart->rescued = LABEL_RESCUE_BEG;
10176 lend->rescued = LABEL_RESCUE_END;
10177
10178 PUSH_LABEL(ret, lstart);
10179 PM_COMPILE_NOT_POPPED(cast->expression);
10180 PUSH_LABEL(ret, lend);
10181
10182 PUSH_INSN(ret, location, nop);
10183 PUSH_LABEL(ret, lcont);
10184 if (popped) PUSH_INSN(ret, location, pop);
10185
10186 PUSH_CATCH_ENTRY(CATCH_TYPE_RESCUE, lstart, lend, rescue_iseq, lcont);
10187 PUSH_CATCH_ENTRY(CATCH_TYPE_RETRY, lend, lcont, NULL, lstart);
10188 return;
10189 }
10190 case PM_RETURN_NODE:
10191 // return
10192 // ^^^^^^
10193 //
10194 // return 1
10195 // ^^^^^^^^
10196 pm_compile_return_node(iseq, (const pm_return_node_t *) node, &location, ret, popped, scope_node);
10197 return;
10198 case PM_RETRY_NODE: {
10199 // retry
10200 // ^^^^^
10201 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_RESCUE) {
10202 PUSH_INSN(ret, location, putnil);
10203 PUSH_INSN1(ret, location, throw, INT2FIX(TAG_RETRY));
10204 if (popped) PUSH_INSN(ret, location, pop);
10205 }
10206 else {
10207 COMPILE_ERROR(iseq, location.line, "Invalid retry");
10208 return;
10209 }
10210 return;
10211 }
10212 case PM_SCOPE_NODE:
10213 pm_compile_scope_node(iseq, (pm_scope_node_t *) node, &location, ret, popped);
10214 return;
10215 case PM_SELF_NODE: {
10216 // self
10217 // ^^^^
10218 if (!popped) {
10219 PUSH_INSN(ret, location, putself);
10220 }
10221 return;
10222 }
10223 case PM_SHAREABLE_CONSTANT_NODE: {
10224 // A value that is being written to a constant that is being marked as
10225 // shared depending on the current lexical context.
10226 const pm_shareable_constant_node_t *cast = (const pm_shareable_constant_node_t *) node;
10227 pm_node_flags_t shareability = (cast->base.flags & (PM_SHAREABLE_CONSTANT_NODE_FLAGS_LITERAL | PM_SHAREABLE_CONSTANT_NODE_FLAGS_EXPERIMENTAL_EVERYTHING | PM_SHAREABLE_CONSTANT_NODE_FLAGS_EXPERIMENTAL_COPY));
10228
10229 switch (PM_NODE_TYPE(cast->write)) {
10230 case PM_CONSTANT_WRITE_NODE:
10231 pm_compile_constant_write_node(iseq, (const pm_constant_write_node_t *) cast->write, shareability, &location, ret, popped, scope_node);
10232 break;
10233 case PM_CONSTANT_AND_WRITE_NODE:
10234 pm_compile_constant_and_write_node(iseq, (const pm_constant_and_write_node_t *) cast->write, shareability, &location, ret, popped, scope_node);
10235 break;
10236 case PM_CONSTANT_OR_WRITE_NODE:
10237 pm_compile_constant_or_write_node(iseq, (const pm_constant_or_write_node_t *) cast->write, shareability, &location, ret, popped, scope_node);
10238 break;
10239 case PM_CONSTANT_OPERATOR_WRITE_NODE:
10240 pm_compile_constant_operator_write_node(iseq, (const pm_constant_operator_write_node_t *) cast->write, shareability, &location, ret, popped, scope_node);
10241 break;
10242 case PM_CONSTANT_PATH_WRITE_NODE:
10243 pm_compile_constant_path_write_node(iseq, (const pm_constant_path_write_node_t *) cast->write, shareability, &location, ret, popped, scope_node);
10244 break;
10245 case PM_CONSTANT_PATH_AND_WRITE_NODE:
10246 pm_compile_constant_path_and_write_node(iseq, (const pm_constant_path_and_write_node_t *) cast->write, shareability, &location, ret, popped, scope_node);
10247 break;
10248 case PM_CONSTANT_PATH_OR_WRITE_NODE:
10249 pm_compile_constant_path_or_write_node(iseq, (const pm_constant_path_or_write_node_t *) cast->write, shareability, &location, ret, popped, scope_node);
10250 break;
10251 case PM_CONSTANT_PATH_OPERATOR_WRITE_NODE:
10252 pm_compile_constant_path_operator_write_node(iseq, (const pm_constant_path_operator_write_node_t *) cast->write, shareability, &location, ret, popped, scope_node);
10253 break;
10254 default:
10255 rb_bug("Unexpected node type for shareable constant write: %s", pm_node_type_to_str(PM_NODE_TYPE(cast->write)));
10256 break;
10257 }
10258
10259 return;
10260 }
10261 case PM_SINGLETON_CLASS_NODE: {
10262 // class << self; end
10263 // ^^^^^^^^^^^^^^^^^^
10264 const pm_singleton_class_node_t *cast = (const pm_singleton_class_node_t *) node;
10265
10266 pm_scope_node_t next_scope_node;
10267 pm_scope_node_init((const pm_node_t *) cast, &next_scope_node, scope_node);
10268 const rb_iseq_t *child_iseq = NEW_ISEQ(&next_scope_node, rb_fstring_lit("singleton class"), ISEQ_TYPE_CLASS, location.line);
10269 pm_scope_node_destroy(&next_scope_node);
10270
10271 PM_COMPILE_NOT_POPPED(cast->expression);
10272 PUSH_INSN(ret, location, putnil);
10273
10274 ID singletonclass;
10275 CONST_ID(singletonclass, "singletonclass");
10276 PUSH_INSN3(ret, location, defineclass, ID2SYM(singletonclass), child_iseq, INT2FIX(VM_DEFINECLASS_TYPE_SINGLETON_CLASS));
10277
10278 if (popped) PUSH_INSN(ret, location, pop);
10279 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE) child_iseq);
10280
10281 return;
10282 }
10283 case PM_SOURCE_ENCODING_NODE: {
10284 // __ENCODING__
10285 // ^^^^^^^^^^^^
10286 if (!popped) {
10287 VALUE value = pm_static_literal_value(iseq, node, scope_node);
10288 PUSH_INSN1(ret, location, putobject, value);
10289 }
10290 return;
10291 }
10292 case PM_SOURCE_FILE_NODE: {
10293 // __FILE__
10294 // ^^^^^^^^
10295 if (!popped) {
10296 const pm_source_file_node_t *cast = (const pm_source_file_node_t *) node;
10297 VALUE string = pm_source_file_value(cast, scope_node);
10298
10299 if (PM_NODE_FLAG_P(cast, PM_STRING_FLAGS_FROZEN)) {
10300 PUSH_INSN1(ret, location, putobject, string);
10301 }
10302 else if (PM_NODE_FLAG_P(cast, PM_STRING_FLAGS_MUTABLE)) {
10303 PUSH_INSN1(ret, location, putstring, string);
10304 }
10305 else {
10306 PUSH_INSN1(ret, location, putchilledstring, string);
10307 }
10308 }
10309 return;
10310 }
10311 case PM_SOURCE_LINE_NODE: {
10312 // __LINE__
10313 // ^^^^^^^^
10314 if (!popped) {
10315 VALUE value = pm_static_literal_value(iseq, node, scope_node);
10316 PUSH_INSN1(ret, location, putobject, value);
10317 }
10318 return;
10319 }
10320 case PM_SPLAT_NODE: {
10321 // foo(*bar)
10322 // ^^^^
10323 const pm_splat_node_t *cast = (const pm_splat_node_t *) node;
10324 if (cast->expression) {
10325 PM_COMPILE(cast->expression);
10326 }
10327
10328 if (!popped) {
10329 PUSH_INSN1(ret, location, splatarray, Qtrue);
10330 }
10331 return;
10332 }
10333 case PM_STATEMENTS_NODE: {
10334 // A list of statements.
10335 const pm_statements_node_t *cast = (const pm_statements_node_t *) node;
10336 const pm_node_list_t *body = &cast->body;
10337
10338 if (body->size > 0) {
10339 for (size_t index = 0; index < body->size - 1; index++) {
10340 PM_COMPILE_POPPED(body->nodes[index]);
10341 }
10342 PM_COMPILE(body->nodes[body->size - 1]);
10343 }
10344 else {
10345 PUSH_INSN(ret, location, putnil);
10346 }
10347 return;
10348 }
10349 case PM_STRING_NODE: {
10350 // "foo"
10351 // ^^^^^
10352 if (!popped) {
10353 const pm_string_node_t *cast = (const pm_string_node_t *) node;
10354 VALUE value = parse_static_literal_string(iseq, scope_node, node, &cast->unescaped);
10355
10356 if (PM_NODE_FLAG_P(node, PM_STRING_FLAGS_FROZEN)) {
10357 PUSH_INSN1(ret, location, putobject, value);
10358 }
10359 else if (PM_NODE_FLAG_P(node, PM_STRING_FLAGS_MUTABLE)) {
10360 PUSH_INSN1(ret, location, putstring, value);
10361 }
10362 else {
10363 PUSH_INSN1(ret, location, putchilledstring, value);
10364 }
10365 }
10366 return;
10367 }
10368 case PM_SUPER_NODE:
10369 // super()
10370 // super(foo)
10371 // super(...)
10372 pm_compile_super_node(iseq, (const pm_super_node_t *) node, &location, ret, popped, scope_node);
10373 return;
10374 case PM_SYMBOL_NODE: {
10375 // :foo
10376 // ^^^^
10377 if (!popped) {
10378 VALUE value = pm_static_literal_value(iseq, node, scope_node);
10379 PUSH_INSN1(ret, location, putobject, value);
10380 }
10381 return;
10382 }
10383 case PM_TRUE_NODE: {
10384 // true
10385 // ^^^^
10386 if (!popped) {
10387 PUSH_INSN1(ret, location, putobject, Qtrue);
10388 }
10389 return;
10390 }
10391 case PM_UNDEF_NODE: {
10392 // undef foo
10393 // ^^^^^^^^^
10394 const pm_undef_node_t *cast = (const pm_undef_node_t *) node;
10395 const pm_node_list_t *names = &cast->names;
10396
10397 for (size_t index = 0; index < names->size; index++) {
10398 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
10399 PUSH_INSN1(ret, location, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CBASE));
10400
10401 PM_COMPILE_NOT_POPPED(names->nodes[index]);
10402 PUSH_SEND(ret, location, id_core_undef_method, INT2NUM(2));
10403
10404 if (index < names->size - 1) {
10405 PUSH_INSN(ret, location, pop);
10406 }
10407 }
10408
10409 if (popped) PUSH_INSN(ret, location, pop);
10410 return;
10411 }
10412 case PM_UNLESS_NODE: {
10413 // unless foo; bar end
10414 // ^^^^^^^^^^^^^^^^^^^
10415 //
10416 // bar unless foo
10417 // ^^^^^^^^^^^^^^
10418 const pm_unless_node_t *cast = (const pm_unless_node_t *) node;
10419 const pm_statements_node_t *statements = NULL;
10420 if (cast->else_clause != NULL) {
10421 statements = ((const pm_else_node_t *) cast->else_clause)->statements;
10422 }
10423
10424 pm_compile_conditional(iseq, &location, PM_UNLESS_NODE, (const pm_node_t *) cast, statements, (const pm_node_t *) cast->statements, cast->predicate, ret, popped, scope_node);
10425 return;
10426 }
10427 case PM_UNTIL_NODE: {
10428 // until foo; bar end
10429 // ^^^^^^^^^^^^^^^^^
10430 //
10431 // bar until foo
10432 // ^^^^^^^^^^^^^
10433 const pm_until_node_t *cast = (const pm_until_node_t *) node;
10434 pm_compile_loop(iseq, &location, cast->base.flags, PM_UNTIL_NODE, (const pm_node_t *) cast, cast->statements, cast->predicate, ret, popped, scope_node);
10435 return;
10436 }
10437 case PM_WHILE_NODE: {
10438 // while foo; bar end
10439 // ^^^^^^^^^^^^^^^^^^
10440 //
10441 // bar while foo
10442 // ^^^^^^^^^^^^^
10443 const pm_while_node_t *cast = (const pm_while_node_t *) node;
10444 pm_compile_loop(iseq, &location, cast->base.flags, PM_WHILE_NODE, (const pm_node_t *) cast, cast->statements, cast->predicate, ret, popped, scope_node);
10445 return;
10446 }
10447 case PM_X_STRING_NODE: {
10448 // `foo`
10449 // ^^^^^
10450 const pm_x_string_node_t *cast = (const pm_x_string_node_t *) node;
10451 VALUE value = parse_static_literal_string(iseq, scope_node, node, &cast->unescaped);
10452
10453 PUSH_INSN(ret, location, putself);
10454 PUSH_INSN1(ret, location, putobject, value);
10455 PUSH_SEND_WITH_FLAG(ret, location, idBackquote, INT2NUM(1), INT2FIX(VM_CALL_FCALL | VM_CALL_ARGS_SIMPLE));
10456 if (popped) PUSH_INSN(ret, location, pop);
10457
10458 return;
10459 }
10460 case PM_YIELD_NODE:
10461 // yield
10462 // ^^^^^
10463 //
10464 // yield 1
10465 // ^^^^^^^
10466 pm_compile_yield_node(iseq, (const pm_yield_node_t *) node, &location, ret, popped, scope_node);
10467 return;
10468 default:
10469 rb_raise(rb_eNotImpError, "node type %s not implemented", pm_node_type_to_str(PM_NODE_TYPE(node)));
10470 return;
10471 }
10472}
10473
10474#undef PM_CONTAINER_P
10475
10477static inline bool
10478pm_iseq_pre_execution_p(rb_iseq_t *iseq)
10479{
10480 switch (ISEQ_BODY(iseq)->type) {
10481 case ISEQ_TYPE_TOP:
10482 case ISEQ_TYPE_EVAL:
10483 case ISEQ_TYPE_MAIN:
10484 return true;
10485 default:
10486 return false;
10487 }
10488}
10489
10497VALUE
10498pm_iseq_compile_node(rb_iseq_t *iseq, pm_scope_node_t *node)
10499{
10500 DECL_ANCHOR(ret);
10501
10502 if (pm_iseq_pre_execution_p(iseq)) {
10503 // Because these ISEQs can have BEGIN{}, we're going to create two
10504 // anchors to compile them, a "pre" and a "body". We'll mark the "pre"
10505 // on the scope node so that when BEGIN{} is found, its contents will be
10506 // added to the "pre" anchor.
10507 DECL_ANCHOR(pre);
10508 node->pre_execution_anchor = pre;
10509
10510 // Now we'll compile the body as normal. We won't compile directly into
10511 // the "ret" anchor yet because we want to add the "pre" anchor to the
10512 // beginning of the "ret" anchor first.
10513 DECL_ANCHOR(body);
10514 pm_compile_node(iseq, (const pm_node_t *) node, body, false, node);
10515
10516 // Now we'll join both anchors together so that the content is in the
10517 // correct order.
10518 PUSH_SEQ(ret, pre);
10519 PUSH_SEQ(ret, body);
10520 }
10521 else {
10522 // In other circumstances, we can just compile the node directly into
10523 // the "ret" anchor.
10524 pm_compile_node(iseq, (const pm_node_t *) node, ret, false, node);
10525 }
10526
10527 CHECK(iseq_setup_insn(iseq, ret));
10528 return iseq_setup(iseq, ret);
10529}
10530
10535void
10536pm_parse_result_free(pm_parse_result_t *result)
10537{
10538 if (result->node.ast_node != NULL) {
10539 pm_node_destroy(&result->parser, result->node.ast_node);
10540 }
10541
10542 if (result->parsed) {
10543 xfree(result->node.constants);
10544 pm_scope_node_destroy(&result->node);
10545 }
10546
10547 pm_parser_free(&result->parser);
10548 pm_string_free(&result->input);
10549 pm_options_free(&result->options);
10550}
10551
10553typedef struct {
10556
10558 int32_t line;
10559
10562
10564 uint32_t column_end;
10566
10568typedef struct {
10570 const char *number_prefix;
10571
10573 const char *blank_prefix;
10574
10576 const char *divider;
10577
10580
10584
10585#define PM_COLOR_BOLD "\033[1m"
10586#define PM_COLOR_GRAY "\033[2m"
10587#define PM_COLOR_RED "\033[1;31m"
10588#define PM_COLOR_RESET "\033[m"
10589#define PM_ERROR_TRUNCATE 30
10590
10591static inline pm_parse_error_t *
10592pm_parse_errors_format_sort(const pm_parser_t *parser, const pm_list_t *error_list, const pm_newline_list_t *newline_list) {
10593 pm_parse_error_t *errors = xcalloc(error_list->size, sizeof(pm_parse_error_t));
10594 if (errors == NULL) return NULL;
10595
10596 int32_t start_line = parser->start_line;
10597 pm_diagnostic_t *finish = (pm_diagnostic_t * )error_list->tail->next;
10598
10599 for (pm_diagnostic_t *error = (pm_diagnostic_t *) error_list->head; error != finish; error = (pm_diagnostic_t *) error->node.next) {
10600 pm_line_column_t start = pm_newline_list_line_column(newline_list, error->location.start, start_line);
10601 pm_line_column_t end = pm_newline_list_line_column(newline_list, error->location.end, start_line);
10602
10603 // We're going to insert this error into the array in sorted order. We
10604 // do this by finding the first error that has a line number greater
10605 // than the current error and then inserting the current error before
10606 // that one.
10607 size_t index = 0;
10608 while (
10609 (index < error_list->size) &&
10610 (errors[index].error != NULL) &&
10611 (
10612 (errors[index].line < start.line) ||
10613 ((errors[index].line == start.line) && (errors[index].column_start < start.column))
10614 )
10615 ) index++;
10616
10617 // Now we're going to shift all of the errors after this one down one
10618 // index to make room for the new error.
10619 if (index + 1 < error_list->size) {
10620 memmove(&errors[index + 1], &errors[index], sizeof(pm_parse_error_t) * (error_list->size - index - 1));
10621 }
10622
10623 // Finally, we'll insert the error into the array.
10624 uint32_t column_end;
10625 if (start.line == end.line) {
10626 column_end = end.column;
10627 } else {
10628 column_end = (uint32_t) (newline_list->offsets[start.line - start_line + 1] - newline_list->offsets[start.line - start_line] - 1);
10629 }
10630
10631 // Ensure we have at least one column of error.
10632 if (start.column == column_end) column_end++;
10633
10634 errors[index] = (pm_parse_error_t) {
10635 .error = error,
10636 .line = start.line,
10637 .column_start = start.column,
10638 .column_end = column_end
10639 };
10640 }
10641
10642 return errors;
10643}
10644
10645/* Append a literal string to the buffer. */
10646#define pm_buffer_append_literal(buffer, str) pm_buffer_append_string(buffer, str, rb_strlen_lit(str))
10647
10648static inline void
10649pm_parse_errors_format_line(const pm_parser_t *parser, const pm_newline_list_t *newline_list, const char *number_prefix, int32_t line, uint32_t column_start, uint32_t column_end, pm_buffer_t *buffer) {
10650 int32_t line_delta = line - parser->start_line;
10651 assert(line_delta >= 0);
10652
10653 size_t index = (size_t) line_delta;
10654 assert(index < newline_list->size);
10655
10656 const uint8_t *start = &parser->start[newline_list->offsets[index]];
10657 const uint8_t *end;
10658
10659 if (index >= newline_list->size - 1) {
10660 end = parser->end;
10661 } else {
10662 end = &parser->start[newline_list->offsets[index + 1]];
10663 }
10664
10665 pm_buffer_append_format(buffer, number_prefix, line);
10666
10667 // Here we determine if we should truncate the end of the line.
10668 bool truncate_end = false;
10669 if ((column_end != 0) && ((end - (start + column_end)) >= PM_ERROR_TRUNCATE)) {
10670 const uint8_t *end_candidate = start + column_end + PM_ERROR_TRUNCATE;
10671
10672 for (const uint8_t *ptr = start; ptr < end_candidate;) {
10673 size_t char_width = parser->encoding->char_width(ptr, parser->end - ptr);
10674
10675 // If we failed to decode a character, then just bail out and
10676 // truncate at the fixed width.
10677 if (char_width == 0) break;
10678
10679 // If this next character would go past the end candidate,
10680 // then we need to truncate before it.
10681 if (ptr + char_width > end_candidate) {
10682 end_candidate = ptr;
10683 break;
10684 }
10685
10686 ptr += char_width;
10687 }
10688
10689 end = end_candidate;
10690 truncate_end = true;
10691 }
10692
10693 // Here we determine if we should truncate the start of the line.
10694 if (column_start >= PM_ERROR_TRUNCATE) {
10695 pm_buffer_append_string(buffer, "... ", 4);
10696 start += column_start;
10697 }
10698
10699 pm_buffer_append_string(buffer, (const char *) start, (size_t) (end - start));
10700
10701 if (truncate_end) {
10702 pm_buffer_append_string(buffer, " ...\n", 5);
10703 } else if (end == parser->end && end[-1] != '\n') {
10704 pm_buffer_append_string(buffer, "\n", 1);
10705 }
10706}
10707
10711static void
10712pm_parse_errors_format(const pm_parser_t *parser, const pm_list_t *error_list, pm_buffer_t *buffer, int highlight, bool inline_messages) {
10713 assert(error_list->size != 0);
10714
10715 // First, we're going to sort all of the errors by line number using an
10716 // insertion sort into a newly allocated array.
10717 const int32_t start_line = parser->start_line;
10718 const pm_newline_list_t *newline_list = &parser->newline_list;
10719
10720 pm_parse_error_t *errors = pm_parse_errors_format_sort(parser, error_list, newline_list);
10721 if (errors == NULL) return;
10722
10723 // Now we're going to determine how we're going to format line numbers and
10724 // blank lines based on the maximum number of digits in the line numbers
10725 // that are going to be displaid.
10726 pm_parse_error_format_t error_format;
10727 int32_t first_line_number = errors[0].line;
10728 int32_t last_line_number = errors[error_list->size - 1].line;
10729
10730 // If we have a maximum line number that is negative, then we're going to
10731 // use the absolute value for comparison but multiple by 10 to additionally
10732 // have a column for the negative sign.
10733 if (first_line_number < 0) first_line_number = (-first_line_number) * 10;
10734 if (last_line_number < 0) last_line_number = (-last_line_number) * 10;
10735 int32_t max_line_number = first_line_number > last_line_number ? first_line_number : last_line_number;
10736
10737 if (max_line_number < 10) {
10738 if (highlight > 0) {
10739 error_format = (pm_parse_error_format_t) {
10740 .number_prefix = PM_COLOR_GRAY "%1" PRIi32 " | " PM_COLOR_RESET,
10741 .blank_prefix = PM_COLOR_GRAY " | " PM_COLOR_RESET,
10742 .divider = PM_COLOR_GRAY " ~~~~~" PM_COLOR_RESET "\n"
10743 };
10744 } else {
10745 error_format = (pm_parse_error_format_t) {
10746 .number_prefix = "%1" PRIi32 " | ",
10747 .blank_prefix = " | ",
10748 .divider = " ~~~~~\n"
10749 };
10750 }
10751 } else if (max_line_number < 100) {
10752 if (highlight > 0) {
10753 error_format = (pm_parse_error_format_t) {
10754 .number_prefix = PM_COLOR_GRAY "%2" PRIi32 " | " PM_COLOR_RESET,
10755 .blank_prefix = PM_COLOR_GRAY " | " PM_COLOR_RESET,
10756 .divider = PM_COLOR_GRAY " ~~~~~~" PM_COLOR_RESET "\n"
10757 };
10758 } else {
10759 error_format = (pm_parse_error_format_t) {
10760 .number_prefix = "%2" PRIi32 " | ",
10761 .blank_prefix = " | ",
10762 .divider = " ~~~~~~\n"
10763 };
10764 }
10765 } else if (max_line_number < 1000) {
10766 if (highlight > 0) {
10767 error_format = (pm_parse_error_format_t) {
10768 .number_prefix = PM_COLOR_GRAY "%3" PRIi32 " | " PM_COLOR_RESET,
10769 .blank_prefix = PM_COLOR_GRAY " | " PM_COLOR_RESET,
10770 .divider = PM_COLOR_GRAY " ~~~~~~~" PM_COLOR_RESET "\n"
10771 };
10772 } else {
10773 error_format = (pm_parse_error_format_t) {
10774 .number_prefix = "%3" PRIi32 " | ",
10775 .blank_prefix = " | ",
10776 .divider = " ~~~~~~~\n"
10777 };
10778 }
10779 } else if (max_line_number < 10000) {
10780 if (highlight > 0) {
10781 error_format = (pm_parse_error_format_t) {
10782 .number_prefix = PM_COLOR_GRAY "%4" PRIi32 " | " PM_COLOR_RESET,
10783 .blank_prefix = PM_COLOR_GRAY " | " PM_COLOR_RESET,
10784 .divider = PM_COLOR_GRAY " ~~~~~~~~" PM_COLOR_RESET "\n"
10785 };
10786 } else {
10787 error_format = (pm_parse_error_format_t) {
10788 .number_prefix = "%4" PRIi32 " | ",
10789 .blank_prefix = " | ",
10790 .divider = " ~~~~~~~~\n"
10791 };
10792 }
10793 } else {
10794 if (highlight > 0) {
10795 error_format = (pm_parse_error_format_t) {
10796 .number_prefix = PM_COLOR_GRAY "%5" PRIi32 " | " PM_COLOR_RESET,
10797 .blank_prefix = PM_COLOR_GRAY " | " PM_COLOR_RESET,
10798 .divider = PM_COLOR_GRAY " ~~~~~~~~" PM_COLOR_RESET "\n"
10799 };
10800 } else {
10801 error_format = (pm_parse_error_format_t) {
10802 .number_prefix = "%5" PRIi32 " | ",
10803 .blank_prefix = " | ",
10804 .divider = " ~~~~~~~~\n"
10805 };
10806 }
10807 }
10808
10809 error_format.blank_prefix_length = strlen(error_format.blank_prefix);
10810 error_format.divider_length = strlen(error_format.divider);
10811
10812 // Now we're going to iterate through every error in our error list and
10813 // display it. While we're iterating, we will display some padding lines of
10814 // the source before the error to give some context. We'll be careful not to
10815 // display the same line twice in case the errors are close enough in the
10816 // source.
10817 int32_t last_line = parser->start_line - 1;
10818 uint32_t last_column_start = 0;
10819 const pm_encoding_t *encoding = parser->encoding;
10820
10821 for (size_t index = 0; index < error_list->size; index++) {
10822 pm_parse_error_t *error = &errors[index];
10823
10824 // Here we determine how many lines of padding of the source to display,
10825 // based on the difference from the last line that was displaid.
10826 if (error->line - last_line > 1) {
10827 if (error->line - last_line > 2) {
10828 if ((index != 0) && (error->line - last_line > 3)) {
10829 pm_buffer_append_string(buffer, error_format.divider, error_format.divider_length);
10830 }
10831
10832 pm_buffer_append_string(buffer, " ", 2);
10833 pm_parse_errors_format_line(parser, newline_list, error_format.number_prefix, error->line - 2, 0, 0, buffer);
10834 }
10835
10836 pm_buffer_append_string(buffer, " ", 2);
10837 pm_parse_errors_format_line(parser, newline_list, error_format.number_prefix, error->line - 1, 0, 0, buffer);
10838 }
10839
10840 // If this is the first error or we're on a new line, then we'll display
10841 // the line that has the error in it.
10842 if ((index == 0) || (error->line != last_line)) {
10843 if (highlight > 1) {
10844 pm_buffer_append_literal(buffer, PM_COLOR_RED "> " PM_COLOR_RESET);
10845 } else if (highlight > 0) {
10846 pm_buffer_append_literal(buffer, PM_COLOR_BOLD "> " PM_COLOR_RESET);
10847 } else {
10848 pm_buffer_append_literal(buffer, "> ");
10849 }
10850
10851 last_column_start = error->column_start;
10852
10853 // Find the maximum column end of all the errors on this line.
10854 uint32_t column_end = error->column_end;
10855 for (size_t next_index = index + 1; next_index < error_list->size; next_index++) {
10856 if (errors[next_index].line != error->line) break;
10857 if (errors[next_index].column_end > column_end) column_end = errors[next_index].column_end;
10858 }
10859
10860 pm_parse_errors_format_line(parser, newline_list, error_format.number_prefix, error->line, error->column_start, column_end, buffer);
10861 }
10862
10863 const uint8_t *start = &parser->start[newline_list->offsets[error->line - start_line]];
10864 if (start == parser->end) pm_buffer_append_byte(buffer, '\n');
10865
10866 // Now we'll display the actual error message. We'll do this by first
10867 // putting the prefix to the line, then a bunch of blank spaces
10868 // depending on the column, then as many carets as we need to display
10869 // the width of the error, then the error message itself.
10870 //
10871 // Note that this doesn't take into account the width of the actual
10872 // character when displaid in the terminal. For some east-asian
10873 // languages or emoji, this means it can be thrown off pretty badly. We
10874 // will need to solve this eventually.
10875 pm_buffer_append_string(buffer, " ", 2);
10876 pm_buffer_append_string(buffer, error_format.blank_prefix, error_format.blank_prefix_length);
10877
10878 size_t column = 0;
10879 if (last_column_start >= PM_ERROR_TRUNCATE) {
10880 pm_buffer_append_string(buffer, " ", 4);
10881 column = last_column_start;
10882 }
10883
10884 while (column < error->column_start) {
10885 pm_buffer_append_byte(buffer, ' ');
10886
10887 size_t char_width = encoding->char_width(start + column, parser->end - (start + column));
10888 column += (char_width == 0 ? 1 : char_width);
10889 }
10890
10891 if (highlight > 1) pm_buffer_append_literal(buffer, PM_COLOR_RED);
10892 else if (highlight > 0) pm_buffer_append_literal(buffer, PM_COLOR_BOLD);
10893 pm_buffer_append_byte(buffer, '^');
10894
10895 size_t char_width = encoding->char_width(start + column, parser->end - (start + column));
10896 column += (char_width == 0 ? 1 : char_width);
10897
10898 while (column < error->column_end) {
10899 pm_buffer_append_byte(buffer, '~');
10900
10901 size_t char_width = encoding->char_width(start + column, parser->end - (start + column));
10902 column += (char_width == 0 ? 1 : char_width);
10903 }
10904
10905 if (highlight > 0) pm_buffer_append_literal(buffer, PM_COLOR_RESET);
10906
10907 if (inline_messages) {
10908 pm_buffer_append_byte(buffer, ' ');
10909 assert(error->error != NULL);
10910
10911 const char *message = error->error->message;
10912 pm_buffer_append_string(buffer, message, strlen(message));
10913 }
10914
10915 pm_buffer_append_byte(buffer, '\n');
10916
10917 // Here we determine how many lines of padding to display after the
10918 // error, depending on where the next error is in source.
10919 last_line = error->line;
10920 int32_t next_line;
10921
10922 if (index == error_list->size - 1) {
10923 next_line = (((int32_t) newline_list->size) + parser->start_line);
10924
10925 // If the file ends with a newline, subtract one from our "next_line"
10926 // so that we don't output an extra line at the end of the file
10927 if ((parser->start + newline_list->offsets[newline_list->size - 1]) == parser->end) {
10928 next_line--;
10929 }
10930 }
10931 else {
10932 next_line = errors[index + 1].line;
10933 }
10934
10935 if (next_line - last_line > 1) {
10936 pm_buffer_append_string(buffer, " ", 2);
10937 pm_parse_errors_format_line(parser, newline_list, error_format.number_prefix, ++last_line, 0, 0, buffer);
10938 }
10939
10940 if (next_line - last_line > 1) {
10941 pm_buffer_append_string(buffer, " ", 2);
10942 pm_parse_errors_format_line(parser, newline_list, error_format.number_prefix, ++last_line, 0, 0, buffer);
10943 }
10944 }
10945
10946 // Finally, we'll free the array of errors that we allocated.
10947 xfree(errors);
10948}
10949
10950#undef PM_ERROR_TRUNCATE
10951#undef PM_COLOR_GRAY
10952#undef PM_COLOR_RED
10953#undef PM_COLOR_RESET
10954
10961static bool
10962pm_parse_process_error_utf8_p(const pm_parser_t *parser, const pm_location_t *location)
10963{
10964 const size_t start_line = pm_newline_list_line_column(&parser->newline_list, location->start, 1).line;
10965 const size_t end_line = pm_newline_list_line_column(&parser->newline_list, location->end, 1).line;
10966
10967 const uint8_t *start = parser->start + parser->newline_list.offsets[start_line - 1];
10968 const uint8_t *end = ((end_line == parser->newline_list.size) ? parser->end : (parser->start + parser->newline_list.offsets[end_line]));
10969 size_t width;
10970
10971 while (start < end) {
10972 if ((width = pm_encoding_utf_8_char_width(start, end - start)) == 0) return false;
10973 start += width;
10974 }
10975
10976 return true;
10977}
10978
10983static VALUE
10984pm_parse_process_error(const pm_parse_result_t *result)
10985{
10986 const pm_parser_t *parser = &result->parser;
10987 const pm_diagnostic_t *head = (const pm_diagnostic_t *) parser->error_list.head;
10988 bool valid_utf8 = true;
10989
10990 pm_buffer_t buffer = { 0 };
10991 const pm_string_t *filepath = &parser->filepath;
10992
10993 int highlight = rb_stderr_tty_p();
10994 if (highlight) {
10995 const char *no_color = getenv("NO_COLOR");
10996 highlight = (no_color == NULL || no_color[0] == '\0') ? 2 : 1;
10997 }
10998
10999 for (const pm_diagnostic_t *error = head; error != NULL; error = (const pm_diagnostic_t *) error->node.next) {
11000 switch (error->level) {
11002 // It is implicitly assumed that the error messages will be
11003 // encodeable as UTF-8. Because of this, we can't include source
11004 // examples that contain invalid byte sequences. So if any source
11005 // examples include invalid UTF-8 byte sequences, we will skip
11006 // showing source examples entirely.
11007 if (valid_utf8 && !pm_parse_process_error_utf8_p(parser, &error->location)) {
11008 valid_utf8 = false;
11009 }
11010 break;
11012 // Any errors with the level PM_ERROR_LEVEL_ARGUMENT take over as
11013 // the only argument that gets raised. This is to allow priority
11014 // messages that should be handled before anything else.
11015 int32_t line_number = (int32_t) pm_location_line_number(parser, &error->location);
11016
11017 pm_buffer_append_format(
11018 &buffer,
11019 "%.*s:%" PRIi32 ": %s",
11020 (int) pm_string_length(filepath),
11021 pm_string_source(filepath),
11022 line_number,
11023 error->message
11024 );
11025
11026 if (pm_parse_process_error_utf8_p(parser, &error->location)) {
11027 pm_buffer_append_byte(&buffer, '\n');
11028
11029 pm_list_node_t *list_node = (pm_list_node_t *) error;
11030 pm_list_t error_list = { .size = 1, .head = list_node, .tail = list_node };
11031
11032 pm_parse_errors_format(parser, &error_list, &buffer, highlight, false);
11033 }
11034
11035 VALUE value = rb_exc_new(rb_eArgError, pm_buffer_value(&buffer), pm_buffer_length(&buffer));
11036 pm_buffer_free(&buffer);
11037
11038 return value;
11039 }
11040 case PM_ERROR_LEVEL_LOAD: {
11041 // Load errors are much simpler, because they don't include any of
11042 // the source in them. We create the error directly from the
11043 // message.
11044 VALUE message = rb_enc_str_new_cstr(error->message, rb_locale_encoding());
11045 VALUE value = rb_exc_new3(rb_eLoadError, message);
11046 rb_ivar_set(value, rb_intern_const("@path"), Qnil);
11047 return value;
11048 }
11049 }
11050 }
11051
11052 pm_buffer_append_format(
11053 &buffer,
11054 "%.*s:%" PRIi32 ": syntax error%s found\n",
11055 (int) pm_string_length(filepath),
11056 pm_string_source(filepath),
11057 (int32_t) pm_location_line_number(parser, &head->location),
11058 (parser->error_list.size > 1) ? "s" : ""
11059 );
11060
11061 if (valid_utf8) {
11062 pm_parse_errors_format(parser, &parser->error_list, &buffer, highlight, true);
11063 }
11064 else {
11065 for (const pm_diagnostic_t *error = head; error != NULL; error = (const pm_diagnostic_t *) error->node.next) {
11066 if (error != head) pm_buffer_append_byte(&buffer, '\n');
11067 pm_buffer_append_format(&buffer, "%.*s:%" PRIi32 ": %s", (int) pm_string_length(filepath), pm_string_source(filepath), (int32_t) pm_location_line_number(parser, &error->location), error->message);
11068 }
11069 }
11070
11071 VALUE message = rb_enc_str_new(pm_buffer_value(&buffer), pm_buffer_length(&buffer), result->node.encoding);
11072 VALUE error = rb_exc_new_str(rb_eSyntaxError, message);
11073
11074 rb_encoding *filepath_encoding = result->node.filepath_encoding != NULL ? result->node.filepath_encoding : rb_utf8_encoding();
11075 VALUE path = rb_enc_str_new((const char *) pm_string_source(filepath), pm_string_length(filepath), filepath_encoding);
11076
11077 rb_ivar_set(error, rb_intern_const("@path"), path);
11078 pm_buffer_free(&buffer);
11079
11080 return error;
11081}
11082
11088static VALUE
11089pm_parse_process(pm_parse_result_t *result, pm_node_t *node, VALUE *script_lines)
11090{
11091 pm_parser_t *parser = &result->parser;
11092
11093 // First, set up the scope node so that the AST node is attached and can be
11094 // freed regardless of whether or we return an error.
11095 pm_scope_node_t *scope_node = &result->node;
11096 rb_encoding *filepath_encoding = scope_node->filepath_encoding;
11097 int coverage_enabled = scope_node->coverage_enabled;
11098
11099 pm_scope_node_init(node, scope_node, NULL);
11100 scope_node->filepath_encoding = filepath_encoding;
11101
11102 scope_node->encoding = rb_enc_find(parser->encoding->name);
11103 if (!scope_node->encoding) rb_bug("Encoding not found %s!", parser->encoding->name);
11104
11105 scope_node->coverage_enabled = coverage_enabled;
11106
11107 // If RubyVM.keep_script_lines is set to true, then we need to create that
11108 // array of script lines here.
11109 if (script_lines != NULL) {
11110 *script_lines = rb_ary_new_capa(parser->newline_list.size);
11111
11112 for (size_t index = 0; index < parser->newline_list.size; index++) {
11113 size_t offset = parser->newline_list.offsets[index];
11114 size_t length = index == parser->newline_list.size - 1 ? ((size_t) (parser->end - (parser->start + offset))) : (parser->newline_list.offsets[index + 1] - offset);
11115 rb_ary_push(*script_lines, rb_enc_str_new((const char *) parser->start + offset, length, scope_node->encoding));
11116 }
11117
11118 scope_node->script_lines = script_lines;
11119 }
11120
11121 // Emit all of the various warnings from the parse.
11122 const pm_diagnostic_t *warning;
11123 const char *warning_filepath = (const char *) pm_string_source(&parser->filepath);
11124
11125 for (warning = (const pm_diagnostic_t *) parser->warning_list.head; warning != NULL; warning = (const pm_diagnostic_t *) warning->node.next) {
11126 int line = pm_location_line_number(parser, &warning->location);
11127
11128 if (warning->level == PM_WARNING_LEVEL_VERBOSE) {
11129 rb_enc_compile_warning(scope_node->encoding, warning_filepath, line, "%s", warning->message);
11130 }
11131 else {
11132 rb_enc_compile_warn(scope_node->encoding, warning_filepath, line, "%s", warning->message);
11133 }
11134 }
11135
11136 // If there are errors, raise an appropriate error and free the result.
11137 if (parser->error_list.size > 0) {
11138 VALUE error = pm_parse_process_error(result);
11139
11140 // TODO: We need to set the backtrace.
11141 // rb_funcallv(error, rb_intern("set_backtrace"), 1, &path);
11142 return error;
11143 }
11144
11145 // Now set up the constant pool and intern all of the various constants into
11146 // their corresponding IDs.
11147 scope_node->parser = parser;
11148 scope_node->constants = parser->constant_pool.size ? xcalloc(parser->constant_pool.size, sizeof(ID)) : NULL;
11149
11150 for (uint32_t index = 0; index < parser->constant_pool.size; index++) {
11151 pm_constant_t *constant = &parser->constant_pool.constants[index];
11152 scope_node->constants[index] = rb_intern3((const char *) constant->start, constant->length, scope_node->encoding);
11153 }
11154
11155 scope_node->index_lookup_table = st_init_numtable();
11156 pm_constant_id_list_t *locals = &scope_node->locals;
11157 for (size_t index = 0; index < locals->size; index++) {
11158 st_insert(scope_node->index_lookup_table, locals->ids[index], index);
11159 }
11160
11161 // If we got here, this is a success and we can return Qnil to indicate that
11162 // no error should be raised.
11163 result->parsed = true;
11164 return Qnil;
11165}
11166
11171static void
11172pm_options_frozen_string_literal_init(pm_options_t *options)
11173{
11174 int frozen_string_literal = rb_iseq_opt_frozen_string_literal();
11175
11176 switch (frozen_string_literal) {
11177 case ISEQ_FROZEN_STRING_LITERAL_UNSET:
11178 break;
11179 case ISEQ_FROZEN_STRING_LITERAL_DISABLED:
11180 pm_options_frozen_string_literal_set(options, false);
11181 break;
11182 case ISEQ_FROZEN_STRING_LITERAL_ENABLED:
11183 pm_options_frozen_string_literal_set(options, true);
11184 break;
11185 default:
11186 rb_bug("pm_options_frozen_string_literal_init: invalid frozen_string_literal=%d", frozen_string_literal);
11187 break;
11188 }
11189}
11190
11195static inline VALUE
11196pm_parse_file_script_lines(const pm_scope_node_t *scope_node, const pm_parser_t *parser)
11197{
11198 const pm_newline_list_t *newline_list = &parser->newline_list;
11199 const char *start = (const char *) parser->start;
11200 const char *end = (const char *) parser->end;
11201
11202 // If we end exactly on a newline, then there's no need to push on a final
11203 // segment. If we don't, then we need to push on the last offset up to the
11204 // end of the string.
11205 size_t last_offset = newline_list->offsets[newline_list->size - 1];
11206 bool last_push = start + last_offset != end;
11207
11208 // Create the ruby strings that represent the lines of the source.
11209 VALUE lines = rb_ary_new_capa(newline_list->size - (last_push ? 0 : 1));
11210
11211 for (size_t index = 0; index < newline_list->size - 1; index++) {
11212 size_t offset = newline_list->offsets[index];
11213 size_t length = newline_list->offsets[index + 1] - offset;
11214
11215 rb_ary_push(lines, rb_enc_str_new(start + offset, length, scope_node->encoding));
11216 }
11217
11218 // Push on the last line if we need to.
11219 if (last_push) {
11220 rb_ary_push(lines, rb_enc_str_new(start + last_offset, end - (start + last_offset), scope_node->encoding));
11221 }
11222
11223 return lines;
11224}
11225
11226// This is essentially pm_string_mapped_init(), preferring to memory map the
11227// file, with additional handling for files that require blocking to properly
11228// read (e.g. pipes).
11230pm_read_file(pm_string_t *string, const char *filepath)
11231{
11232#ifdef _WIN32
11233 // Open the file for reading.
11234 int length = MultiByteToWideChar(CP_UTF8, 0, filepath, -1, NULL, 0);
11235 if (length == 0) return PM_STRING_INIT_ERROR_GENERIC;
11236
11237 WCHAR *wfilepath = xmalloc(sizeof(WCHAR) * ((size_t) length));
11238 if ((wfilepath == NULL) || (MultiByteToWideChar(CP_UTF8, 0, filepath, -1, wfilepath, length) == 0)) {
11239 xfree(wfilepath);
11241 }
11242
11243 HANDLE file = CreateFileW(wfilepath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
11244 if (file == INVALID_HANDLE_VALUE) {
11246
11247 if (GetLastError() == ERROR_ACCESS_DENIED) {
11248 DWORD attributes = GetFileAttributesW(wfilepath);
11249 if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
11251 }
11252 }
11253
11254 xfree(wfilepath);
11255 return result;
11256 }
11257
11258 // Get the file size.
11259 DWORD file_size = GetFileSize(file, NULL);
11260 if (file_size == INVALID_FILE_SIZE) {
11261 CloseHandle(file);
11262 xfree(wfilepath);
11264 }
11265
11266 // If the file is empty, then we don't need to do anything else, we'll set
11267 // the source to a constant empty string and return.
11268 if (file_size == 0) {
11269 CloseHandle(file);
11270 xfree(wfilepath);
11271 const uint8_t source[] = "";
11272 *string = (pm_string_t) { .type = PM_STRING_CONSTANT, .source = source, .length = 0 };
11274 }
11275
11276 // Create a mapping of the file.
11277 HANDLE mapping = CreateFileMapping(file, NULL, PAGE_READONLY, 0, 0, NULL);
11278 if (mapping == NULL) {
11279 CloseHandle(file);
11280 xfree(wfilepath);
11282 }
11283
11284 // Map the file into memory.
11285 uint8_t *source = (uint8_t *) MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);
11286 CloseHandle(mapping);
11287 CloseHandle(file);
11288 xfree(wfilepath);
11289
11290 if (source == NULL) {
11292 }
11293
11294 *string = (pm_string_t) { .type = PM_STRING_MAPPED, .source = source, .length = (size_t) file_size };
11296#elif defined(_POSIX_MAPPED_FILES)
11297 // Open the file for reading
11298 const int open_mode = O_RDONLY | O_NONBLOCK;
11299 int fd = open(filepath, open_mode);
11300 if (fd == -1) {
11302 }
11303
11304 // Stat the file to get the file size
11305 struct stat sb;
11306 if (fstat(fd, &sb) == -1) {
11307 close(fd);
11309 }
11310
11311 // Ensure it is a file and not a directory
11312 if (S_ISDIR(sb.st_mode)) {
11313 close(fd);
11315 }
11316
11317 // We need to wait for data first before reading from pipes and character
11318 // devices. To not block the entire VM, we need to release the GVL while
11319 // reading. Use IO#read to do this and let the GC handle closing the FD.
11320 if (S_ISFIFO(sb.st_mode) || S_ISCHR(sb.st_mode)) {
11321 VALUE io = rb_io_fdopen((int) fd, open_mode, filepath);
11323 VALUE contents = rb_funcall(io, rb_intern("read"), 0);
11324
11325 if (!RB_TYPE_P(contents, T_STRING)) {
11327 }
11328
11329 long len = RSTRING_LEN(contents);
11330 if (len < 0) {
11332 }
11333
11334 size_t length = (size_t) len;
11335 uint8_t *source = malloc(length);
11336 memcpy(source, RSTRING_PTR(contents), length);
11337 *string = (pm_string_t) { .type = PM_STRING_OWNED, .source = source, .length = length };
11338
11340 }
11341
11342 // mmap the file descriptor to virtually get the contents
11343 size_t size = (size_t) sb.st_size;
11344 uint8_t *source = NULL;
11345
11346 if (size == 0) {
11347 close(fd);
11348 const uint8_t source[] = "";
11349 *string = (pm_string_t) { .type = PM_STRING_CONSTANT, .source = source, .length = 0 };
11351 }
11352
11353 source = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
11354 if (source == MAP_FAILED) {
11355 close(fd);
11357 }
11358
11359 close(fd);
11360 *string = (pm_string_t) { .type = PM_STRING_MAPPED, .source = source, .length = size };
11362#else
11363 return pm_string_file_init(string, filepath);
11364#endif
11365}
11366
11371VALUE
11372pm_load_file(pm_parse_result_t *result, VALUE filepath, bool load_error)
11373{
11374 pm_string_init_result_t init_result = pm_read_file(&result->input, RSTRING_PTR(filepath));
11375
11376 if (init_result == PM_STRING_INIT_SUCCESS) {
11377 pm_options_frozen_string_literal_init(&result->options);
11378 return Qnil;
11379 }
11380
11381 int err;
11382 if (init_result == PM_STRING_INIT_ERROR_DIRECTORY) {
11383 err = EISDIR;
11384 } else {
11385#ifdef _WIN32
11386 err = rb_w32_map_errno(GetLastError());
11387#else
11388 err = errno;
11389#endif
11390 }
11391
11392 VALUE error;
11393 if (load_error) {
11394 VALUE message = rb_str_buf_new_cstr(strerror(err));
11395 rb_str_cat2(message, " -- ");
11396 rb_str_append(message, filepath);
11397
11398 error = rb_exc_new3(rb_eLoadError, message);
11399 rb_ivar_set(error, rb_intern_const("@path"), filepath);
11400 } else {
11401 error = rb_syserr_new(err, RSTRING_PTR(filepath));
11402 RB_GC_GUARD(filepath);
11403 }
11404
11405 return error;
11406}
11407
11414VALUE
11415pm_parse_file(pm_parse_result_t *result, VALUE filepath, VALUE *script_lines)
11416{
11417 result->node.filepath_encoding = rb_enc_get(filepath);
11418 pm_options_filepath_set(&result->options, RSTRING_PTR(filepath));
11419 RB_GC_GUARD(filepath);
11420
11421 pm_options_version_for_current_ruby_set(&result->options);
11422
11423 pm_parser_init(&result->parser, pm_string_source(&result->input), pm_string_length(&result->input), &result->options);
11424 pm_node_t *node = pm_parse(&result->parser);
11425
11426 VALUE error = pm_parse_process(result, node, script_lines);
11427
11428 // If we're parsing a filepath, then we need to potentially support the
11429 // SCRIPT_LINES__ constant, which can be a hash that has an array of lines
11430 // of every read file.
11431 ID id_script_lines = rb_intern("SCRIPT_LINES__");
11432
11433 if (rb_const_defined_at(rb_cObject, id_script_lines)) {
11434 VALUE constant_script_lines = rb_const_get_at(rb_cObject, id_script_lines);
11435
11436 if (RB_TYPE_P(constant_script_lines, T_HASH)) {
11437 rb_hash_aset(constant_script_lines, filepath, pm_parse_file_script_lines(&result->node, &result->parser));
11438 }
11439 }
11440
11441 return error;
11442}
11443
11448VALUE
11449pm_load_parse_file(pm_parse_result_t *result, VALUE filepath, VALUE *script_lines)
11450{
11451 VALUE error = pm_load_file(result, filepath, false);
11452 if (NIL_P(error)) {
11453 error = pm_parse_file(result, filepath, script_lines);
11454 }
11455
11456 return error;
11457}
11458
11465VALUE
11466pm_parse_string(pm_parse_result_t *result, VALUE source, VALUE filepath, VALUE *script_lines)
11467{
11468 rb_encoding *encoding = rb_enc_get(source);
11469 if (!rb_enc_asciicompat(encoding)) {
11470 return rb_exc_new_cstr(rb_eArgError, "invalid source encoding");
11471 }
11472
11473 pm_options_frozen_string_literal_init(&result->options);
11474 pm_string_constant_init(&result->input, RSTRING_PTR(source), RSTRING_LEN(source));
11475 pm_options_encoding_set(&result->options, rb_enc_name(encoding));
11476
11477 result->node.filepath_encoding = rb_enc_get(filepath);
11478 pm_options_filepath_set(&result->options, RSTRING_PTR(filepath));
11479
11480 pm_options_version_for_current_ruby_set(&result->options);
11481
11482 pm_parser_init(&result->parser, pm_string_source(&result->input), pm_string_length(&result->input), &result->options);
11483 pm_node_t *node = pm_parse(&result->parser);
11484
11485 VALUE error = pm_parse_process(result, node, script_lines);
11486
11487 RB_GC_GUARD(source);
11488 RB_GC_GUARD(filepath);
11489 return error;
11490}
11491
11493 VALUE rb_stdin;
11494 int eof_seen;
11495};
11496
11497static int
11498pm_parse_stdin_eof(void *stream)
11499{
11500 struct rb_stdin_wrapper * wrapped_stdin = (struct rb_stdin_wrapper *)stream;
11501 return wrapped_stdin->eof_seen;
11502}
11503
11504VALUE rb_io_gets_limit_internal(VALUE io, long limit);
11505
11509static char *
11510pm_parse_stdin_fgets(char *string, int size, void *stream)
11511{
11512 RUBY_ASSERT(size > 0);
11513
11514 struct rb_stdin_wrapper * wrapped_stdin = (struct rb_stdin_wrapper *)stream;
11515
11516 VALUE line = rb_io_gets_limit_internal(wrapped_stdin->rb_stdin, size - 1);
11517 if (NIL_P(line)) {
11518 return NULL;
11519 }
11520
11521 const char *cstr = RSTRING_PTR(line);
11522 long length = RSTRING_LEN(line);
11523
11524 memcpy(string, cstr, length);
11525 string[length] = '\0';
11526
11527 // We're reading strings from stdin via gets. We'll assume that if the
11528 // string is smaller than the requested length, and doesn't end with a
11529 // newline, that we hit EOF.
11530 if (length < (size - 1) && string[length - 1] != '\n') {
11531 wrapped_stdin->eof_seen = 1;
11532 }
11533
11534 return string;
11535}
11536
11537// We need access to this function when we're done parsing stdin.
11538void rb_reset_argf_lineno(long n);
11539
11545VALUE
11546pm_parse_stdin(pm_parse_result_t *result)
11547{
11548 pm_options_frozen_string_literal_init(&result->options);
11549
11550 struct rb_stdin_wrapper wrapped_stdin = {
11551 rb_stdin,
11552 0
11553 };
11554
11555 pm_buffer_t buffer;
11556 pm_node_t *node = pm_parse_stream(&result->parser, &buffer, (void *) &wrapped_stdin, pm_parse_stdin_fgets, pm_parse_stdin_eof, &result->options);
11557
11558 // Copy the allocated buffer contents into the input string so that it gets
11559 // freed. At this point we've handed over ownership, so we don't need to
11560 // free the buffer itself.
11561 pm_string_owned_init(&result->input, (uint8_t *) pm_buffer_value(&buffer), pm_buffer_length(&buffer));
11562
11563 // When we're done parsing, we reset $. because we don't want the fact that
11564 // we went through an IO object to be visible to the user.
11565 rb_reset_argf_lineno(0);
11566
11567 return pm_parse_process(result, node, NULL);
11568}
11569
11570#define PM_VERSION_FOR_RELEASE(major, minor) PM_VERSION_FOR_RELEASE_IMPL(major, minor)
11571#define PM_VERSION_FOR_RELEASE_IMPL(major, minor) PM_OPTIONS_VERSION_CRUBY_##major##_##minor
11572
11573void pm_options_version_for_current_ruby_set(pm_options_t *options) {
11574 options->version = PM_VERSION_FOR_RELEASE(RUBY_API_VERSION_MAJOR, RUBY_API_VERSION_MINOR);
11575}
11576
11577#undef NEW_ISEQ
11578#define NEW_ISEQ OLD_ISEQ
11579
11580#undef NEW_CHILD_ISEQ
11581#define NEW_CHILD_ISEQ OLD_CHILD_ISEQ
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
@ PM_WARNING_LEVEL_VERBOSE
For warnings which should be emitted if $VERBOSE == true.
Definition diagnostic.h:417
@ PM_ERROR_LEVEL_ARGUMENT
For errors that should raise an argument error.
Definition diagnostic.h:403
@ PM_ERROR_LEVEL_LOAD
For errors that should raise a load error.
Definition diagnostic.h:406
@ PM_ERROR_LEVEL_SYNTAX
For errors that should raise a syntax error.
Definition diagnostic.h:400
#define RUBY_EVENT_END
Encountered an end of a class clause.
Definition event.h:40
#define RUBY_EVENT_B_RETURN
Encountered a next statement.
Definition event.h:56
#define RUBY_EVENT_CLASS
Encountered a new class.
Definition event.h:39
#define RUBY_EVENT_LINE
Encountered a new line.
Definition event.h:38
#define RUBY_EVENT_RETURN
Encountered a return statement.
Definition event.h:42
#define RUBY_EVENT_B_CALL
Encountered an yield statement.
Definition event.h:55
#define RUBY_EVENT_CALL
A method, written in Ruby, is called.
Definition event.h:41
#define RUBY_EVENT_RESCUE
Encountered a rescue statement.
Definition event.h:61
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
#define ALLOCV
Old name of RB_ALLOCV.
Definition memory.h:404
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:400
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define ZALLOC_N
Old name of RB_ZALLOC_N.
Definition memory.h:401
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition error.h:38
#define FLONUM_P
Old name of RB_FLONUM_P.
#define Qtrue
Old name of RUBY_Qtrue.
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define xcalloc
Old name of ruby_xcalloc.
Definition xmalloc.h:55
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define UINT2NUM
Old name of RB_UINT2NUM.
Definition int.h:46
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
Definition error.h:486
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1441
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:664
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1428
VALUE rb_eLoadError
LoadError exception.
Definition error.c:1449
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eNoMatchingPatternError
NoMatchingPatternError exception.
Definition error.c:1444
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_exc_new(VALUE etype, const char *ptr, long len)
Creates an instance of the passed exception class.
Definition error.c:1469
VALUE rb_eNoMatchingPatternKeyError
NoMatchingPatternKeyError exception.
Definition error.c:1445
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1482
VALUE rb_errinfo(void)
This is the same as $! in Ruby.
Definition eval.c:2056
VALUE rb_eSyntaxError
SyntaxError exception.
Definition error.c:1448
VALUE rb_syserr_new(int n, const char *mesg)
Creates an exception object that represents the given C errno.
Definition error.c:3895
VALUE rb_cArray
Array class.
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:100
VALUE rb_stdin
STDIN constant.
Definition io.c:201
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1342
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:615
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
rb_encoding * rb_utf8_encoding(void)
Queries the encoding that represents UTF-8.
Definition encoding.c:1535
rb_encoding * rb_ascii8bit_encoding(void)
Queries the encoding that represents ASCII-8BIT a.k.a.
Definition encoding.c:1523
rb_encoding * rb_usascii_encoding(void)
Queries the encoding that represents US-ASCII.
Definition encoding.c:1547
int rb_enc_str_coderange(VALUE str)
Scans the passed string to collect its code range.
Definition string.c:947
VALUE rb_enc_interned_str(const char *ptr, long len, rb_encoding *enc)
Identical to rb_enc_str_new(), except it returns a "f"string.
Definition string.c:12728
VALUE rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc)
Identical to rb_enc_str_new(), except it assumes the passed pointer is a pointer to a C string.
Definition string.c:1155
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1117
VALUE rb_ary_cat(VALUE ary, const VALUE *train, long len)
Destructively appends multiple elements at the end of the array.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_hidden_new(long capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1484
VALUE rb_io_fdopen(int fd, int flags, const char *path)
Creates an IO instance whose backend is the given file descriptor.
Definition io.c:9358
VALUE rb_range_new(VALUE beg, VALUE end, int excl)
Creates a new Range.
Definition range.c:69
VALUE rb_rational_new(VALUE num, VALUE den)
Constructs a Rational, with reduction.
Definition rational.c:2022
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3799
VALUE rb_str_tmp_new(long len)
Allocates a "temporary" string.
Definition string.c:1746
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_exc_new_cstr(exc, str)
Identical to rb_exc_new(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1671
#define rb_str_buf_new_cstr(str)
Identical to rb_str_new_cstr, except done differently.
Definition string.h:1640
VALUE rb_str_concat(VALUE dst, VALUE src)
Identical to rb_str_append(), except it also accepts an integer as a codepoint.
Definition string.c:4036
VALUE rb_str_freeze(VALUE str)
This is the implementation of String#freeze.
Definition string.c:3280
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1515
VALUE rb_obj_as_string(VALUE obj)
Try converting an object to its stringised representation using its to_s method, if any.
Definition string.c:1850
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2030
VALUE rb_const_get_at(VALUE space, ID name)
Identical to rb_const_defined_at(), except it returns the actual defined value.
Definition variable.c:3511
int rb_const_defined_at(VALUE space, ID name)
Identical to rb_const_defined(), except it doesn't look for parent classes.
Definition variable.c:3843
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
VALUE rb_id2sym(ID id)
Allocates an instance of rb_cSymbol that has the given id.
Definition symbol.c:974
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:993
@ RUBY_IO_READABLE
IO::READABLE
Definition io.h:97
VALUE rb_io_wait(VALUE io, VALUE events, VALUE timeout)
Blocks until the passed IO is ready for the passed events.
Definition io.c:1482
int len
Length of the buffer.
Definition io.h:8
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:235
VALUE rb_ractor_make_shareable(VALUE obj)
Destructively transforms the passed object so that multiple Ractors can share it.
Definition ractor.c:1547
#define DECIMAL_SIZE_OF(expr)
An approximation of decimal representation size.
Definition util.h:48
#define RUBY_API_VERSION_MAJOR
Major version.
Definition version.h:64
#define RUBY_API_VERSION_MINOR
Minor version.
Definition version.h:70
#define RB_INT2NUM
Just another name of rb_int2num_inline.
Definition int.h:37
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE type(ANYARGS)
ANYARGS-ed function type.
struct pm_options pm_options_t
The options that can be passed to the parser.
struct pm_parser pm_parser_t
The parser used to parse Ruby source.
Definition parser.h:267
uint32_t pm_constant_id_t
A constant id is a unique identifier for a constant in the constant pool.
struct pm_list_node pm_list_node_t
This struct represents an abstract linked list that provides common functionality.
pm_string_init_result_t
Represents the result of calling pm_string_mapped_init or pm_string_file_init.
Definition pm_string.h:105
@ PM_STRING_INIT_SUCCESS
Indicates that the string was successfully initialized.
Definition pm_string.h:107
@ PM_STRING_INIT_ERROR_GENERIC
Indicates a generic error from a string_*_init function, where the type of error should be read from ...
Definition pm_string.h:112
@ PM_STRING_INIT_ERROR_DIRECTORY
Indicates that the file that was attempted to be opened was a directory.
Definition pm_string.h:116
#define PM_ENCODING_US_ASCII_ENTRY
This is the US-ASCII encoding.
Definition encoding.h:252
#define PM_NODE_LIST_FOREACH(list, index, node)
Loop through each node in the node list, writing each node to the given pm_node_t pointer.
Definition node.h:17
The main header file for the prism parser.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define RTEST
This is an old name of RB_TEST.
struct pm_node * old_name
AliasGlobalVariableNode::old_name.
Definition ast.h:1139
struct pm_node * new_name
AliasGlobalVariableNode::new_name.
Definition ast.h:1129
struct pm_node * old_name
AliasMethodNode::old_name.
Definition ast.h:1199
struct pm_node * new_name
AliasMethodNode::new_name.
Definition ast.h:1183
struct pm_node * left
AlternationPatternNode::left.
Definition ast.h:1237
struct pm_node * right
AlternationPatternNode::right.
Definition ast.h:1247
struct pm_node * left
AndNode::left.
Definition ast.h:1288
struct pm_node * right
AndNode::right.
Definition ast.h:1301
pm_node_t base
The embedded base node.
Definition ast.h:1335
struct pm_node_list arguments
ArgumentsNode::arguments.
Definition ast.h:1346
struct pm_node_list elements
ArrayNode::elements.
Definition ast.h:1374
struct pm_node_list requireds
ArrayPatternNode::requireds.
Definition ast.h:1454
struct pm_node * rest
ArrayPatternNode::rest.
Definition ast.h:1464
struct pm_node * constant
ArrayPatternNode::constant.
Definition ast.h:1444
struct pm_node_list posts
ArrayPatternNode::posts.
Definition ast.h:1474
struct pm_node * value
AssocNode::value.
Definition ast.h:1541
struct pm_node * key
AssocNode::key.
Definition ast.h:1528
struct pm_node * value
AssocSplatNode::value.
Definition ast.h:1579
pm_node_t base
The embedded base node.
Definition ast.h:1606
struct pm_ensure_node * ensure_clause
BeginNode::ensure_clause.
Definition ast.h:1688
struct pm_rescue_node * rescue_clause
BeginNode::rescue_clause.
Definition ast.h:1668
struct pm_statements_node * statements
BeginNode::statements.
Definition ast.h:1658
struct pm_else_node * else_clause
BeginNode::else_clause.
Definition ast.h:1678
struct pm_node * expression
BlockArgumentNode::expression.
Definition ast.h:1726
struct pm_node * parameters
BlockNode::parameters.
Definition ast.h:1809
struct pm_node * body
BlockNode::body.
Definition ast.h:1819
pm_constant_id_list_t locals
BlockNode::locals.
Definition ast.h:1795
struct pm_arguments_node * arguments
BreakNode::arguments.
Definition ast.h:1999
A pm_buffer_t is a simple memory buffer that stores data in a contiguous block of memory.
Definition pm_buffer.h:22
struct pm_node * value
CallAndWriteNode::value.
Definition ast.h:2103
pm_constant_id_t read_name
CallAndWriteNode::read_name.
Definition ast.h:2073
pm_constant_id_t write_name
CallAndWriteNode::write_name.
Definition ast.h:2083
struct pm_node * receiver
CallAndWriteNode::receiver.
Definition ast.h:2043
pm_location_t closing_loc
CallNode::closing_loc.
Definition ast.h:2220
struct pm_node * receiver
CallNode::receiver.
Definition ast.h:2158
pm_constant_id_t name
CallNode::name.
Definition ast.h:2181
pm_node_t base
The embedded base node.
Definition ast.h:2141
pm_location_t message_loc
CallNode::message_loc.
Definition ast.h:2191
struct pm_arguments_node * arguments
CallNode::arguments.
Definition ast.h:2210
struct pm_node * block
CallNode::block.
Definition ast.h:2243
pm_constant_id_t read_name
CallOperatorWriteNode::read_name.
Definition ast.h:2307
pm_constant_id_t binary_operator
CallOperatorWriteNode::binary_operator.
Definition ast.h:2327
struct pm_node * receiver
CallOperatorWriteNode::receiver.
Definition ast.h:2277
pm_constant_id_t write_name
CallOperatorWriteNode::write_name.
Definition ast.h:2317
struct pm_node * value
CallOperatorWriteNode::value.
Definition ast.h:2347
struct pm_node * receiver
CallOrWriteNode::receiver.
Definition ast.h:2381
struct pm_node * value
CallOrWriteNode::value.
Definition ast.h:2441
pm_constant_id_t write_name
CallOrWriteNode::write_name.
Definition ast.h:2421
pm_constant_id_t read_name
CallOrWriteNode::read_name.
Definition ast.h:2411
pm_constant_id_t name
CallTargetNode::name.
Definition ast.h:2503
struct pm_node * receiver
CallTargetNode::receiver.
Definition ast.h:2483
struct pm_local_variable_target_node * target
CapturePatternNode::target.
Definition ast.h:2551
struct pm_node * value
CapturePatternNode::value.
Definition ast.h:2541
struct pm_node_list conditions
CaseMatchNode::conditions.
Definition ast.h:2601
struct pm_else_node * else_clause
CaseMatchNode::else_clause.
Definition ast.h:2611
struct pm_node * predicate
CaseMatchNode::predicate.
Definition ast.h:2591
struct pm_node * predicate
CaseNode::predicate.
Definition ast.h:2661
struct pm_else_node * else_clause
CaseNode::else_clause.
Definition ast.h:2681
struct pm_node_list conditions
CaseNode::conditions.
Definition ast.h:2671
struct pm_node * constant_path
ClassNode::constant_path.
Definition ast.h:2739
pm_constant_id_list_t locals
ClassNode::locals.
Definition ast.h:2724
pm_constant_id_t name
ClassNode::name.
Definition ast.h:2789
struct pm_node * body
ClassNode::body.
Definition ast.h:2770
struct pm_node * superclass
ClassNode::superclass.
Definition ast.h:2759
struct pm_node * value
ClassVariableAndWriteNode::value.
Definition ast.h:2847
pm_constant_id_t name
ClassVariableAndWriteNode::name.
Definition ast.h:2817
pm_constant_id_t name
ClassVariableOperatorWriteNode::name.
Definition ast.h:2870
pm_constant_id_t binary_operator
ClassVariableOperatorWriteNode::binary_operator.
Definition ast.h:2890
struct pm_node * value
ClassVariableOperatorWriteNode::value.
Definition ast.h:2885
pm_constant_id_t name
ClassVariableOrWriteNode::name.
Definition ast.h:2913
struct pm_node * value
ClassVariableOrWriteNode::value.
Definition ast.h:2928
pm_constant_id_t name
ClassVariableReadNode::name.
Definition ast.h:2957
pm_constant_id_t name
ClassVariableTargetNode::name.
Definition ast.h:2980
struct pm_node * value
ClassVariableWriteNode::value.
Definition ast.h:3032
pm_constant_id_t name
ClassVariableWriteNode::name.
Definition ast.h:3009
pm_location_t name_loc
ConstantAndWriteNode::name_loc.
Definition ast.h:3070
pm_constant_id_t name
ConstantAndWriteNode::name.
Definition ast.h:3065
struct pm_node * value
ConstantAndWriteNode::value.
Definition ast.h:3080
A list of constant IDs.
size_t size
The number of constant ids in the list.
size_t capacity
The number of constant ids that have been allocated in the list.
pm_constant_id_t * ids
The constant ids in the list.
pm_constant_id_t name
ConstantOperatorWriteNode::name.
Definition ast.h:3103
pm_location_t name_loc
ConstantOperatorWriteNode::name_loc.
Definition ast.h:3108
pm_constant_id_t binary_operator
ConstantOperatorWriteNode::binary_operator.
Definition ast.h:3123
struct pm_node * value
ConstantOperatorWriteNode::value.
Definition ast.h:3118
pm_location_t name_loc
ConstantOrWriteNode::name_loc.
Definition ast.h:3151
pm_constant_id_t name
ConstantOrWriteNode::name.
Definition ast.h:3146
struct pm_node * value
ConstantOrWriteNode::value.
Definition ast.h:3161
struct pm_constant_path_node * target
ConstantPathAndWriteNode::target.
Definition ast.h:3184
struct pm_node * value
ConstantPathAndWriteNode::value.
Definition ast.h:3194
pm_constant_id_t name
ConstantPathNode::name.
Definition ast.h:3235
struct pm_node * parent
ConstantPathNode::parent.
Definition ast.h:3228
struct pm_constant_path_node * target
ConstantPathOperatorWriteNode::target.
Definition ast.h:3284
struct pm_node * value
ConstantPathOperatorWriteNode::value.
Definition ast.h:3294
pm_constant_id_t binary_operator
ConstantPathOperatorWriteNode::binary_operator.
Definition ast.h:3299
struct pm_node * value
ConstantPathOrWriteNode::value.
Definition ast.h:3332
struct pm_constant_path_node * target
ConstantPathOrWriteNode::target.
Definition ast.h:3322
struct pm_node * parent
ConstantPathTargetNode::parent.
Definition ast.h:3355
pm_constant_id_t name
ConstantPathTargetNode::name.
Definition ast.h:3360
struct pm_constant_path_node * target
ConstantPathWriteNode::target.
Definition ast.h:3407
struct pm_node * value
ConstantPathWriteNode::value.
Definition ast.h:3427
uint32_t size
The number of buckets in the hash map.
pm_constant_t * constants
The constants that are stored in the buckets.
pm_node_t base
The embedded base node.
Definition ast.h:3444
pm_constant_id_t name
ConstantReadNode::name.
Definition ast.h:3456
A constant in the pool which effectively stores a string.
size_t length
The length of the string.
const uint8_t * start
A pointer to the start of the string.
pm_constant_id_t name
ConstantTargetNode::name.
Definition ast.h:3479
struct pm_node * value
ConstantWriteNode::value.
Definition ast.h:3531
pm_constant_id_t name
ConstantWriteNode::name.
Definition ast.h:3508
struct pm_parameters_node * parameters
DefNode::parameters.
Definition ast.h:3580
pm_constant_id_t name
DefNode::name.
Definition ast.h:3565
struct pm_node * body
DefNode::body.
Definition ast.h:3585
struct pm_node * receiver
DefNode::receiver.
Definition ast.h:3575
pm_node_t base
The embedded base node.
Definition ast.h:3559
pm_constant_id_list_t locals
DefNode::locals.
Definition ast.h:3590
struct pm_node * value
DefinedNode::value.
Definition ast.h:3648
This struct represents a diagnostic generated during parsing.
Definition diagnostic.h:368
pm_location_t location
The location of the diagnostic in the source.
Definition diagnostic.h:373
const char * message
The message associated with the diagnostic.
Definition diagnostic.h:379
pm_list_node_t node
The embedded base node.
Definition diagnostic.h:370
uint8_t level
The level of the diagnostic, see pm_error_level_t and pm_warning_level_t for possible values.
Definition diagnostic.h:392
struct pm_statements_node * statements
ElseNode::statements.
Definition ast.h:3686
struct pm_statements_node * statements
EmbeddedStatementsNode::statements.
Definition ast.h:3719
struct pm_node * variable
EmbeddedVariableNode::variable.
Definition ast.h:3752
This struct defines the functions necessary to implement the encoding interface so we can determine h...
Definition encoding.h:23
size_t(* char_width)(const uint8_t *b, ptrdiff_t n)
Return the number of bytes that the next character takes if it is valid in the encoding.
Definition encoding.h:29
const char * name
The name of the encoding.
Definition encoding.h:56
struct pm_statements_node * statements
EnsureNode::statements.
Definition ast.h:3784
struct pm_node * constant
FindPatternNode::constant.
Definition ast.h:3844
struct pm_node * right
FindPatternNode::right.
Definition ast.h:3883
struct pm_node_list requireds
FindPatternNode::requireds.
Definition ast.h:3870
struct pm_splat_node * left
FindPatternNode::left.
Definition ast.h:3857
pm_node_t base
The embedded base node.
Definition ast.h:3929
struct pm_node * left
FlipFlopNode::left.
Definition ast.h:3935
struct pm_node * right
FlipFlopNode::right.
Definition ast.h:3940
double value
FloatNode::value.
Definition ast.h:3970
struct pm_statements_node * statements
ForNode::statements.
Definition ast.h:4020
struct pm_node * collection
ForNode::collection.
Definition ast.h:4008
struct pm_block_node * block
ForwardingSuperNode::block.
Definition ast.h:4129
struct pm_node * value
GlobalVariableAndWriteNode::value.
Definition ast.h:4167
pm_constant_id_t name
GlobalVariableAndWriteNode::name.
Definition ast.h:4152
pm_constant_id_t name
GlobalVariableOperatorWriteNode::name.
Definition ast.h:4190
pm_constant_id_t binary_operator
GlobalVariableOperatorWriteNode::binary_operator.
Definition ast.h:4210
struct pm_node * value
GlobalVariableOperatorWriteNode::value.
Definition ast.h:4205
pm_constant_id_t name
GlobalVariableOrWriteNode::name.
Definition ast.h:4233
struct pm_node * value
GlobalVariableOrWriteNode::value.
Definition ast.h:4248
pm_constant_id_t name
GlobalVariableReadNode::name.
Definition ast.h:4277
pm_constant_id_t name
GlobalVariableTargetNode::name.
Definition ast.h:4300
struct pm_node * value
GlobalVariableWriteNode::value.
Definition ast.h:4352
pm_constant_id_t name
GlobalVariableWriteNode::name.
Definition ast.h:4329
struct pm_node_list elements
HashNode::elements.
Definition ast.h:4403
struct pm_node_list elements
HashPatternNode::elements.
Definition ast.h:4463
struct pm_node * rest
HashPatternNode::rest.
Definition ast.h:4479
struct pm_node * constant
HashPatternNode::constant.
Definition ast.h:4453
struct pm_node * predicate
IfNode::predicate.
Definition ast.h:4559
struct pm_statements_node * statements
IfNode::statements.
Definition ast.h:4586
struct pm_node * numeric
ImaginaryNode::numeric.
Definition ast.h:4640
struct pm_node * value
ImplicitNode::value.
Definition ast.h:4669
struct pm_statements_node * statements
InNode::statements.
Definition ast.h:4724
struct pm_node * pattern
InNode::pattern.
Definition ast.h:4719
struct pm_arguments_node * arguments
IndexAndWriteNode::arguments.
Definition ast.h:4778
struct pm_node * receiver
IndexAndWriteNode::receiver.
Definition ast.h:4763
struct pm_block_argument_node * block
IndexAndWriteNode::block.
Definition ast.h:4788
struct pm_node * value
IndexAndWriteNode::value.
Definition ast.h:4798
struct pm_block_argument_node * block
IndexOperatorWriteNode::block.
Definition ast.h:4852
struct pm_node * value
IndexOperatorWriteNode::value.
Definition ast.h:4867
struct pm_arguments_node * arguments
IndexOperatorWriteNode::arguments.
Definition ast.h:4842
pm_constant_id_t binary_operator
IndexOperatorWriteNode::binary_operator.
Definition ast.h:4857
struct pm_node * receiver
IndexOperatorWriteNode::receiver.
Definition ast.h:4827
struct pm_block_argument_node * block
IndexOrWriteNode::block.
Definition ast.h:4921
struct pm_node * receiver
IndexOrWriteNode::receiver.
Definition ast.h:4896
struct pm_node * value
IndexOrWriteNode::value.
Definition ast.h:4931
struct pm_arguments_node * arguments
IndexOrWriteNode::arguments.
Definition ast.h:4911
struct pm_node * receiver
IndexTargetNode::receiver.
Definition ast.h:4968
struct pm_arguments_node * arguments
IndexTargetNode::arguments.
Definition ast.h:4978
struct pm_block_argument_node * block
IndexTargetNode::block.
Definition ast.h:4988
struct pm_node * value
InstanceVariableAndWriteNode::value.
Definition ast.h:5026
pm_constant_id_t name
InstanceVariableAndWriteNode::name.
Definition ast.h:5011
struct pm_node * value
InstanceVariableOperatorWriteNode::value.
Definition ast.h:5064
pm_constant_id_t binary_operator
InstanceVariableOperatorWriteNode::binary_operator.
Definition ast.h:5069
pm_constant_id_t name
InstanceVariableOperatorWriteNode::name.
Definition ast.h:5049
struct pm_node * value
InstanceVariableOrWriteNode::value.
Definition ast.h:5107
pm_constant_id_t name
InstanceVariableOrWriteNode::name.
Definition ast.h:5092
pm_constant_id_t name
InstanceVariableReadNode::name.
Definition ast.h:5136
pm_constant_id_t name
InstanceVariableTargetNode::name.
Definition ast.h:5159
pm_constant_id_t name
InstanceVariableWriteNode::name.
Definition ast.h:5188
struct pm_node * value
InstanceVariableWriteNode::value.
Definition ast.h:5211
pm_integer_t value
IntegerNode::value.
Definition ast.h:5252
A structure represents an arbitrary-sized integer.
Definition pm_integer.h:20
size_t length
The number of allocated values.
Definition pm_integer.h:25
uint32_t value
Embedded value for small integer.
Definition pm_integer.h:36
uint32_t * values
List of 32-bit integers.
Definition pm_integer.h:30
bool negative
Whether or not the integer is negative.
Definition pm_integer.h:42
struct pm_node_list parts
InterpolatedStringNode::parts.
Definition ast.h:5376
struct pm_node_list parts
InterpolatedSymbolNode::parts.
Definition ast.h:5409
struct pm_node_list parts
InterpolatedXStringNode::parts.
Definition ast.h:5442
struct pm_node_list elements
KeywordHashNode::elements.
Definition ast.h:5509
struct pm_node * body
LambdaNode::body.
Definition ast.h:5594
pm_location_t opening_loc
LambdaNode::opening_loc.
Definition ast.h:5579
struct pm_node * parameters
LambdaNode::parameters.
Definition ast.h:5589
pm_location_t operator_loc
LambdaNode::operator_loc.
Definition ast.h:5574
pm_constant_id_list_t locals
LambdaNode::locals.
Definition ast.h:5569
A line and column in a string.
uint32_t column
The column number.
int32_t line
The line number.
struct pm_list_node * next
A pointer to the next node in the list.
Definition pm_list.h:48
This represents the overall linked list.
Definition pm_list.h:55
pm_list_node_t * tail
A pointer to the tail of the list.
Definition pm_list.h:63
pm_list_node_t * head
A pointer to the head of the list.
Definition pm_list.h:60
size_t size
The size of the list.
Definition pm_list.h:57
pm_constant_id_t name
LocalVariableAndWriteNode::name.
Definition ast.h:5632
uint32_t depth
LocalVariableAndWriteNode::depth.
Definition ast.h:5637
struct pm_node * value
LocalVariableAndWriteNode::value.
Definition ast.h:5627
uint32_t depth
LocalVariableOperatorWriteNode::depth.
Definition ast.h:5685
pm_constant_id_t binary_operator
LocalVariableOperatorWriteNode::binary_operator.
Definition ast.h:5680
struct pm_node * value
LocalVariableOperatorWriteNode::value.
Definition ast.h:5670
pm_constant_id_t name
LocalVariableOperatorWriteNode::name.
Definition ast.h:5675
uint32_t depth
LocalVariableOrWriteNode::depth.
Definition ast.h:5728
struct pm_node * value
LocalVariableOrWriteNode::value.
Definition ast.h:5718
pm_constant_id_t name
LocalVariableOrWriteNode::name.
Definition ast.h:5723
uint32_t depth
LocalVariableReadNode::depth.
Definition ast.h:5774
pm_constant_id_t name
LocalVariableReadNode::name.
Definition ast.h:5761
uint32_t depth
LocalVariableTargetNode::depth.
Definition ast.h:5805
pm_constant_id_t name
LocalVariableTargetNode::name.
Definition ast.h:5800
struct pm_node * value
LocalVariableWriteNode::value.
Definition ast.h:5874
uint32_t depth
LocalVariableWriteNode::depth.
Definition ast.h:5847
pm_constant_id_t name
LocalVariableWriteNode::name.
Definition ast.h:5834
This represents a range of bytes in the source string to which a node or token corresponds.
Definition ast.h:544
const uint8_t * start
A pointer to the start location of the range in the source.
Definition ast.h:546
const uint8_t * end
A pointer to the end location of the range in the source.
Definition ast.h:549
struct pm_node * pattern
MatchPredicateNode::pattern.
Definition ast.h:5963
struct pm_node * value
MatchPredicateNode::value.
Definition ast.h:5958
struct pm_node * value
MatchRequiredNode::value.
Definition ast.h:5996
struct pm_node * pattern
MatchRequiredNode::pattern.
Definition ast.h:6045
struct pm_node_list targets
MatchWriteNode::targets.
Definition ast.h:6083
struct pm_call_node * call
MatchWriteNode::call.
Definition ast.h:6078
struct pm_node * constant_path
ModuleNode::constant_path.
Definition ast.h:6131
struct pm_node * body
ModuleNode::body.
Definition ast.h:6136
pm_constant_id_list_t locals
ModuleNode::locals.
Definition ast.h:6121
pm_constant_id_t name
ModuleNode::name.
Definition ast.h:6146
struct pm_node_list lefts
MultiTargetNode::lefts.
Definition ast.h:6184
struct pm_node * rest
MultiTargetNode::rest.
Definition ast.h:6204
struct pm_node_list rights
MultiTargetNode::rights.
Definition ast.h:6214
This is a node in the multi target state linked list.
As we're compiling a multi target, we need to track additional information whenever there is a parent...
struct pm_node * value
MultiWriteNode::value.
Definition ast.h:6337
struct pm_node * rest
MultiWriteNode::rest.
Definition ast.h:6287
struct pm_node_list rights
MultiWriteNode::rights.
Definition ast.h:6297
struct pm_node_list lefts
MultiWriteNode::lefts.
Definition ast.h:6267
A list of offsets of newlines in a string.
const uint8_t * start
A pointer to the start of the source string.
size_t * offsets
The list of offsets.
size_t size
The number of offsets in the list.
struct pm_arguments_node * arguments
NextNode::arguments.
Definition ast.h:6360
size_t size
The number of nodes in the list.
Definition ast.h:559
struct pm_node ** nodes
The nodes in the list.
Definition ast.h:565
This compiler defines its own concept of the location of a node.
int32_t line
This is the line number of a node.
uint32_t node_id
This is a unique identifier for the node.
pm_node_type_t type
This represents the type of the node.
Definition ast.h:1057
uint32_t node_id
The unique identifier for this node, which is deterministic based on the source.
Definition ast.h:1069
pm_node_flags_t flags
This represents any flags on the node.
Definition ast.h:1063
pm_location_t location
This is the location of the node in the source.
Definition ast.h:1075
uint32_t number
NumberedReferenceReadNode::number.
Definition ast.h:6466
pm_constant_id_t name
OptionalKeywordParameterNode::name.
Definition ast.h:6493
struct pm_node * value
OptionalKeywordParameterNode::value.
Definition ast.h:6503
struct pm_node * value
OptionalParameterNode::value.
Definition ast.h:6545
pm_constant_id_t name
OptionalParameterNode::name.
Definition ast.h:6530
pm_options_version_t version
The version of prism that we should be parsing with.
Definition options.h:156
struct pm_node * left
OrNode::left.
Definition ast.h:6576
struct pm_node * right
OrNode::right.
Definition ast.h:6589
struct pm_node * rest
ParametersNode::rest.
Definition ast.h:6633
struct pm_node_list requireds
ParametersNode::requireds.
Definition ast.h:6623
struct pm_block_parameter_node * block
ParametersNode::block.
Definition ast.h:6653
struct pm_node_list optionals
ParametersNode::optionals.
Definition ast.h:6628
struct pm_node_list posts
ParametersNode::posts.
Definition ast.h:6638
pm_node_t base
The embedded base node.
Definition ast.h:6617
struct pm_node * keyword_rest
ParametersNode::keyword_rest.
Definition ast.h:6648
struct pm_node_list keywords
ParametersNode::keywords.
Definition ast.h:6643
struct pm_node * body
ParenthesesNode::body.
Definition ast.h:6679
The format that will be used to format the errors into the output.
size_t blank_prefix_length
The length of the blank prefix.
const char * blank_prefix
The prefix that will be used for blank lines.
size_t divider_length
The length of the divider.
const char * number_prefix
The prefix that will be used for line numbers.
const char * divider
The divider that will be used between sections of source code.
An error that is going to be formatted into the output.
pm_diagnostic_t * error
A pointer to the diagnostic that was generated during parsing.
uint32_t column_end
The column end of the diagnostic message.
int32_t line
The start line of the diagnostic message.
uint32_t column_start
The column start of the diagnostic message.
bool parsed
Whether or not this parse result has performed its parsing yet.
pm_scope_node_t node
The resulting scope node that will hold the generated AST.
pm_string_t input
The input that represents the source to be parsed.
pm_parser_t parser
The parser that will do the actual parsing.
pm_options_t options
The options that will be passed to the parser.
const pm_encoding_t * encoding
The encoding functions for the current file is attached to the parser as it's parsing so that it can ...
Definition parser.h:758
const uint8_t * end
The pointer to the end of the source.
Definition parser.h:697
pm_constant_pool_t constant_pool
This constant pool keeps all of the constants defined throughout the file so that we can reference th...
Definition parser.h:789
const uint8_t * start
The pointer to the start of the source.
Definition parser.h:694
pm_list_t error_list
The list of errors that have been found while parsing.
Definition parser.h:737
pm_list_t warning_list
The list of warnings that have been found while parsing.
Definition parser.h:734
int32_t start_line
The line number at the start of the parse.
Definition parser.h:812
pm_string_t filepath
This is the path of the file being parsed.
Definition parser.h:783
pm_newline_list_t newline_list
This is the list of newline offsets in the source file.
Definition parser.h:792
struct pm_node * variable
PinnedVariableNode::variable.
Definition ast.h:6775
struct pm_statements_node * statements
PostExecutionNode::statements.
Definition ast.h:6808
struct pm_statements_node * statements
PreExecutionNode::statements.
Definition ast.h:6846
struct pm_statements_node * statements
ProgramNode::statements.
Definition ast.h:6886
struct pm_node * right
RangeNode::right.
Definition ast.h:6937
struct pm_node * left
RangeNode::left.
Definition ast.h:6923
pm_integer_t denominator
RationalNode::denominator.
Definition ast.h:6986
pm_integer_t numerator
RationalNode::numerator.
Definition ast.h:6977
pm_constant_id_t name
RequiredParameterNode::name.
Definition ast.h:7114
struct pm_node * rescue_expression
RescueModifierNode::rescue_expression.
Definition ast.h:7147
struct pm_node * expression
RescueModifierNode::expression.
Definition ast.h:7137
struct pm_rescue_node * subsequent
RescueNode::subsequent.
Definition ast.h:7205
struct pm_node * reference
RescueNode::reference.
Definition ast.h:7190
struct pm_node_list exceptions
RescueNode::exceptions.
Definition ast.h:7180
struct pm_statements_node * statements
RescueNode::statements.
Definition ast.h:7200
struct pm_arguments_node * arguments
ReturnNode::arguments.
Definition ast.h:7288
rb_encoding * filepath_encoding
This is the encoding of the actual filepath object that will be used when a FILE node is compiled or ...
struct iseq_link_anchor * pre_execution_anchor
This will only be set on the top-level scope node.
VALUE * script_lines
This is a pointer to the list of script lines for the ISEQs that will be associated with this scope n...
struct pm_node * write
ShareableConstantNode::write.
Definition ast.h:7337
pm_node_t base
The embedded base node.
Definition ast.h:7329
pm_constant_id_list_t locals
SingletonClassNode::locals.
Definition ast.h:7360
struct pm_node * expression
SingletonClassNode::expression.
Definition ast.h:7375
struct pm_node * body
SingletonClassNode::body.
Definition ast.h:7380
pm_string_t filepath
SourceFileNode::filepath.
Definition ast.h:7434
struct pm_node * expression
SplatNode::expression.
Definition ast.h:7480
struct pm_node_list body
StatementsNode::body.
Definition ast.h:7503
pm_node_t base
The embedded base node.
Definition ast.h:7497
pm_string_t unescaped
StringNode::unescaped.
Definition ast.h:7553
A generic string type that can have various ownership semantics.
Definition pm_string.h:33
struct pm_arguments_node * arguments
SuperNode::arguments.
Definition ast.h:7593
struct pm_node * block
SuperNode::block.
Definition ast.h:7603
pm_string_t unescaped
SymbolNode::unescaped.
Definition ast.h:7649
pm_node_t base
The embedded base node.
Definition ast.h:7628
struct pm_node_list names
UndefNode::names.
Definition ast.h:7690
struct pm_statements_node * statements
UnlessNode::statements.
Definition ast.h:7763
struct pm_node * predicate
UnlessNode::predicate.
Definition ast.h:7742
struct pm_else_node * else_clause
UnlessNode::else_clause.
Definition ast.h:7773
pm_node_t base
The embedded base node.
Definition ast.h:7806
pm_node_t base
The embedded base node.
Definition ast.h:7895
pm_string_t unescaped
XStringNode::unescaped.
Definition ast.h:7963
struct pm_arguments_node * arguments
YieldNode::arguments.
Definition ast.h:7996
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376