class RBS::Rewriter
Rewriter performs targeted character-range replacements on Buffer content.
Unlike Writer which regenerates entire source from AST, Rewriter preserves everything outside the rewritten ranges, including non-documentation comments.
Rewrite requests are buffered and applied all at once when string is called.
Attributes
buffer
[R]
Buffer
Public Class Methods
(Buffer buffer) → void
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.1/lib/rbs/rewriter.rb, line 7 def initialize(buffer) raise "Rewriter only supports toplevel buffers" if buffer.parent @buffer = buffer @rewrites = [] end
Initialize with a toplevel buffer. Raises if the buffer has a parent (non-toplevel).
Public Instance Methods
(*Location[untyped, untyped] locations, content: String) → self
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.1/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
Add a new comment before the earliest of the given locations.
(AST::Comment comment) → self
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.1/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
Delete an existing comment.
(AST::Comment comment, content: String) → self
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.1/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
Replace an existing commentโs content.
(Location[untyped, untyped] location, String string) → self
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.1/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
Register a rewrite request for the given location.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.1/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
Apply all buffered rewrites and return the resulting string.
Raises if any rewrite ranges overlap.