This represents a source of Ruby code that has been parsed. It is used in conjunction with locations to allow them to resolve line numbers and source ranges.

Attributes
Read

The list of newline byte offsets in the source code.

Read

The source code that this source object represents.

Read

The line number where this source starts.

Class Methods

Create a new source object with the given source code. This method should be used instead of new and it will return either a Source or a specialized and more performant ASCIISource if no multibyte characters are present in the source code.

Note that if you are calling this method manually, you will need to supply the start_line and offsets parameters. start_line is the line number that the source starts on, which is typically 1 but can be different if this source is a subset of a larger source or if this is an eval. offsets is an array of byte offsets for the start of each line in the source code, which can be calculated by iterating through the source code and recording the byte offset whenever a newline character is encountered.

Create a new source object with the given source code.

Instance Methods

Converts the line number and column in bytes to a byte offset.

Return the column in characters for the given byte offset.

Return the character offset for the given byte offset.

Generate a cache that targets a specific encoding for calculating code unit offsets.

Returns the column in code units for the given encoding for the given byte offset.

Returns the offset from the start of the file for the given byte offset counting in code units for the given encoding.

This method is tested with UTF-8, UTF-16, and UTF-32. If there is the concept of code units that differs from the number of characters in other encodings, it is not captured here.

We purposefully replace invalid and undefined characters with replacement characters in this conversion. This happens for two reasons. First, it’s possible that the given byte offset will not occur on a character boundary. Second, it’s possible that the source code will contain a character that has no equivalent in the given encoding.

Return the column in bytes for the given byte offset.

Freeze this object and the objects it contains.

Returns the encoding of the source code, which is set by parameters to the parser or by the encoding magic comment.

Binary search through the offsets to find the line number for the given byte offset.

Returns the byte offset of the end of the line corresponding to the given byte offset.

Returns the lines of the source code as an array of strings.

Return the byte offset of the start of the line corresponding to the given byte offset.

Replace the value of offsets with the given value.

Replace the value of start_line with the given value.

Perform a byteslice on the source code using the given byte offset and byte length.