rubocop 1.50.2 → 1.54.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (151) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +3 -3
  3. data/config/default.yml +80 -6
  4. data/lib/rubocop/cli/command/lsp.rb +19 -0
  5. data/lib/rubocop/cli.rb +3 -0
  6. data/lib/rubocop/config.rb +4 -0
  7. data/lib/rubocop/config_loader_resolver.rb +4 -3
  8. data/lib/rubocop/config_obsoletion.rb +2 -2
  9. data/lib/rubocop/cop/base.rb +5 -1
  10. data/lib/rubocop/cop/bundler/gem_comment.rb +1 -1
  11. data/lib/rubocop/cop/bundler/gem_version.rb +2 -2
  12. data/lib/rubocop/cop/correctors/alignment_corrector.rb +1 -1
  13. data/lib/rubocop/cop/gemspec/dependency_version.rb +2 -2
  14. data/lib/rubocop/cop/gemspec/development_dependencies.rb +1 -1
  15. data/lib/rubocop/cop/internal_affairs/cop_description.rb +32 -8
  16. data/lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb +3 -1
  17. data/lib/rubocop/cop/internal_affairs/node_matcher_directive.rb +5 -5
  18. data/lib/rubocop/cop/layout/class_structure.rb +7 -0
  19. data/lib/rubocop/cop/layout/closing_heredoc_indentation.rb +1 -2
  20. data/lib/rubocop/cop/layout/empty_line_between_defs.rb +27 -4
  21. data/lib/rubocop/cop/layout/empty_lines_around_exception_handling_keywords.rb +2 -0
  22. data/lib/rubocop/cop/layout/heredoc_argument_closing_parenthesis.rb +2 -2
  23. data/lib/rubocop/cop/layout/indentation_style.rb +1 -1
  24. data/lib/rubocop/cop/layout/indentation_width.rb +2 -2
  25. data/lib/rubocop/cop/layout/line_end_string_concatenation_indentation.rb +2 -0
  26. data/lib/rubocop/cop/layout/redundant_line_break.rb +1 -1
  27. data/lib/rubocop/cop/layout/space_after_comma.rb +9 -1
  28. data/lib/rubocop/cop/layout/space_around_operators.rb +3 -1
  29. data/lib/rubocop/cop/layout/space_inside_block_braces.rb +2 -0
  30. data/lib/rubocop/cop/layout/space_inside_range_literal.rb +1 -1
  31. data/lib/rubocop/cop/lint/ambiguous_block_association.rb +13 -1
  32. data/lib/rubocop/cop/lint/debugger.rb +9 -5
  33. data/lib/rubocop/cop/lint/duplicate_hash_key.rb +2 -1
  34. data/lib/rubocop/cop/lint/duplicate_regexp_character_class_element.rb +46 -19
  35. data/lib/rubocop/cop/lint/erb_new_arguments.rb +3 -4
  36. data/lib/rubocop/cop/lint/heredoc_method_call_position.rb +1 -1
  37. data/lib/rubocop/cop/lint/identity_comparison.rb +0 -1
  38. data/lib/rubocop/cop/lint/incompatible_io_select_with_fiber_scheduler.rb +5 -3
  39. data/lib/rubocop/cop/lint/inherit_exception.rb +9 -0
  40. data/lib/rubocop/cop/lint/lambda_without_literal_block.rb +1 -1
  41. data/lib/rubocop/cop/lint/missing_super.rb +34 -5
  42. data/lib/rubocop/cop/lint/mixed_case_range.rb +111 -0
  43. data/lib/rubocop/cop/lint/number_conversion.rb +5 -0
  44. data/lib/rubocop/cop/lint/numbered_parameter_assignment.rb +2 -2
  45. data/lib/rubocop/cop/lint/ordered_magic_comments.rb +0 -1
  46. data/lib/rubocop/cop/lint/out_of_range_regexp_ref.rb +2 -2
  47. data/lib/rubocop/cop/lint/redundant_regexp_quantifiers.rb +130 -0
  48. data/lib/rubocop/cop/lint/redundant_require_statement.rb +8 -3
  49. data/lib/rubocop/cop/lint/redundant_string_coercion.rb +1 -1
  50. data/lib/rubocop/cop/lint/send_with_mixin_argument.rb +1 -2
  51. data/lib/rubocop/cop/lint/shadowed_exception.rb +5 -11
  52. data/lib/rubocop/cop/lint/suppressed_exception.rb +1 -1
  53. data/lib/rubocop/cop/lint/symbol_conversion.rb +1 -1
  54. data/lib/rubocop/cop/lint/top_level_return_with_argument.rb +23 -9
  55. data/lib/rubocop/cop/lint/useless_assignment.rb +59 -1
  56. data/lib/rubocop/cop/lint/void.rb +57 -7
  57. data/lib/rubocop/cop/metrics/utils/abc_size_calculator.rb +1 -2
  58. data/lib/rubocop/cop/metrics/utils/code_length_calculator.rb +30 -2
  59. data/lib/rubocop/cop/migration/department_name.rb +2 -2
  60. data/lib/rubocop/cop/mixin/allowed_receivers.rb +34 -0
  61. data/lib/rubocop/cop/mixin/comments_help.rb +7 -3
  62. data/lib/rubocop/cop/mixin/end_keyword_alignment.rb +1 -1
  63. data/lib/rubocop/cop/mixin/heredoc.rb +6 -2
  64. data/lib/rubocop/cop/mixin/percent_literal.rb +1 -1
  65. data/lib/rubocop/cop/mixin/space_after_punctuation.rb +1 -1
  66. data/lib/rubocop/cop/naming/block_forwarding.rb +1 -1
  67. data/lib/rubocop/cop/naming/constant_name.rb +1 -1
  68. data/lib/rubocop/cop/naming/memoized_instance_variable_name.rb +25 -10
  69. data/lib/rubocop/cop/naming/rescued_exceptions_variable_name.rb +11 -3
  70. data/lib/rubocop/cop/naming/variable_name.rb +6 -1
  71. data/lib/rubocop/cop/style/accessor_grouping.rb +5 -1
  72. data/lib/rubocop/cop/style/attr.rb +11 -1
  73. data/lib/rubocop/cop/style/begin_block.rb +1 -2
  74. data/lib/rubocop/cop/style/block_comments.rb +1 -1
  75. data/lib/rubocop/cop/style/block_delimiters.rb +3 -3
  76. data/lib/rubocop/cop/style/class_and_module_children.rb +1 -1
  77. data/lib/rubocop/cop/style/class_equality_comparison.rb +17 -39
  78. data/lib/rubocop/cop/style/collection_compact.rb +16 -6
  79. data/lib/rubocop/cop/style/colon_method_call.rb +2 -2
  80. data/lib/rubocop/cop/style/combinable_loops.rb +26 -6
  81. data/lib/rubocop/cop/style/conditional_assignment.rb +5 -3
  82. data/lib/rubocop/cop/style/copyright.rb +5 -2
  83. data/lib/rubocop/cop/style/dir.rb +1 -1
  84. data/lib/rubocop/cop/style/dir_empty.rb +8 -14
  85. data/lib/rubocop/cop/style/document_dynamic_eval_definition.rb +1 -1
  86. data/lib/rubocop/cop/style/documentation.rb +1 -1
  87. data/lib/rubocop/cop/style/eval_with_location.rb +5 -5
  88. data/lib/rubocop/cop/style/exact_regexp_match.rb +68 -0
  89. data/lib/rubocop/cop/style/file_read.rb +2 -2
  90. data/lib/rubocop/cop/style/guard_clause.rb +2 -0
  91. data/lib/rubocop/cop/style/hash_each_methods.rb +1 -22
  92. data/lib/rubocop/cop/style/hash_except.rb +19 -8
  93. data/lib/rubocop/cop/style/hash_transform_keys.rb +2 -2
  94. data/lib/rubocop/cop/style/hash_transform_values.rb +2 -2
  95. data/lib/rubocop/cop/style/identical_conditional_branches.rb +6 -2
  96. data/lib/rubocop/cop/style/if_inside_else.rb +6 -0
  97. data/lib/rubocop/cop/style/if_unless_modifier.rb +3 -0
  98. data/lib/rubocop/cop/style/if_with_semicolon.rb +2 -2
  99. data/lib/rubocop/cop/style/invertible_unless_condition.rb +10 -6
  100. data/lib/rubocop/cop/style/lambda.rb +3 -3
  101. data/lib/rubocop/cop/style/method_call_with_args_parentheses/omit_parentheses.rb +3 -4
  102. data/lib/rubocop/cop/style/multiple_comparison.rb +14 -0
  103. data/lib/rubocop/cop/style/numeric_literals.rb +1 -1
  104. data/lib/rubocop/cop/style/percent_literal_delimiters.rb +1 -1
  105. data/lib/rubocop/cop/style/preferred_hash_methods.rb +1 -1
  106. data/lib/rubocop/cop/style/redundant_array_constructor.rb +77 -0
  107. data/lib/rubocop/cop/style/redundant_begin.rb +1 -1
  108. data/lib/rubocop/cop/style/redundant_conditional.rb +1 -1
  109. data/lib/rubocop/cop/style/redundant_current_directory_in_path.rb +38 -0
  110. data/lib/rubocop/cop/style/redundant_filter_chain.rb +101 -0
  111. data/lib/rubocop/cop/style/redundant_line_continuation.rb +7 -3
  112. data/lib/rubocop/cop/style/redundant_parentheses.rb +1 -1
  113. data/lib/rubocop/cop/style/redundant_regexp_argument.rb +100 -0
  114. data/lib/rubocop/cop/style/redundant_regexp_constructor.rb +46 -0
  115. data/lib/rubocop/cop/style/redundant_regexp_escape.rb +2 -1
  116. data/lib/rubocop/cop/style/redundant_self_assignment_branch.rb +3 -1
  117. data/lib/rubocop/cop/style/redundant_sort.rb +1 -1
  118. data/lib/rubocop/cop/style/redundant_string_escape.rb +2 -0
  119. data/lib/rubocop/cop/style/regexp_literal.rb +11 -2
  120. data/lib/rubocop/cop/style/require_order.rb +11 -5
  121. data/lib/rubocop/cop/style/rescue_modifier.rb +1 -3
  122. data/lib/rubocop/cop/style/return_nil_in_predicate_method_definition.rb +81 -0
  123. data/lib/rubocop/cop/style/select_by_regexp.rb +15 -5
  124. data/lib/rubocop/cop/style/semicolon.rb +12 -1
  125. data/lib/rubocop/cop/style/signal_exception.rb +1 -1
  126. data/lib/rubocop/cop/style/single_line_methods.rb +1 -1
  127. data/lib/rubocop/cop/style/sole_nested_conditional.rb +3 -1
  128. data/lib/rubocop/cop/style/special_global_vars.rb +3 -4
  129. data/lib/rubocop/cop/style/yaml_file_read.rb +66 -0
  130. data/lib/rubocop/cop/style/yoda_condition.rb +4 -2
  131. data/lib/rubocop/cop/team.rb +1 -1
  132. data/lib/rubocop/cop/util.rb +1 -1
  133. data/lib/rubocop/cop/utils/regexp_ranges.rb +100 -0
  134. data/lib/rubocop/cop/variable_force/assignment.rb +47 -4
  135. data/lib/rubocop/cop/variable_force/variable_table.rb +2 -2
  136. data/lib/rubocop/cop/variable_force.rb +1 -0
  137. data/lib/rubocop/cops_documentation_generator.rb +1 -1
  138. data/lib/rubocop/ext/regexp_parser.rb +4 -1
  139. data/lib/rubocop/lsp/logger.rb +22 -0
  140. data/lib/rubocop/lsp/routes.rb +231 -0
  141. data/lib/rubocop/lsp/runtime.rb +82 -0
  142. data/lib/rubocop/lsp/server.rb +66 -0
  143. data/lib/rubocop/lsp/severity.rb +27 -0
  144. data/lib/rubocop/options.rb +11 -1
  145. data/lib/rubocop/result_cache.rb +1 -1
  146. data/lib/rubocop/rspec/cop_helper.rb +1 -1
  147. data/lib/rubocop/server/client_command/exec.rb +2 -1
  148. data/lib/rubocop/target_ruby.rb +3 -2
  149. data/lib/rubocop/version.rb +10 -6
  150. data/lib/rubocop.rb +13 -0
  151. metadata +38 -6
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module Style
6
+ # Checks for the use of `YAML.load`, `YAML.safe_load`, and `YAML.parse` with
7
+ # `File.read` argument.
8
+ #
9
+ # NOTE: `YAML.safe_load_file` was introduced in Ruby 3.0.
10
+ #
11
+ # @example
12
+ #
13
+ # # bad
14
+ # YAML.load(File.read(path))
15
+ # YAML.parse(File.read(path))
16
+ #
17
+ # # good
18
+ # YAML.load_file(path)
19
+ # YAML.parse_file(path)
20
+ #
21
+ # # bad
22
+ # YAML.safe_load(File.read(path)) # Ruby 3.0 and newer
23
+ #
24
+ # # good
25
+ # YAML.safe_load_file(path) # Ruby 3.0 and newer
26
+ #
27
+ class YAMLFileRead < Base
28
+ extend AutoCorrector
29
+
30
+ MSG = 'Use `%<prefer>s` instead.'
31
+ RESTRICT_ON_SEND = %i[load safe_load parse].freeze
32
+
33
+ # @!method yaml_file_read?(node)
34
+ def_node_matcher :yaml_file_read?, <<~PATTERN
35
+ (send
36
+ (const {cbase nil?} :YAML) _
37
+ (send
38
+ (const {cbase nil?} :File) :read $_) $...)
39
+ PATTERN
40
+
41
+ def on_send(node)
42
+ return if node.method?(:safe_load) && target_ruby_version <= 2.7
43
+ return unless (file_path, rest_arguments = yaml_file_read?(node))
44
+
45
+ range = offense_range(node)
46
+ rest_arguments = if rest_arguments.empty?
47
+ ''
48
+ else
49
+ ", #{rest_arguments.map(&:source).join(', ')}"
50
+ end
51
+ prefer = "#{node.method_name}_file(#{file_path.source}#{rest_arguments})"
52
+
53
+ add_offense(range, message: format(MSG, prefer: prefer)) do |corrector|
54
+ corrector.replace(range, prefer)
55
+ end
56
+ end
57
+
58
+ private
59
+
60
+ def offense_range(node)
61
+ node.loc.selector.join(node.source_range.end)
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
@@ -118,16 +118,18 @@ module RuboCop
118
118
  node.comparison_method? && !noncommutative_operator?(node)
119
119
  end
120
120
 
121
+ # rubocop:disable Metrics/CyclomaticComplexity
121
122
  def valid_yoda?(node)
122
- lhs = node.receiver
123
- rhs = node.first_argument
123
+ return true unless (rhs = node.first_argument)
124
124
 
125
+ lhs = node.receiver
125
126
  return true if (constant_portion?(lhs) && constant_portion?(rhs)) ||
126
127
  (!constant_portion?(lhs) && !constant_portion?(rhs)) ||
127
128
  interpolation?(lhs)
128
129
 
129
130
  enforce_yoda? ? constant_portion?(lhs) : constant_portion?(rhs)
130
131
  end
132
+ # rubocop:enable Metrics/CyclomaticComplexity
131
133
 
132
134
  def message(node)
133
135
  format(MSG, source: node.source)
@@ -112,7 +112,7 @@ module RuboCop
112
112
  end
113
113
 
114
114
  def external_dependency_checksum
115
- keys = cops.map(&:external_dependency_checksum).compact
115
+ keys = cops.filter_map(&:external_dependency_checksum)
116
116
  Digest::SHA1.hexdigest(keys.join)
117
117
  end
118
118
 
@@ -142,7 +142,7 @@ module RuboCop
142
142
  end
143
143
 
144
144
  def escape_string(string)
145
- string.inspect[1..-2].tap { |s| s.gsub!(/\\"/, '"') }
145
+ string.inspect[1..-2].tap { |s| s.gsub!('\\"', '"') }
146
146
  end
147
147
 
148
148
  def to_string_literal(string)
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module Utils
6
+ # Helper to abstract complexity of building range pairs
7
+ # with octal escape reconstruction (needed for regexp_parser < 2.7).
8
+ class RegexpRanges
9
+ attr_reader :compound_token, :root
10
+
11
+ def initialize(root)
12
+ @root = root
13
+ @compound_token = []
14
+ end
15
+
16
+ def pairs
17
+ unless @pairs
18
+ @pairs = []
19
+ populate(root)
20
+ end
21
+
22
+ # If either bound is a compound the first one is an escape
23
+ # and that's all we need to work with.
24
+ # If there are any cops that wanted to operate on the compound
25
+ # expression we could wrap it with a facade class.
26
+ @pairs.map { |pair| pair.map(&:first) }
27
+ end
28
+
29
+ private
30
+
31
+ def populate(expr)
32
+ expressions = expr.expressions.to_a
33
+
34
+ until expressions.empty?
35
+ current = expressions.shift
36
+
37
+ if escaped_octal?(current)
38
+ compound_token << current
39
+ compound_token.concat(pop_octal_digits(expressions))
40
+ # If we have all the digits we can discard.
41
+ end
42
+
43
+ next unless current.type == :set
44
+
45
+ process_set(expressions, current)
46
+ compound_token.clear
47
+ end
48
+ end
49
+
50
+ def process_set(expressions, current)
51
+ case current.token
52
+ when :range
53
+ @pairs << compose_range(expressions, current)
54
+ when :character
55
+ # Child expressions may include the range we are looking for.
56
+ populate(current)
57
+ when :intersection
58
+ # Each child expression could have child expressions that lead to ranges.
59
+ current.expressions.each do |intersected|
60
+ populate(intersected)
61
+ end
62
+ end
63
+ end
64
+
65
+ def compose_range(expressions, current)
66
+ range_start, range_end = current.expressions
67
+ range_start = if compound_token.size.between?(1, 2) && octal_digit?(range_start.text)
68
+ compound_token.dup << range_start
69
+ else
70
+ [range_start]
71
+ end
72
+ range_end = [range_end]
73
+ range_end.concat(pop_octal_digits(expressions)) if escaped_octal?(range_end.first)
74
+ [range_start, range_end]
75
+ end
76
+
77
+ def escaped_octal?(expr)
78
+ expr.text =~ /^\\[0-7]$/
79
+ end
80
+
81
+ def octal_digit?(char)
82
+ ('0'..'7').cover?(char)
83
+ end
84
+
85
+ def pop_octal_digits(expressions)
86
+ digits = []
87
+
88
+ 2.times do
89
+ next unless (next_child = expressions.first)
90
+ next unless next_child.type == :literal && next_child.text =~ /^[0-7]$/
91
+
92
+ digits << expressions.shift
93
+ end
94
+
95
+ digits
96
+ end
97
+ end
98
+ end
99
+ end
100
+ end
@@ -47,6 +47,10 @@ module RuboCop
47
47
  @node.type == REGEXP_NAMED_CAPTURE_TYPE
48
48
  end
49
49
 
50
+ def exception_assignment?
51
+ node.parent&.resbody_type? && node.parent.exception_variable == node
52
+ end
53
+
50
54
  def operator_assignment?
51
55
  return false unless meta_assignment_node
52
56
 
@@ -59,6 +63,18 @@ module RuboCop
59
63
  meta_assignment_node.type == MULTIPLE_ASSIGNMENT_TYPE
60
64
  end
61
65
 
66
+ def rest_assignment?
67
+ return false unless meta_assignment_node
68
+
69
+ meta_assignment_node.type == REST_ASSIGNMENT_TYPE
70
+ end
71
+
72
+ def for_assignment?
73
+ return false unless meta_assignment_node
74
+
75
+ meta_assignment_node.for_type?
76
+ end
77
+
62
78
  def operator
63
79
  assignment_node = meta_assignment_node || @node
64
80
  assignment_node.loc.operator.source
@@ -66,7 +82,10 @@ module RuboCop
66
82
 
67
83
  def meta_assignment_node
68
84
  unless instance_variable_defined?(:@meta_assignment_node)
69
- @meta_assignment_node = operator_assignment_node || multiple_assignment_node
85
+ @meta_assignment_node = operator_assignment_node ||
86
+ multiple_assignment_node ||
87
+ rest_assignment_node ||
88
+ for_assignment_node
70
89
  end
71
90
 
72
91
  @meta_assignment_node
@@ -83,13 +102,37 @@ module RuboCop
83
102
  end
84
103
 
85
104
  def multiple_assignment_node
86
- grandparent_node = node.parent&.parent
87
- return nil unless grandparent_node
105
+ return nil unless (grandparent_node = node.parent&.parent)
106
+ if (node = find_multiple_assignment_node(grandparent_node))
107
+ return node
108
+ end
88
109
  return nil unless grandparent_node.type == MULTIPLE_ASSIGNMENT_TYPE
89
- return nil unless node.parent.type == MULTIPLE_LEFT_HAND_SIDE_TYPE
90
110
 
91
111
  grandparent_node
92
112
  end
113
+
114
+ def rest_assignment_node
115
+ return nil unless node.parent
116
+ return nil unless node.parent.type == REST_ASSIGNMENT_TYPE
117
+
118
+ node.parent
119
+ end
120
+
121
+ def for_assignment_node
122
+ return nil unless node.parent&.for_type?
123
+
124
+ node.parent
125
+ end
126
+
127
+ def find_multiple_assignment_node(grandparent_node)
128
+ return unless grandparent_node.type == MULTIPLE_LEFT_HAND_SIDE_TYPE
129
+ return if grandparent_node.children.any?(&:splat_type?)
130
+
131
+ parent = grandparent_node.parent
132
+ return parent if parent.type == MULTIPLE_ASSIGNMENT_TYPE
133
+
134
+ find_multiple_assignment_node(parent)
135
+ end
93
136
  end
94
137
  end
95
138
  end
@@ -113,14 +113,14 @@ module RuboCop
113
113
  def accessible_variables
114
114
  scope_stack.reverse_each.with_object([]) do |scope, variables|
115
115
  variables.concat(scope.variables.values)
116
- break variables unless scope.node.block_type?
116
+ break variables unless scope.node.block_type? || scope.node.numblock_type?
117
117
  end
118
118
  end
119
119
 
120
120
  private
121
121
 
122
122
  def mark_variable_as_captured_by_block_if_so(variable)
123
- return unless current_scope.node.block_type?
123
+ return unless current_scope.node.block_type? || current_scope.node.numblock_type?
124
124
  return if variable.scope == current_scope
125
125
 
126
126
  variable.capture_with_block!
@@ -40,6 +40,7 @@ module RuboCop
40
40
  OPERATOR_ASSIGNMENT_TYPES = (LOGICAL_OPERATOR_ASSIGNMENT_TYPES + [:op_asgn]).freeze
41
41
 
42
42
  MULTIPLE_ASSIGNMENT_TYPE = :masgn
43
+ REST_ASSIGNMENT_TYPE = :splat
43
44
 
44
45
  VARIABLE_REFERENCE_TYPE = :lvar
45
46
 
@@ -198,7 +198,7 @@ class CopsDocumentationGenerator # rubocop:disable Metrics/ClassLength
198
198
  table = ['|===', "| #{header.join(' | ')}\n\n"].join("\n")
199
199
  marked_contents = content.map do |plain_content|
200
200
  # Escape `|` with backslash to prevent the regexp `|` is not used as a table separator.
201
- plain_content.map { |c| "| #{c.gsub(/\|/, '\|')}" }.join("\n")
201
+ plain_content.map { |c| "| #{c.gsub('|', '\|')}" }.join("\n")
202
202
  end
203
203
  table << marked_contents.join("\n\n")
204
204
  table << "\n|===\n"
@@ -68,7 +68,9 @@ module RuboCop
68
68
  return { body: expression } unless (q = quantifier)
69
69
 
70
70
  body = expression.adjust(end_pos: -q.text.length)
71
- q_loc = expression.with(begin_pos: body.end_pos)
71
+ q.origin = origin
72
+ q.source = source if q.respond_to?(:source=) # for regexp_parser 1.8
73
+ q_loc = q.expression
72
74
  { body: body, quantifier: q_loc }
73
75
  end
74
76
  end
@@ -86,6 +88,7 @@ module RuboCop
86
88
  end
87
89
  end
88
90
  ::Regexp::Expression::Base.include Expression::Base
91
+ ::Regexp::Expression::Quantifier.include Expression::Base
89
92
  ::Regexp::Expression::CharacterSet.include Expression::CharacterSet
90
93
  end
91
94
  end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # This code is based on https://github.com/standardrb/standard.
5
+ #
6
+ # Copyright (c) 2023 Test Double, Inc.
7
+ #
8
+ # The MIT License (MIT)
9
+ #
10
+ # https://github.com/standardrb/standard/blob/main/LICENSE.txt
11
+ #
12
+ module RuboCop
13
+ module Lsp
14
+ # Log for Language Server Protocol of RuboCop.
15
+ # @api private
16
+ class Logger
17
+ def self.log(message)
18
+ warn("[server] #{message}")
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,231 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'severity'
4
+
5
+ #
6
+ # This code is based on https://github.com/standardrb/standard.
7
+ #
8
+ # Copyright (c) 2023 Test Double, Inc.
9
+ #
10
+ # The MIT License (MIT)
11
+ #
12
+ # https://github.com/standardrb/standard/blob/main/LICENSE.txt
13
+ #
14
+ module RuboCop
15
+ module Lsp
16
+ # Routes for Language Server Protocol of RuboCop.
17
+ # @api private
18
+ class Routes
19
+ def self.handle(name, &block)
20
+ define_method("handle_#{name}", &block)
21
+ end
22
+
23
+ private_class_method :handle
24
+
25
+ def initialize(server)
26
+ @server = server
27
+
28
+ @text_cache = {}
29
+ end
30
+
31
+ def for(name)
32
+ name = "handle_#{name}"
33
+ return unless respond_to?(name)
34
+
35
+ method(name)
36
+ end
37
+
38
+ handle 'initialize' do |request|
39
+ @server.configure(safe_autocorrect: safe_autocorrect?(request))
40
+
41
+ @server.write(
42
+ id: request[:id],
43
+ result: LanguageServer::Protocol::Interface::InitializeResult.new(
44
+ capabilities: LanguageServer::Protocol::Interface::ServerCapabilities.new(
45
+ document_formatting_provider: true,
46
+ diagnostic_provider: true,
47
+ text_document_sync: LanguageServer::Protocol::Interface::TextDocumentSyncOptions.new(
48
+ change: LanguageServer::Protocol::Constant::TextDocumentSyncKind::FULL,
49
+ open_close: true
50
+ )
51
+ )
52
+ )
53
+ )
54
+ end
55
+
56
+ handle 'initialized' do |_request|
57
+ version = RuboCop::Version::STRING
58
+
59
+ Logger.log("RuboCop #{version} language server initialized, PID #{Process.pid}")
60
+ end
61
+
62
+ handle 'shutdown' do |request|
63
+ Logger.log('Client asked to shutdown RuboCop language server.')
64
+ @server.stop do
65
+ @server.write(id: request[:id], result: nil)
66
+ Logger.log('Exiting...')
67
+ end
68
+ end
69
+
70
+ handle 'textDocument/diagnostic' do |request|
71
+ doc = request[:params][:textDocument]
72
+ result = diagnostic(doc[:uri], doc[:text])
73
+ @server.write(result)
74
+ end
75
+
76
+ handle 'textDocument/didChange' do |request|
77
+ params = request[:params]
78
+ result = diagnostic(params[:textDocument][:uri], params[:contentChanges][0][:text])
79
+ @server.write(result)
80
+ end
81
+
82
+ handle 'textDocument/didOpen' do |request|
83
+ doc = request[:params][:textDocument]
84
+ result = diagnostic(doc[:uri], doc[:text])
85
+ @server.write(result)
86
+ end
87
+
88
+ handle 'textDocument/didClose' do |request|
89
+ @text_cache.delete(request.dig(:params, :textDocument, :uri))
90
+ end
91
+
92
+ handle 'textDocument/formatting' do |request|
93
+ uri = request[:params][:textDocument][:uri]
94
+ @server.write(id: request[:id], result: format_file(uri))
95
+ end
96
+
97
+ handle 'workspace/didChangeConfiguration' do |_request|
98
+ Logger.log('Ignoring workspace/didChangeConfiguration')
99
+ end
100
+
101
+ handle 'workspace/didChangeWatchedFiles' do |request|
102
+ changed = request[:params][:changes].any? do |change|
103
+ change[:uri].end_with?(RuboCop::ConfigFinder::DOTFILE)
104
+ end
105
+
106
+ if changed
107
+ Logger.log('Configuration file changed; restart required')
108
+ @server.stop
109
+ end
110
+ end
111
+
112
+ handle 'workspace/executeCommand' do |request|
113
+ if request[:params][:command] == 'rubocop.formatAutocorrects'
114
+ uri = request[:params][:arguments][0][:uri]
115
+ @server.write(
116
+ id: request[:id],
117
+ method: 'workspace/applyEdit',
118
+ params: {
119
+ label: 'Format with RuboCop autocorrects',
120
+ edit: {
121
+ changes: {
122
+ uri => format_file(uri)
123
+ }
124
+ }
125
+ }
126
+ )
127
+ else
128
+ handle_unsupported_method(request, request[:params][:command])
129
+ end
130
+ end
131
+
132
+ handle 'textDocument/willSave' do |_request|
133
+ # Nothing to do
134
+ end
135
+
136
+ handle 'textDocument/didSave' do |_request|
137
+ # Nothing to do
138
+ end
139
+
140
+ handle '$/cancelRequest' do |_request|
141
+ # Can't cancel anything because single-threaded
142
+ end
143
+
144
+ handle '$/setTrace' do |_request|
145
+ # No-op, we log everything
146
+ end
147
+
148
+ def handle_unsupported_method(request, method = request[:method])
149
+ @server.write(
150
+ id: request[:id],
151
+ error: LanguageServer::Protocol::Interface::ResponseError.new(
152
+ code: LanguageServer::Protocol::Constant::ErrorCodes::METHOD_NOT_FOUND,
153
+ message: "Unsupported Method: #{method}"
154
+ )
155
+ )
156
+ Logger.log("Unsupported Method: #{method}")
157
+ end
158
+
159
+ def handle_method_missing(request)
160
+ return unless request.key?(:id)
161
+
162
+ @server.write(id: request[:id], result: nil)
163
+ end
164
+
165
+ private
166
+
167
+ def safe_autocorrect?(request)
168
+ safe_autocorrect = request.dig(:params, :initializationOptions, :safeAutocorrect)
169
+
170
+ safe_autocorrect.nil? || safe_autocorrect == true
171
+ end
172
+
173
+ def format_file(file_uri)
174
+ unless (text = @text_cache[file_uri])
175
+ Logger.log("Format request arrived before text synchronized; skipping: `#{file_uri}'")
176
+
177
+ return []
178
+ end
179
+
180
+ new_text = @server.format(remove_file_protocol_from(file_uri), text)
181
+
182
+ return [] if new_text == text
183
+
184
+ [
185
+ newText: new_text,
186
+ range: {
187
+ start: { line: 0, character: 0 },
188
+ end: { line: text.count("\n") + 1, character: 0 }
189
+ }
190
+ ]
191
+ end
192
+
193
+ def diagnostic(file_uri, text)
194
+ @text_cache[file_uri] = text
195
+ offenses = @server.offenses(remove_file_protocol_from(file_uri), text)
196
+ diagnostics = offenses.map { |offense| to_diagnostic(offense) }
197
+
198
+ {
199
+ method: 'textDocument/publishDiagnostics',
200
+ params: {
201
+ uri: file_uri,
202
+ diagnostics: diagnostics
203
+ }
204
+ }
205
+ end
206
+
207
+ def remove_file_protocol_from(uri)
208
+ uri.delete_prefix('file://')
209
+ end
210
+
211
+ def to_diagnostic(offense)
212
+ code = offense[:cop_name]
213
+ message = offense[:message]
214
+ loc = offense[:location]
215
+ rubocop_severity = offense[:severity]
216
+ severity = Severity.find_by(rubocop_severity)
217
+
218
+ {
219
+ code: code, message: message, range: to_range(loc), severity: severity, source: 'rubocop'
220
+ }
221
+ end
222
+
223
+ def to_range(location)
224
+ {
225
+ start: { character: location[:start_column] - 1, line: location[:start_line] - 1 },
226
+ end: { character: location[:last_column] - 1, line: location[:last_line] - 1 }
227
+ }
228
+ end
229
+ end
230
+ end
231
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # This code is based on https://github.com/standardrb/standard.
5
+ #
6
+ # Copyright (c) 2023 Test Double, Inc.
7
+ #
8
+ # The MIT License (MIT)
9
+ #
10
+ # https://github.com/standardrb/standard/blob/main/LICENSE.txt
11
+ #
12
+ module RuboCop
13
+ module Lsp
14
+ # Runtime for Language Server Protocol of RuboCop.
15
+ # @api private
16
+ class Runtime
17
+ attr_writer :safe_autocorrect
18
+
19
+ def initialize(config_store)
20
+ @config_store = config_store
21
+ @logged_paths = []
22
+ @safe_autocorrect = true
23
+ end
24
+
25
+ # This abuses the `--stdin` option of rubocop and reads the formatted text
26
+ # from the `options[:stdin]` that rubocop mutates. This depends on
27
+ # `parallel: false` as well as the fact that RuboCop doesn't otherwise dup
28
+ # or reassign that options object. Risky business!
29
+ #
30
+ # Reassigning `options[:stdin]` is done here:
31
+ # https://github.com/rubocop/rubocop/blob/v1.52.0/lib/rubocop/cop/team.rb#L131
32
+ # Printing `options[:stdin]`
33
+ # https://github.com/rubocop/rubocop/blob/v1.52.0/lib/rubocop/cli/command/execute_runner.rb#L95
34
+ # Setting `parallel: true` would break this here:
35
+ # https://github.com/rubocop/rubocop/blob/v1.52.0/lib/rubocop/runner.rb#L72
36
+ def format(path, text)
37
+ formatting_options = {
38
+ stdin: text, force_exclusion: true, autocorrect: true, safe_autocorrect: @safe_autocorrect
39
+ }
40
+
41
+ redirect_stdout { run_rubocop(formatting_options, path) }
42
+
43
+ formatting_options[:stdin]
44
+ end
45
+
46
+ def offenses(path, text)
47
+ diagnostic_options = {
48
+ stdin: text, force_exclusion: true, formatters: ['json'], format: 'json'
49
+ }
50
+
51
+ json = redirect_stdout { run_rubocop(diagnostic_options, path) }
52
+ results = JSON.parse(json, symbolize_names: true)
53
+
54
+ if results[:files].empty?
55
+ unless @logged_paths.include?(path)
56
+ Logger.log "Ignoring file, per configuration: #{path}"
57
+ @logged_paths << path
58
+ end
59
+ return []
60
+ end
61
+
62
+ results.dig(:files, 0, :offenses)
63
+ end
64
+
65
+ private
66
+
67
+ def redirect_stdout(&block)
68
+ stdout = StringIO.new
69
+
70
+ RuboCop::Server::Helper.redirect(stdout: stdout, &block)
71
+
72
+ stdout.string
73
+ end
74
+
75
+ def run_rubocop(options, path)
76
+ runner = RuboCop::Runner.new(options, @config_store)
77
+
78
+ runner.run([path])
79
+ end
80
+ end
81
+ end
82
+ end