Skip to content

Commit 1d89447

Browse files
committed
Ensure Source#offsets is set correctly in all cases
* See #3861
1 parent eceb44d commit 1d89447

2 files changed

Lines changed: 16 additions & 4 deletions

File tree

lib/prism/parse_result.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ class Source
2626
# source is a subset of a larger source or if this is an eval. offsets is an
2727
# array of byte offsets for the start of each line in the source code, which
2828
# can be calculated by iterating through the source code and recording the
29-
# byte offset whenever a newline character is encountered.
29+
# byte offset whenever a newline character is encountered. The first
30+
# element is always 0 to mark the first line.
3031
#--
3132
#: (String source, Integer start_line, Array[Integer] offsets) -> Source
3233
def self.for(source, start_line, offsets)

templates/lib/prism/dsl.rb.erb

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
#--
22
# rbs_inline: enabled
33

4+
require_relative "polyfill/byteindex"
5+
46
module Prism
57
# The DSL module provides a set of methods that can be used to create prism
68
# nodes in a more concise manner. For example, instead of writing:
79
#
8-
# source = Prism::Source.for("[1]", 1, [])
10+
# source = Prism::Source.for("[1]", 1, [0])
911
#
1012
# Prism::ArrayNode.new(
1113
# source,
@@ -62,7 +64,16 @@ module Prism
6264
#--
6365
#: (String string) -> Source
6466
def source(string)
65-
Source.for(string, 1, [])
67+
Source.for(string, 1, compute_offsets(string))
68+
end
69+
70+
private def compute_offsets(code)
71+
offsets = [0]
72+
start = 0
73+
while i = code.byteindex("\n", start)
74+
offsets << (start = i + 1)
75+
end
76+
offsets
6677
end
6778

6879
# Create a new Location object.
@@ -136,7 +147,7 @@ module Prism
136147
#--
137148
#: () -> Source
138149
def default_source
139-
Source.for("", 1, [])
150+
Source.for("", 1, [0])
140151
end
141152

142153
# The default location object that gets attached to nodes if no location is

0 commit comments

Comments
 (0)