Skip to content

Commit 2375d7a

Browse files
committed
Lazily compute code_units_cache in FileContext
Instead of eagerly computing the UTF-16 code units cache during parsing, store the Prism source and defer computation until first access. This avoids expensive String#encode calls when code_range positions are not immediately needed.
1 parent 5752d56 commit 2375d7a

2 files changed

Lines changed: 9 additions & 4 deletions

File tree

lib/typeprof/core/ast.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def self.parse_rb(path, src)
1111
raise unless raw_scope.type == :program_node
1212

1313
prism_source = result.source
14-
file_context = FileContext.new(path, prism_source.code_units_cache(Encoding::UTF_16LE), result.comments)
14+
file_context = FileContext.new(path, prism_source, result.comments)
1515

1616
cref = CRef::Toplevel
1717
lenv = LocalEnv.new(file_context, cref, {}, [])

lib/typeprof/core/env.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -305,12 +305,17 @@ class Hash[K, V]
305305
end
306306

307307
class FileContext
308-
attr_reader :path, :code_units_cache, :comments
309-
def initialize(path, code_units_cache = nil, comments = nil)
308+
attr_reader :path, :comments
309+
def initialize(path, prism_source = nil, comments = nil)
310310
@path = path
311-
@code_units_cache = code_units_cache
311+
@prism_source = prism_source
312+
@code_units_cache = nil
312313
@comments = comments
313314
end
315+
316+
def code_units_cache
317+
@code_units_cache ||= @prism_source&.code_units_cache(Encoding::UTF_16LE)
318+
end
314319
end
315320

316321
class LocalEnv

0 commit comments

Comments
 (0)