Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/prism/parse_result.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ class Source
# 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.
# byte offset whenever a newline character is encountered. The first
# element is always 0 to mark the first line.
#--
#: (String source, Integer start_line, Array[Integer] offsets) -> Source
def self.for(source, start_line, offsets)
Expand Down
6 changes: 5 additions & 1 deletion rbi/generated/prism/dsl.rbi

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion rbi/generated/prism/parse_result.rbi

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion sig/generated/prism/dsl.rbs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion sig/generated/prism/parse_result.rbs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 17 additions & 3 deletions templates/lib/prism/dsl.rb.erb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module Prism
# The DSL module provides a set of methods that can be used to create prism
# nodes in a more concise manner. For example, instead of writing:
#
# source = Prism::Source.for("[1]", 1, [])
# source = Prism::Source.for("[1]", 1, [0])
#
# Prism::ArrayNode.new(
# source,
Expand Down Expand Up @@ -62,7 +62,7 @@ module Prism
#--
#: (String string) -> Source
def source(string)
Source.for(string, 1, [])
Source.for(string, 1, build_offsets(string))
end

# Create a new Location object.
Expand Down Expand Up @@ -136,7 +136,7 @@ module Prism
#--
#: () -> Source
def default_source
Source.for("", 1, [])
Source.for("", 1, [0])
end

# The default location object that gets attached to nodes if no location is
Expand All @@ -154,5 +154,19 @@ module Prism
def default_node(source, location)
MissingNode.new(source, -1, location, 0)
end

private

# Build the newline byte offset array for the given source string.
#--
#: (String source) -> Array[Integer]
def build_offsets(source)
offsets = [0]
start = 0
while (index = source.byteindex("\n", start))
offsets << (start = index + 1)
end
offsets
end
end
end