Skip to content

Commit

Permalink
Migrate parsing to Prism
Browse files Browse the repository at this point in the history
Signed-off-by: Alexandre Terrasa <alexandre.terrasa@shopify.com>
  • Loading branch information
Morriar committed Mar 12, 2024
1 parent b399fbc commit a4d233a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 10 deletions.
25 changes: 17 additions & 8 deletions lib/spoom/deadcode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# frozen_string_literal: true

require "erubi"
require "syntax_tree"
require "prism"

require_relative "deadcode/erb"
require_relative "deadcode/index"
Expand All @@ -18,10 +18,15 @@
module Spoom
module Deadcode
class Error < Spoom::Error
extend T::Sig
extend T::Helpers

abstract!
end

class ParserError < Error; end

class IndexerError < Error
extend T::Sig

sig { params(message: String, parent: Exception).void }
def initialize(message, parent:)
Expand All @@ -30,17 +35,21 @@ def initialize(message, parent:)
end
end

class ParserError < Error; end
class IndexerError < Error; end

class << self
extend T::Sig

sig { params(ruby: String, file: String).returns(SyntaxTree::Node) }
def parse_ruby(ruby, file:)
SyntaxTree.parse(ruby)
rescue SyntaxTree::Parser::ParseError => e
raise ParserError.new("Error while parsing #{file} (#{e.message} at #{e.lineno}:#{e.column})", parent: e)
result = Prism.parse(ruby)
unless result.success?
message = result.errors.map do |e|
"#{e.message} (at #{e.location.start_line}:#{e.location.start_column})."
end.join(" ")

raise ParserError, "Error while parsing #{file}: #{message}"
end

result.value
end

sig do
Expand Down
3 changes: 2 additions & 1 deletion test/spoom/deadcode/index_definitions_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ def foo(
end

assert_equal(
"Error while parsing foo.rb (syntax error, unexpected end-of-input, expecting ')' at 1:9)",
"Error while parsing foo.rb: expected a `)` to close the parameters (at 1:8). " \
"cannot parse the expression (at 1:8). expected an `end` to close the `def` statement (at 1:8).",
exception.message,
)
end
Expand Down
2 changes: 1 addition & 1 deletion test/spoom/deadcode/plugins/graphql_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def dead; end
def test_ignore_method_splats
@project.write!("foo.rb", <<~RB)
field(:field1)
field(*args, **kwargs, &block) {}
field(*args, **kwargs) {}
def field1; end
RB
Expand Down

0 comments on commit a4d233a

Please sign in to comment.