Debian Codegraph @

lib/prism/parse_result.rb

raw symbols SCIP
1 # frozen_string_literal: true
2 # :markup: markdown
3
4 module Prism
5 # This represents a source of Ruby code that has been parsed. It is used in
6 # conjunction with locations to allow them to resolve line numbers and source
7 # ranges.
8 class Source
9 # Create a new source object with the given source code. This method should
10 # be used instead of `new` and it will return either a `Source` or a
11 # specialized and more performant `ASCIISource` if no multibyte characters
12 # are present in the source code.
13 def self.for(source, start_line = 1, offsets = [])
14 if source.ascii_only?
15 ASCIISource.new(source, start_line, offsets)
16 elsif source.encoding == Encoding::BINARY
17 source.force_encoding(Encoding::UTF_8)
18
19 if source.valid_encoding?
20 new(source, start_line, offsets)
21 else
22 # This is an extremely niche use case where the file is marked as
23 # binary, contains multi-byte characters, and those characters are not
24 # valid UTF-8. In this case we'll mark it as binary and fall back to
25 # treating everything as a single-byte character. This _may_ cause
26 # problems when asking for code units, but it appears to be the
27 # cleanest solution at the moment.
28 source.force_encoding(Encoding::BINARY)
29 ASCIISource.new(source, start_line, offsets)
30 end
31 else
32 new(source, start_line, offsets)
33 end
34 end
35
36 # The source code that this source object represents.
37 attr_reader :source
38
39 # The line number where this source starts.
40 attr_reader :start_line
41
42 # The list of newline byte offsets in the source code.
43 attr_reader :offsets
44
45 # Create a new source object with the given source code.
46 def initialize(source, start_line = 1, offsets = [])
47 @source = source
48 @start_line = start_line # set after parsing is done
49 @offsets = offsets # set after parsing is done
50 end
51
52 # Replace the value of start_line with the given value.
53 def replace_start_line(start_line)
54 @start_line = start_line
55 end
56
57 # Replace the value of offsets with the given value.
58 def replace_offsets(offsets)
59 @offsets.replace(offsets)
60 end
61
62 # Returns the encoding of the source code, which is set by parameters to the
63 # parser or by the encoding magic comment.
64 def encoding
65 source.encoding
66 end
67
68 # Returns the lines of the source code as an array of strings.
69 def lines
70 source.lines
71 end
72
73 # Perform a byteslice on the source code using the given byte offset and
74 # byte length.
75 def slice(byte_offset, length)
76 source.byteslice(byte_offset, length) or raise
77 end
78
79 # Converts the line number and column in bytes to a byte offset.
80 def byte_offset(line, column)
81 normal = line - @start_line
82 raise IndexError if normal < 0
83 offsets.fetch(normal) + column
84 rescue IndexError
85 raise ArgumentError, "line #{line} is out of range"
86 end
87
88 # Binary search through the offsets to find the line number for the given
89 # byte offset.
90 def line(byte_offset)
91 start_line + find_line(byte_offset)
92 end
93
94 # Return the byte offset of the start of the line corresponding to the given
95 # byte offset.
96 def line_start(byte_offset)
97 offsets[find_line(byte_offset)]
98 end
99
100 # Returns the byte offset of the end of the line corresponding to the given
101 # byte offset.
102 def line_end(byte_offset)
103 offsets[find_line(byte_offset) + 1] || source.bytesize
104 end
105
106 # Return the column number for the given byte offset.
107 def column(byte_offset)
108 byte_offset - line_start(byte_offset)
109 end
110
111 # Return the character offset for the given byte offset.
112 def character_offset(byte_offset)
113 (source.byteslice(0, byte_offset) or raise).length
114 end
115
116 # Return the column number in characters for the given byte offset.
117 def character_column(byte_offset)
118 character_offset(byte_offset) - character_offset(line_start(byte_offset))
119 end
120
121 # Returns the offset from the start of the file for the given byte offset
122 # counting in code units for the given encoding.
123 #
124 # This method is tested with UTF-8, UTF-16, and UTF-32. If there is the
125 # concept of code units that differs from the number of characters in other
126 # encodings, it is not captured here.
127 #
128 # We purposefully replace invalid and undefined characters with replacement
129 # characters in this conversion. This happens for two reasons. First, it's
130 # possible that the given byte offset will not occur on a character
131 # boundary. Second, it's possible that the source code will contain a
132 # character that has no equivalent in the given encoding.
133 def code_units_offset(byte_offset, encoding)
134 byteslice = (source.byteslice(0, byte_offset) or raise).encode(encoding, invalid: :replace, undef: :replace)
135
136 if encoding == Encoding::UTF_16LE || encoding == Encoding::UTF_16BE
137 byteslice.bytesize / 2
138 else
139 byteslice.length
140 end
141 end
142
143 # Generate a cache that targets a specific encoding for calculating code
144 # unit offsets.
145 def code_units_cache(encoding)
146 CodeUnitsCache.new(source, encoding)
147 end
148
149 # Returns the column number in code units for the given encoding for the
150 # given byte offset.
151 def code_units_column(byte_offset, encoding)
152 code_units_offset(byte_offset, encoding) - code_units_offset(line_start(byte_offset), encoding)
153 end
154
155 # Freeze this object and the objects it contains.
156 def deep_freeze
157 source.freeze
158 offsets.freeze
159 freeze
160 end
161
162 private
163
164 # Binary search through the offsets to find the line number for the given
165 # byte offset.
166 def find_line(byte_offset)
167 index = offsets.bsearch_index { |offset| offset > byte_offset } || offsets.length
168 index - 1
169 end
170 end
171
172 # A cache that can be used to quickly compute code unit offsets from byte
173 # offsets. It purposefully provides only a single #[] method to access the
174 # cache in order to minimize surface area.
175 #
176 # Note that there are some known issues here that may or may not be addressed
177 # in the future:
178 #
179 # * The first is that there are issues when the cache computes values that are
180 # not on character boundaries. This can result in subsequent computations
181 # being off by one or more code units.
182 # * The second is that this cache is currently unbounded. In theory we could
183 # introduce some kind of LRU cache to limit the number of entries, but this
184 # has not yet been implemented.
185 #
186 class CodeUnitsCache
187 class UTF16Counter # :nodoc:
188 def initialize(source, encoding)
189 @source = source
190 @encoding = encoding
191 end
192
193 def count(byte_offset, byte_length)
194 @source.byteslice(byte_offset, byte_length).encode(@encoding, invalid: :replace, undef: :replace).bytesize / 2
195 end
196 end
197
198 class LengthCounter # :nodoc:
199 def initialize(source, encoding)
200 @source = source
201 @encoding = encoding
202 end
203
204 def count(byte_offset, byte_length)
205 @source.byteslice(byte_offset, byte_length).encode(@encoding, invalid: :replace, undef: :replace).length
206 end
207 end
208
209 private_constant :UTF16Counter, :LengthCounter
210
211 # Initialize a new cache with the given source and encoding.
212 def initialize(source, encoding)
213 @source = source
214 @counter =
215 if encoding == Encoding::UTF_16LE || encoding == Encoding::UTF_16BE
216 UTF16Counter.new(source, encoding)
217 else
218 LengthCounter.new(source, encoding)
219 end
220
221 @cache = {} #: Hash[Integer, Integer]
222 @offsets = [] #: Array[Integer]
223 end
224
225 # Retrieve the code units offset from the given byte offset.
226 def [](byte_offset)
227 @cache[byte_offset] ||=
228 if (index = @offsets.bsearch_index { |offset| offset > byte_offset }).nil?
229 @offsets << byte_offset
230 @counter.count(0, byte_offset)
231 elsif index == 0
232 @offsets.unshift(byte_offset)
233 @counter.count(0, byte_offset)
234 else
235 @offsets.insert(index, byte_offset)
236 offset = @offsets[index - 1]
237 @cache[offset] + @counter.count(offset, byte_offset - offset)
238 end
239 end
240 end
241
242 # Specialized version of Prism::Source for source code that includes ASCII
243 # characters only. This class is used to apply performance optimizations that
244 # cannot be applied to sources that include multibyte characters.
245 #
246 # In the extremely rare case that a source includes multi-byte characters but
247 # is marked as binary because of a magic encoding comment and it cannot be
248 # eagerly converted to UTF-8, this class will be used as well. This is because
249 # at that point we will treat everything as single-byte characters.
250 class ASCIISource < Source
251 # Return the character offset for the given byte offset.
252 def character_offset(byte_offset)
253 byte_offset
254 end
255
256 # Return the column number in characters for the given byte offset.
257 def character_column(byte_offset)
258 byte_offset - line_start(byte_offset)
259 end
260
261 # Returns the offset from the start of the file for the given byte offset
262 # counting in code units for the given encoding.
263 #
264 # This method is tested with UTF-8, UTF-16, and UTF-32. If there is the
265 # concept of code units that differs from the number of characters in other
266 # encodings, it is not captured here.
267 def code_units_offset(byte_offset, encoding)
268 byte_offset
269 end
270
271 # Returns a cache that is the identity function in order to maintain the
272 # same interface. We can do this because code units are always equivalent to
273 # byte offsets for ASCII-only sources.
274 def code_units_cache(encoding)
275 ->(byte_offset) { byte_offset }
276 end
277
278 # Specialized version of `code_units_column` that does not depend on
279 # `code_units_offset`, which is a more expensive operation. This is
280 # essentially the same as `Prism::Source#column`.
281 def code_units_column(byte_offset, encoding)
282 byte_offset - line_start(byte_offset)
283 end
284 end
285
286 # This represents a location in the source.
287 class Location
288 # A Source object that is used to determine more information from the given
289 # offset and length.
290 attr_reader :source
291 protected :source
292
293 # The byte offset from the beginning of the source where this location
294 # starts.
295 attr_reader :start_offset
296
297 # The length of this location in bytes.
298 attr_reader :length
299
300 # Create a new location object with the given source, start byte offset, and
301 # byte length.
302 def initialize(source, start_offset, length)
303 @source = source
304 @start_offset = start_offset
305 @length = length
306
307 # These are used to store comments that are associated with this location.
308 # They are initialized to `nil` to save on memory when there are no
309 # comments to be attached and/or the comment-related APIs are not used.
310 @leading_comments = nil
311 @trailing_comments = nil
312 end
313
314 # These are the comments that are associated with this location that exist
315 # before the start of this location.
316 def leading_comments
317 @leading_comments ||= []
318 end
319
320 # Attach a comment to the leading comments of this location.
321 def leading_comment(comment)
322 leading_comments << comment
323 end
324
325 # These are the comments that are associated with this location that exist
326 # after the end of this location.
327 def trailing_comments
328 @trailing_comments ||= []
329 end
330
331 # Attach a comment to the trailing comments of this location.
332 def trailing_comment(comment)
333 trailing_comments << comment
334 end
335
336 # Returns all comments that are associated with this location (both leading
337 # and trailing comments).
338 def comments
339 [*@leading_comments, *@trailing_comments]
340 end
341
342 # Create a new location object with the given options.
343 def copy(source: self.source, start_offset: self.start_offset, length: self.length)
344 Location.new(source, start_offset, length)
345 end
346
347 # Returns a new location that is the result of chopping off the last byte.
348 def chop
349 copy(length: length == 0 ? length : length - 1)
350 end
351
352 # Returns a string representation of this location.
353 def inspect
354 "#<Prism::Location @start_offset=#{@start_offset} @length=#{@length} start_line=#{start_line}>"
355 end
356
357 # Returns all of the lines of the source code associated with this location.
358 def source_lines
359 source.lines
360 end
361
362 # The source code that this location represents.
363 def slice
364 source.slice(start_offset, length)
365 end
366
367 # The source code that this location represents starting from the beginning
368 # of the line that this location starts on to the end of the line that this
369 # location ends on.
370 def slice_lines
371 line_start = source.line_start(start_offset)
372 line_end = source.line_end(end_offset)
373 source.slice(line_start, line_end - line_start)
374 end
375
376 # The character offset from the beginning of the source where this location
377 # starts.
378 def start_character_offset
379 source.character_offset(start_offset)
380 end
381
382 # The offset from the start of the file in code units of the given encoding.
383 def start_code_units_offset(encoding = Encoding::UTF_16LE)
384 source.code_units_offset(start_offset, encoding)
385 end
386
387 # The start offset from the start of the file in code units using the given
388 # cache to fetch or calculate the value.
389 def cached_start_code_units_offset(cache)
390 cache[start_offset]
391 end
392
393 # The byte offset from the beginning of the source where this location ends.
394 def end_offset
395 start_offset + length
396 end
397
398 # The character offset from the beginning of the source where this location
399 # ends.
400 def end_character_offset
401 source.character_offset(end_offset)
402 end
403
404 # The offset from the start of the file in code units of the given encoding.
405 def end_code_units_offset(encoding = Encoding::UTF_16LE)
406 source.code_units_offset(end_offset, encoding)
407 end
408
409 # The end offset from the start of the file in code units using the given
410 # cache to fetch or calculate the value.
411 def cached_end_code_units_offset(cache)
412 cache[end_offset]
413 end
414
415 # The line number where this location starts.
416 def start_line
417 source.line(start_offset)
418 end
419
420 # The content of the line where this location starts before this location.
421 def start_line_slice
422 offset = source.line_start(start_offset)
423 source.slice(offset, start_offset - offset)
424 end
425
426 # The line number where this location ends.
427 def end_line
428 source.line(end_offset)
429 end
430
431 # The column number in bytes where this location starts from the start of
432 # the line.
433 def start_column
434 source.column(start_offset)
435 end
436
437 # The column number in characters where this location ends from the start of
438 # the line.
439 def start_character_column
440 source.character_column(start_offset)
441 end
442
443 # The column number in code units of the given encoding where this location
444 # starts from the start of the line.
445 def start_code_units_column(encoding = Encoding::UTF_16LE)
446 source.code_units_column(start_offset, encoding)
447 end
448
449 # The start column in code units using the given cache to fetch or calculate
450 # the value.
451 def cached_start_code_units_column(cache)
452 cache[start_offset] - cache[source.line_start(start_offset)]
453 end
454
455 # The column number in bytes where this location ends from the start of the
456 # line.
457 def end_column
458 source.column(end_offset)
459 end
460
461 # The column number in characters where this location ends from the start of
462 # the line.
463 def end_character_column
464 source.character_column(end_offset)
465 end
466
467 # The column number in code units of the given encoding where this location
468 # ends from the start of the line.
469 def end_code_units_column(encoding = Encoding::UTF_16LE)
470 source.code_units_column(end_offset, encoding)
471 end
472
473 # The end column in code units using the given cache to fetch or calculate
474 # the value.
475 def cached_end_code_units_column(cache)
476 cache[end_offset] - cache[source.line_start(end_offset)]
477 end
478
479 # Implement the hash pattern matching interface for Location.
480 def deconstruct_keys(keys)
481 { start_offset: start_offset, end_offset: end_offset }
482 end
483
484 # Implement the pretty print interface for Location.
485 def pretty_print(q)
486 q.text("(#{start_line},#{start_column})-(#{end_line},#{end_column})")
487 end
488
489 # Returns true if the given other location is equal to this location.
490 def ==(other)
491 Location === other &&
492 other.start_offset == start_offset &&
493 other.end_offset == end_offset
494 end
495
496 # Returns a new location that stretches from this location to the given
497 # other location. Raises an error if this location is not before the other
498 # location or if they don't share the same source.
499 def join(other)
500 raise "Incompatible sources" if source != other.source
501 raise "Incompatible locations" if start_offset > other.start_offset
502
503 Location.new(source, start_offset, other.end_offset - start_offset)
504 end
505
506 # Join this location with the first occurrence of the string in the source
507 # that occurs after this location on the same line, and return the new
508 # location. This will raise an error if the string does not exist.
509 def adjoin(string)
510 line_suffix = source.slice(end_offset, source.line_end(end_offset) - end_offset)
511
512 line_suffix_index = line_suffix.byteindex(string)
513 raise "Could not find #{string}" if line_suffix_index.nil?
514
515 Location.new(source, start_offset, length + line_suffix_index + string.bytesize)
516 end
517 end
518
519 # This represents a comment that was encountered during parsing. It is the
520 # base class for all comment types.
521 class Comment
522 # The location of this comment in the source.
523 attr_reader :location
524
525 # Create a new comment object with the given location.
526 def initialize(location)
527 @location = location
528 end
529
530 # Implement the hash pattern matching interface for Comment.
531 def deconstruct_keys(keys)
532 { location: location }
533 end
534
535 # Returns the content of the comment by slicing it from the source code.
536 def slice
537 location.slice
538 end
539 end
540
541 # InlineComment objects are the most common. They correspond to comments in
542 # the source file like this one that start with #.
543 class InlineComment < Comment
544 # Returns true if this comment happens on the same line as other code and
545 # false if the comment is by itself.
546 def trailing?
547 !location.start_line_slice.strip.empty?
548 end
549
550 # Returns a string representation of this comment.
551 def inspect
552 "#<Prism::InlineComment @location=#{location.inspect}>"
553 end
554 end
555
556 # EmbDocComment objects correspond to comments that are surrounded by =begin
557 # and =end.
558 class EmbDocComment < Comment
559 # This can only be true for inline comments.
560 def trailing?
561 false
562 end
563
564 # Returns a string representation of this comment.
565 def inspect
566 "#<Prism::EmbDocComment @location=#{location.inspect}>"
567 end
568 end
569
570 # This represents a magic comment that was encountered during parsing.
571 class MagicComment
572 # A Location object representing the location of the key in the source.
573 attr_reader :key_loc
574
575 # A Location object representing the location of the value in the source.
576 attr_reader :value_loc
577
578 # Create a new magic comment object with the given key and value locations.
579 def initialize(key_loc, value_loc)
580 @key_loc = key_loc
581 @value_loc = value_loc
582 end
583
584 # Returns the key of the magic comment by slicing it from the source code.
585 def key
586 key_loc.slice
587 end
588
589 # Returns the value of the magic comment by slicing it from the source code.
590 def value
591 value_loc.slice
592 end
593
594 # Implement the hash pattern matching interface for MagicComment.
595 def deconstruct_keys(keys)
596 { key_loc: key_loc, value_loc: value_loc }
597 end
598
599 # Returns a string representation of this magic comment.
600 def inspect
601 "#<Prism::MagicComment @key=#{key.inspect} @value=#{value.inspect}>"
602 end
603 end
604
605 # This represents an error that was encountered during parsing.
606 class ParseError
607 # The type of error. This is an _internal_ symbol that is used for
608 # communicating with translation layers. It is not meant to be public API.
609 attr_reader :type
610
611 # The message associated with this error.
612 attr_reader :message
613
614 # A Location object representing the location of this error in the source.
615 attr_reader :location
616
617 # The level of this error.
618 attr_reader :level
619
620 # Create a new error object with the given message and location.
621 def initialize(type, message, location, level)
622 @type = type
623 @message = message
624 @location = location
625 @level = level
626 end
627
628 # Implement the hash pattern matching interface for ParseError.
629 def deconstruct_keys(keys)
630 { type: type, message: message, location: location, level: level }
631 end
632
633 # Returns a string representation of this error.
634 def inspect
635 "#<Prism::ParseError @type=#{@type.inspect} @message=#{@message.inspect} @location=#{@location.inspect} @level=#{@level.inspect}>"
636 end
637 end
638
639 # This represents a warning that was encountered during parsing.
640 class ParseWarning
641 # The type of warning. This is an _internal_ symbol that is used for
642 # communicating with translation layers. It is not meant to be public API.
643 attr_reader :type
644
645 # The message associated with this warning.
646 attr_reader :message
647
648 # A Location object representing the location of this warning in the source.
649 attr_reader :location
650
651 # The level of this warning.
652 attr_reader :level
653
654 # Create a new warning object with the given message and location.
655 def initialize(type, message, location, level)
656 @type = type
657 @message = message
658 @location = location
659 @level = level
660 end
661
662 # Implement the hash pattern matching interface for ParseWarning.
663 def deconstruct_keys(keys)
664 { type: type, message: message, location: location, level: level }
665 end
666
667 # Returns a string representation of this warning.
668 def inspect
669 "#<Prism::ParseWarning @type=#{@type.inspect} @message=#{@message.inspect} @location=#{@location.inspect} @level=#{@level.inspect}>"
670 end
671 end
672
673 # This represents the result of a call to ::parse or ::parse_file. It contains
674 # the requested structure, any comments that were encounters, and any errors
675 # that were encountered.
676 class Result
677 # The list of comments that were encountered during parsing.
678 attr_reader :comments
679
680 # The list of magic comments that were encountered during parsing.
681 attr_reader :magic_comments
682
683 # An optional location that represents the location of the __END__ marker
684 # and the rest of the content of the file. This content is loaded into the
685 # DATA constant when the file being parsed is the main file being executed.
686 attr_reader :data_loc
687
688 # The list of errors that were generated during parsing.
689 attr_reader :errors
690
691 # The list of warnings that were generated during parsing.
692 attr_reader :warnings
693
694 # A Source instance that represents the source code that was parsed.
695 attr_reader :source
696
697 # Create a new result object with the given values.
698 def initialize(comments, magic_comments, data_loc, errors, warnings, source)
699 @comments = comments
700 @magic_comments = magic_comments
701 @data_loc = data_loc
702 @errors = errors
703 @warnings = warnings
704 @source = source
705 end
706
707 # Implement the hash pattern matching interface for Result.
708 def deconstruct_keys(keys)
709 { comments: comments, magic_comments: magic_comments, data_loc: data_loc, errors: errors, warnings: warnings }
710 end
711
712 # Returns the encoding of the source code that was parsed.
713 def encoding
714 source.encoding
715 end
716
717 # Returns true if there were no errors during parsing and false if there
718 # were.
719 def success?
720 errors.empty?
721 end
722
723 # Returns true if there were errors during parsing and false if there were
724 # not.
725 def failure?
726 !success?
727 end
728
729 # Create a code units cache for the given encoding.
730 def code_units_cache(encoding)
731 source.code_units_cache(encoding)
732 end
733 end
734
735 # This is a result specific to the `parse` and `parse_file` methods.
736 class ParseResult < Result
737 autoload :Comments, "prism/parse_result/comments"
738 autoload :Errors, "prism/parse_result/errors"
739 autoload :Newlines, "prism/parse_result/newlines"
740
741 private_constant :Comments
742 private_constant :Errors
743 private_constant :Newlines
744
745 # The syntax tree that was parsed from the source code.
746 attr_reader :value
747
748 # Create a new parse result object with the given values.
749 def initialize(value, comments, magic_comments, data_loc, errors, warnings, source)
750 @value = value
751 super(comments, magic_comments, data_loc, errors, warnings, source)
752 end
753
754 # Implement the hash pattern matching interface for ParseResult.
755 def deconstruct_keys(keys)
756 super.merge!(value: value)
757 end
758
759 # Attach the list of comments to their respective locations in the tree.
760 def attach_comments!
761 Comments.new(self).attach! # steep:ignore
762 end
763
764 # Walk the tree and mark nodes that are on a new line, loosely emulating
765 # the behavior of CRuby's `:line` tracepoint event.
766 def mark_newlines!
767 value.accept(Newlines.new(source.offsets.size)) # steep:ignore
768 end
769
770 # Returns a string representation of the syntax tree with the errors
771 # displayed inline.
772 def errors_format
773 Errors.new(self).format
774 end
775 end
776
777 # This is a result specific to the `lex` and `lex_file` methods.
778 class LexResult < Result
779 # The list of tokens that were parsed from the source code.
780 attr_reader :value
781
782 # Create a new lex result object with the given values.
783 def initialize(value, comments, magic_comments, data_loc, errors, warnings, source)
784 @value = value
785 super(comments, magic_comments, data_loc, errors, warnings, source)
786 end
787
788 # Implement the hash pattern matching interface for LexResult.
789 def deconstruct_keys(keys)
790 super.merge!(value: value)
791 end
792 end
793
794 # This is a result specific to the `parse_lex` and `parse_lex_file` methods.
795 class ParseLexResult < Result
796 # A tuple of the syntax tree and the list of tokens that were parsed from
797 # the source code.
798 attr_reader :value
799
800 # Create a new parse lex result object with the given values.
801 def initialize(value, comments, magic_comments, data_loc, errors, warnings, source)
802 @value = value
803 super(comments, magic_comments, data_loc, errors, warnings, source)
804 end
805
806 # Implement the hash pattern matching interface for ParseLexResult.
807 def deconstruct_keys(keys)
808 super.merge!(value: value)
809 end
810 end
811
812 # This represents a token from the Ruby source.
813 class Token
814 # The Source object that represents the source this token came from.
815 attr_reader :source
816 private :source
817
818 # The type of token that this token is.
819 attr_reader :type
820
821 # A byteslice of the source that this token represents.
822 attr_reader :value
823
824 # Create a new token object with the given type, value, and location.
825 def initialize(source, type, value, location)
826 @source = source
827 @type = type
828 @value = value
829 @location = location
830 end
831
832 # Implement the hash pattern matching interface for Token.
833 def deconstruct_keys(keys)
834 { type: type, value: value, location: location }
835 end
836
837 # A Location object representing the location of this token in the source.
838 def location
839 location = @location
840 return location if location.is_a?(Location)
841 @location = Location.new(source, location >> 32, location & 0xFFFFFFFF)
842 end
843
844 # Implement the pretty print interface for Token.
845 def pretty_print(q)
846 q.group do
847 q.text(type.to_s)
848 self.location.pretty_print(q)
849 q.text("(")
850 q.nest(2) do
851 q.breakable("")
852 q.pp(value)
853 end
854 q.breakable("")
855 q.text(")")
856 end
857 end
858
859 # Returns true if the given other token is equal to this token.
860 def ==(other)
861 Token === other &&
862 other.type == type &&
863 other.value == value
864 end
865
866 # Returns a string representation of this token.
867 def inspect
868 location
869 super
870 end
871
872 # Freeze this object and the objects it contains.
873 def deep_freeze
874 value.freeze
875 location.freeze
876 freeze
877 end
878 end
879
880 # This object is passed to the various Prism.* methods that accept the
881 # `scopes` option as an element of the list. It defines both the local
882 # variables visible at that scope as well as the forwarding parameters
883 # available at that scope.
884 class Scope
885 # The list of local variables that are defined in this scope. This should be
886 # defined as an array of symbols.
887 attr_reader :locals
888
889 # The list of local variables that are forwarded to the next scope. This
890 # should by defined as an array of symbols containing the specific values of
891 # :*, :**, :&, or :"...".
892 attr_reader :forwarding
893
894 # Create a new scope object with the given locals and forwarding.
895 def initialize(locals, forwarding)
896 @locals = locals
897 @forwarding = forwarding
898 end
899 end
900
901 # Create a new scope with the given locals and forwarding options that is
902 # suitable for passing into one of the Prism.* methods that accepts the
903 # `scopes` option.
904 def self.scope(locals: [], forwarding: [])
905 Scope.new(locals, forwarding)
906 end
907 end