Class: RuboCop::AST::ProcessedSource
| Relationships & Source Files | |
| Inherits: | Object |
| Defined in: | lib/rubocop/ast/processed_source.rb |
Overview
ProcessedSource contains objects which are generated by Parser and other information such as disabled lines for cops. It also provides a convenient way to access source lines.
Constant Summary
-
INVALID_LEVELS =
private
# File 'lib/rubocop/ast/processed_source.rb', line 73%i[error fatal].freeze
-
PARSER_ENGINES =
private
# File 'lib/rubocop/ast/processed_source.rb', line 76%i[default parser_whitequark parser_prism prism].freeze
-
STRING_SOURCE_NAME =
# File 'lib/rubocop/ast/processed_source.rb', line 71'(string)'
Class Attribute Summary
-
.parser_gem_available? ⇒ Boolean
readonly
Whether the
parsergem is installed.
Class Method Summary
-
.default_parser_engine(ruby_version) ⇒ Symbol
The parser engine that
:defaultstands for with a target Ruby version. - .from_file(path, ruby_version, parser_engine: :default)
-
.lazy_tokens_parser_class(base)
Internal use only
Subclasses of the prism translation parsers with lazily built tokens.
- .new(source, ruby_version, path = nil, parser_engine: :default, prism_result: nil) ⇒ ProcessedSource constructor
Instance Attribute Summary
- #ast readonly
- #blank? ⇒ Boolean readonly
- #buffer readonly
- #comments readonly
- #diagnostics readonly
- #parser_engine readonly
- #parser_error readonly
- #path readonly
- #raw_source readonly
- #ruby_version readonly
- #valid_syntax? ⇒ Boolean readonly
- #tokens_sorted? ⇒ Boolean readonly private
Instance Method Summary
- #[](*args)
- #ast_with_comments
-
#checksum
Raw source checksum for tracking infinite loops.
- #comment_at_line(line) ⇒ Comment?
-
#commented?(source_range)
Alias for #contains_comment?.
- #comments_before_line(line) deprecated Deprecated.
-
#contains_comment?(source_range) ⇒ Boolean
(also: #commented?)
Consider using #each_comment_in_lines instead.
- #current_line(token)
-
#each_comment(&block)
deprecated
Deprecated.
Use
comments.each -
#each_comment_in_lines(line_range)
Enumerates on the comments contained with the given
line_range. -
#each_token(&block)
deprecated
Deprecated.
Use
tokens.each - #file_path
-
#find_comment(&block)
deprecated
Deprecated.
Use #comment_at_line, #each_comment_in_lines, or
comments.find -
#find_token(&block)
deprecated
Deprecated.
Use
tokens.find - #first_token_of(range_or_node)
- #following_line(token)
- #last_token_of(range_or_node)
- #line_indentation(line_number)
- #line_with_comment?(line) ⇒ Boolean
-
#lines
Returns the source lines, line break characters removed, excluding a possible END and everything that comes after.
- #preceding_line(token)
-
#sorted_tokens
The tokens list is out of order when a heredoc is passed as a method argument (the heredoc contents' tokens are interleaved) and, more commonly, whenever the source contains comments, whose tokens the lexer emits out of band.
- #start_with?(string) ⇒ Boolean
-
#tokens
The tokens of the source.
- #tokens_within(range_or_node)
- #comment_index private
-
#create_parser(ruby_version, parser_engine, prism_result)
private
rubocop:disable-next Metrics/AbcSize, Metrics/MethodLength.
- #first_token_index(range_or_node) private
- #last_token_index(range_or_node) private
- #normalize_parser_engine(parser_engine, ruby_version) private
- #parse(source, ruby_version, parser_engine, prism_result) private
- #parse_and_lex(parser) private
-
#parser_class(ruby_version, parser_engine)
private
rubocop:disable-next Lint/FloatComparison, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength.
- #parser_tokens private
- #sort_tokens private
- #source_range(range_or_node) private
-
#store_tokens(tokens)
private
The tokens may be an already converted array, or a deferred conversion to be performed when the tokens are first accessed.
- #tokenize(parser) private
- #translation_parser(ruby_version, prism) private
-
#trim_lines_after_data_marker(all_lines)
private
ENDonly starts a data section when it isn’t nested inside a string or heredoc, which is what the last token’s line disambiguates.
Constructor Details
.new(source, ruby_version, path = nil, parser_engine: :default, prism_result: nil) ⇒ ProcessedSource
# File 'lib/rubocop/ast/processed_source.rb', line 119
def initialize( source, ruby_version, path = nil, parser_engine: :default, prism_result: nil ) parser_engine = normalize_parser_engine(parser_engine, ruby_version) # Defaults source encoding to UTF-8, regardless of the encoding it has # been read with, which could be non-utf8 depending on the default # external encoding. source = (+source).force_encoding(Encoding::UTF_8) unless source.encoding == Encoding::UTF_8 @raw_source = source @path = path @diagnostics = [] @ruby_version = ruby_version @parser_engine = parser_engine @parser_error = nil parse(source, ruby_version, parser_engine, prism_result) end
Class Attribute Details
.parser_gem_available? ⇒ Boolean (readonly)
Whether the parser gem is installed. The parser_whitequark and
parser_prism engines need it, the prism engine does not.
# File 'lib/rubocop/ast/processed_source.rb', line 108
def self.parser_gem_available? !ParserSource.vendored? end
Class Method Details
.default_parser_engine(ruby_version) ⇒ Symbol
The parser engine that :default stands for with a target Ruby version.
Prism is used for all Ruby versions it can parse (3.3 and later);
the Parser gem does not support Ruby 3.5 or later and is not fully
compatible with Ruby 3.4. The prism engine needs Prism 2, so with
an older Prism its translation layer is used, which needs the Parser
gem as well.
# File 'lib/rubocop/ast/processed_source.rb', line 96
def self.default_parser_engine(ruby_version) if ruby_version < 3.3 :parser_whitequark elsif !parser_gem_available? || ::Prism::VERSION.to_i >= 2 :prism else :parser_prism end end
.from_file(path, ruby_version, parser_engine: :default)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 82
def self.from_file(path, ruby_version, parser_engine: :default) file = File.read(path, mode: 'rb') new(file, ruby_version, path, parser_engine: parser_engine) end
.lazy_tokens_parser_class(base)
Subclasses of the prism translation parsers with lazily built tokens.
# File 'lib/rubocop/ast/processed_source.rb', line 114
def self.lazy_tokens_parser_class(base) @lazy_tokens_parser_classes ||= {} @lazy_tokens_parser_classes[base] ||= Class.new(base) { include PrismLazyTokens } end
Instance Attribute Details
#ast (readonly)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 79
attr_reader :path, :buffer, :ast, :comments, :diagnostics, :parser_error, :raw_source, :ruby_version, :parser_engine
#blank? ⇒ Boolean (readonly)
[ GitHub ]
# File 'lib/rubocop/ast/processed_source.rb', line 199
def blank? ast.nil? end
#buffer (readonly)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 79
attr_reader :path, :buffer, :ast, :comments, :diagnostics, :parser_error, :raw_source, :ruby_version, :parser_engine
#comments (readonly)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 79
attr_reader :path, :buffer, :ast, :comments, :diagnostics, :parser_error, :raw_source, :ruby_version, :parser_engine
#diagnostics (readonly)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 79
attr_reader :path, :buffer, :ast, :comments, :diagnostics, :parser_error, :raw_source, :ruby_version, :parser_engine
#parser_engine (readonly)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 79
attr_reader :path, :buffer, :ast, :comments, :diagnostics, :parser_error, :raw_source, :ruby_version, :parser_engine
#parser_error (readonly)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 79
attr_reader :path, :buffer, :ast, :comments, :diagnostics, :parser_error, :raw_source, :ruby_version, :parser_engine
#path (readonly)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 79
attr_reader :path, :buffer, :ast, :comments, :diagnostics, :parser_error, :raw_source, :ruby_version, :parser_engine
#raw_source (readonly)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 79
attr_reader :path, :buffer, :ast, :comments, :diagnostics, :parser_error, :raw_source, :ruby_version, :parser_engine
#ruby_version (readonly)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 79
attr_reader :path, :buffer, :ast, :comments, :diagnostics, :parser_error, :raw_source, :ruby_version, :parser_engine
#tokens_sorted? ⇒ Boolean (readonly, private)
[ GitHub ]
#valid_syntax? ⇒ Boolean (readonly)
[ GitHub ]
# File 'lib/rubocop/ast/processed_source.rb', line 164
def valid_syntax? return false if @parser_error @diagnostics.none? { |d| INVALID_LEVELS.include?(d.level) } end
Instance Method Details
#[](*args)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 160
def [](*args) lines[*args] end
#ast_with_comments
[ GitHub ]#checksum
Raw source checksum for tracking infinite loops.
# File 'lib/rubocop/ast/processed_source.rb', line 171
def checksum @checksum ||= Digest::SHA1.hexdigest(@raw_source) end
#comment_at_line(line) ⇒ Comment?
# File 'lib/rubocop/ast/processed_source.rb', line 204
def comment_at_line(line) comment_index[line] end
#comment_index (private)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 334
def comment_index @comment_index ||= {}.tap do |hash| comments.each { |c| hash[c.location.line] = c } end end
#commented?(source_range)
Alias for #contains_comment?.
# File 'lib/rubocop/ast/processed_source.rb', line 230
alias commented? contains_comment?
#comments_before_line(line)
Should have been called comments_before_or_at_line. Doubtful it has of any valid use.
# File 'lib/rubocop/ast/processed_source.rb', line 234
def comments_before_line(line) each_comment_in_lines(0..line).to_a end
#contains_comment?(source_range) ⇒ Boolean
Also known as: #commented?
Consider using #each_comment_in_lines instead
# File 'lib/rubocop/ast/processed_source.rb', line 226
def contains_comment?(source_range) each_comment_in_lines(source_range.line..source_range.last_line).any? end
#create_parser(ruby_version, parser_engine, prism_result) (private)
rubocop:disable-next Metrics/AbcSize, Metrics/MethodLength
# File 'lib/rubocop/ast/processed_source.rb', line 485
def create_parser(ruby_version, parser_engine, prism_result) # NOTE: Since it is intended for use with Ruby LSP, it targets only Prism. # If there is no reuse of a pre-parsed result, such as in Ruby LSP, # regular parsing with Prism occurs. prism = PrismPreparsed.new(prism_result) if prism_result && parser_engine != :parser_whitequark parser_instance = case parser_engine when :prism PrismParser.new(ruby_version, prism: prism || Prism) when :parser_prism translation_parser(ruby_version, prism) else parser_class(ruby_version, parser_engine).new(Builder.new) end parser_instance.tap do |parser| # On JRuby there's a risk that we hang in tokenize() if we # don't set the all errors as fatal flag. The problem is caused by a bug # in Racc that is discussed in issue #93 of the whitequark/parser # project on GitHub. parser.diagnostics.all_errors_are_fatal = (RUBY_ENGINE != 'ruby') parser.diagnostics.ignore_warnings = false parser.diagnostics.consumer = lambda do |diagnostic| @diagnostics << diagnostic end end end
#current_line(token)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 250
def current_line(token) lines[token.line - 1] end
#each_comment(&block)
Use comments.each
# File 'lib/rubocop/ast/processed_source.rb', line 176
def each_comment(&block) comments.each(&block) end
#each_comment_in_lines(line_range)
Enumerates on the comments contained with the given line_range
# File 'lib/rubocop/ast/processed_source.rb', line 214
def each_comment_in_lines(line_range) return to_enum(:each_comment_in_lines, line_range) unless block_given? line_range.each do |line| if (comment = comment_index[line]) yield comment end end end
#each_token(&block)
Use tokens.each
# File 'lib/rubocop/ast/processed_source.rb', line 186
def each_token(&block) tokens.each(&block) end
#file_path
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 195
def file_path buffer.name end
#find_comment(&block)
Use #comment_at_line, #each_comment_in_lines, or comments.find
# File 'lib/rubocop/ast/processed_source.rb', line 181
def find_comment(&block) comments.find(&block) end
#find_token(&block)
Use tokens.find
# File 'lib/rubocop/ast/processed_source.rb', line 191
def find_token(&block) tokens.find(&block) end
#first_token_index(range_or_node) (private)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 527
def first_token_index(range_or_node) begin_pos = source_range(range_or_node).begin_pos sorted_tokens.bsearch_index { |token| token.begin_pos >= begin_pos } end
#first_token_of(range_or_node)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 284
def first_token_of(range_or_node) sorted_tokens[first_token_index(range_or_node)] end
#following_line(token)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 254
def following_line(token) lines[token.line] end
#last_token_index(range_or_node) (private)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 532
def last_token_index(range_or_node) end_pos = source_range(range_or_node).end_pos sorted_tokens.bsearch_index { |token| token.end_pos >= end_pos } end
#last_token_of(range_or_node)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 288
def last_token_of(range_or_node) sorted_tokens[last_token_index(range_or_node)] end
#line_indentation(line_number)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 258
def line_indentation(line_number) lines[line_number - 1] .match(/^(\s*)/)[1] .to_s .length end
#line_with_comment?(line) ⇒ Boolean
# File 'lib/rubocop/ast/processed_source.rb', line 209
def line_with_comment?(line) comment_index.include?(line) end
#lines
Returns the source lines, line break characters removed, excluding a possible END and everything that comes after.
# File 'lib/rubocop/ast/processed_source.rb', line 147
def lines @lines ||= begin all_lines = @buffer.source_lines if all_lines.include?('__END__') trim_lines_after_data_marker(all_lines) else # Don't consult the tokens (which may have to be built first) when # the source can't contain a data section. all_lines.dup end end end
#normalize_parser_engine(parser_engine, ruby_version) (private)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 513
def normalize_parser_engine(parser_engine, ruby_version) parser_engine = parser_engine.to_sym unless PARSER_ENGINES.include?(parser_engine) raise ArgumentError, 'The keyword argument `parser_engine` accepts `default`, ' \ "`parser_whitequark`, `parser_prism`, or `prism`, but `#{parser_engine}` " \ 'was passed.' end if parser_engine == :default self.class.default_parser_engine(ruby_version) else parser_engine end end
#parse(source, ruby_version, parser_engine, prism_result) (private)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 340
def parse(source, ruby_version, parser_engine, prism_result) @buffer = Parser::Source::Buffer.new(@path || STRING_SOURCE_NAME, 1) begin @buffer.source = source rescue EncodingError, Parser::UnknownEncodingInMagicComment => e @parser_error = e @ast = nil @comments = [] @tokens = [] return end parser = create_parser(ruby_version, parser_engine, prism_result) @ast, @comments, tokens = tokenize(parser) store_tokens(tokens) end
#parse_and_lex(parser) (private)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 391
def parse_and_lex(parser) if parser.respond_to?(:tokenize_deferred) parser.tokenize_deferred(@buffer) else parser.tokenize(@buffer) end end
#parser_class(ruby_version, parser_engine) (private)
rubocop:disable-next Lint/FloatComparison, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength
# File 'lib/rubocop/ast/processed_source.rb', line 409
def parser_class(ruby_version, parser_engine) ParserSource.ensure_parser_gem(parser_engine) case parser_engine when :parser_whitequark case ruby_version when 1.9 require 'parser/ruby19' Parser::Ruby19 when 2.0 require 'parser/ruby20' Parser::Ruby20 when 2.1 require 'parser/ruby21' Parser::Ruby21 when 2.2 require 'parser/ruby22' Parser::Ruby22 when 2.3 require 'parser/ruby23' Parser::Ruby23 when 2.4 require 'parser/ruby24' Parser::Ruby24 when 2.5 require 'parser/ruby25' Parser::Ruby25 when 2.6 require 'parser/ruby26' Parser::Ruby26 when 2.7 require 'parser/ruby27' Parser::Ruby27 when 2.8, 3.0 require 'parser/ruby30' Parser::Ruby30 when 3.1 require 'parser/ruby31' Parser::Ruby31 when 3.2 require 'parser/ruby32' Parser::Ruby32 when 3.3 require 'parser/ruby33' Parser::Ruby33 when 3.4 require 'parser/ruby34' Parser::Ruby34 else raise ArgumentError, 'RuboCop supports target Ruby versions 3.4 and below with ' \ "`parser`. Specified target Ruby version: #{ruby_version.inspect}" end when :parser_prism case ruby_version when 3.3 Prism::Translation::Parser33 when 3.4 Prism::Translation::Parser34 when 3.5, 4.0 Prism::Translation::Parser40 when 4.1 Prism::Translation::Parser41 else raise ArgumentError, 'RuboCop supports target Ruby versions 3.3 and above with Prism. ' \ "Specified target Ruby version: #{ruby_version.inspect}" end end end
#parser_tokens (private)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 399
def parser_tokens if @deferred_parser_tokens @parser_tokens = @deferred_parser_tokens.call @deferred_parser_tokens = nil end @parser_tokens end
#preceding_line(token)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 244
def preceding_line(token) return nil if token.line < 2 lines[token.line - 2] end
#sort_tokens (private)
[ GitHub ]#sorted_tokens
The tokens list is out of order when a heredoc is passed as a method argument (the heredoc contents' tokens are interleaved) and, more commonly, whenever the source contains comments, whose tokens the lexer emits out of band.
# File 'lib/rubocop/ast/processed_source.rb', line 296
def sorted_tokens # Callers only ever read from the returned array, so it is safe to # reuse `tokens` as is when it's already in order. @sorted_tokens ||= if tokens_sorted? tokens else sort_tokens end end
#source_range(range_or_node) (private)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 537
def source_range(range_or_node) if range_or_node.respond_to?(:source_range) range_or_node.source_range else range_or_node end end
#start_with?(string) ⇒ Boolean
# File 'lib/rubocop/ast/processed_source.rb', line 238
def start_with?(string) return false if self[0].nil? self[0].start_with?(string) end
#store_tokens(tokens) (private)
The tokens may be an already converted array, or a deferred conversion to be performed when the tokens are first accessed.
#tokenize(parser) (private)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 369
def tokenize(parser) begin ast, comments, tokens = parse_and_lex(parser) ast ||= nil # force `false` to `nil`, see https://github.com/whitequark/parser/pull/722 rescue Parser::SyntaxError # All errors are in diagnostics. No need to handle exception. comments = [] tokens = [] rescue StandardError => e # The parser gem may fail on invalid sources with an exception other than `Parser::SyntaxError` # and without a diagnostic, e.g. with `RegexpError` for `/\c\xFF/ =~ ""`. Keep the exception # so that it can be reported instead of crashing the caller. @parser_error = e comments = [] tokens = [] end ast&.complete! [ast, comments, tokens] end
#tokens
The tokens of the source. With the prism engine the tokens are built lazily on first access, since their conversion is costly and not every caller needs them.
# File 'lib/rubocop/ast/processed_source.rb', line 268
def tokens @tokens ||= begin tokens = parser_tokens.map { |t| Token.from_parser_token(t) } # The parser tokens are no longer needed, and the deferred conversion # holds on to the parser instance, so release both. @parser_tokens = nil tokens end end
#tokens_within(range_or_node)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 278
def tokens_within(range_or_node) begin_index = first_token_index(range_or_node) end_index = last_token_index(range_or_node) sorted_tokens[begin_index..end_index] end
#translation_parser(ruby_version, prism) (private)
[ GitHub ]# File 'lib/rubocop/ast/processed_source.rb', line 478
def translation_parser(ruby_version, prism) parser_class = self.class.lazy_tokens_parser_class(parser_class(ruby_version, :parser_prism)) prism ? parser_class.new(BuilderPrism.new, parser: prism) : parser_class.new(BuilderPrism.new) end
#trim_lines_after_data_marker(all_lines) (private)
END only starts a data section when it isn’t nested inside a
string or heredoc, which is what the last token’s line disambiguates.