Skip to content
Open
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
17 changes: 14 additions & 3 deletions templates/lib/prism/dsl.rb.erb
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#--
# rbs_inline: enabled

require_relative "polyfill/byteindex"

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 +64,16 @@ module Prism
#--
#: (String string) -> Source
def source(string)
Source.for(string, 1, [])
Source.for(string, 1, compute_offsets(string))
end

private def compute_offsets(code)
offsets = [0]
start = 0
while i = code.byteindex("\n", start)
offsets << (start = i + 1)
end
offsets
end

# Create a new Location object.
Expand Down Expand Up @@ -136,7 +147,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 Down
Loading