Class: RBS::Rewriter
- Inherits:
-
Object
- Object
- RBS::Rewriter
- Defined in:
- lib/rbs/rewriter.rb
Instance Attribute Summary collapse
-
#buffer ⇒ Object
readonly
Returns the value of attribute buffer.
Instance Method Summary collapse
- #add_comment(*locations, content:) ⇒ Object
- #delete_comment(comment) ⇒ Object
-
#initialize(buffer) ⇒ Rewriter
constructor
A new instance of Rewriter.
- #replace_comment(comment, content:) ⇒ Object
- #rewrite(location, string) ⇒ Object
- #string ⇒ Object
Constructor Details
#initialize(buffer) ⇒ Rewriter
Returns a new instance of Rewriter.
7 8 9 10 11 12 |
# File 'lib/rbs/rewriter.rb', line 7 def initialize(buffer) raise "Rewriter only supports toplevel buffers" if buffer.parent @buffer = buffer @rewrites = [] end |
Instance Attribute Details
#buffer ⇒ Object (readonly)
Returns the value of attribute buffer.
5 6 7 |
# File 'lib/rbs/rewriter.rb', line 5 def buffer @buffer end |
Instance Method Details
#add_comment(*locations, content:) ⇒ Object
25 26 27 28 29 30 31 32 33 34 |
# File 'lib/rbs/rewriter.rb', line 25 def add_comment(*locations, content:) earliest = locations.min_by(&:start_pos) or raise "At least one location is required" insert_pos = earliest.start_pos indent = " " * earliest.start_column formatted = format_comment(content, indent) loc = Location.new(buffer, insert_pos, insert_pos) rewrite(loc, "#{formatted}\n#{indent}") end |
#delete_comment(comment) ⇒ Object
43 44 45 46 47 48 49 |
# File 'lib/rbs/rewriter.rb', line 43 def delete_comment(comment) location = comment.location or raise "Comment must have a location" line_start = location.start_pos - location.start_column line_end = location.end_pos + 1 loc = Location.new(buffer, line_start, line_end) rewrite(loc, "") end |
#replace_comment(comment, content:) ⇒ Object
36 37 38 39 40 41 |
# File 'lib/rbs/rewriter.rb', line 36 def replace_comment(comment, content:) location = comment.location or raise "Comment must have a location" indent = " " * location.start_column rewrite(location, format_comment(content, indent)) end |
#rewrite(location, string) ⇒ Object
14 15 16 17 18 19 20 21 22 23 |
# File 'lib/rbs/rewriter.rb', line 14 def rewrite(location, string) @rewrites.each do |existing_location, _| if location.start_pos < existing_location.end_pos && existing_location.start_pos < location.end_pos raise "Overlapping rewrites: #{existing_location} and #{location}" end end @rewrites << [location, string] self end |
#string ⇒ Object
51 52 53 54 55 56 57 58 59 |
# File 'lib/rbs/rewriter.rb', line 51 def string result = buffer.content.dup @rewrites.sort_by { |location, _| location.start_pos }.reverse_each do |location, replacement| result[location.start_pos...location.end_pos] = replacement end result end |