yard_to_rbs_inline 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 75ff275975592a47d67427039bdbb4eb3a617b4dd5b0b08f64529a51a71aac9a
4
+ data.tar.gz: c15d5a93607172ed4a3753b3bcef47ffa9429c657a470423bdbc9d135398b6ab
5
+ SHA512:
6
+ metadata.gz: 1809ffd8bfa11fef92442a8450be27c12c11fbe178d62c896308f3bb5bf7024626cbd95e73a760053462625b025117e14a03547d97d5491328a6ece252fdc8b5
7
+ data.tar.gz: 9974e192dd12b4d49f25ebf3284b32f19aa9b86be7c34a9afeb1d30a3c5a4be7e694922a256021daa6ec07f37329f8dd998c18e04fd23ed8241151c18ea2689f
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-05-10
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at tomo.asleep@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Tomoya Chiba
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # yard → rbs-inline
2
+
3
+ Rewrite YARD type annotations in Your codes to rbs-inline.
4
+
5
+ ## Usage
6
+
7
+ ```console
8
+ bundle
9
+
10
+ # Print rewrited code to stdout.
11
+ ./exe/yard-rbs-inline --dry-run your-file.rb
12
+
13
+ # Overwrite files.
14
+ ./exe/yard-rbs-inline your-file.rb
15
+ ```
data/Rakefile ADDED
@@ -0,0 +1,21 @@
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
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
13
+
14
+ desc "Build parser files generated by racc"
15
+ task racc: [
16
+ "lib/yard_to_rbs_inline/yard_type/parser.rb"
17
+ ]
18
+
19
+ rule ".rb" => ".y" do |t|
20
+ sh "bundle exec racc #{t.source} -o #{t.name}"
21
+ end
@@ -0,0 +1,23 @@
1
+ class Code
2
+ # @return [String]
3
+ attr_reader :source
4
+
5
+ # @param source [String]
6
+ def initialize(source)
7
+ @source = source
8
+ end
9
+
10
+ # @param new_source [String]
11
+ # @return [Code]
12
+ def rewrite(new_source)
13
+ @source = new_source
14
+
15
+ self
16
+ end
17
+
18
+ # @param recover [Boolean].
19
+ # @return [Array<Token>]
20
+ def tokenize(recover: false)
21
+ parser.tokenize(source, recover: recover)
22
+ end
23
+ end
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ if Dir.exist?(File.join(__dir__, "..", ".git"))
4
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
5
+ end
6
+
7
+ require 'yard_to_rbs_inline'
8
+ YardToRbsInline::Cli.start(ARGV)
@@ -0,0 +1,19 @@
1
+ # rbs_inline: enabled
2
+
3
+ require 'optparse'
4
+
5
+ module YardToRbsInline
6
+ class Cli
7
+ def self.start(argv)
8
+ opt = OptionParser.new
9
+ dry_run = false
10
+
11
+ opt.on('-n', '--dry-run', 'Dry run') { dry_run = true }
12
+ opt.parse!(argv)
13
+
14
+ argv.each do |file|
15
+ Converter.convert(file, dry_run: dry_run)
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,270 @@
1
+ # rbs_inline: enabled
2
+
3
+ require_relative 'subscriptable'
4
+
5
+ module YardToRbsInline
6
+ module Converter
7
+ class CodeVisitor < Prism::Visitor
8
+ include Subscriptable
9
+
10
+ # @!rbs
11
+ # type mod = PrependLine | AppendLineContent
12
+
13
+ attr_reader :source #:: Prism::Source
14
+
15
+ attr_reader :comments #:: Array[Prism::InlineComment]
16
+
17
+ attr_reader :text_with_mod #:: TextWithMod
18
+
19
+ #:: (source: Prism::Source, comments: Array[Prism::InlineComment]) -> untyped
20
+ def initialize(source:, comments:)
21
+ @source = source
22
+ @comments = comments
23
+ @text_with_mod = TextWithMod.new(source.source)
24
+ end
25
+
26
+ #:: (Prism::CallNode) -> void
27
+ def visit_call_node(node)
28
+ parse_annotation = lambda do
29
+ annotation_comments = annotations_for(node)
30
+ annotation_strs = annotation_comments.map(&method(:source_for_comment))
31
+ annotation_strs.map(&:chomp).join("\n")
32
+ end
33
+
34
+ case node.name.to_sym
35
+ when :attr_reader
36
+ annotation = parse_annotation.call
37
+
38
+ unless annotation.match?(/^\s*#(::|\s*@rbs)/)
39
+ docstring = YARD::DocstringParser.new.parse(annotation.gsub(/^\s*#\s*/, '')).to_docstring
40
+
41
+ sig = capture_error_to_write_comment(node) { build_return_sig(docstring) }
42
+ text_with_mod.mods << AppendLineContent.from_node_and_content(node, "#:: #{sig}")
43
+ end
44
+ end
45
+
46
+ super
47
+ end
48
+
49
+ #:: (Prism::DefNode) -> void
50
+ def visit_def_node(node)
51
+ annotation_comments = annotations_for(node)
52
+ annotation_strs = annotation_comments.map(&method(:source_for_comment))
53
+ annotation = annotation_strs.map(&:chomp).join("\n")
54
+
55
+ unless annotation.match?(/^\s*#(::|\s*@rbs)/)
56
+ docstring = YARD::DocstringParser.new.parse(annotation.gsub(/^\s*#\s*/, '')).to_docstring
57
+
58
+ sig = capture_error_to_write_comment(node) { build_signature(node.parameters, docstring) }
59
+
60
+ text_with_mod.mods << PrependLine.from_node_and_content(node, "#:: #{sig}")
61
+
62
+ # STDERR.puts "#{node.name_loc.inspect} #{node.name}: #{sig}"
63
+ end
64
+
65
+ super
66
+ end
67
+
68
+ private
69
+
70
+ #:: (YARD::Docstring) -> String
71
+ def build_return_sig(docstring)
72
+ return_tag = docstring.tag("return") #:: YARD::Tags::Tag | nil
73
+
74
+ if return_tag&.types
75
+ convert_types(return_tag.types)
76
+ else
77
+ "untyped"
78
+ end
79
+ end
80
+
81
+ #:: (Prism::ParametersNode | nil, YARD::Docstring) -> String
82
+ def build_signature(params, docstring)
83
+ params_sig = build_params_signature(params, docstring)
84
+ return_sig = build_return_sig(docstring)
85
+
86
+ "(#{params_sig}) -> #{return_sig}"
87
+ end
88
+
89
+ #:: (Prism::ParametersNode | nil, YARD::Docstring) -> String
90
+ def build_params_signature(params, docstring)
91
+ return "" unless params
92
+
93
+ param_tags = docstring.tags("param") #:: Array[YARD::Tags::Tag]
94
+
95
+ find_tag = proc do |name|
96
+ if name
97
+ param_tags.find { |tag| tag.name == name.to_s }
98
+ else
99
+ nil
100
+ end
101
+ end
102
+
103
+ param_sigs = []
104
+ params.requireds.each do |param|
105
+ tag = find_tag.call(param.name)
106
+
107
+ if tag&.types
108
+ param_sigs << "#{convert_types(tag.types)} #{param.name}"
109
+ else
110
+ param_sigs << "untyped #{param.name}"
111
+ end
112
+ end
113
+
114
+ params.optionals.each do |param|
115
+ tag = find_tag.call(param.name)
116
+
117
+ if tag&.types
118
+ param_sigs << "?#{convert_types(tag.types)} #{param.name}"
119
+ else
120
+ param_sigs << "?untyped #{param.name}"
121
+ end
122
+ end
123
+
124
+ if (param = params.rest)
125
+ tag = find_tag.call(param.name)
126
+
127
+ if tag&.types
128
+ param_sigs << "*#{convert_types(tag.types)} #{param.name}"
129
+ else
130
+ param_sigs << "*untyped #{param.name}"
131
+ end
132
+ end
133
+
134
+ params.posts.each do |param|
135
+ tag = find_tag.call(param.name)
136
+
137
+ if tag&.types
138
+ param_sigs << "#{convert_types(tag.types)} #{param.name}"
139
+ else
140
+ param_sigs << "untyped #{param.name}"
141
+ end
142
+ end
143
+
144
+ params.keywords.each do |param|
145
+ tag = find_tag.call(param.name)
146
+
147
+ prefix =
148
+ case param.type
149
+ when :required_keyword_parameter_node
150
+ ""
151
+ when :optional_keyword_parameter_node
152
+ "?"
153
+ end
154
+
155
+ if tag && tag.types
156
+ param_sigs << "#{prefix}#{param.name}: #{convert_types(tag.types)}"
157
+ else
158
+ param_sigs << "#{prefix}#{param.name}: untyped"
159
+ end
160
+ end
161
+
162
+ if (param = params.keyword_rest)
163
+ tag = find_tag.call(param.name)
164
+
165
+ if tag&.types
166
+ param_sigs << "**#{convert_types(tag.types)} #{param.name}"
167
+ else
168
+ param_sigs << "**untyped #{param.name}"
169
+ end
170
+ end
171
+
172
+ # Remove trailing spaces for unnamed params
173
+ param_sigs.map(&:strip).join(", ")
174
+ end
175
+
176
+ #:: (Array[String], node: Prism::Node) -> String
177
+ def convert_types(yard_type_literals)
178
+ new_types = yard_type_literals.map do |literal|
179
+ yard_type = YardToRbsInline::YardType::Parser.new.parse(literal)
180
+ convert_yard_type(yard_type)
181
+ rescue Racc::ParseError, Yoda::Parsing::YardType::Scanner::ScanError => e
182
+ # STDERR.puts "Cannot parse #{literal}: #{e}"
183
+ emit_error_message("Cannot parse #{literal}: #{e}")
184
+
185
+ 'untyped'
186
+ end.uniq
187
+
188
+ new_types.empty? ? 'untyped' : new_types.join(' | ')
189
+ end
190
+
191
+ #:: (YardToRbsInline::YardType::Ast::node, node: Prism::Node) -> String
192
+ def convert_yard_type(yard_type)
193
+ case yard_type
194
+ in YardType::Ast::Type(name:)
195
+ case name
196
+ when "Object"
197
+ "untyped"
198
+ when "Boolean", "TrueClass", "FalseClass", "boolean", "true", "false"
199
+ "bool"
200
+ else
201
+ name
202
+ end
203
+ in YardType::Ast::DuckType(name:)
204
+ case name
205
+ when "each"
206
+ "Enumerable"
207
+ else
208
+ emit_error_message("Unknown duck type: ##{name}")
209
+ "untyped"
210
+ end
211
+ in YardType::Ast::LiteralType(content:)
212
+ content
213
+ in YardType::Ast::GenericType(container_type:, types:)
214
+ container_sig = container_type ? convert_yard_type(container_type) : "Array"
215
+ "#{container_sig}[#{types.map(&method(:convert_yard_type)).join(' | ')}]"
216
+ in YardType::Ast::TupleType(container_type:, types:)
217
+ container_sig = container_type ? convert_yard_type(container_type) : "Array"
218
+ "#{container_sig} & [#{types.map(&method(:convert_yard_type)).join(', ')}]"
219
+ in YardType::Ast::HashType(container_type:, type_pair: [key_type, value_type])
220
+ container_sig = container_type ? convert_yard_type(container_type) : "Hash"
221
+ "#{container_sig}[#{convert_yard_type(key_type)}, #{convert_yard_type(value_type)}]"
222
+ in YardType::Ast::UnionType(types:)
223
+ types.map(&method(:convert_yard_type)).join(' | ')
224
+ end
225
+ end
226
+
227
+ #:: (Prism::Node) -> Integer
228
+ def start_line_of_node(node)
229
+ gather_comment_targets = proc do |l|
230
+ if l.respond_to?(:comment_targets)
231
+ l.comment_targets.flat_map { |t| gather_comment_targets.call(t) }
232
+ else
233
+ [l]
234
+ end
235
+ end
236
+
237
+ gather_comment_targets.call(node).map(&:start_line).min || 0
238
+ end
239
+
240
+ #:: (Prism::Node) -> Array[Prism::InlineComment]
241
+ def annotations_for(node)
242
+ start_line = start_line_of_node(node)
243
+
244
+ matched_comments = []
245
+ matched_comments += comments_by_line[start_line] if comments_by_line[start_line]
246
+
247
+ (start_line - 1).downto(1) do |line|
248
+ current_comments = comments_by_line[line]
249
+ if current_comments
250
+ matched_comments += current_comments
251
+ else
252
+ break
253
+ end
254
+ end
255
+
256
+ matched_comments
257
+ end
258
+
259
+ #:: (Prism::InlineComment) -> String
260
+ def source_for_comment(comment)
261
+ source.slice(comment.location.start_offset, comment.location.length)
262
+ end
263
+
264
+ #:: () -> Hash[Integer, Array[Prism::InlineComment]]
265
+ def comments_by_line
266
+ @comments_by_line ||= comments.group_by { |comment| comment.location.start_line }
267
+ end
268
+ end
269
+ end
270
+ end
@@ -0,0 +1,34 @@
1
+ # rbs_inline: enabled
2
+
3
+ module YardToRbsInline
4
+ module Converter
5
+ module Subscriptable
6
+ # @rbs!
7
+ # type subscriber = ^(String) -> void
8
+
9
+ #:: (String) -> void
10
+ def emit_error_message(error_message)
11
+ (@subscribers || []).each { |subscriber| subscriber.call(error_message) }
12
+ end
13
+
14
+ #:: [X] (subscriber) { () -> X } -> X
15
+ def capture_error_message(subscriber)
16
+ @subscribers ||= []
17
+ @subscribers.push(subscriber)
18
+ yield
19
+ ensure
20
+ @subscribers.pop
21
+ end
22
+
23
+ #:: (Prism::Node) -> subscriber
24
+ def subscriber_to_prepend_error(node)
25
+ lambda { |message| text_with_mod.mods << PrependLine.from_node_and_content(node, "# YARD to RBS Error: #{message}") }
26
+ end
27
+
28
+ #:: [X] (Prism::Node) { () -> X } -> X
29
+ def capture_error_to_write_comment(node)
30
+ capture_error_message(subscriber_to_prepend_error(node)) { yield }
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,56 @@
1
+ # rbs_inline: enabled
2
+
3
+ module YardToRbsInline
4
+ module Converter
5
+ PrependLine = Data.define(:line_num, :content) do
6
+ #:: (Prism::Node, String) -> PrependLine
7
+ def self.from_node_and_content(node, comment_content)
8
+ start_line = node.location.start_line
9
+ start_column = node.location.start_column
10
+
11
+ line = ' ' * start_column + comment_content
12
+
13
+ PrependLine.new(line_num: start_line, content: line)
14
+ end
15
+ end
16
+
17
+ AppendLineContent = Data.define(:line_num, :content) do
18
+ #:: (Prism::Node, String) -> PrependLine
19
+ def self.from_node_and_content(node, comment_content)
20
+ start_line = node.location.start_line
21
+
22
+ AppendLineContent.new(line_num: start_line, content: ' ' + comment_content)
23
+ end
24
+ end
25
+
26
+ class TextWithMod
27
+ attr_reader :original_text #:: Prism::Source
28
+
29
+ attr_reader :mods #:: Array[mod]
30
+
31
+ #:: (String) -> untyped
32
+ def initialize(original_text)
33
+ @original_text = original_text
34
+ @mods = []
35
+ end
36
+
37
+ #:: () -> String
38
+ def modified_text
39
+ prepended_line_nums = []
40
+ mods.reduce(original_text.lines(chomp: true)) do |source_lines, mod|
41
+ real_line_num = mod.line_num + prepended_line_nums.map { |i| i <= mod.line_num }.length # 1-index
42
+
43
+ case mod
44
+ in PrependLine(content:)
45
+ prepended_line_nums << mod.line_num
46
+ source_lines.insert(real_line_num - 1, content)
47
+ in AppendLineContent(content:)
48
+ source_lines[real_line_num - 1] += content
49
+ end
50
+
51
+ source_lines
52
+ end.join("\n") + "\n"
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,28 @@
1
+ require 'prism'
2
+ require 'yard'
3
+
4
+ module YardToRbsInline
5
+ module Converter
6
+ def self.convert(file, dry_run: false)
7
+ result = Prism.parse_file(file)
8
+
9
+ visitor = CodeVisitor.new(source: result.source, comments: result.comments)
10
+ unless result.source.source.match(/^# rbs_inline:/)
11
+ visitor.text_with_mod.mods << PrependLine.new(line_num: 1, content: "# rbs_inline: enabled")
12
+ visitor.text_with_mod.mods << PrependLine.new(line_num: 1, content: "")
13
+ end
14
+
15
+ result.value.accept(visitor)
16
+
17
+ if dry_run
18
+ puts visitor.text_with_mod.modified_text
19
+ else
20
+ File.write(file, visitor.text_with_mod.modified_text)
21
+ end
22
+ end
23
+ end
24
+ end
25
+
26
+ require_relative "converter/code_visitor"
27
+ require_relative "converter/subscriptable"
28
+ require_relative "converter/text_with_mod"
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YardToRbsInline
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,27 @@
1
+ # rbs_inline: enabled
2
+
3
+ module YardToRbsInline
4
+ module YardType
5
+ module Ast
6
+ # @rbs!
7
+ # type node = Type | LiteralType | DuckType | GenericType | TupleType | HashType | UnionType
8
+
9
+ Type = Struct.new(:name, keyword_init: true)
10
+ LiteralType = Struct.new(:content, keyword_init: true)
11
+ DuckType = Struct.new(:name, keyword_init: true)
12
+ GenericType = Struct.new(:container_type, :types, keyword_init: true)
13
+ TupleType = Struct.new(:container_type, :types, keyword_init: true)
14
+ HashType = Struct.new(:container_type, :type_pair, keyword_init: true)
15
+ UnionType = Struct.new(:types, keyword_init: true) do
16
+ #:: (untyped types) -> untyped
17
+ def self.build(types)
18
+ if types.length == 1
19
+ types.first
20
+ else
21
+ UnionType.new(types: types)
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,307 @@
1
+ #
2
+ # DO NOT MODIFY!!!!
3
+ # This file is automatically generated by Racc 1.7.1
4
+ # from Racc grammar file "".
5
+ #
6
+
7
+ require 'racc/parser.rb'
8
+
9
+ # Note: Prepend magic comment by script because default comments are prepended to header.
10
+
11
+ module YardToRbsInline
12
+ module YardType
13
+ class Parser < Racc::Parser
14
+
15
+ module_eval(<<'...end parser.y/module_eval...', 'parser.y', 34)
16
+
17
+ #:: (String) -> Ast::node
18
+ def parse(string)
19
+ @tokens = Scanner.new(string).to_racc_tokens
20
+
21
+ do_parse()
22
+ end
23
+
24
+ #:: () -> untyped
25
+ def next_token
26
+ @tokens.shift
27
+ end
28
+
29
+ ...end parser.y/module_eval...
30
+ ##### State transition tables begin ###
31
+
32
+ racc_action_table = [
33
+ 8, 9, 16, 10, 17, 11, 17, 12, 13, 14,
34
+ 15, 8, 9, 32, 10, 21, 11, 17, 12, 13,
35
+ 14, 15, 8, 9, 36, 10, 26, 11, 33, 12,
36
+ 13, 14, 15, 8, 9, 34, 10, 37, 11, nil,
37
+ 12, 13, 14, 15, 8, 9, nil, 10, nil, 11,
38
+ nil, 12, 13, 14, 15, 8, 9, nil, 10, nil,
39
+ 11, nil, 12, 13, 14, 15, 8, 9, nil, 10,
40
+ nil, 11, nil, 12, 13, 14, 15, 8, 9, nil,
41
+ 10, nil, 11, nil, 12, 13, 14, 15, 8, 9,
42
+ nil, 10, 18, 11, 19, 12, 13, 14, 15, 20,
43
+ 18, 17, 19, 17, nil, nil, 31, 20, 35 ]
44
+
45
+ racc_action_check = [
46
+ 0, 0, 1, 0, 2, 0, 23, 0, 0, 0,
47
+ 0, 10, 10, 23, 10, 8, 10, 29, 10, 10,
48
+ 10, 10, 11, 11, 29, 11, 16, 11, 24, 11,
49
+ 11, 11, 11, 15, 15, 25, 15, 30, 15, nil,
50
+ 15, 15, 15, 15, 17, 17, nil, 17, nil, 17,
51
+ nil, 17, 17, 17, 17, 18, 18, nil, 18, nil,
52
+ 18, nil, 18, 18, 18, 18, 19, 19, nil, 19,
53
+ nil, 19, nil, 19, 19, 19, 19, 20, 20, nil,
54
+ 20, nil, 20, nil, 20, 20, 20, 20, 33, 33,
55
+ nil, 33, 3, 33, 3, 33, 33, 33, 33, 3,
56
+ 27, 22, 27, 28, nil, nil, 22, 27, 28 ]
57
+
58
+ racc_action_pointer = [
59
+ -3, 2, 2, 86, nil, nil, nil, nil, 11, nil,
60
+ 8, 19, nil, nil, nil, 30, 26, 41, 52, 63,
61
+ 74, nil, 99, 4, 23, 21, nil, 94, 101, 15,
62
+ 23, nil, nil, 85, nil, nil, nil, nil, nil ]
63
+
64
+ racc_action_default = [
65
+ -20, -20, -1, -3, -4, -5, -6, -7, -20, -9,
66
+ -20, -20, -15, -16, -17, -20, -20, -20, -20, -20,
67
+ -20, -8, -20, -20, -20, -20, 39, -2, -20, -20,
68
+ -20, -12, -14, -20, -19, -11, -13, -18, -10 ]
69
+
70
+ racc_goto_table = [
71
+ 1, 22, 23, 25, 27, nil, nil, nil, 30, 28,
72
+ 29, nil, nil, nil, nil, nil, nil, nil, nil, nil,
73
+ nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
74
+ nil, nil, nil, 38 ]
75
+
76
+ racc_goto_check = [
77
+ 1, 2, 2, 8, 3, nil, nil, nil, 8, 2,
78
+ 2, nil, nil, nil, nil, nil, nil, nil, nil, nil,
79
+ nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
80
+ nil, nil, nil, 1 ]
81
+
82
+ racc_goto_pointer = [
83
+ nil, 0, -9, -13, nil, nil, nil, nil, -12 ]
84
+
85
+ racc_goto_default = [
86
+ nil, 24, 2, 3, 4, 5, 6, 7, nil ]
87
+
88
+ racc_reduce_table = [
89
+ 0, 0, :racc_error,
90
+ 1, 16, :_reduce_1,
91
+ 3, 17, :_reduce_2,
92
+ 1, 17, :_reduce_3,
93
+ 1, 18, :_reduce_none,
94
+ 1, 18, :_reduce_none,
95
+ 1, 18, :_reduce_none,
96
+ 1, 18, :_reduce_7,
97
+ 2, 18, :_reduce_8,
98
+ 1, 18, :_reduce_9,
99
+ 3, 23, :_reduce_10,
100
+ 4, 19, :_reduce_11,
101
+ 3, 19, :_reduce_12,
102
+ 4, 20, :_reduce_13,
103
+ 3, 20, :_reduce_14,
104
+ 1, 22, :_reduce_none,
105
+ 1, 22, :_reduce_none,
106
+ 1, 22, :_reduce_none,
107
+ 4, 21, :_reduce_18,
108
+ 3, 21, :_reduce_19 ]
109
+
110
+ racc_reduce_n = 20
111
+
112
+ racc_shift_n = 39
113
+
114
+ racc_token_table = {
115
+ false => 0,
116
+ :error => 1,
117
+ :SEPARATOR => 2,
118
+ :DUCK_SYMBOL => 3,
119
+ :NAME => 4,
120
+ :ARROW => 5,
121
+ :GENERIC_START => 6,
122
+ :GENERIC_END => 7,
123
+ :TUPLE_START => 8,
124
+ :TUPLE_END => 9,
125
+ :SYMBOL => 10,
126
+ :STRING => 11,
127
+ :INTEGER => 12,
128
+ :HASH_START => 13,
129
+ :HASH_END => 14 }
130
+
131
+ racc_nt_base = 15
132
+
133
+ racc_use_result_var = true
134
+
135
+ Racc_arg = [
136
+ racc_action_table,
137
+ racc_action_check,
138
+ racc_action_default,
139
+ racc_action_pointer,
140
+ racc_goto_table,
141
+ racc_goto_check,
142
+ racc_goto_default,
143
+ racc_goto_pointer,
144
+ racc_nt_base,
145
+ racc_reduce_table,
146
+ racc_token_table,
147
+ racc_shift_n,
148
+ racc_reduce_n,
149
+ racc_use_result_var ]
150
+ Ractor.make_shareable(Racc_arg) if defined?(Ractor)
151
+
152
+ Racc_token_to_s_table = [
153
+ "$end",
154
+ "error",
155
+ "SEPARATOR",
156
+ "DUCK_SYMBOL",
157
+ "NAME",
158
+ "ARROW",
159
+ "GENERIC_START",
160
+ "GENERIC_END",
161
+ "TUPLE_START",
162
+ "TUPLE_END",
163
+ "SYMBOL",
164
+ "STRING",
165
+ "INTEGER",
166
+ "HASH_START",
167
+ "HASH_END",
168
+ "$start",
169
+ "expression",
170
+ "type_list",
171
+ "type_single",
172
+ "generic_type",
173
+ "tuple_type",
174
+ "hash_type",
175
+ "literal_type",
176
+ "type_pair" ]
177
+ Ractor.make_shareable(Racc_token_to_s_table) if defined?(Ractor)
178
+
179
+ Racc_debug_parser = false
180
+
181
+ ##### State transition tables end #####
182
+
183
+ # reduce 0 omitted
184
+
185
+ module_eval(<<'.,.,', 'parser.y', 3)
186
+ def _reduce_1(val, _values, result)
187
+ result = Ast::UnionType.build(val[0])
188
+ result
189
+ end
190
+ .,.,
191
+
192
+ module_eval(<<'.,.,', 'parser.y', 5)
193
+ def _reduce_2(val, _values, result)
194
+ result = [*val[0], val[2]]
195
+ result
196
+ end
197
+ .,.,
198
+
199
+ module_eval(<<'.,.,', 'parser.y', 6)
200
+ def _reduce_3(val, _values, result)
201
+ result = [val[0]]
202
+ result
203
+ end
204
+ .,.,
205
+
206
+ # reduce 4 omitted
207
+
208
+ # reduce 5 omitted
209
+
210
+ # reduce 6 omitted
211
+
212
+ module_eval(<<'.,.,', 'parser.y', 11)
213
+ def _reduce_7(val, _values, result)
214
+ result = Ast::LiteralType.new(content: val[0])
215
+ result
216
+ end
217
+ .,.,
218
+
219
+ module_eval(<<'.,.,', 'parser.y', 12)
220
+ def _reduce_8(val, _values, result)
221
+ result = Ast::DuckType.new(name: val[1])
222
+ result
223
+ end
224
+ .,.,
225
+
226
+ module_eval(<<'.,.,', 'parser.y', 13)
227
+ def _reduce_9(val, _values, result)
228
+ result = Ast::Type.new(name: val[0])
229
+ result
230
+ end
231
+ .,.,
232
+
233
+ module_eval(<<'.,.,', 'parser.y', 15)
234
+ def _reduce_10(val, _values, result)
235
+ result = [val[0], val[2]]
236
+ result
237
+ end
238
+ .,.,
239
+
240
+ module_eval(<<'.,.,', 'parser.y', 17)
241
+ def _reduce_11(val, _values, result)
242
+ result = Ast::GenericType.new(container_type: val[0], types: val[2])
243
+ result
244
+ end
245
+ .,.,
246
+
247
+ module_eval(<<'.,.,', 'parser.y', 18)
248
+ def _reduce_12(val, _values, result)
249
+ result = Ast::GenericType.new(types: val[1])
250
+ result
251
+ end
252
+ .,.,
253
+
254
+ module_eval(<<'.,.,', 'parser.y', 20)
255
+ def _reduce_13(val, _values, result)
256
+ result = Ast::TupleType.new(container_type: val[0], types: val[2])
257
+ result
258
+ end
259
+ .,.,
260
+
261
+ module_eval(<<'.,.,', 'parser.y', 21)
262
+ def _reduce_14(val, _values, result)
263
+ result = Ast::TupleType.new(types: val[1])
264
+ result
265
+ end
266
+ .,.,
267
+
268
+ # reduce 15 omitted
269
+
270
+ # reduce 16 omitted
271
+
272
+ # reduce 17 omitted
273
+
274
+ module_eval(<<'.,.,', 'parser.y', 25)
275
+ def _reduce_18(val, _values, result)
276
+ result = Ast::HashType.new(container_type: val[0], type_pair: val[2])
277
+ result
278
+ end
279
+ .,.,
280
+
281
+ module_eval(<<'.,.,', 'parser.y', 26)
282
+ def _reduce_19(val, _values, result)
283
+ result = Ast::HashType.new(type_pair: val[1])
284
+ result
285
+ end
286
+ .,.,
287
+
288
+ def _reduce_none(val, _values, result)
289
+ val[0]
290
+ end
291
+
292
+ end # class Parser
293
+ end # module YardType
294
+ end # module YardToRbsInline
295
+
296
+
297
+ module Yoda
298
+ module Parsing
299
+ module YardType
300
+ class Parser
301
+ # @rbs!
302
+ # def parse: (String) -> Ast::node
303
+ # def next_token: () -> untyped
304
+ end
305
+ end
306
+ end
307
+ end
@@ -0,0 +1,59 @@
1
+ class YardToRbsInline::YardType::Parser
2
+ start expression
3
+ rule
4
+ expression : type_list { result = Ast::UnionType.build(val[0]) }
5
+
6
+ type_list : type_list SEPARATOR type_single { result = [*val[0], val[2]] }
7
+ | type_single { result = [val[0]] }
8
+
9
+ type_single : generic_type
10
+ | tuple_type
11
+ | hash_type
12
+ | literal_type { result = Ast::LiteralType.new(content: val[0]) }
13
+ | DUCK_SYMBOL NAME { result = Ast::DuckType.new(name: val[1]) }
14
+ | NAME { result = Ast::Type.new(name: val[0]) }
15
+
16
+ type_pair : expression ARROW expression { result = [val[0], val[2]] }
17
+
18
+ generic_type : type_single GENERIC_START type_list GENERIC_END { result = Ast::GenericType.new(container_type: val[0], types: val[2]) }
19
+ | GENERIC_START type_list GENERIC_END { result = Ast::GenericType.new(types: val[1]) }
20
+
21
+ tuple_type : type_single TUPLE_START type_list TUPLE_END { result = Ast::TupleType.new(container_type: val[0], types: val[2]) }
22
+ | TUPLE_START type_list TUPLE_END { result = Ast::TupleType.new(types: val[1]) }
23
+
24
+ literal_type : SYMBOL | STRING | INTEGER
25
+
26
+ hash_type : type_single HASH_START type_pair HASH_END { result = Ast::HashType.new(container_type: val[0], type_pair: val[2]) }
27
+ | HASH_START type_pair HASH_END { result = Ast::HashType.new(type_pair: val[1]) }
28
+ end
29
+
30
+ ---- header
31
+ # Note: Prepend magic comment by script because default comments are prepended to header.
32
+
33
+ ---- inner
34
+
35
+ #:: (String) -> Ast::node
36
+ def parse(string)
37
+ @tokens = Scanner.new(string).to_racc_tokens
38
+
39
+ do_parse()
40
+ end
41
+
42
+ #:: () -> untyped
43
+ def next_token
44
+ @tokens.shift
45
+ end
46
+
47
+ ---- footer
48
+
49
+ module Yoda
50
+ module Parsing
51
+ module YardType
52
+ class Parser
53
+ # @rbs!
54
+ # def parse: (String) -> Ast::node
55
+ # def next_token: () -> untyped
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,69 @@
1
+ # rbs_inline: enabled
2
+
3
+ require 'strscan'
4
+
5
+ module YardToRbsInline::YardType
6
+ class Scanner
7
+ class ScanError < StandardError; end
8
+
9
+ Token = Struct.new(:kind, :content, keyword_init: true)
10
+
11
+ TOKEN_PATTERNS = {
12
+ generic_start: /</,
13
+ generic_end: />/,
14
+ tuple_start: /\(/,
15
+ tuple_end: /\)/,
16
+ duck_symbol: /#/,
17
+ separator: /[,;]/,
18
+ arrow: /\=>/,
19
+ hash_start: /\{/,
20
+ hash_end: /\}/,
21
+ name: /(::|\w)+/,
22
+ symbol: /:\w+/,
23
+ string: [/\"[^"]*\"/, /\'[^']*\'/],
24
+ integer: /\d+/,
25
+ spaces: /\s+/,
26
+ }
27
+
28
+ attr_reader :text #:: String
29
+
30
+ #:: (String text) -> untyped
31
+ def initialize(text)
32
+ @text = text
33
+ end
34
+
35
+ #:: () -> Array[[Symbol | bool, String]]
36
+ def to_racc_tokens
37
+ tokens.map { |token| [token.kind.to_s.upcase.to_sym, token.content] } + [[false, "EOS"]]
38
+ end
39
+
40
+ #:: () -> Array[Token]
41
+ def tokens
42
+ @tokens ||= begin
43
+ scanner = StringScanner.new(text)
44
+ tokens = []
45
+
46
+ scan_step = lambda do
47
+ TOKEN_PATTERNS.each do |kind, pattern_or_patterns|
48
+ Array(pattern_or_patterns).each do |pattern|
49
+ if (matched = scanner.scan(pattern))
50
+ tokens << Token.new(kind: kind, content: matched) unless kind == :spaces
51
+ return
52
+ end
53
+ end
54
+ end
55
+
56
+ raise ScanError, "Unknown keyword #{scanner.rest} (in #{text})"
57
+ end
58
+
59
+ until scanner.eos? do
60
+ scan_step.call
61
+ end
62
+
63
+ tokens
64
+ end
65
+ end
66
+ end
67
+
68
+
69
+ end
@@ -0,0 +1,9 @@
1
+ # rbs_inline: enabled
2
+
3
+ module YardToRbsInline
4
+ module YardType
5
+ require_relative 'yard_type/ast'
6
+ require_relative 'yard_type/parser'
7
+ require_relative 'yard_type/scanner'
8
+ end
9
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "yard_to_rbs_inline/version"
4
+
5
+ module YardToRbsInline
6
+ class Error < StandardError; end
7
+ end
8
+
9
+ require_relative "yard_to_rbs_inline/cli"
10
+ require_relative "yard_to_rbs_inline/converter"
11
+ require_relative "yard_to_rbs_inline/yard_type"
@@ -0,0 +1,4 @@
1
+ module YardToRbsInline
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,82 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: yard_to_rbs_inline
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Tomoya Chiba
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-05-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: yard
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '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'
27
+ description: Converter of yard to rbs-inline
28
+ email:
29
+ - tomo.asleep@gmail.com
30
+ executables:
31
+ - yard-to-rbs-inline
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".rspec"
36
+ - ".rubocop.yml"
37
+ - CHANGELOG.md
38
+ - CODE_OF_CONDUCT.md
39
+ - LICENSE
40
+ - README.md
41
+ - Rakefile
42
+ - examples/example.rb
43
+ - exe/yard-to-rbs-inline
44
+ - lib/yard_to_rbs_inline.rb
45
+ - lib/yard_to_rbs_inline/cli.rb
46
+ - lib/yard_to_rbs_inline/converter.rb
47
+ - lib/yard_to_rbs_inline/converter/code_visitor.rb
48
+ - lib/yard_to_rbs_inline/converter/subscriptable.rb
49
+ - lib/yard_to_rbs_inline/converter/text_with_mod.rb
50
+ - lib/yard_to_rbs_inline/version.rb
51
+ - lib/yard_to_rbs_inline/yard_type.rb
52
+ - lib/yard_to_rbs_inline/yard_type/ast.rb
53
+ - lib/yard_to_rbs_inline/yard_type/parser.rb
54
+ - lib/yard_to_rbs_inline/yard_type/parser.y
55
+ - lib/yard_to_rbs_inline/yard_type/scanner.rb
56
+ - sig/yard_to_rbs_inline_example.rbs
57
+ homepage: https://github.com/tomoasleep/yard_to_rbs_inline
58
+ licenses: []
59
+ metadata:
60
+ homepage_uri: https://github.com/tomoasleep/yard_to_rbs_inline
61
+ source_code_uri: https://github.com/tomoasleep/yard_to_rbs_inline
62
+ changelog_uri: https://github.com/tomoasleep/yard_to_rbs_inline/blob/main/CHANGELOG.md
63
+ post_install_message:
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: 2.6.0
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ requirements: []
78
+ rubygems_version: 3.5.9
79
+ signing_key:
80
+ specification_version: 4
81
+ summary: Converter of yard to rbs-inline
82
+ test_files: []