123456789_123456789_123456789_123456789_123456789_

Module: RuboCop::Cop::RangeHelp

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Extended In:
Included In:
Bundler::DuplicatedGem, Bundler::DuplicatedGroup, EndKeywordAlignment, Gemspec::DeprecatedAttributeAssignment, Gemspec::DuplicatedAssignment, InternalAffairs::MethodNameEndWith, InternalAffairs::NodeFirstOrLastArgument, InternalAffairs::NodeMatcherDirective, InternalAffairs::RedundantContextConfigParameter, InternalAffairs::RedundantDescribedClassAsSubject, InternalAffairs::RedundantLetRuboCopConfigNew, InternalAffairs::RedundantLocationArgument, InternalAffairs::RedundantMessageArgument, InternalAffairs::RedundantMethodDispatchNode, Layout::AccessModifierIndentation, Layout::BeginEndAlignment, Layout::BlockAlignment, Layout::CaseIndentation, Layout::ConditionPosition, Layout::DefEndAlignment, Layout::DotPosition, Layout::ElseAlignment, Layout::EmptyComment, Layout::EmptyLineAfterGuardClause, Layout::EmptyLineAfterMagicComment, Layout::EmptyLineAfterMultilineCondition, Layout::EmptyLineBetweenDefs, Layout::EmptyLines, Layout::EmptyLinesAroundAccessModifier, Layout::EmptyLinesAroundArguments, Layout::EmptyLinesAroundAttributeAccessor, Layout::EmptyLinesAroundBeginBody, Layout::EmptyLinesAroundBlockBody, Layout::EmptyLinesAroundBody, Layout::EmptyLinesAroundClassBody, Layout::EmptyLinesAroundExceptionHandlingKeywords, Layout::EmptyLinesAroundMethodBody, Layout::EmptyLinesAroundModuleBody, Layout::EndAlignment, Layout::EndOfLine, Layout::ExtraSpacing, Layout::FirstArgumentIndentation, Layout::HashAlignment, Layout::HeredocArgumentClosingParenthesis, Layout::IndentationStyle, Layout::IndentationWidth, Layout::InitialIndentation, Layout::LeadingCommentSpace, Layout::LineContinuationLeadingSpace, Layout::LineContinuationSpacing, Layout::LineLength, Layout::MultilineAssignmentLayout, Layout::MultilineBlockLayout, Layout::RescueEnsureAlignment, Layout::SingleLineBlockChain, Layout::SpaceAfterMethodName, Layout::SpaceAfterNot, Layout::SpaceAroundBlockParameters, Layout::SpaceAroundEqualsInParameterDefault, Layout::SpaceAroundMethodCallOperator, Layout::SpaceAroundOperators, Layout::SpaceBeforeBlockBraces, Layout::SpaceBeforeBrackets, Layout::SpaceBeforeComma, Layout::SpaceBeforeFirstArg, Layout::SpaceBeforeSemicolon, Layout::SpaceInLambdaLiteral, Layout::SpaceInsideArrayLiteralBrackets, Layout::SpaceInsideArrayPercentLiteral, Layout::SpaceInsideBlockBraces, Layout::SpaceInsideHashLiteralBraces, Layout::SpaceInsideParens, Layout::SpaceInsidePercentLiteralDelimiters, Layout::SpaceInsideReferenceBrackets, Layout::SpaceInsideStringInterpolation, Layout::TrailingEmptyLines, Layout::TrailingWhitespace, Lint::AmbiguousAssignment, Lint::ConstantOverwrittenInRescue, Lint::DeprecatedOpenSSLConstant, Lint::DuplicateMagicComment, Lint::DuplicateRegexpCharacterClassElement, Lint::DuplicateRequire, Lint::ElseLayout, Lint::EmptyConditionalBody, Lint::ErbNewArguments, Lint::HeredocMethodCallPosition, Lint::LiteralAsCondition, Lint::LiteralInInterpolation, Lint::MissingCopEnableDirective, Lint::MixedCaseRange, Lint::NestedPercentLiteral, Lint::ParenthesesAsGroupedExpression, Lint::PercentStringArray, Lint::PercentSymbolArray, Lint::RedundantCopDisableDirective, Lint::RedundantCopEnableDirective, Lint::RedundantRegexpQuantifiers, Lint::RedundantRequireStatement, Lint::RedundantWithIndex, Lint::RedundantWithObject, Lint::RequireParentheses, Lint::RequireRelativeSelfPath, Lint::SendWithMixinArgument, Lint::ShadowedException, Lint::TrailingCommaInAttributeDeclaration, Lint::UselessAccessModifier, Lint::UselessAssignment, Lint::UselessTimes, Lint::Void, MatchRange, Migration::DepartmentName, MultilineLiteralBraceCorrector, Naming::AsciiIdentifiers, Naming::BlockForwarding, Naming::InclusiveLanguage, Naming::MethodName, PercentLiteral, SpaceBeforePunctuation, Style::AccessModifierDeclarations, Style::AccessorGrouping, Style::AmbiguousEndlessMethodDefinition, Style::AndOr, Style::ArgumentsForwarding, Style::AsciiComments, Style::Attr, Style::BisectedAttrAccessor, Style::BlockComments, Style::BlockDelimiters, Style::CaseLikeIf, Style::ClassAndModuleChildren, Style::ClassEqualityComparison, Style::ClassMethodsDefinitions, Style::CollectionCompact, Style::CombinableDefined, Style::CommentAnnotation, Style::CommentedKeyword, Style::Copyright, Style::DataInheritance, Style::Documentation, Style::EachWithObject, Style::EmptyBlockParameter, Style::EmptyCaseCondition, Style::EmptyElse, Style::EmptyHeredoc, Style::EmptyLambdaParameter, Style::EmptyLiteral, Style::Encoding, Style::ExpandPathArguments, Style::ExplicitBlockArgument, Style::FileRead, Style::FileWrite, Style::FrozenStringLiteralComment, Style::GuardClause, Style::HashAsLastArrayItem, Style::HashExcept, Style::HashSyntax, Style::IdenticalConditionalBranches, Style::IfInsideElse, Style::IfUnlessModifier, Style::InverseMethods, Style::KeywordParametersOrder, Style::LineEndConcatenation, Style::MapIntoArray, Style::MapToHash, Style::MapToSet, Style::MethodCallWithArgsParentheses, Style::MethodCallWithArgsParentheses::OmitParentheses, Style::MethodCalledOnDoEndBlock, Style::MethodDefParentheses, Style::MinMaxComparison, Style::MultilineBlockChain, Style::MultilineIfThen, Style::MultilineInPatternThen, Style::MultilineMethodSignature, Style::MultilineWhenThen, Style::NegatedIfElseCondition, Style::NestedFileDirname, Style::NestedModifier, Style::NestedParenthesizedCalls, Style::NestedTernaryOperator, Style::Next, Style::NilLambda, Style::Not, Style::ParenthesesAroundCondition, Style::PercentLiteralDelimiters, Style::PercentQLiterals, Style::RedundantArgument, Style::RedundantBegin, Style::RedundantCapitalW, Style::RedundantCondition, Style::RedundantCurrentDirectoryInPath, Style::RedundantFetchBlock, Style::RedundantFileExtensionInRequire, Style::RedundantInitialize, Style::RedundantInterpolation, Style::RedundantLineContinuation, Style::RedundantRegexpEscape, Style::RedundantReturn, Style::RedundantSelfAssignment, Style::RedundantSort, Style::RedundantSortBy, Style::RedundantStringEscape, Style::RegexpLiteral, Style::RequireOrder, Style::RescueModifier, Style::RescueStandardError, Style::SafeNavigation, Style::SelectByRegexp, Style::Semicolon, Style::SoleNestedConditional, Style::SpecialGlobalVars, Style::StaticClass, Style::StderrPuts, Style::StringChars, Style::StringConcatenation, Style::Strip, Style::StructInheritance, Style::SwapValues, Style::SymbolProc, Style::TernaryParentheses, Style::TrailingCommaInArguments, Style::TrailingCommaInArrayLiteral, Style::TrailingCommaInHashLiteral, Style::TrailingUnderscoreVariable, Style::UnlessElse, Style::YodaCondition, SurroundingSpace, TrailingComma
Defined in: lib/rubocop/cop/mixin/range_help.rb

Overview

Methods that calculate and return Parser::Source::Ranges

Constant Summary

Instance Method Summary

Instance Method Details

#add_range(range1, range2) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 140

def add_range(range1, range2)
  range1.with(
    begin_pos: [range1.begin_pos, range2.begin_pos].min,
    end_pos: [range1.end_pos, range2.end_pos].max
  )
end

#column_offset_between(base_range, range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 81

def column_offset_between(base_range, range)
  effective_column(base_range) - effective_column(range)
end

#contents_range(node) (private)

A range containing only the contents of a literal with delimiters (e.g. in %i{1 2 3} this will be the range covering 1 2 3 only).

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 32

def contents_range(node)
  range_between(node.loc.begin.end_pos, node.loc.end.begin_pos)
end

#directions(side) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 99

def directions(side)
  if side == :both
    [true, true]
  else
    [side == :left, side == :right]
  end
end

#effective_column(range) (private)

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value. This gives the column as it appears when viewing the file in an editor.

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 91

def effective_column(range)
  if range.line == 1 && @processed_source.raw_source.codepoints.first == BYTE_ORDER_MARK
    range.column - 1
  else
    range.column
  end
end

#final_pos(src, pos, increment, continuations, newlines, whitespace) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 108

def final_pos(src, pos, increment, continuations, newlines, whitespace)
  pos = move_pos(src, pos, increment, true, /[ \t]/)
  pos = move_pos_str(src, pos, increment, continuations, "\\\n")
  pos = move_pos(src, pos, increment, newlines, /\n/)
  move_pos(src, pos, increment, whitespace, /\s/)
end

#move_pos(src, pos, step, condition, regexp) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 116

def move_pos(src, pos, step, condition, regexp)
  offset = step == -1 ? -1 : 0
  pos += step while condition && regexp.match?(src[pos + offset])
  pos.negative? ? 0 : pos
end

#move_pos_str(src, pos, step, condition, needle) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 122

def move_pos_str(src, pos, step, condition, needle)
  size = needle.length
  offset = step == -1 ? -size : 0
  pos += size * step while condition && src[pos + offset, size] == needle
  pos.negative? ? 0 : pos
end

#range_between(start_pos, end_pos) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 36

def range_between(start_pos, end_pos)
  Parser::Source::Range.new(processed_source.buffer, start_pos, end_pos)
end

#range_by_whole_lines(range, include_final_newline: false, buffer: @processed_source.buffer) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 72

def range_by_whole_lines(range, include_final_newline: false,
                         buffer: @processed_source.buffer)
  last_line = buffer.source_line(range.last_line)
  end_offset = last_line.length - range.last_column
  end_offset += 1 if include_final_newline

  range.adjust(begin_pos: -range.column, end_pos: end_offset).intersect(buffer.source_range)
end

#range_with_comments(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 133

def range_with_comments(node)
  ranges = [node, *@processed_source.ast_with_comments[node]].map(&:source_range)
  ranges.reduce do |result, range|
    add_range(result, range)
  end
end

#range_with_comments_and_lines(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 129

def range_with_comments_and_lines(node)
  range_by_whole_lines(range_with_comments(node), include_final_newline: true)
end

#range_with_surrounding_comma(range, side = :both) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 40

def range_with_surrounding_comma(range, side = :both)
  buffer = @processed_source.buffer
  src = buffer.source

  go_left, go_right = directions(side)

  begin_pos = range.begin_pos
  end_pos = range.end_pos
  begin_pos = move_pos(src, begin_pos, -1, go_left, /,/)
  end_pos = move_pos(src, end_pos, 1, go_right, /,/)

  Parser::Source::Range.new(buffer, begin_pos, end_pos)
end

#range_with_surrounding_space(range_positional = NOT_GIVEN, range: NOT_GIVEN, side: :both, newlines: true, whitespace: false, continuations: false, buffer: @processed_source.buffer) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 55

def range_with_surrounding_space(range_positional = NOT_GIVEN, # rubocop:disable Metrics/ParameterLists
                                 range: NOT_GIVEN, side: :both, newlines: true,
                                 whitespace: false, continuations: false,
                                 buffer: @processed_source.buffer)
  range = range_positional unless range_positional == NOT_GIVEN

  src = buffer.source

  go_left, go_right = directions(side)

  begin_pos = range.begin_pos
  begin_pos = final_pos(src, begin_pos, -1, continuations, newlines, whitespace) if go_left
  end_pos = range.end_pos
  end_pos = final_pos(src, end_pos, 1, continuations, newlines, whitespace) if go_right
  Parser::Source::Range.new(buffer, begin_pos, end_pos)
end

#source_range(source_buffer, line_number, column, length = 1) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/mixin/range_help.rb', line 11

def source_range(source_buffer, line_number, column, length = 1)
  if column.is_a?(Range)
    column_index = column.begin
    length = column.size
  else
    column_index = column
  end

  line_begin_pos = if line_number.zero?
                     0
                   else
                     source_buffer.line_range(line_number).begin_pos
                   end
  begin_pos = line_begin_pos + column_index
  end_pos = begin_pos + length

  Parser::Source::Range.new(source_buffer, begin_pos, end_pos)
end