Created
June 10, 2023 07:32
-
-
Save tk0miya/852e2a8f05769f433985dc829add1b29 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# | |
# RBS::Location を marshal 可能にする試み。 | |
# ダンプサイズを減らし、load 後のメモリ使用量を抑える目的で、RBS::Buffer はそのままダンプせず、 | |
# ロード時に .rbs ファイルを再読み込みするようにしている。 | |
# | |
# marhsal キャッシュ導入前: | |
# 3.80s, 3.58s, 3.65s | |
# | |
# mashal キャッシュ導入後 (キャッシュなし): | |
# 8.50s, 8.15s, 7.97s | |
# | |
# mashal キャッシュ導入後 (キャッシュなし): | |
# 5.28s, 5.21s, 5.60s | |
# | |
# キャッシュを導入したほうがオリジナルコードより遅くなってしまうため、 | |
# このコードの採用は見送る。 | |
# ※ RBS::Writer を使って型情報をキャッシュする方式のほうが効果が見込める | |
# | |
require "rbs" | |
require "rbs/cli" | |
module RBS | |
module BufferMap | |
def self.find(filename) | |
@buffer_map ||= {} | |
@buffer_map[filename] ||= Buffer.new(name: filename, content: read(filename)) | |
end | |
def self.read(filename) | |
@content_map ||= {} | |
@content_map[filename] ||= File.read(filename) | |
end | |
end | |
class Buffer | |
def marshal_dump | |
name | |
end | |
def marshal_load(name) | |
@name = name | |
@content = BufferMap.read(name) | |
end | |
end | |
class Location | |
def marshal_dump | |
requireds = _required_keys.map { |key| [key, aref(key).range] } | |
optionals = _optional_keys.map { |key| [key, aref(key)&.range] } | |
[buffer.name, start_pos, end_pos, requireds, optionals] | |
end | |
def marshal_load(data) | |
filename, start_pos, end_pos, requireds, optionals = data | |
location = RBS::Location.new(buffer: BufferMap.find(filename), start_pos:, end_pos:) | |
requireds.reverse_each { |r| location.add_required_child(r[0], r[1]) } | |
optionals.reverse_each { |o| location.add_optional_child(o[0], o[1]) } | |
initialize_copy(location) | |
end | |
end | |
end | |
loader = RBS::CLI::LibraryOptions.new.loader | |
loader.add path: Pathname("sig") | |
env = RBS::Environment.from_loader(loader).resolve_type_names | |
location = env.declarations[0].location | |
p location | |
p location._required_keys | |
p location._optional_keys | |
File.open("test.dump", "wb") do |f| | |
f.write Marshal.dump(env) | |
end | |
File.open("test.dump", "rb") do |f| | |
env = Marshal.load(f.read) | |
end | |
location = env.declarations[0].location | |
p location | |
p location._required_keys | |
p location._optional_keys |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment