File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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 )
Original file line number Diff line number Diff line change 11#--
22# rbs_inline: enabled
33
4+ require_relative "polyfill/byteindex"
5+
46module 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
You can’t perform that action at this time.
0 commit comments