Skip to content

Commit

Permalink
+ Add Source::TreeRewriter.default_diagnostics
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Jul 14, 2020
1 parent f14df41 commit 11e3e12
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
18 changes: 14 additions & 4 deletions lib/parser/source/tree_rewriter.rb
Expand Up @@ -95,6 +95,7 @@ def initialize(source_buffer,
crossing_deletions: :accept,
different_replacements: :accept,
swallowed_insertions: :accept)
@diagnostics = nil
@source_buffer = source_buffer
@in_transaction = false

Expand Down Expand Up @@ -321,12 +322,20 @@ def transaction
# Provides access to a diagnostic engine.
# By default outputs diagnostic to $stderr
#
def diagnostics
@diagnostics ||= Diagnostic::Engine.new.tap do |engine|
def self.default_diagnostics
@default_diagnostics ||= Diagnostic::Engine.new.tap do |engine|
engine.consumer = -> diag { $stderr.puts diag.render }
end
end

##
# Provides access to a diagnostic engine.
# By default: self.class.default_diagnostics
#
def diagnostics
@diagnostics ||= self.class.default_diagnostics.dup
end

def in_transaction?
@in_transaction
end
Expand Down Expand Up @@ -409,11 +418,12 @@ def policy(event)
def trigger_policy(event, range: raise, conflict: nil, **arguments)
action = policy(event)
diag = Parser::Diagnostic.new(POLICY_TO_LEVEL[action], event, arguments, range)
@diagnostics.process(diag)
engine = @diagnostics || self.class.default_diagnostics
engine.process(diag)
if conflict
range, *highlights = conflict
diag = Parser::Diagnostic.new(POLICY_TO_LEVEL[action], :"#{event}_conflict", arguments, range, highlights)
@diagnostics.process(diag)
engine.process(diag)
end
raise Parser::ClobberingError, "Parser::Source::TreeRewriter detected clobbering" if action == :raise
end
Expand Down
13 changes: 13 additions & 0 deletions test/test_source_tree_rewriter.rb
Expand Up @@ -298,6 +298,19 @@ def test_ordered_replacements
result.map {|r, s| [r.to_range, s]}
)
end

def test_default_diagnostics
default = Parser::Source::TreeRewriter.default_diagnostics
before = default.consumer
diagnostics = []
default.consumer = -> diag { diagnostics << diag.render }
rewriter = Parser::Source::TreeRewriter.new(@buf, swallowed_insertions: :warn)
rewriter.replace(@ll, 'xx')
rewriter.remove(@hello)
assert_equal(2, diagnostics.size)
ensure
default.consumer = before
end
end

class TestSourceTreeRewriterImport < Minitest::Test
Expand Down

0 comments on commit 11e3e12

Please sign in to comment.