Coverage Report

Created: 2026-11-10 14:14

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