class

Ameba::Source::Rewriter

Inherits Reference < Object

This class performs the heavy lifting in the source rewriting process. It schedules code updates to be performed in the correct order.

For simple cases, the resulting source will be obvious.

Examples for more complex cases follow. Assume these examples are acting on the source puts(:hello, :world). The methods #wrap, #remove, etc. receive a range as the first two arguments; for clarity, examples below use English sentences and a string of raw code instead.

Overlapping deletions:

  • remove :hello,
  • remove , :world

The overlapping ranges are merged and :hello, :world will be removed.

Multiple actions at the same end points:

Results will always be independent of the order they were given. Exception: rewriting actions done on exactly the same range (covered next).

Example:

  • replace , by =>
  • wrap :hello, :world with { and }
  • replace :world with :everybody
  • wrap :world with [, ]

The resulting string will be puts({:hello => [:everybody]}) and this result is independent of the order the instructions were given in.

Multiple wraps on same range:

  • wrap :hello with ( and )
  • wrap :hello with [ and ]

The wraps are combined in order given and results would be puts([(:hello)], :world).

Multiple replacements on same range:

  • replace :hello by :hi, then
  • replace :hello by :hey

The replacements are made in the order given, so the latter replacement supersedes the former and :hello will be replaced by :hey.

Swallowed insertions:

  • wrap world by __, __
  • replace :hello, :world with :hi

A containing replacement will swallow the contained rewriting actions and :hello, :world will be replaced by :hi.

Implementation

The updates are organized in a tree, according to the ranges they act on (where children are strictly contained by their parent).

Constructors

new(code : String)
Source

Instance methods

code
Source
empty?

Returns true if no (non trivial) update has been recorded

Source
insert_after(begin_pos, end_pos, content)

Shortcut for wrap(begin_pos, end_pos, nil, content)

Source
insert_after(pos, content)

Shortcut for insert_after(pos, pos, content)

Source
insert_before(begin_pos, end_pos, content)

Shortcut for wrap(begin_pos, end_pos, content, nil)

Source
insert_before(pos, content)

Shortcut for insert_before(pos, pos, content)

Source
process

Applies all scheduled changes and returns modified source as a new string.

Source
remove(begin_pos, end_pos)

Shortcut for replace(begin_pos, end_pos, "")

Source
replace(begin_pos, end_pos, content)

Replaces the code of the given range with content.

Source
wrap(begin_pos, end_pos, insert_before, insert_after)

Inserts the given strings before and after the given range.

Source