yard2rbs 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 74d0fab907be0a8229347fbda564913a08a6688b3b1c76db58ab98e52a783c3b
4
+ data.tar.gz: 1e51981642df3c3ee35cfd8a0e8c9651d6c03db6fff51bb7fd8d995f96101b13
5
+ SHA512:
6
+ metadata.gz: c29df8ed7704ff31f8a7640a52f3f50e02ccf654e0d999c25d3c228b162e9488c1abf598e71d63f39ec4c240ee1a2cd685dcd9a2b898d2d6c35b665035865d6c
7
+ data.tar.gz: 20c59a4b6462c4d14636587d7426faf377b2931ccb6c9ce7ae6eebaf5725ed58cc5dcc4859c6be00b46e6afd70e8efeec1c233bdba648e0b47a4d12d70b74bbb
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Kieran Pilkington
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # Yard2Rbs
2
+
3
+ Convert YARD documentation in Ruby files into RBS type definitions.
4
+
5
+ Utilizes `prism` Ruby parser to parse files and validates resulting RBS files.
6
+
7
+ ## Installation
8
+
9
+ Install the gem and add to the application's Gemfile by executing:
10
+
11
+ $ bundle add yard2rbs
12
+
13
+ If bundler is not being used to manage dependencies, install the gem by executing:
14
+
15
+ $ gem install yard2rbs
16
+
17
+ ## Usage
18
+
19
+ Convert all files:
20
+
21
+ ```
22
+ yard2rbs **/*.rb
23
+ ```
24
+
25
+ Convert specific files:
26
+
27
+ ```
28
+ yard2rbs app/models/user.rb app/services/user_creator.rb
29
+ ```
30
+
31
+ ## Contributing
32
+
33
+ Bug reports and pull requests are welcome on GitHub at https://github.com/KieranP/yard2rbs.
34
+
35
+ ## License
36
+
37
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/exe/yard2rbs ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "yard2rbs"
6
+
7
+ Yard2rbs.convert(ARGV)
@@ -0,0 +1,265 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "prism"
4
+
5
+ # https://ruby.github.io/prism/rb/index.html
6
+ # https://github.com/ruby/rbs/blob/master/docs/syntax.md
7
+ # https://github.com/ruby/rbs/blob/master/lib/rbs/prototype/rb.rb
8
+
9
+ module Yard2rbs
10
+ class Converter
11
+ # @param input_path [String]
12
+ # @return [void]
13
+ def initialize(input_path)
14
+ @parse_result = Prism.parse_file(input_path)
15
+ @parse_result.attach_comments!
16
+ @output = []
17
+ end
18
+
19
+ # @return [String]
20
+ def convert
21
+ @_indent_level = 0
22
+ # puts @parse_result.value.inspect
23
+ process(@parse_result.value)
24
+ output = @output.join("\n")
25
+ validate(output)
26
+ output
27
+ end
28
+
29
+ private
30
+
31
+ # @param node [Prism::Node]
32
+ # @return [true]
33
+ def process(node)
34
+ case node
35
+ when Array
36
+ node.each do |v|
37
+ process(v)
38
+ end
39
+
40
+ when Prism::ClassNode
41
+ if node.superclass
42
+ output("class #{node.constant_path.name} < #{node.superclass.name}")
43
+ else
44
+ output("class #{node.constant_path.name}")
45
+ end
46
+ @_indent_level += 1
47
+ process(node.compact_child_nodes)
48
+ @_indent_level -= 1
49
+ output("end")
50
+
51
+ when Prism::SingletonClassNode
52
+ @_within_singleton = true
53
+ process(node.compact_child_nodes)
54
+ @_within_singleton = false
55
+
56
+ when Prism::ModuleNode
57
+ output("module #{node.constant_path.name}")
58
+ @_indent_level += 1
59
+ process(node.compact_child_nodes)
60
+ @_indent_level -= 1
61
+ output("end")
62
+
63
+ when Prism::ConstantWriteNode
64
+ types = parse_comments(node)
65
+ type = format_types(types[:returns])
66
+ output("#{node.name}: #{type}")
67
+
68
+ when Prism::ClassVariableWriteNode
69
+ output("#{node.name}: untyped")
70
+
71
+ when Prism::InstanceVariableWriteNode
72
+ output("self.#{node.name}: untyped")
73
+
74
+ when Prism::DefNode
75
+ visibility = @_visibility_node&.name
76
+ receiver = "self." if self?(node)
77
+
78
+ types = parse_comments(@_visibility_node || node)
79
+ params = []
80
+ block = nil
81
+
82
+ if node.parameters
83
+ if node.parameters.requireds
84
+ node.parameters.requireds.each do |arg|
85
+ type = format_types(types[:params][arg.name.to_s])
86
+ params << "#{type} #{arg.name}"
87
+ end
88
+ end
89
+
90
+ if node.parameters.optionals
91
+ node.parameters.optionals.each do |arg|
92
+ type = format_types(types[:params][arg.name.to_s])
93
+ params << "?#{type} #{arg.name}"
94
+ end
95
+ end
96
+
97
+ if arg = node.parameters.rest
98
+ type = format_types(types[:params][arg.name.to_s])
99
+ params << "*#{type} #{arg.name}"
100
+ end
101
+
102
+ if node.parameters.keywords
103
+ node.parameters.keywords.each do |arg|
104
+ type = format_types(types[:params][arg.name.to_s])
105
+ if arg.is_a?(Prism::OptionalKeywordParameterNode)
106
+ params << "?#{arg.name}: #{type}"
107
+ else
108
+ params << "#{arg.name}: #{type}"
109
+ end
110
+ end
111
+ end
112
+
113
+ if arg = node.parameters.keyword_rest
114
+ type = format_types(types[:params][arg.name.to_s])
115
+ params << "**#{type} #{arg.name}"
116
+ end
117
+
118
+ if arg = node.parameters.block
119
+ block = "{ (?) -> untyped }"
120
+ end
121
+ end
122
+
123
+ return_type = format_types(types[:returns])
124
+
125
+ output([
126
+ visibility,
127
+ "def",
128
+ "#{receiver}#{node.name}:",
129
+ "(#{params.join(", ")})",
130
+ block,
131
+ "-> #{return_type}"
132
+ ].compact.join(' '))
133
+
134
+ when Prism::CallNode
135
+ case node.name
136
+ when :public, :private
137
+ if node.arguments
138
+ @_visibility_node = node
139
+ node.arguments.arguments.each do |inner_node|
140
+ process(inner_node)
141
+ end
142
+ @_visibility_node = nil
143
+ else
144
+ receiver = "self." if self?(node)
145
+ output("#{receiver}#{node.name}")
146
+ end
147
+
148
+ when :attr_accessor, :attr_reader, :attr_writer
149
+ if node.arguments
150
+ receiver = "self." if self?(node)
151
+ node.arguments.arguments.each do |arg|
152
+ output([
153
+ "#{receiver}#{node.name}",
154
+ "#{arg.unescaped}: untyped"
155
+ ].compact.join(' '))
156
+ end
157
+ end
158
+
159
+ when :extend, :prepend, :include
160
+ if node.arguments
161
+ receiver = "self." if self?(node)
162
+ node.arguments.arguments.each do |arg|
163
+ output("#{receiver}#{node.name} #{arg.name}")
164
+ end
165
+ end
166
+
167
+ when :alias_method
168
+ if node.arguments
169
+ args = node.arguments.arguments
170
+ new_name = args.first.unescaped
171
+ old_name = args.last.unescaped
172
+ output("#{receiver}alias #{new_name} #{old_name}")
173
+ end
174
+
175
+ else
176
+ process(node.compact_child_nodes)
177
+ end
178
+
179
+ when Prism::AliasMethodNode
180
+ new_name = node.new_name.unescaped
181
+ old_name = node.old_name.unescaped
182
+ output("alias #{new_name} #{old_name}")
183
+
184
+ else
185
+ process(node.compact_child_nodes)
186
+ end
187
+
188
+ true
189
+ end
190
+
191
+ # @param output [String]
192
+ # @return [true]
193
+ def validate(output)
194
+ RBS::Parser.parse_signature(output)
195
+ true
196
+ end
197
+
198
+ # @param str [String]
199
+ # @return [String]
200
+ def output(str)
201
+ @output << (" " * @_indent_level) + str
202
+ end
203
+
204
+ # @param node [Prism::Node]
205
+ # @return [Boolean]
206
+ def self?(node)
207
+ node.receiver&.type == :self_node ||
208
+ @_within_singleton
209
+ end
210
+
211
+ # @param node [Prism::Node]
212
+ # @return [Hash]
213
+ def parse_comments(node)
214
+ params = {}
215
+ returns = []
216
+
217
+ comments = node.location.comments
218
+ comments&.each do |comment|
219
+ line = comment.slice
220
+
221
+ case line
222
+ when /@param/
223
+ if matches = line.match(/# @param ([^\s]+) \[([^\]]+)\].*/)
224
+ types = matches[2].split(',').map(&:strip)
225
+ params[matches[1]] = convert_types(types)
226
+ end
227
+ when /@return/
228
+ if matches = line.match(/# @return \[([^\]]+)\].*/)
229
+ types = matches[1].split(',').map(&:strip)
230
+ returns += convert_types(types)
231
+ end
232
+ end
233
+ end
234
+
235
+ {
236
+ params: params,
237
+ returns: returns,
238
+ }
239
+ end
240
+
241
+ # @param types [String]
242
+ # @return [Array<String>]
243
+ def convert_types(types)
244
+ types.map do |type|
245
+ type.
246
+ gsub(/Array\<([^>]+)\>/, 'Array[\1]').
247
+ gsub(/Hash\<([^>]+),\s*([^>]+)\>/, 'Hash[\1,\2]')
248
+ end
249
+ end
250
+
251
+ # @param types [Array<String>]
252
+ # @return [String]
253
+ def format_types(types)
254
+ return 'untyped' if !types || types.size == 0
255
+
256
+ nilable = true if types.delete('nil')
257
+
258
+ if types.size > 1
259
+ "(#{types.join(' | ')})#{'?' if nilable}"
260
+ else
261
+ "#{types.first}#{'?' if nilable}"
262
+ end
263
+ end
264
+ end
265
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yard2rbs
4
+ # @return [String]
5
+ VERSION = "0.0.1"
6
+ end
data/lib/yard2rbs.rb ADDED
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "yard2rbs/converter"
4
+ require_relative "yard2rbs/version"
5
+
6
+ require "rbs"
7
+
8
+ module Yard2rbs
9
+ class << self
10
+ # @param file_paths [Array<String>]
11
+ # @return [Boolean]
12
+ def convert(file_paths)
13
+ # TODO: Clear out rbs/ directory
14
+
15
+ file_paths.each do |file_path|
16
+ output = Converter.new(file_path).convert
17
+ next if output.empty?
18
+
19
+ input_dirname = File.dirname(file_path)
20
+ input_filename = File.basename(file_path, ".*")
21
+
22
+ output_dirname = File.join("sig", input_dirname)
23
+ output_filename = "#{input_filename}.rbs"
24
+ output_path = File.join(output_dirname, output_filename)
25
+
26
+ FileUtils.mkdir_p(output_dirname)
27
+ File.open(output_path, 'w+') do |file|
28
+ file.puts(output)
29
+ end
30
+ end
31
+
32
+ true
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,14 @@
1
+ module Yard2rbs
2
+ class Converter
3
+ def initialize: (String input_path) -> void
4
+ def convert: () -> String
5
+ private
6
+ def process: (Prism::Node node) -> true
7
+ def validate: (String output) -> true
8
+ def output: (String str) -> String
9
+ def self?: (Prism::Node node) -> Boolean
10
+ def parse_comments: (Prism::Node node) -> Hash
11
+ def convert_types: (String types) -> Array[String]
12
+ def format_types: (Array[String] types) -> String
13
+ end
14
+ end
@@ -0,0 +1,3 @@
1
+ module Yard2rbs
2
+ VERSION: String
3
+ end
@@ -0,0 +1,3 @@
1
+ module Yard2rbs
2
+ def self.convert: (Array[String] file_paths) -> Boolean
3
+ end
metadata ADDED
@@ -0,0 +1,83 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: yard2rbs
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Kieran Pilkington
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-06-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: prism
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.30.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.30.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: rbs
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 3.5.1
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 3.5.1
41
+ description:
42
+ email:
43
+ - kieran776@gmail.com
44
+ executables:
45
+ - yard2rbs
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - ".rspec"
50
+ - LICENSE.txt
51
+ - README.md
52
+ - Rakefile
53
+ - exe/yard2rbs
54
+ - lib/yard2rbs.rb
55
+ - lib/yard2rbs/converter.rb
56
+ - lib/yard2rbs/version.rb
57
+ - sig/lib/yard2rbs.rbs
58
+ - sig/lib/yard2rbs/converter.rbs
59
+ - sig/lib/yard2rbs/version.rbs
60
+ homepage:
61
+ licenses:
62
+ - MIT
63
+ metadata: {}
64
+ post_install_message:
65
+ rdoc_options: []
66
+ require_paths:
67
+ - lib
68
+ required_ruby_version: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: 3.0.0
73
+ required_rubygems_version: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ version: '0'
78
+ requirements: []
79
+ rubygems_version: 3.5.9
80
+ signing_key:
81
+ specification_version: 4
82
+ summary: Convert YARD documentation into RBS files
83
+ test_files: []