Debian Codegraph @

lib/prism/lex_compat.rb

raw symbols SCIP
1 # frozen_string_literal: true
2 # :markup: markdown
3
4 module Prism
5 # This class is responsible for lexing the source using prism and then
6 # converting those tokens to be compatible with Ripper. In the vast majority
7 # of cases, this is a one-to-one mapping of the token type. Everything else
8 # generally lines up. However, there are a few cases that require special
9 # handling.
10 class LexCompat # :nodoc:
11 # A result class specialized for holding tokens produced by the lexer.
12 class Result < Prism::Result
13 # The list of tokens that were produced by the lexer.
14 attr_reader :value
15
16 # Create a new lex compat result object with the given values.
17 def initialize(value, comments, magic_comments, data_loc, errors, warnings, source)
18 @value = value
19 super(comments, magic_comments, data_loc, errors, warnings, source)
20 end
21
22 # Implement the hash pattern matching interface for Result.
23 def deconstruct_keys(keys)
24 super.merge!(value: value)
25 end
26 end
27
28 # This is a mapping of prism token types to Ripper token types. This is a
29 # many-to-one mapping because we split up our token types, whereas Ripper
30 # tends to group them.
31 RIPPER = {
32 AMPERSAND: :on_op,
33 AMPERSAND_AMPERSAND: :on_op,
34 AMPERSAND_AMPERSAND_EQUAL: :on_op,
35 AMPERSAND_DOT: :on_op,
36 AMPERSAND_EQUAL: :on_op,
37 BACK_REFERENCE: :on_backref,
38 BACKTICK: :on_backtick,
39 BANG: :on_op,
40 BANG_EQUAL: :on_op,
41 BANG_TILDE: :on_op,
42 BRACE_LEFT: :on_lbrace,
43 BRACE_RIGHT: :on_rbrace,
44 BRACKET_LEFT: :on_lbracket,
45 BRACKET_LEFT_ARRAY: :on_lbracket,
46 BRACKET_LEFT_RIGHT: :on_op,
47 BRACKET_LEFT_RIGHT_EQUAL: :on_op,
48 BRACKET_RIGHT: :on_rbracket,
49 CARET: :on_op,
50 CARET_EQUAL: :on_op,
51 CHARACTER_LITERAL: :on_CHAR,
52 CLASS_VARIABLE: :on_cvar,
53 COLON: :on_op,
54 COLON_COLON: :on_op,
55 COMMA: :on_comma,
56 COMMENT: :on_comment,
57 CONSTANT: :on_const,
58 DOT: :on_period,
59 DOT_DOT: :on_op,
60 DOT_DOT_DOT: :on_op,
61 EMBDOC_BEGIN: :on_embdoc_beg,
62 EMBDOC_END: :on_embdoc_end,
63 EMBDOC_LINE: :on_embdoc,
64 EMBEXPR_BEGIN: :on_embexpr_beg,
65 EMBEXPR_END: :on_embexpr_end,
66 EMBVAR: :on_embvar,
67 EOF: :on_eof,
68 EQUAL: :on_op,
69 EQUAL_EQUAL: :on_op,
70 EQUAL_EQUAL_EQUAL: :on_op,
71 EQUAL_GREATER: :on_op,
72 EQUAL_TILDE: :on_op,
73 FLOAT: :on_float,
74 FLOAT_IMAGINARY: :on_imaginary,
75 FLOAT_RATIONAL: :on_rational,
76 FLOAT_RATIONAL_IMAGINARY: :on_imaginary,
77 GREATER: :on_op,
78 GREATER_EQUAL: :on_op,
79 GREATER_GREATER: :on_op,
80 GREATER_GREATER_EQUAL: :on_op,
81 GLOBAL_VARIABLE: :on_gvar,
82 HEREDOC_END: :on_heredoc_end,
83 HEREDOC_START: :on_heredoc_beg,
84 IDENTIFIER: :on_ident,
85 IGNORED_NEWLINE: :on_ignored_nl,
86 INTEGER: :on_int,
87 INTEGER_IMAGINARY: :on_imaginary,
88 INTEGER_RATIONAL: :on_rational,
89 INTEGER_RATIONAL_IMAGINARY: :on_imaginary,
90 INSTANCE_VARIABLE: :on_ivar,
91 INVALID: :INVALID,
92 KEYWORD___ENCODING__: :on_kw,
93 KEYWORD___LINE__: :on_kw,
94 KEYWORD___FILE__: :on_kw,
95 KEYWORD_ALIAS: :on_kw,
96 KEYWORD_AND: :on_kw,
97 KEYWORD_BEGIN: :on_kw,
98 KEYWORD_BEGIN_UPCASE: :on_kw,
99 KEYWORD_BREAK: :on_kw,
100 KEYWORD_CASE: :on_kw,
101 KEYWORD_CLASS: :on_kw,
102 KEYWORD_DEF: :on_kw,
103 KEYWORD_DEFINED: :on_kw,
104 KEYWORD_DO: :on_kw,
105 KEYWORD_DO_LOOP: :on_kw,
106 KEYWORD_ELSE: :on_kw,
107 KEYWORD_ELSIF: :on_kw,
108 KEYWORD_END: :on_kw,
109 KEYWORD_END_UPCASE: :on_kw,
110 KEYWORD_ENSURE: :on_kw,
111 KEYWORD_FALSE: :on_kw,
112 KEYWORD_FOR: :on_kw,
113 KEYWORD_IF: :on_kw,
114 KEYWORD_IF_MODIFIER: :on_kw,
115 KEYWORD_IN: :on_kw,
116 KEYWORD_MODULE: :on_kw,
117 KEYWORD_NEXT: :on_kw,
118 KEYWORD_NIL: :on_kw,
119 KEYWORD_NOT: :on_kw,
120 KEYWORD_OR: :on_kw,
121 KEYWORD_REDO: :on_kw,
122 KEYWORD_RESCUE: :on_kw,
123 KEYWORD_RESCUE_MODIFIER: :on_kw,
124 KEYWORD_RETRY: :on_kw,
125 KEYWORD_RETURN: :on_kw,
126 KEYWORD_SELF: :on_kw,
127 KEYWORD_SUPER: :on_kw,
128 KEYWORD_THEN: :on_kw,
129 KEYWORD_TRUE: :on_kw,
130 KEYWORD_UNDEF: :on_kw,
131 KEYWORD_UNLESS: :on_kw,
132 KEYWORD_UNLESS_MODIFIER: :on_kw,
133 KEYWORD_UNTIL: :on_kw,
134 KEYWORD_UNTIL_MODIFIER: :on_kw,
135 KEYWORD_WHEN: :on_kw,
136 KEYWORD_WHILE: :on_kw,
137 KEYWORD_WHILE_MODIFIER: :on_kw,
138 KEYWORD_YIELD: :on_kw,
139 LABEL: :on_label,
140 LABEL_END: :on_label_end,
141 LAMBDA_BEGIN: :on_tlambeg,
142 LESS: :on_op,
143 LESS_EQUAL: :on_op,
144 LESS_EQUAL_GREATER: :on_op,
145 LESS_LESS: :on_op,
146 LESS_LESS_EQUAL: :on_op,
147 METHOD_NAME: :on_ident,
148 MINUS: :on_op,
149 MINUS_EQUAL: :on_op,
150 MINUS_GREATER: :on_tlambda,
151 NEWLINE: :on_nl,
152 NUMBERED_REFERENCE: :on_backref,
153 PARENTHESIS_LEFT: :on_lparen,
154 PARENTHESIS_LEFT_PARENTHESES: :on_lparen,
155 PARENTHESIS_RIGHT: :on_rparen,
156 PERCENT: :on_op,
157 PERCENT_EQUAL: :on_op,
158 PERCENT_LOWER_I: :on_qsymbols_beg,
159 PERCENT_LOWER_W: :on_qwords_beg,
160 PERCENT_LOWER_X: :on_backtick,
161 PERCENT_UPPER_I: :on_symbols_beg,
162 PERCENT_UPPER_W: :on_words_beg,
163 PIPE: :on_op,
164 PIPE_EQUAL: :on_op,
165 PIPE_PIPE: :on_op,
166 PIPE_PIPE_EQUAL: :on_op,
167 PLUS: :on_op,
168 PLUS_EQUAL: :on_op,
169 QUESTION_MARK: :on_op,
170 RATIONAL_FLOAT: :on_rational,
171 RATIONAL_INTEGER: :on_rational,
172 REGEXP_BEGIN: :on_regexp_beg,
173 REGEXP_END: :on_regexp_end,
174 SEMICOLON: :on_semicolon,
175 SLASH: :on_op,
176 SLASH_EQUAL: :on_op,
177 STAR: :on_op,
178 STAR_EQUAL: :on_op,
179 STAR_STAR: :on_op,
180 STAR_STAR_EQUAL: :on_op,
181 STRING_BEGIN: :on_tstring_beg,
182 STRING_CONTENT: :on_tstring_content,
183 STRING_END: :on_tstring_end,
184 SYMBOL_BEGIN: :on_symbeg,
185 TILDE: :on_op,
186 UAMPERSAND: :on_op,
187 UCOLON_COLON: :on_op,
188 UDOT_DOT: :on_op,
189 UDOT_DOT_DOT: :on_op,
190 UMINUS: :on_op,
191 UMINUS_NUM: :on_op,
192 UPLUS: :on_op,
193 USTAR: :on_op,
194 USTAR_STAR: :on_op,
195 WORDS_SEP: :on_words_sep,
196 "__END__": :on___end__
197 }.freeze
198
199 # When we produce tokens, we produce the same arrays that Ripper does.
200 # However, we add a couple of convenience methods onto them to make them a
201 # little easier to work with. We delegate all other methods to the array.
202 class Token < BasicObject
203 # Create a new token object with the given ripper-compatible array.
204 def initialize(array)
205 @array = array
206 end
207
208 # The location of the token in the source.
209 def location
210 @array[0]
211 end
212
213 # The type of the token.
214 def event
215 @array[1]
216 end
217
218 # The slice of the source that this token represents.
219 def value
220 @array[2]
221 end
222
223 # The state of the lexer when this token was produced.
224 def state
225 @array[3]
226 end
227
228 # We want to pretend that this is just an Array.
229 def ==(other) # :nodoc:
230 @array == other
231 end
232
233 def respond_to_missing?(name, include_private = false) # :nodoc:
234 @array.respond_to?(name, include_private)
235 end
236
237 def method_missing(name, ...) # :nodoc:
238 @array.send(name, ...)
239 end
240 end
241
242 # Tokens where state should be ignored
243 # used for :on_sp, :on_comment, :on_heredoc_end, :on_embexpr_end
244 class IgnoreStateToken < Token
245 def ==(other) # :nodoc:
246 self[0...-1] == other[0...-1]
247 end
248 end
249
250 # A heredoc in this case is a list of tokens that belong to the body of the
251 # heredoc that should be appended onto the list of tokens when the heredoc
252 # closes.
253 module Heredoc # :nodoc:
254 # Heredocs that are no dash or tilde heredocs are just a list of tokens.
255 # We need to keep them around so that we can insert them in the correct
256 # order back into the token stream and set the state of the last token to
257 # the state that the heredoc was opened in.
258 class PlainHeredoc # :nodoc:
259 attr_reader :tokens
260
261 def initialize
262 @tokens = []
263 end
264
265 def <<(token)
266 tokens << token
267 end
268
269 def to_a
270 tokens
271 end
272 end
273
274 # Dash heredocs are a little more complicated. They are a list of tokens
275 # that need to be split on "\\\n" to mimic Ripper's behavior. We also need
276 # to keep track of the state that the heredoc was opened in.
277 class DashHeredoc # :nodoc:
278 attr_reader :split, :tokens
279
280 def initialize(split)
281 @split = split
282 @tokens = []
283 end
284
285 def <<(token)
286 tokens << token
287 end
288
289 def to_a
290 embexpr_balance = 0
291
292 tokens.each_with_object([]) do |token, results| #$ Array[Token]
293 case token.event
294 when :on_embexpr_beg
295 embexpr_balance += 1
296 results << token
297 when :on_embexpr_end
298 embexpr_balance -= 1
299 results << token
300 when :on_tstring_content
301 if embexpr_balance == 0
302 lineno = token[0][0]
303 column = token[0][1]
304
305 if split
306 # Split on "\\\n" to mimic Ripper's behavior. Use a lookbehind
307 # to keep the delimiter in the result.
308 token.value.split(/(?<=[^\\]\\\n)|(?<=[^\\]\\\r\n)/).each_with_index do |value, index|
309 column = 0 if index > 0
310 results << Token.new([[lineno, column], :on_tstring_content, value, token.state])
311 lineno += value.count("\n")
312 end
313 else
314 results << token
315 end
316 else
317 results << token
318 end
319 else
320 results << token
321 end
322 end
323 end
324 end
325
326 # Heredocs that are dedenting heredocs are a little more complicated.
327 # Ripper outputs on_ignored_sp tokens for the whitespace that is being
328 # removed from the output. prism only modifies the node itself and keeps
329 # the token the same. This simplifies prism, but makes comparing against
330 # Ripper much harder because there is a length mismatch.
331 #
332 # Fortunately, we already have to pull out the heredoc tokens in order to
333 # insert them into the stream in the correct order. As such, we can do
334 # some extra manipulation on the tokens to make them match Ripper's
335 # output by mirroring the dedent logic that Ripper uses.
336 class DedentingHeredoc # :nodoc:
337 TAB_WIDTH = 8
338
339 attr_reader :tokens, :dedent_next, :dedent, :embexpr_balance
340
341 def initialize
342 @tokens = []
343 @dedent_next = true
344 @dedent = nil
345 @embexpr_balance = 0
346 @ended_on_newline = false
347 end
348
349 # As tokens are coming in, we track the minimum amount of common leading
350 # whitespace on plain string content tokens. This allows us to later
351 # remove that amount of whitespace from the beginning of each line.
352 def <<(token)
353 case token.event
354 when :on_embexpr_beg, :on_heredoc_beg
355 @embexpr_balance += 1
356 @dedent = 0 if @dedent_next && @ended_on_newline
357 when :on_embexpr_end, :on_heredoc_end
358 @embexpr_balance -= 1
359 when :on_tstring_content
360 if embexpr_balance == 0
361 line = token.value
362
363 if dedent_next && !(line.strip.empty? && line.end_with?("\n"))
364 leading = line[/\A(\s*)\n?/, 1]
365 next_dedent = 0
366
367 leading.each_char do |char|
368 if char == "\t"
369 next_dedent = next_dedent - (next_dedent % TAB_WIDTH) + TAB_WIDTH
370 else
371 next_dedent += 1
372 end
373 end
374
375 @dedent = [dedent, next_dedent].compact.min
376 @dedent_next = true
377 @ended_on_newline = line.end_with?("\n")
378 tokens << token
379 return
380 end
381 end
382 end
383
384 @dedent_next = token.event == :on_tstring_content && embexpr_balance == 0
385 @ended_on_newline = false
386 tokens << token
387 end
388
389 def to_a
390 # If every line in the heredoc is blank, we still need to split up the
391 # string content token into multiple tokens.
392 if dedent.nil?
393 results = [] #: Array[Token]
394 embexpr_balance = 0
395
396 tokens.each do |token|
397 case token.event
398 when :on_embexpr_beg, :on_heredoc_beg
399 embexpr_balance += 1
400 results << token
401 when :on_embexpr_end, :on_heredoc_end
402 embexpr_balance -= 1
403 results << token
404 when :on_tstring_content
405 if embexpr_balance == 0
406 lineno = token[0][0]
407 column = token[0][1]
408
409 token.value.split(/(?<=\n)/).each_with_index do |value, index|
410 column = 0 if index > 0
411 results << Token.new([[lineno, column], :on_tstring_content, value, token.state])
412 lineno += 1
413 end
414 else
415 results << token
416 end
417 else
418 results << token
419 end
420 end
421
422 return results
423 end
424
425 # If the minimum common whitespace is 0, then we need to concatenate
426 # string nodes together that are immediately adjacent.
427 if dedent == 0
428 results = [] #: Array[Token]
429 embexpr_balance = 0
430
431 index = 0
432 max_index = tokens.length
433
434 while index < max_index
435 token = tokens[index]
436 results << token
437 index += 1
438
439 case token.event
440 when :on_embexpr_beg, :on_heredoc_beg
441 embexpr_balance += 1
442 when :on_embexpr_end, :on_heredoc_end
443 embexpr_balance -= 1
444 when :on_tstring_content
445 if embexpr_balance == 0
446 while index < max_index && tokens[index].event == :on_tstring_content && !token.value.match?(/\\\r?\n\z/)
447 token.value << tokens[index].value
448 index += 1
449 end
450 end
451 end
452 end
453
454 return results
455 end
456
457 # Otherwise, we're going to run through each token in the list and
458 # insert on_ignored_sp tokens for the amount of dedent that we need to
459 # perform. We also need to remove the dedent from the beginning of
460 # each line of plain string content tokens.
461 results = [] #: Array[Token]
462 dedent_next = true
463 embexpr_balance = 0
464
465 tokens.each do |token|
466 # Notice that the structure of this conditional largely matches the
467 # whitespace calculation we performed above. This is because
468 # checking if the subsequent token needs to be dedented is common to
469 # both the dedent calculation and the ignored_sp insertion.
470 case token.event
471 when :on_embexpr_beg
472 embexpr_balance += 1
473 results << token
474 when :on_embexpr_end
475 embexpr_balance -= 1
476 results << token
477 when :on_tstring_content
478 if embexpr_balance == 0
479 # Here we're going to split the string on newlines, but maintain
480 # the newlines in the resulting array. We'll do that with a look
481 # behind assertion.
482 splits = token.value.split(/(?<=\n)/)
483 index = 0
484
485 while index < splits.length
486 line = splits[index]
487 lineno = token[0][0] + index
488 column = token[0][1]
489
490 # Blank lines do not count toward common leading whitespace
491 # calculation and do not need to be dedented.
492 if dedent_next || index > 0
493 column = 0
494 end
495
496 # If the dedent is 0 and we're not supposed to dedent the next
497 # line or this line doesn't start with whitespace, then we
498 # should concatenate the rest of the string to match ripper.
499 if dedent == 0 && (!dedent_next || !line.start_with?(/\s/))
500 line = splits[index..].join
501 index = splits.length
502 end
503
504 # If we are supposed to dedent this line or if this is not the
505 # first line of the string and this line isn't entirely blank,
506 # then we need to insert an on_ignored_sp token and remove the
507 # dedent from the beginning of the line.
508 if (dedent > 0) && (dedent_next || index > 0)
509 deleting = 0
510 deleted_chars = [] #: Array[String]
511
512 # Gather up all of the characters that we're going to
513 # delete, stopping when you hit a character that would put
514 # you over the dedent amount.
515 line.each_char.with_index do |char, i|
516 case char
517 when "\r"
518 if line[i + 1] == "\n"
519 break
520 end
521 when "\n"
522 break
523 when "\t"
524 deleting = deleting - (deleting % TAB_WIDTH) + TAB_WIDTH
525 else
526 deleting += 1
527 end
528
529 break if deleting > dedent
530 deleted_chars << char
531 end
532
533 # If we have something to delete, then delete it from the
534 # string and insert an on_ignored_sp token.
535 if deleted_chars.any?
536 ignored = deleted_chars.join
537 line.delete_prefix!(ignored)
538
539 results << Token.new([[lineno, 0], :on_ignored_sp, ignored, token[3]])
540 column = ignored.length
541 end
542 end
543
544 results << Token.new([[lineno, column], token[1], line, token[3]]) unless line.empty?
545 index += 1
546 end
547 else
548 results << token
549 end
550 else
551 results << token
552 end
553
554 dedent_next =
555 ((token.event == :on_tstring_content) || (token.event == :on_heredoc_end)) &&
556 embexpr_balance == 0
557 end
558
559 results
560 end
561 end
562
563 # Here we will split between the two types of heredocs and return the
564 # object that will store their tokens.
565 def self.build(opening)
566 case opening.value[2]
567 when "~"
568 DedentingHeredoc.new
569 when "-"
570 DashHeredoc.new(opening.value[3] != "'")
571 else
572 PlainHeredoc.new
573 end
574 end
575 end
576
577 private_constant :Heredoc
578
579 # In previous versions of Ruby, Ripper wouldn't flush the bom before the
580 # first token, so we had to have a hack in place to account for that.
581 BOM_FLUSHED = RUBY_VERSION >= "3.3.0"
582 private_constant :BOM_FLUSHED
583
584 attr_reader :options
585
586 def initialize(code, **options)
587 @code = code
588 @options = options
589 end
590
591 def result
592 tokens = [] #: Array[LexCompat::Token]
593
594 state = :default
595 heredoc_stack = [[]] #: Array[Array[Heredoc::PlainHeredoc | Heredoc::DashHeredoc | Heredoc::DedentingHeredoc]]
596
597 result = Prism.lex(@code, **options)
598 source = result.source
599 result_value = result.value
600 previous_state = nil #: State?
601 last_heredoc_end = nil #: Integer?
602 eof_token = nil
603
604 bom = source.slice(0, 3) == "\xEF\xBB\xBF"
605
606 result_value.each_with_index do |(token, lex_state), index|
607 lineno = token.location.start_line
608 column = token.location.start_column
609
610 # If there's a UTF-8 byte-order mark as the start of the file, then for
611 # certain tokens ripper sets the first token back by 3 bytes. It also
612 # keeps the byte order mark in the first token's value. This is weird,
613 # and I don't want to mirror that in our parser. So instead, we'll match
614 # up the columns and values here.
615 if bom && lineno == 1
616 column -= 3
617
618 if index == 0 && column == 0 && !BOM_FLUSHED
619 flushed =
620 case token.type
621 when :BACK_REFERENCE, :INSTANCE_VARIABLE, :CLASS_VARIABLE,
622 :GLOBAL_VARIABLE, :NUMBERED_REFERENCE, :PERCENT_LOWER_I,
623 :PERCENT_LOWER_X, :PERCENT_LOWER_W, :PERCENT_UPPER_I,
624 :PERCENT_UPPER_W, :STRING_BEGIN
625 true
626 when :REGEXP_BEGIN, :SYMBOL_BEGIN
627 token.value.start_with?("%")
628 else
629 false
630 end
631
632 unless flushed
633 column -= 3
634 value = token.value
635 value.prepend(String.new("\xEF\xBB\xBF", encoding: value.encoding))
636 end
637 end
638 end
639
640 event = RIPPER.fetch(token.type)
641 value = token.value
642 lex_state = Translation::Ripper::Lexer::State.cached(lex_state)
643
644 token =
645 case event
646 when :on___end__
647 # Ripper doesn't include the rest of the token in the event, so we need to
648 # trim it down to just the content on the first line.
649 value = value[0..value.index("\n")]
650 Token.new([[lineno, column], event, value, lex_state])
651 when :on_comment
652 IgnoreStateToken.new([[lineno, column], event, value, lex_state])
653 when :on_heredoc_end
654 # Heredoc end tokens can be emitted in an odd order, so we don't
655 # want to bother comparing the state on them.
656 last_heredoc_end = token.location.end_offset
657 IgnoreStateToken.new([[lineno, column], event, value, lex_state])
658 when :on_embexpr_end
659 IgnoreStateToken.new([[lineno, column], event, value, lex_state])
660 when :on_words_sep
661 # Ripper emits one token each per line.
662 value.each_line.with_index do |line, index|
663 if index > 0
664 lineno += 1
665 column = 0
666 end
667 tokens << Token.new([[lineno, column], event, line, lex_state])
668 end
669 tokens.pop
670 when :on_regexp_end
671 # On regex end, Ripper scans and then sets end state, so the ripper
672 # lexed output is begin, when it should be end. prism sets lex state
673 # correctly to end state, but we want to be able to compare against
674 # Ripper's lexed state. So here, if it's a regexp end token, we
675 # output the state as the previous state, solely for the sake of
676 # comparison.
677 previous_token = result_value[index - 1][0]
678 lex_state =
679 if RIPPER.fetch(previous_token.type) == :on_embexpr_end
680 # If the previous token is embexpr_end, then we have to do even
681 # more processing. The end of an embedded expression sets the
682 # state to the state that it had at the beginning of the
683 # embedded expression. So we have to go and find that state and
684 # set it here.
685 counter = 1
686 current_index = index - 1
687
688 until counter == 0
689 current_index -= 1
690 current_event = RIPPER.fetch(result_value[current_index][0].type)
691 counter += { on_embexpr_beg: -1, on_embexpr_end: 1 }[current_event] || 0
692 end
693
694 Translation::Ripper::Lexer::State.cached(result_value[current_index][1])
695 else
696 previous_state
697 end
698
699 Token.new([[lineno, column], event, value, lex_state])
700 when :on_eof
701 eof_token = token
702 previous_token = result_value[index - 1][0]
703
704 # If we're at the end of the file and the previous token was a
705 # comment and there is still whitespace after the comment, then
706 # Ripper will append a on_nl token (even though there isn't
707 # necessarily a newline). We mirror that here.
708 if previous_token.type == :COMMENT
709 # If the comment is at the start of a heredoc: <<HEREDOC # comment
710 # then the comment's end_offset is up near the heredoc_beg.
711 # This is not the correct offset to use for figuring out if
712 # there is trailing whitespace after the last token.
713 # Use the greater offset of the two to determine the start of
714 # the trailing whitespace.
715 start_offset = [previous_token.location.end_offset, last_heredoc_end].compact.max
716 end_offset = token.location.start_offset
717
718 if start_offset < end_offset
719 if bom
720 start_offset += 3
721 end_offset += 3
722 end
723
724 tokens << Token.new([[lineno, 0], :on_nl, source.slice(start_offset, end_offset - start_offset), lex_state])
725 end
726 end
727
728 Token.new([[lineno, column], event, value, lex_state])
729 else
730 Token.new([[lineno, column], event, value, lex_state])
731 end
732
733 previous_state = lex_state
734
735 # The order in which tokens appear in our lexer is different from the
736 # order that they appear in Ripper. When we hit the declaration of a
737 # heredoc in prism, we skip forward and lex the rest of the content of
738 # the heredoc before going back and lexing at the end of the heredoc
739 # identifier.
740 #
741 # To match up to ripper, we keep a small state variable around here to
742 # track whether we're in the middle of a heredoc or not. In this way we
743 # can shuffle around the token to match Ripper's output.
744 case state
745 when :default
746 # The default state is when there are no heredocs at all. In this
747 # state we can append the token to the list of tokens and move on.
748 tokens << token
749
750 # If we get the declaration of a heredoc, then we open a new heredoc
751 # and move into the heredoc_opened state.
752 if event == :on_heredoc_beg
753 state = :heredoc_opened
754 heredoc_stack.last << Heredoc.build(token)
755 end
756 when :heredoc_opened
757 # The heredoc_opened state is when we've seen the declaration of a
758 # heredoc and are now lexing the body of the heredoc. In this state we
759 # push tokens onto the most recently created heredoc.
760 heredoc_stack.last.last << token
761
762 case event
763 when :on_heredoc_beg
764 # If we receive a heredoc declaration while lexing the body of a
765 # heredoc, this means we have nested heredocs. In this case we'll
766 # push a new heredoc onto the stack and stay in the heredoc_opened
767 # state since we're now lexing the body of the new heredoc.
768 heredoc_stack << [Heredoc.build(token)]
769 when :on_heredoc_end
770 # If we receive the end of a heredoc, then we're done lexing the
771 # body of the heredoc. In this case we now have a completed heredoc
772 # but need to wait for the next newline to push it into the token
773 # stream.
774 state = :heredoc_closed
775 end
776 when :heredoc_closed
777 if %i[on_nl on_ignored_nl on_comment].include?(event) || (event == :on_tstring_content && value.end_with?("\n"))
778 if heredoc_stack.size > 1
779 flushing = heredoc_stack.pop
780 heredoc_stack.last.last << token
781
782 flushing.each do |heredoc|
783 heredoc.to_a.each do |flushed_token|
784 heredoc_stack.last.last << flushed_token
785 end
786 end
787
788 state = :heredoc_opened
789 next
790 end
791 elsif event == :on_heredoc_beg
792 tokens << token
793 state = :heredoc_opened
794 heredoc_stack.last << Heredoc.build(token)
795 next
796 elsif heredoc_stack.size > 1
797 heredoc_stack[-2].last << token
798 next
799 end
800
801 heredoc_stack.last.each do |heredoc|
802 tokens.concat(heredoc.to_a)
803 end
804
805 heredoc_stack.last.clear
806 state = :default
807
808 tokens << token
809 end
810 end
811
812 # Drop the EOF token from the list
813 tokens = tokens[0...-1]
814
815 # We sort by location because Ripper.lex sorts.
816 # Manually implemented instead of `sort_by!(&:location)` for performance.
817 tokens.sort_by! do |token|
818 line, column = token.location
819 source.byte_offset(line, column)
820 end
821
822 # Add :on_sp tokens
823 tokens = add_on_sp_tokens(tokens, source, result.data_loc, bom, eof_token)
824
825 Result.new(tokens, result.comments, result.magic_comments, result.data_loc, result.errors, result.warnings, source)
826 end
827
828 def add_on_sp_tokens(tokens, source, data_loc, bom, eof_token)
829 new_tokens = []
830
831 prev_token_state = Translation::Ripper::Lexer::State.cached(Translation::Ripper::EXPR_BEG)
832 prev_token_end = bom ? 3 : 0
833
834 tokens.each do |token|
835 line, column = token.location
836 start_offset = source.byte_offset(line, column)
837
838 # Ripper reports columns on line 1 without counting the BOM, so we
839 # adjust to get the real offset
840 start_offset += 3 if line == 1 && bom
841
842 if start_offset > prev_token_end
843 sp_value = source.slice(prev_token_end, start_offset - prev_token_end)
844 sp_line = source.line(prev_token_end)
845 sp_column = source.column(prev_token_end)
846 # Ripper reports columns on line 1 without counting the BOM
847 sp_column -= 3 if sp_line == 1 && bom
848 continuation_index = sp_value.byteindex("\\")
849
850 # ripper emits up to three :on_sp tokens when line continuations are used
851 if continuation_index
852 next_whitespace_index = continuation_index + 1
853 next_whitespace_index += 1 if sp_value.byteslice(next_whitespace_index) == "\r"
854 next_whitespace_index += 1
855 first_whitespace = sp_value[0...continuation_index]
856 continuation = sp_value[continuation_index...next_whitespace_index]
857 second_whitespace = sp_value[next_whitespace_index..]
858
859 new_tokens << IgnoreStateToken.new([
860 [sp_line, sp_column],
861 :on_sp,
862 first_whitespace,
863 prev_token_state
864 ]) unless first_whitespace.empty?
865
866 new_tokens << IgnoreStateToken.new([
867 [sp_line, sp_column + continuation_index],
868 :on_sp,
869 continuation,
870 prev_token_state
871 ])
872
873 new_tokens << IgnoreStateToken.new([
874 [sp_line + 1, 0],
875 :on_sp,
876 second_whitespace,
877 prev_token_state
878 ]) unless second_whitespace.empty?
879 else
880 new_tokens << IgnoreStateToken.new([
881 [sp_line, sp_column],
882 :on_sp,
883 sp_value,
884 prev_token_state
885 ])
886 end
887 end
888
889 new_tokens << token
890 prev_token_state = token.state
891 prev_token_end = start_offset + token.value.bytesize
892 end
893
894 unless data_loc # no trailing :on_sp with __END__ as it is always preceded by :on_nl
895 end_offset = eof_token.location.end_offset
896 if prev_token_end < end_offset
897 new_tokens << IgnoreStateToken.new([
898 [source.line(prev_token_end), source.column(prev_token_end)],
899 :on_sp,
900 source.slice(prev_token_end, end_offset - prev_token_end),
901 prev_token_state
902 ])
903 end
904 end
905
906 new_tokens
907 end
908 end
909
910 private_constant :LexCompat
911 end