Ruby 4.1.0dev (2026-12-01 revision afadaed84ccb23517ffb57fd15f116f2e4a85917)
parser.h
1#ifndef PRISM_INTERNAL_PARSER_H
2#define PRISM_INTERNAL_PARSER_H
3
7
8#include "prism/internal/arena.h"
9#include "prism/internal/buffer.h"
10#include "prism/internal/comments.h"
11#include "prism/internal/constant_pool.h"
12#include "prism/internal/encoding.h"
13#include "prism/internal/list.h"
14#include "prism/internal/node.h"
15#include "prism/internal/options.h"
16#include "prism/internal/static_literals.h"
17#include "prism/internal/strpbrk.h"
18
19#include "prism/ast.h"
21#include "prism/parser.h"
22
23#include <stdbool.h>
24#include <stddef.h>
25#include <stdint.h>
26
27/*
28 * A place in the unescaped content of a regular expression where it stops
29 * lining up with the source, because the lexer dropped or rewrote an escape
30 * just before it. From here up to the next such place, each byte of the content
31 * is the byte at the same distance into the source.
32 */
33typedef struct {
34 /* The offset of the place in the unescaped content. */
35 uint32_t content;
36
37 /* The offset in the source of the byte at that place. */
38 uint32_t source;
40
41/*
42 * The places where the unescaped content of a regular expression stops lining
43 * up with the source, in order. Before the first one, each byte of the content
44 * is the byte at the same distance from the start of the content in the source.
45 * The values are allocated in the scratch arena, since they are only read while
46 * the regular expression is validated.
47 */
48typedef struct {
49 /* The places, in order of their offsets in the content. */
50 pm_regexp_offset_t *values;
51
52 /* The number of places. */
53 size_t size;
54
55 /* The number of places that fit in the values before they must grow. */
56 size_t capacity;
58
59/*
60 * This enum provides various bits that represent different kinds of states that
61 * the lexer can track. This is used to determine which kind of token to return
62 * based on the context of the parser.
63 */
64typedef enum {
65 PM_LEX_STATE_BIT_BEG,
66 PM_LEX_STATE_BIT_END,
67 PM_LEX_STATE_BIT_ENDARG,
68 PM_LEX_STATE_BIT_ENDFN,
69 PM_LEX_STATE_BIT_ARG,
70 PM_LEX_STATE_BIT_CMDARG,
71 PM_LEX_STATE_BIT_MID,
72 PM_LEX_STATE_BIT_FNAME,
73 PM_LEX_STATE_BIT_DOT,
74 PM_LEX_STATE_BIT_CLASS,
75 PM_LEX_STATE_BIT_LABEL,
76 PM_LEX_STATE_BIT_LABELED,
77 PM_LEX_STATE_BIT_FITEM
78} pm_lex_state_bit_t;
79
80/*
81 * This enum combines the various bits from the above enum into individual
82 * values that represent the various states of the lexer.
83 */
84typedef enum {
85 PM_LEX_STATE_NONE = 0,
86 PM_LEX_STATE_BEG = (1 << PM_LEX_STATE_BIT_BEG),
87 PM_LEX_STATE_END = (1 << PM_LEX_STATE_BIT_END),
88 PM_LEX_STATE_ENDARG = (1 << PM_LEX_STATE_BIT_ENDARG),
89 PM_LEX_STATE_ENDFN = (1 << PM_LEX_STATE_BIT_ENDFN),
90 PM_LEX_STATE_ARG = (1 << PM_LEX_STATE_BIT_ARG),
91 PM_LEX_STATE_CMDARG = (1 << PM_LEX_STATE_BIT_CMDARG),
92 PM_LEX_STATE_MID = (1 << PM_LEX_STATE_BIT_MID),
93 PM_LEX_STATE_FNAME = (1 << PM_LEX_STATE_BIT_FNAME),
94 PM_LEX_STATE_DOT = (1 << PM_LEX_STATE_BIT_DOT),
95 PM_LEX_STATE_CLASS = (1 << PM_LEX_STATE_BIT_CLASS),
96 PM_LEX_STATE_LABEL = (1 << PM_LEX_STATE_BIT_LABEL),
97 PM_LEX_STATE_LABELED = (1 << PM_LEX_STATE_BIT_LABELED),
98 PM_LEX_STATE_FITEM = (1 << PM_LEX_STATE_BIT_FITEM),
99 PM_LEX_STATE_BEG_ANY = PM_LEX_STATE_BEG | PM_LEX_STATE_MID | PM_LEX_STATE_CLASS,
100 PM_LEX_STATE_ARG_ANY = PM_LEX_STATE_ARG | PM_LEX_STATE_CMDARG,
101 PM_LEX_STATE_END_ANY = PM_LEX_STATE_END | PM_LEX_STATE_ENDARG | PM_LEX_STATE_ENDFN
102} pm_lex_state_t;
103
104/*
105 * The type of quote that a heredoc uses.
106 */
107typedef enum {
108 PM_HEREDOC_QUOTE_NONE,
109 PM_HEREDOC_QUOTE_SINGLE = '\'',
110 PM_HEREDOC_QUOTE_DOUBLE = '"',
111 PM_HEREDOC_QUOTE_BACKTICK = '`',
112} pm_heredoc_quote_t;
113
114/*
115 * The type of indentation that a heredoc uses.
116 */
117typedef enum {
118 PM_HEREDOC_INDENT_NONE,
119 PM_HEREDOC_INDENT_DASH,
120 PM_HEREDOC_INDENT_TILDE,
121} pm_heredoc_indent_t;
122
123/*
124 * All of the information necessary to store to lexing a heredoc.
125 */
126typedef struct {
127 /* A pointer to the start of the heredoc identifier. */
128 const uint8_t *ident_start;
129
130 /* The length of the heredoc identifier. */
131 size_t ident_length;
132
133 /* The type of quote that the heredoc uses. */
134 pm_heredoc_quote_t quote;
135
136 /* The type of indentation that the heredoc uses. */
137 pm_heredoc_indent_t indent;
139
140/*
141 * When lexing Ruby source, the lexer has a small amount of state to tell which
142 * kind of token it is currently lexing. For example, when we find the start of
143 * a string, the first token that we return is a TOKEN_STRING_BEGIN token. After
144 * that the lexer is now in the PM_LEX_STRING mode, and will return tokens that
145 * are found as part of a string.
146 */
147typedef struct pm_lex_mode {
148 /* The type of this lex mode. */
149 enum {
150 /* This state is used when any given token is being lexed. */
151 PM_LEX_DEFAULT,
152
153 /*
154 * This state is used when we're lexing as normal but inside an embedded
155 * expression of a string.
156 */
157 PM_LEX_EMBEXPR,
158
159 /*
160 * This state is used when we're lexing a variable that is embedded
161 * directly inside of a string with the # shorthand.
162 */
163 PM_LEX_EMBVAR,
164
165 /* This state is used when you are inside the content of a heredoc. */
166 PM_LEX_HEREDOC,
167
168 /*
169 * This state is used when we are lexing a list of tokens, as in a %w
170 * word list literal or a %i symbol list literal.
171 */
172 PM_LEX_LIST,
173
174 /*
175 * This state is used when a regular expression has been begun and we
176 * are looking for the terminator.
177 */
178 PM_LEX_REGEXP,
179
180 /*
181 * This state is used when we are lexing a string or a string-like
182 * token, as in string content with either quote or an xstring.
183 */
184 PM_LEX_STRING
185 } mode;
186
187 /* The data associated with this type of lex mode. */
188 union {
189 struct {
190 /* This keeps track of the nesting level of the list. */
191 size_t nesting;
192
193 /* Whether or not interpolation is allowed in this list. */
194 bool interpolation;
195
196 /*
197 * Whether any token has been emitted from this list. A word
198 * separator delimits the opener from the first word, so one
199 * without source characters is emitted when the list does not
200 * start with whitespace.
201 */
202 bool started;
203
204 /*
205 * Whether the previously emitted token was a word separator. A
206 * word separator delimits the last word from the terminator, so
207 * one without source characters is emitted when the list does
208 * not end with whitespace.
209 */
210 bool separated;
211
212 /*
213 * When lexing a list, it takes into account balancing the
214 * terminator if the terminator is one of (), [], {}, or <>.
215 */
216 uint8_t incrementor;
217
218 /* This is the terminator of the list literal. */
219 uint8_t terminator;
220
221 /*
222 * This is the character set that should be used to delimit the
223 * tokens within the list.
224 */
225 uint8_t breakpoints[PM_STRPBRK_CACHE_SIZE];
226 } list;
227
228 struct {
229 /*
230 * This keeps track of the nesting level of the regular expression.
231 */
232 size_t nesting;
233
234 /*
235 * When lexing a regular expression, it takes into account balancing
236 * the terminator if the terminator is one of (), [], {}, or <>.
237 */
238 uint8_t incrementor;
239
240 /* This is the terminator of the regular expression. */
241 uint8_t terminator;
242
243 /*
244 * This is the character set that should be used to delimit the
245 * tokens within the regular expression.
246 */
247 uint8_t breakpoints[PM_STRPBRK_CACHE_SIZE];
248 } regexp;
249
250 struct {
251 /* This keeps track of the nesting level of the string. */
252 size_t nesting;
253
254 /* Whether or not interpolation is allowed in this string. */
255 bool interpolation;
256
257 /*
258 * Whether or not at the end of the string we should allow a :,
259 * which would indicate this was a dynamic symbol instead of a
260 * string.
261 */
262 bool label_allowed;
263
264 /* Whether the final content token joined text after the last
265 * breakpoint, where this string used to split at EOF. */
266 bool joined_at_eof;
267
268 /*
269 * When lexing a string, it takes into account balancing the
270 * terminator if the terminator is one of (), [], {}, or <>.
271 */
272 uint8_t incrementor;
273
274 /*
275 * This is the terminator of the string. It is typically either a
276 * single or double quote.
277 */
278 uint8_t terminator;
279
280 /*
281 * This is the character set that should be used to delimit the
282 * tokens within the string.
283 */
284 uint8_t breakpoints[PM_STRPBRK_CACHE_SIZE];
285 } string;
286
287 struct {
288 /*
289 * All of the data necessary to lex a heredoc.
290 */
292
293 /*
294 * This is the pointer to the character where lexing should resume
295 * once the heredoc has been completely processed.
296 */
297 const uint8_t *next_start;
298
299 /*
300 * This is used to track the amount of common whitespace on each
301 * line so that we know how much to dedent each line in the case of
302 * a tilde heredoc.
303 */
304 size_t *common_whitespace;
305
306 /* True if the previous token ended with a line continuation. */
307 bool line_continuation;
308 } heredoc;
309 } as;
310
311 /* The previous lex state so that it knows how to pop. */
312 struct pm_lex_mode *prev;
313} pm_lex_mode_t;
314
315/*
316 * While parsing, we keep track of a stack of contexts. This is helpful for
317 * error recovery so that we can pop back to a previous context when we hit a
318 * token that is understood by a parent context but not by the current context.
319 */
320typedef enum {
321 /* a null context, used for returning a value from a function */
322 PM_CONTEXT_NONE = 0,
323
324 /* a begin statement */
325 PM_CONTEXT_BEGIN,
326
327 /* expressions in block arguments using braces */
328 PM_CONTEXT_BLOCK_BRACES,
329
330 /* expressions in block arguments using do..end */
331 PM_CONTEXT_BLOCK_KEYWORDS,
332
333 /* expressions in block parameters `foo do |...| end ` */
334 PM_CONTEXT_BLOCK_PARAMETERS,
335
336 /* a case when statements */
337 PM_CONTEXT_CASE_WHEN,
338
339 /* a case in statements */
340 PM_CONTEXT_CASE_IN,
341
342 /* a class declaration */
343 PM_CONTEXT_CLASS,
344
345 /* a method definition */
346 PM_CONTEXT_DEF,
347
348 /* a method definition's parameters */
349 PM_CONTEXT_DEF_PARAMS,
350
351 /* a defined? expression */
352 PM_CONTEXT_DEFINED,
353
354 /* a method definition's default parameter */
355 PM_CONTEXT_DEFAULT_PARAMS,
356
357 /* an else clause */
358 PM_CONTEXT_ELSE,
359
360 /* an elsif clause */
361 PM_CONTEXT_ELSIF,
362
363 /* an interpolated expression */
364 PM_CONTEXT_EMBEXPR,
365
366 /* a for loop */
367 PM_CONTEXT_FOR,
368
369 /* a for loop's index */
370 PM_CONTEXT_FOR_INDEX,
371
372 /* an if statement */
373 PM_CONTEXT_IF,
374
375 /* a lambda expression with braces */
376 PM_CONTEXT_LAMBDA_BRACES,
377
378 /* a lambda expression with do..end */
379 PM_CONTEXT_LAMBDA_DO_END,
380
381 /* expressions in lambda parameters */
382 PM_CONTEXT_LAMBDA_PARAMETERS,
383
384 /* the predicate clause of a loop statement */
385 PM_CONTEXT_LOOP_PREDICATE,
386
387 /* the top level context */
388 PM_CONTEXT_MAIN,
389
390 /* a module declaration */
391 PM_CONTEXT_MODULE,
392
393 /* a multiple target expression */
394 PM_CONTEXT_MULTI_TARGET,
395
396 /* a parenthesized expression */
397 PM_CONTEXT_PARENS,
398
399 /* an END block */
400 PM_CONTEXT_POSTEXE,
401
402 /* a predicate inside an if/elsif/unless statement */
403 PM_CONTEXT_PREDICATE,
404
405 /* a BEGIN block */
406 PM_CONTEXT_PREEXE,
407
408 /* the exception expressions and assignment target of a rescue clause */
409 PM_CONTEXT_RESCUE_HEADER,
410
411 /* the statements of a rescue clause */
412 PM_CONTEXT_RESCUE,
413
414 /* the else clause following a rescue */
415 PM_CONTEXT_RESCUE_ELSE,
416
417 /* the statements of an ensure clause */
418 PM_CONTEXT_ENSURE,
419
420 /* a modifier rescue clause */
421 PM_CONTEXT_RESCUE_MODIFIER,
422
423 /* a singleton class definition */
424 PM_CONTEXT_SCLASS,
425
426 /* a ternary expression */
427 PM_CONTEXT_TERNARY,
428
429 /* an unless statement */
430 PM_CONTEXT_UNLESS,
431
432 /* an until statement */
433 PM_CONTEXT_UNTIL,
434
435 /* a while statement */
436 PM_CONTEXT_WHILE,
437
438 /* the number of contexts, which is not itself a context */
439 PM_CONTEXT_MAXIMUM,
440} pm_context_t;
441
442typedef struct {
443 pm_context_t context;
444
445 /* Popping the outermost occurrence clears this context's membership bit. */
446 bool outermost;
447
448 /* The body's clauses now supply the recovery delimiters for this frame. */
449 bool scope_only;
451
452/* The type of shareable constant value that can be set. */
453typedef uint8_t pm_shareable_constant_value_t;
454static const pm_shareable_constant_value_t PM_SCOPE_SHAREABLE_CONSTANT_NONE = 0x0;
455static const pm_shareable_constant_value_t PM_SCOPE_SHAREABLE_CONSTANT_LITERAL = PM_SHAREABLE_CONSTANT_NODE_FLAGS_LITERAL;
456static const pm_shareable_constant_value_t PM_SCOPE_SHAREABLE_CONSTANT_EXPERIMENTAL_EVERYTHING = PM_SHAREABLE_CONSTANT_NODE_FLAGS_EXPERIMENTAL_EVERYTHING;
457static const pm_shareable_constant_value_t PM_SCOPE_SHAREABLE_CONSTANT_EXPERIMENTAL_COPY = PM_SHAREABLE_CONSTANT_NODE_FLAGS_EXPERIMENTAL_COPY;
458
459/*
460 * This tracks an individual local variable in a certain lexical context, as
461 * well as the number of times is it read. The locals of every live scope are
462 * kept on a single stack on the parser, since a local is only ever declared in
463 * the innermost scope and is discarded when that scope is popped.
464 */
465typedef struct {
466 /* The name of the local variable. */
467 pm_constant_id_t name;
468
469 /* The location of the local variable in the source. */
470 pm_location_t location;
471
472 /* The number of times the local variable is read. */
473 uint32_t reads;
474
475 /* The level of the scope that declares the local variable. */
476 uint32_t level;
477
478 /*
479 * The index in the locals stack of the local with the same name that this
480 * local hides while its scope is live, or 0 if it hides nothing. It is
481 * restored as the binding of the name when the scope is popped.
482 */
483 uint32_t shadowed;
484} pm_local_t;
485
486/* The flags about scope parameters that can be set. */
487typedef uint8_t pm_scope_parameters_t;
488static const pm_scope_parameters_t PM_SCOPE_PARAMETERS_NONE = 0x0;
489static const pm_scope_parameters_t PM_SCOPE_PARAMETERS_FORWARDING_POSITIONALS = 0x1;
490static const pm_scope_parameters_t PM_SCOPE_PARAMETERS_FORWARDING_KEYWORDS = 0x2;
491static const pm_scope_parameters_t PM_SCOPE_PARAMETERS_FORWARDING_BLOCK = 0x4;
492static const pm_scope_parameters_t PM_SCOPE_PARAMETERS_FORWARDING_ALL = 0x8;
493static const pm_scope_parameters_t PM_SCOPE_PARAMETERS_IMPLICIT_DISALLOWED = 0x10;
494static const pm_scope_parameters_t PM_SCOPE_PARAMETERS_NUMBERED_INNER = 0x20;
495static const pm_scope_parameters_t PM_SCOPE_PARAMETERS_NUMBERED_FOUND = 0x40;
496
497/*
498 * This struct represents a node in a linked list of scopes. Some scopes can see
499 * into their parent scopes, while others cannot.
500 */
501typedef struct pm_scope {
502 /* A pointer to the previous scope in the linked list. */
503 struct pm_scope *previous;
504
505 /*
506 * The index in the locals stack of the first local of this scope. The
507 * locals of this scope run from here to the top of the stack.
508 */
509 uint32_t locals_start;
510
511 /*
512 * The position of this scope in the scope stack, where the outermost scope
513 * is at level 1.
514 */
515 uint32_t level;
516
517 /*
518 * The locals_start of the nearest closed scope at or above this one. Every
519 * local below this index in the locals stack belongs to a scope that this
520 * scope cannot see into.
521 */
522 uint32_t floor;
523
524 /*
525 * This is a list of the implicit parameters contained within the block.
526 * These will be processed after the block is parsed to determine the kind
527 * of parameters node that should be used and to check if any errors need to
528 * be added.
529 */
530 pm_scratch_node_list_t implicit_parameters;
531
532 /*
533 * This is a bitfield that indicates the parameters that are being used in
534 * this scope. It is a combination of the PM_SCOPE_PARAMETERS_* constants.
535 * There are three different kinds of parameters that can be used in a
536 * scope:
537 *
538 * - Ordinary parameters (e.g., def foo(bar); end)
539 * - Numbered parameters (e.g., def foo; _1; end)
540 * - The it parameter (e.g., def foo; it; end)
541 *
542 * If ordinary parameters are being used, then certain parameters can be
543 * forwarded to another method/structure. Those are indicated by four
544 * additional bits in the params field. For example, some combinations of:
545 *
546 * - def foo(*); end
547 * - def foo(**); end
548 * - def foo(&); end
549 * - def foo(...); end
550 */
551 pm_scope_parameters_t parameters;
552
553 /*
554 * The current state of constant shareability for this scope. This is
555 * changed by magic shareable_constant_value comments.
556 */
557 pm_shareable_constant_value_t shareable_constant;
558
559 /*
560 * A boolean indicating whether or not this scope can see into its parent.
561 * If closed is true, then the scope cannot see into its parent.
562 */
563 bool closed;
564} pm_scope_t;
565
566/*
567 * A stack of boolean values with no fixed depth limit. The newest frames live
568 * in an inline word, so pushing and popping are usually a shift and a compare.
569 * When that word fills, it moves to the spill array and the inline word starts
570 * over empty. The spill array is only allocated once the nesting is more than
571 * 64 frames deep.
572 */
573typedef struct {
574 /*
575 * The newest frames, with the top of the stack in bit 0. It holds between
576 * 1 and 64 frames while the stack is not empty, and is 0 when it is.
577 */
578 uint64_t top;
579
580 /*
581 * The number of frames on the whole stack. The inline word holds the
582 * frames above the last multiple of 64, so the spill array holds
583 * (depth - 1) / 64 words.
584 */
585 uint32_t depth;
586
587 /* The number of words the spill array has room for. */
588 uint32_t capacity;
589
590 /*
591 * Full words of 64 older frames each, oldest first, allocated from the
592 * scratch arena.
593 */
594 uint64_t *spill;
596
597/*
598 * This struct represents the overall parser. It contains a reference to the
599 * source file, as well as pointers that indicate where in the source it's
600 * currently parsing. It also contains the most recent and current token that
601 * it's considering.
602 */
604 /* The arena used for all AST-lifetime allocations. Caller-owned. */
605 pm_arena_t *arena;
606
607 /*
608 * The arena used for parser metadata (comments, diagnostics, etc.), which
609 * lives as long as the parser.
610 */
611 pm_arena_t metadata_arena;
612
613 /*
614 * The arena used for state that is only needed while parsing, such as
615 * scopes, locals, and contexts. It is released when pm_parse returns, so
616 * nothing allocated in it can be reachable from the tree or from the
617 * parser's metadata.
618 */
619 pm_arena_t scratch_arena;
620
621 /*
622 * The next node identifier that will be assigned. This is a unique
623 * identifier used to track nodes such that the syntax tree can be dropped
624 * but the node can be found through another parse.
625 */
626 uint32_t node_id;
627
628 /*
629 * A single-entry cache for pm_parser_constant_id_raw. Avoids redundant
630 * constant pool lookups when the same token is resolved multiple times
631 * (e.g., once during lexing for local variable detection, and again
632 * during parsing for node creation).
633 */
634 struct {
635 const uint8_t *start;
636 const uint8_t *end;
638 } constant_cache;
639
640 /* The current state of the lexer. */
641 pm_lex_state_t lex_state;
642
643 /* Tracks the current nesting of (), [], and {}. */
644 int enclosure_nesting;
645
646 /*
647 * Used to temporarily track the nesting of enclosures to determine if a {
648 * is the beginning of a lambda following the parameters of a lambda.
649 */
650 int lambda_enclosure_nesting;
651
652 /*
653 * Used to track the nesting of braces to ensure we get the correct value
654 * when we are interpolating blocks with braces.
655 */
656 int brace_nesting;
657
658 /*
659 * The stack used to determine if a do keyword belongs to the predicate of a
660 * while, until, or for loop.
661 */
662 pm_state_stack_t do_loop_stack;
663
664 /*
665 * The stack used to determine if a do keyword belongs to the beginning of a
666 * block.
667 */
668 pm_state_stack_t accepts_block_stack;
669
670 /* A stack of lex modes, linked through their prev pointers. */
671 struct {
672 /* The current mode of the lexer. */
673 pm_lex_mode_t *current;
674
675 /*
676 * The mode at the bottom of the stack, which is never popped. Every
677 * other mode is allocated from the scratch arena.
678 */
679 pm_lex_mode_t base;
680
681 /*
682 * Lex modes that have been popped, kept for reuse by the next push.
683 * They are allocated from the scratch arena, so they are never freed
684 * individually.
685 */
686 pm_lex_mode_t *free;
687 } lex_modes;
688
689 /*
690 * The chunks that open node lists are built in. They are carved from the
691 * scratch arena, so they are never freed individually.
692 */
693 pm_node_chunks_t node_chunks;
694
695 /* The pointer to the start of the source. */
696 const uint8_t *start;
697
698 /* The end of the full input, including the data section. */
699 const uint8_t *end;
700
701 /* The end of the Ruby code, at the start of the __END__ marker if present. */
702 const uint8_t *source_end;
703
704 /* The previous token we were considering. */
705 pm_token_t previous;
706
707 /* The current token we're considering. */
708 pm_token_t current;
709
710 /*
711 * This is a special field set on the parser when we need the parser to jump
712 * to a specific location when lexing the next token, as opposed to just
713 * using the end of the previous token. Normally this is NULL.
714 */
715 const uint8_t *next_start;
716
717 /*
718 * This field indicates the end of a heredoc whose identifier was found on
719 * the current line. If another heredoc is found on the same line, then this
720 * will be moved forward to the end of that heredoc. If no heredocs are
721 * found on a line then this is NULL.
722 */
723 const uint8_t *heredoc_end;
724
725 /* The list of comments that have been found while parsing. */
726 pm_list_t comment_list;
727
728 /*
729 * The attachments of comments to the nodes that own them, populated after
730 * parsing when the attach_comments option is set.
731 */
732 pm_comment_attachments_t comment_attachments;
733
734 /* The list of magic comments that have been found while parsing. */
735 pm_list_t magic_comment_list;
736
737 /*
738 * An optional location that represents the location of the __END__ marker
739 * and the rest of the content of the file. This content is loaded into the
740 * DATA constant when the file being parsed is the main file being executed.
741 */
742 pm_location_t data_loc;
743
744 /* The list of warnings that have been found while parsing. */
745 pm_list_t warning_list;
746
747 /* The list of errors that have been found while parsing. */
748 pm_list_t error_list;
749
750 /* The current local scope. */
751 pm_scope_t *current_scope;
752
753 /*
754 * The locals of every live scope, in the order they were declared. Index 0
755 * is never used, so that 0 can mean the absence of a local.
756 */
757 pm_local_t *locals;
758
759 /* The number of slots in use in locals, including the unused slot 0. */
760 uint32_t locals_size;
761
762 /* The number of slots allocated in locals. */
763 uint32_t locals_capacity;
764
765 /*
766 * The index in the locals stack of the innermost live local with each
767 * constant id as its name, or 0 if there is none. A local that is declared
768 * in a scope replaces the binding of its name, and the binding it replaced
769 * is restored when the scope is popped. Constant ids at or beyond the
770 * capacity have never been declared as locals, so they are unbound.
771 */
772 uint32_t *bindings;
773
774 /* The number of slots allocated in bindings. */
775 uint32_t bindings_capacity;
776
777 /*
778 * Scopes that have been popped, kept for reuse by the next push. Scopes
779 * are allocated from the scratch arena, so they are never freed
780 * individually.
781 */
782 pm_scope_t *free_scopes;
783
784 /* Slot 0 holds PM_CONTEXT_NONE. The depth indexes the current frame. */
785 pm_context_frame_t *contexts;
786 uint32_t context_depth;
787 uint32_t context_capacity;
788
789 /* One bit per context present anywhere on the stack. */
790 uint64_t context_mask;
791
792 /*
793 * The encoding functions for the current file is attached to the parser as
794 * it's parsing so that it can change with a magic comment.
795 */
796 const pm_encoding_t *encoding;
797
798 /*
799 * When the encoding that is being used to parse the source is changed by
800 * prism, we provide the ability here to call out to a user-defined
801 * function.
802 */
803 pm_encoding_changed_callback_t encoding_changed_callback;
804
805 /*
806 * Start of the source line that can contain an encoding comment, or NULL
807 * if there is no eligible line.
808 */
809 const uint8_t *encoding_comment_start;
810
811 /*
812 * When you are lexing through a file, the lexer needs all of the information
813 * that the parser additionally provides (for example, the local table). So if
814 * you want to properly lex Ruby, you need to actually lex it in the context of
815 * the parser. In order to provide this functionality, we optionally allow a
816 * struct to be attached to the parser that calls back out to a user-provided
817 * callback when each token is lexed.
818 */
819 struct {
820 /*
821 * This is the callback that is called when a token is lexed. It is
822 * passed the opaque data pointer, the parser, and the token that was
823 * lexed.
824 */
825 pm_lex_callback_t callback;
826
827 /*
828 * This opaque pointer is used to provide whatever information the user
829 * deemed necessary to the callback. In our case we use it to pass the
830 * array that the tokens get appended into.
831 */
832 void *data;
833 } lex_callback;
834
835 /*
836 * This is the path of the file being parsed. We use the filepath when
837 * constructing SourceFileNodes.
838 */
839 pm_string_t filepath;
840
841 /*
842 * This constant pool keeps all of the constants defined throughout the file
843 * so that we can reference them later.
844 */
845 pm_constant_pool_t constant_pool;
846
847 /* This is the list of line offsets in the source file. */
848 pm_line_offset_list_t line_offsets;
849
850 /*
851 * State communicated from the lexer to the parser for integer tokens.
852 */
853 struct {
854 /*
855 * A flag indicating the base of the integer (binary, octal, decimal,
856 * hexadecimal). Set during lexing and read during node creation.
857 */
858 pm_node_flags_t base;
859
860 /*
861 * When lexing a decimal integer of at most 19 digits, which always
862 * fits in a uint64_t, or a plain 0, we compute the value during
863 * lexing to avoid re-scanning the digits during parsing. If start is
864 * set, this holds the result for the token that begins there and
865 * pm_integer_parse can be skipped.
866 */
867 uint64_t value;
868
869 /*
870 * The start of the token whose value is held in value, or NULL before
871 * any has been. The parser creates the node for a token only after
872 * lexing the next one, which may be another integer that replaces the
873 * value, so node creation checks that it belongs to the token at hand.
874 */
875 const uint8_t *start;
876 } integer;
877
878 /*
879 * This string is used to pass information from the lexer to the parser. It
880 * is particularly necessary because of escape sequences.
881 */
882 pm_string_t current_string;
883
884 /* Reusable workspace for rewriting escaped token content. */
885 pm_buffer_t lex_buffer;
886
887 /*
888 * Where current_string stops lining up with the source, when it is the
889 * content of a regular expression.
890 */
891 pm_regexp_offsets_t current_regexp_offsets;
892
893 /* Named captures from the regexp immediately before a pending =~. */
894 const struct pm_regexp_match *regexp_match;
895
896 /*
897 * The line number at the start of the parse. This will be used to offset
898 * the line numbers of all of the locations.
899 */
900 int32_t start_line;
901
902 /*
903 * When a string-like expression is being lexed, any byte or escape sequence
904 * that resolves to a value whose top bit is set (i.e., >= 0x80) will
905 * explicitly set the encoding to the same encoding as the source.
906 * Alternatively, if a unicode escape sequence is used (e.g., \\u{80}) that
907 * resolves to a value whose top bit is set, then the encoding will be
908 * explicitly set to UTF-8.
909 *
910 * The _next_ time this happens, if the encoding that is about to become the
911 * explicitly set encoding does not match the previously set explicit
912 * encoding, a mixed encoding error will be emitted.
913 *
914 * When the expression is finished being lexed, the explicit encoding
915 * controls the encoding of the expression. For the most part this means
916 * that the expression will either be encoded in the source encoding or
917 * UTF-8. This holds for all encodings except US-ASCII. If the source is
918 * US-ASCII and an explicit encoding was set that was _not_ UTF-8, then the
919 * expression will be encoded as ASCII-8BIT.
920 *
921 * Note that if the expression is a list, different elements within the same
922 * list can have different encodings, so this will get reset between each
923 * element. Furthermore all of this only applies to lists that support
924 * interpolation, because otherwise escapes that could change the encoding
925 * are ignored.
926 *
927 * At first glance, it may make more sense for this to live on the lexer
928 * mode, but we need it here to communicate back to the parser for character
929 * literals that do not push a new lexer mode.
930 */
931 const pm_encoding_t *explicit_encoding;
932
933 /*
934 * When parsing block exits (e.g., break, next, redo), we need to validate
935 * that they are in correct contexts. For the most part we can do this by
936 * looking at our parent contexts. However, modifier while and until
937 * expressions can change that context to make block exits valid. In these
938 * cases, we need to keep track of the block exits and then validate them
939 * after the expression has been parsed.
940 *
941 * We use a pointer here because we don't want to keep a whole list attached
942 * since this will only be used in the context of begin/end expressions.
943 */
944 pm_scratch_node_list_t *current_block_exits;
945
946 /*
947 * The address of the C stack when pm_parse was entered. The stack budget
948 * is measured as the distance from this address.
949 */
950 uintptr_t stack_base;
951
952 /*
953 * The number of bytes of C stack below stack_base that the recursive
954 * descent may use before it reports that the stack is exhausted. SIZE_MAX
955 * when no budget was given, so the check never fires.
956 */
957 size_t stack_budget;
958
959 /* The version of prism that we should use to parse. */
960 pm_options_version_t version;
961
962 /* The command line flags given from the options. */
963 uint8_t command_line;
964
965 /*
966 * Whether or not we have found a frozen_string_literal magic comment with
967 * a true or false value.
968 * May be:
969 * - PM_OPTIONS_FROZEN_STRING_LITERAL_DISABLED
970 * - PM_OPTIONS_FROZEN_STRING_LITERAL_ENABLED
971 * - PM_OPTIONS_FROZEN_STRING_LITERAL_UNSET
972 */
973 int8_t frozen_string_literal;
974
975 /*
976 * Whether or not we are parsing an eval string. This impacts whether or not
977 * we should evaluate if block exits/yields are valid.
978 */
979 bool parsing_eval;
980
981 /*
982 * Whether or not we are parsing a "partial" script, which is a script that
983 * will be evaluated in the context of another script, so we should not
984 * check jumps (next/break/etc.) for validity.
985 */
986 bool partial_script;
987
988 /*
989 * Whether or not comments should be attached to their owning nodes once
990 * parsing has finished.
991 */
992 bool attach_comments;
993
994 /* Whether or not we're at the beginning of a command. */
995 bool command_start;
996
997 /*
998 * Whether or not we're currently parsing the body of an endless method
999 * definition. In this context, PM_TOKEN_KEYWORD_DO_BLOCK should not be
1000 * consumed by commands (it should bubble up to the outer context).
1001 */
1002 bool in_endless_def_body;
1003
1004 /* Whether or not we're currently recovering from a syntax error. */
1005 bool recovering;
1006
1007 /*
1008 * Whether or not the source being parsed could become valid if more input
1009 * were appended. This is set to false when the parser encounters a token
1010 * that is definitively wrong (e.g., a stray `end` or `]`) as opposed to
1011 * merely incomplete.
1012 */
1013 bool continuable;
1014
1015 /*
1016 * This is very specialized behavior for when you want to parse in a context
1017 * that does not respect encoding comments. Its main use case is translating
1018 * into the whitequark/parser AST which re-encodes source files in UTF-8
1019 * before they are parsed and ignores encoding comments.
1020 */
1021 bool encoding_locked;
1022
1023 /*
1024 * Whether or not the encoding has been changed by a magic comment. We use
1025 * this to provide a fast path for the lexer instead of going through the
1026 * function pointer.
1027 */
1028 bool encoding_changed;
1029
1030 /* In bare method parameters and patterns, a newline after a label
1031 * terminates the expression. Braced hash patterns clear this flag. */
1032 bool in_keyword_arg;
1033
1034 /*
1035 * Whether or not the parser has seen a token that has semantic meaning
1036 * (i.e., a token that is not a comment or whitespace).
1037 */
1038 bool semantic_token_seen;
1039
1040 /*
1041 * By default, Ruby always warns about mismatched indentation. This can be
1042 * toggled with a magic comment.
1043 */
1044 bool warn_mismatched_indentation;
1045
1046 /*
1047 * Whether the stack exhausted error has been reported. Once the budget is
1048 * used up, every recursion that unwinds past it would report the error
1049 * again, so it is only reported the first time.
1050 */
1051 bool stack_exhausted_reported;
1052
1053#if defined(PRISM_HAS_NEON) || defined(PRISM_HAS_SSE2) || defined(PRISM_HAS_SWAR)
1054 /* Breakpoint lookup tables shared by the ASCII and encoding-aware scanners. */
1055 struct {
1056 /* The NUL-padded charset used to build the lookup tables. */
1057 uint8_t charset[PM_STRPBRK_CACHE_SIZE];
1058
1059 /* Nibble-based low lookup table for SIMD matching. */
1060 uint8_t low_lut[16];
1061
1062 /* Nibble-based high lookup table for SIMD matching. */
1063 uint8_t high_lut[16];
1064
1065 /* One bit per byte for scalar breakpoint checks. */
1066 uint64_t table[4];
1067 } strpbrk_cache;
1068#endif
1069};
1070
1071/*
1072 * Initialize a parser with the given start and end pointers.
1073 */
1074void pm_parser_init(pm_arena_t *arena, pm_parser_t *parser, const uint8_t *source, size_t size, const pm_options_t *options);
1075
1076/*
1077 * Free the memory held by the given parser.
1078 *
1079 * This does not free the `pm_options_t` object that was used to initialize the
1080 * parser.
1081 */
1082void pm_parser_cleanup(pm_parser_t *parser);
1083
1084/* A non-ASCII source character or byte escape fixes the literal to the source
1085 * encoding. A preceding Unicode escape may already have fixed it to UTF-8. */
1086void pm_parser_explicit_encoding_set(pm_parser_t *parser, uint32_t start, uint32_t length);
1087
1088/*
1089 * Returns true if the bytes between start and end spell a keyword, using the
1090 * same lookup that the lexer does.
1091 */
1092bool pm_keyword_p(const uint8_t *start, const uint8_t *end);
1093
1094/*
1095 * Returns true if parsing has used more C stack since pm_parse was entered than
1096 * the stack budget allows. Every recursion that runs inside pm_parse checks
1097 * this alongside its own depth limit, so that the budget bounds all of them.
1098 * The distance is taken without assuming which direction the stack grows. With
1099 * no budget the limit is SIZE_MAX, so this never fires.
1100 */
1101static PRISM_INLINE bool
1102pm_parser_stack_exhausted(const pm_parser_t *parser) {
1103 uintptr_t current = pm_stack_address();
1104 uintptr_t used = current < parser->stack_base ? parser->stack_base - current : current - parser->stack_base;
1105 return used > parser->stack_budget;
1106}
1107
1108/*
1109 * Reports that the stack budget has been used up, at the given location. This
1110 * is a separate error from the nesting depth limit, with its own error level,
1111 * because the source may be valid and parse with more stack. It is reported
1112 * once per parse.
1113 */
1114void pm_parser_err_stack_exhausted(pm_parser_t *parser, uint32_t start, uint32_t length);
1115
1116#endif
uint32_t pm_constant_id_t
A constant id is a unique identifier for a constant in the constant pool.
#define PRISM_INLINE
Old Visual Studio versions do not support the inline keyword, so we need to define it to be __inline.
Definition inline.h:12
A list of byte offsets of newlines in a string.
The parser used to parse Ruby source.
void(* pm_lex_callback_t)(pm_parser_t *parser, pm_token_t *token, void *data)
This is the callback that is called when a token is lexed.
Definition parser.h:59
void(* pm_encoding_changed_callback_t)(pm_parser_t *parser)
When the encoding that is being used to parse the source is changed by prism, we provide the ability ...
Definition parser.h:53
static PRISM_INLINE uintptr_t pm_stack_address(void)
Returns the current position of the C stack, for measuring how much of it has been consumed since an ...
Definition stack.h:34
C99 shim for <stdbool.h>.
A list of offsets of the start of lines in a string.
This struct represents a slice in the source code, defined by an offset and a length.
Definition ast.h:579
A view of a sequence of bytes.
Definition stringy.h:23
This struct represents a token in the Ruby source.
Definition ast.h:551