rbs_activesupport 1.0.0

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.
Files changed (36) hide show
  1. checksums.yaml +7 -0
  2. data/.rubocop.yml +32 -0
  3. data/.vscode/extensions.json +7 -0
  4. data/.vscode/settings.json +6 -0
  5. data/CODE_OF_CONDUCT.md +132 -0
  6. data/LICENSE.txt +21 -0
  7. data/README.md +49 -0
  8. data/Rakefile +8 -0
  9. data/Steepfile +11 -0
  10. data/lib/generators/rbs_activesupport/install_generator.rb +22 -0
  11. data/lib/rbs_activesupport/ast.rb +60 -0
  12. data/lib/rbs_activesupport/attribute_accessor.rb +40 -0
  13. data/lib/rbs_activesupport/class_attribute.rb +36 -0
  14. data/lib/rbs_activesupport/declaration_builder.rb +122 -0
  15. data/lib/rbs_activesupport/delegate.rb +36 -0
  16. data/lib/rbs_activesupport/generator.rb +82 -0
  17. data/lib/rbs_activesupport/include.rb +61 -0
  18. data/lib/rbs_activesupport/method_searcher.rb +38 -0
  19. data/lib/rbs_activesupport/parser.rb +56 -0
  20. data/lib/rbs_activesupport/rake_task.rb +68 -0
  21. data/lib/rbs_activesupport/version.rb +5 -0
  22. data/lib/rbs_activesupport.rb +17 -0
  23. data/rbs_collection.lock.yaml +272 -0
  24. data/rbs_collection.yaml +19 -0
  25. data/sig/rbs_activesupport/ast.rbs +7 -0
  26. data/sig/rbs_activesupport/attribute_accessor.rbs +15 -0
  27. data/sig/rbs_activesupport/class_attribute.rbs +14 -0
  28. data/sig/rbs_activesupport/declaration_builder.rbs +25 -0
  29. data/sig/rbs_activesupport/delegate.rbs +13 -0
  30. data/sig/rbs_activesupport/generator.rbs +20 -0
  31. data/sig/rbs_activesupport/include.rbs +16 -0
  32. data/sig/rbs_activesupport/method_searcher.rbs +12 -0
  33. data/sig/rbs_activesupport/parser.rbs +22 -0
  34. data/sig/rbs_activesupport/rake_task.rbs +17 -0
  35. data/sig/rbs_activesupport.rbs +4 -0
  36. metadata +122 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 15aaf2bfe1439cdfd04de74b02a684b4dd81be4a076378f8746b6f65fef6eae2
4
+ data.tar.gz: b8f442d762f030c4f7eec6f36de7be7ff90f027968b056e1d996c1da47c7ad0e
5
+ SHA512:
6
+ metadata.gz: 60d85781b44efb807e298c2dc5c261fd135553ba36d08460a99cfc67688616da7171d472fd4d1744c06700ad6caf006433fc70d612ae9c38cde932990e85bdc8
7
+ data.tar.gz: 8ee761e2ce8f2ee1b4e18a90501ee6250ac618351e937abcef5a3cb2e9141e3f128f046d7329ca3174d8f88c6297f9ad832e6fc42ff8f83522c6aedd41b53f17
data/.rubocop.yml ADDED
@@ -0,0 +1,32 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.7
3
+
4
+ Metrics/AbcSize:
5
+ Max: 25
6
+ Exclude:
7
+ - "lib/rbs_activesupport/ast.rb"
8
+
9
+ Metrics/BlockLength:
10
+ Exclude:
11
+ - "spec/**/*.rb"
12
+
13
+ Metrics/ClassLength:
14
+ Max: 200
15
+
16
+ Metrics/CyclomaticComplexity:
17
+ Exclude:
18
+ - "lib/rbs_activesupport/ast.rb"
19
+
20
+ Metrics/MethodLength:
21
+ Max: 30
22
+ Exclude:
23
+ - "lib/rbs_activesupport/ast.rb"
24
+
25
+ Style/Documentation:
26
+ Enabled: false
27
+
28
+ Style/StringLiterals:
29
+ EnforcedStyle: double_quotes
30
+
31
+ Style/StringLiteralsInInterpolation:
32
+ EnforcedStyle: double_quotes
@@ -0,0 +1,7 @@
1
+ {
2
+ "recommendations": [
3
+ "shopify.ruby-lsp",
4
+ "soutaro.steep-vscode",
5
+ "tk0miya.rbs-helper"
6
+ ]
7
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "rbs-helper.signature-directory": "sig/",
3
+ "cSpell.words": [
4
+ "Cyclomatic"
5
+ ]
6
+ }
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Takeshi KOMIYA
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,49 @@
1
+ # rbs_activesupport
2
+
3
+ rbs_activesupport is a RBS generator for Active Support.
4
+
5
+ ## Installation
6
+
7
+ Add a new entry to your Gemfile and run `bundle install`:
8
+
9
+ group :development do
10
+ gem 'rbs_activesupport', require: false
11
+ end
12
+
13
+ After the installation, please run rake task generator:
14
+
15
+ bundle exec rails g rbs_activesupport:install
16
+
17
+ ## Usage
18
+
19
+ Run `rbs:activesupport:setup` task:
20
+
21
+ bundle exec rake rbs:activesupport:setup
22
+
23
+ Then rbs_activesupport will scan your source code and generate RBS file into `sig/activesupport` directory.
24
+
25
+ ## Development
26
+
27
+ After checking out the repo, run `bin/setup` to install dependencies. You can also
28
+ run `bin/console` for an interactive prompt that will allow you to experiment.
29
+
30
+ To install this gem onto your local machine, run `bundle exec rake install`.
31
+
32
+ To release a new version, update the version number in `version.rb`, and then put
33
+ a git tag (ex. `git tag v1.0.0`) and push it to the GitHub. Then GitHub Actions
34
+ will release a new package to [rubygems.org](https://rubygems.org) automatically.
35
+
36
+ ## Contributing
37
+
38
+ Bug reports and pull requests are welcome on GitHub at https://github.com/tk0miya/rbs_activesupport.
39
+ This project is intended to be a safe, welcoming space for collaboration, and contributors are
40
+ expected to adhere to the [code of conduct](https://github.com/tk0miya/rbs_activesupport/blob/main/CODE_OF_CONDUCT.md).
41
+
42
+ ## License
43
+
44
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
45
+
46
+ ## Code of Conduct
47
+
48
+ Everyone interacting in the rbs_activesupport project's codebases, issue trackers is expected to
49
+ follow the [code of conduct](https://github.com/tk0miya/rbs_activesupport/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rubocop/rake_task"
5
+
6
+ RuboCop::RakeTask.new
7
+
8
+ task default: :rubocop
data/Steepfile ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ D = Steep::Diagnostic
4
+
5
+ target :lib do
6
+ signature "sig"
7
+
8
+ check "lib"
9
+
10
+ configure_code_diagnostics(D::Ruby.lenient)
11
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails"
4
+
5
+ module RbsActivesupport
6
+ class InstallGenerator < Rails::Generators::Base
7
+ def create_raketask
8
+ create_file "lib/tasks/rbs_activesupport.rake", <<~RUBY
9
+ # frozen_string_literal: true
10
+
11
+ begin
12
+ require 'rbs_activesupport/rake_task'
13
+
14
+ RbsActivesupport::RakeTask.new do |task|
15
+ end
16
+ rescue LoadError
17
+ # failed to load rbs_activesupport. Skip to load rbs_activesupport tasks.
18
+ end
19
+ RUBY
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbsActivesupport
4
+ module AST
5
+ def eval_args(node)
6
+ # @type var args: Array[Array[Symbol?]]
7
+ *args, _ = eval_node(node)
8
+ args
9
+ end
10
+
11
+ def eval_args_with_options(node)
12
+ # @type var methods: Array[Symbol]
13
+ # @type var options: Hash[Symbol, untyped]
14
+ *args, _ = eval_node(node)
15
+ if args.last.is_a?(Hash)
16
+ options = args.pop
17
+ [args, options]
18
+ else
19
+ [args, {}]
20
+ end
21
+ end
22
+
23
+ def eval_node(node)
24
+ case node
25
+ when nil
26
+ nil
27
+ when Symbol, Hash # Only for debug use
28
+ node
29
+ when Array
30
+ node.map { |e| eval_node(e) }
31
+ when RubyVM::AbstractSyntaxTree::Node
32
+ case node.type
33
+ when :LIT
34
+ node.children.first
35
+ when :HASH
36
+ elem = node.children.first.children.compact.map { |e| eval_node(e) }
37
+ Hash[*elem]
38
+ when :TRUE
39
+ true
40
+ when :FALSE
41
+ false
42
+ when :NIL
43
+ nil
44
+ when :CONST
45
+ node.children
46
+ when :COLON2
47
+ eval_node(node.children.first) + [node.children.last]
48
+ when :COLON3
49
+ [nil, node.children.first]
50
+ else
51
+ p node # for debug
52
+ raise
53
+ end
54
+ else
55
+ p node # for debug
56
+ raise
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbsActivesupport
4
+ class AttributeAccessor
5
+ attr_reader :name, :options
6
+
7
+ def initialize(name, options)
8
+ @name = name
9
+ @options = options
10
+ end
11
+
12
+ def singleton_reader?
13
+ options.fetch(:singleton_reader, true)
14
+ end
15
+
16
+ def singleton_writer?
17
+ options.fetch(:singleton_writer, true)
18
+ end
19
+
20
+ def instance_accessor?
21
+ options.fetch(:instance_accessor, true)
22
+ end
23
+
24
+ def instance_reader?
25
+ options.fetch(:instance_reader, instance_accessor?)
26
+ end
27
+
28
+ def instance_writer?
29
+ options.fetch(:instance_writer, instance_accessor?)
30
+ end
31
+
32
+ def public?
33
+ !private?
34
+ end
35
+
36
+ def private?
37
+ options.fetch(:private, false)
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbsActivesupport
4
+ class ClassAttribute
5
+ attr_reader :name, :options
6
+
7
+ def initialize(name, options)
8
+ @name = name
9
+ @options = options
10
+ end
11
+
12
+ def instance_accessor?
13
+ options.fetch(:instance_accessor, true)
14
+ end
15
+
16
+ def instance_reader?
17
+ options.fetch(:instance_reader, instance_accessor?)
18
+ end
19
+
20
+ def instance_writer?
21
+ options.fetch(:instance_writer, instance_accessor?)
22
+ end
23
+
24
+ def instance_predicate?
25
+ options.fetch(:instance_predicate, true)
26
+ end
27
+
28
+ def public?
29
+ !private?
30
+ end
31
+
32
+ def private?
33
+ options.fetch(:private, false)
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbsActivesupport
4
+ class DeclarationBuilder
5
+ include AST
6
+
7
+ attr_reader :method_searcher
8
+
9
+ def initialize(method_searcher)
10
+ @method_searcher = method_searcher
11
+ end
12
+
13
+ def build(namespace, method_calls)
14
+ public_decls, private_decls = build_method_calls(namespace, method_calls).partition(&:public?)
15
+ [public_decls.map(&method(:render)).compact, # steep:ignore BlockTypeMismatch
16
+ private_decls.map(&method(:render)).compact] # steep:ignore BlockTypeMismatch
17
+ end
18
+
19
+ private
20
+
21
+ def build_method_calls(namespace, method_calls)
22
+ method_calls.flat_map do |method_call|
23
+ case method_call.name
24
+ when :class_attribute
25
+ build_class_attribute(method_call)
26
+ when :delegate
27
+ build_delegate(namespace, method_call)
28
+ when :cattr_accessor, :mattr_accessor, :cattr_reader, :mattr_reader, :cattr_writer, :mattr_writer
29
+ build_attribute_accessor(method_call)
30
+ when :include
31
+ build_include(namespace, method_call)
32
+ end
33
+ rescue StandardError => e
34
+ puts "ERROR: #{namespace}:#{method_call.name}: Failed to build method calls: #{e}"
35
+ nil
36
+ end.compact
37
+ end
38
+
39
+ def build_attribute_accessor(method_call)
40
+ methods, options = eval_args_with_options(method_call.args)
41
+ options[:singleton_reader] = false if %i[cattr_writer mattr_writer].include?(method_call.name)
42
+ options[:singleton_writer] = false if %i[cattr_reader mattr_reader].include?(method_call.name)
43
+ options[:instance_reader] = false if %i[cattr_writer mattr_writer].include?(method_call.name)
44
+ options[:instance_writer] = false if %i[cattr_reader mattr_reader].include?(method_call.name)
45
+ options[:private] = true if method_call.private?
46
+ methods.map do |method|
47
+ AttributeAccessor.new(method, options)
48
+ end
49
+ end
50
+
51
+ def build_class_attribute(method_call)
52
+ methods, options = eval_args_with_options(method_call.args)
53
+ options[:private] = true if method_call.private?
54
+ methods.map do |method|
55
+ ClassAttribute.new(method, options)
56
+ end
57
+ end
58
+
59
+ def build_delegate(namespace, method_call)
60
+ methods, options = eval_args_with_options(method_call.args)
61
+ options[:private] = true if method_call.private?
62
+ methods.map do |method|
63
+ Delegate.new(namespace, method, options)
64
+ end
65
+ end
66
+
67
+ def build_include(namespace, method_call)
68
+ module_paths = eval_args(method_call.args)
69
+ module_paths.map do |module_path|
70
+ Include.new(namespace, module_path, { private: method_call.private? })
71
+ end
72
+ end
73
+
74
+ def render(decl)
75
+ case decl
76
+ when AttributeAccessor
77
+ render_attribute_accessor(decl)
78
+ when ClassAttribute
79
+ render_class_attribute(decl)
80
+ when Delegate
81
+ render_delegate(decl)
82
+ when Include
83
+ render_include(decl)
84
+ end
85
+ end
86
+
87
+ def render_attribute_accessor(decl)
88
+ methods = []
89
+ methods << "def self.#{decl.name}: () -> untyped" if decl.singleton_reader?
90
+ methods << "def self.#{decl.name}=: (untyped) -> untyped" if decl.singleton_writer?
91
+ methods << "def #{decl.name}: () -> untyped" if decl.instance_reader?
92
+ methods << "def #{decl.name}=: (untyped) -> untyped" if decl.instance_writer?
93
+ methods.join("\n")
94
+ end
95
+
96
+ def render_class_attribute(decl)
97
+ methods = []
98
+ methods << "def self.#{decl.name}: () -> untyped"
99
+ methods << "def self.#{decl.name}=: (untyped) -> untyped"
100
+ methods << "def self.#{decl.name}?: () -> bool" if decl.instance_predicate?
101
+ methods << "def #{decl.name}: () -> untyped" if decl.instance_reader?
102
+ methods << "def #{decl.name}=: (untyped) -> untyped" if decl.instance_writer?
103
+ methods << "def #{decl.name}?: () -> bool" if decl.instance_predicate? && decl.instance_reader?
104
+ methods.join("\n")
105
+ end
106
+
107
+ def render_delegate(decl)
108
+ method_types = method_searcher.method_types_for(decl)
109
+
110
+ "def #{decl.method_name}: #{method_types.join(" | ")}"
111
+ end
112
+
113
+ def render_include(decl)
114
+ return unless decl.concern? && decl.classmethods?
115
+
116
+ <<~RBS
117
+ include #{decl.argument.to_s.delete_suffix("::")}
118
+ extend #{decl.argument}ClassMethods
119
+ RBS
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbsActivesupport
4
+ class Delegate
5
+ attr_reader :namespace, :method, :options
6
+
7
+ def initialize(namespace, method, options)
8
+ @namespace = namespace
9
+ @method = method
10
+ @options = options
11
+ end
12
+
13
+ def to
14
+ options[:to]
15
+ end
16
+
17
+ def method_name
18
+ case options[:prefix]
19
+ when true
20
+ :"#{to}_#{method}"
21
+ when String, Symbol
22
+ :"#{options[:prefix]}_#{method}"
23
+ else
24
+ method
25
+ end
26
+ end
27
+
28
+ def public?
29
+ !private?
30
+ end
31
+
32
+ def private?
33
+ options.fetch(:private, false)
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbsActivesupport
4
+ class Generator
5
+ def self.generate(pathname, rbs_builder)
6
+ new(pathname, rbs_builder).generate
7
+ end
8
+
9
+ attr_reader :pathname, :declaration_builder
10
+
11
+ def initialize(pathname, rbs_builder)
12
+ @pathname = pathname
13
+
14
+ method_searcher = MethodSearcher.new(rbs_builder)
15
+ @declaration_builder = DeclarationBuilder.new(method_searcher)
16
+ end
17
+
18
+ def generate
19
+ declarations = parse_source_code
20
+ return if declarations.empty?
21
+
22
+ definition = declarations.map do |namespace, method_calls|
23
+ public_decls, private_decls = declaration_builder.build(namespace, method_calls)
24
+ next if public_decls.empty? && private_decls.empty?
25
+
26
+ <<~RBS
27
+ #{header(namespace)}
28
+ #{public_decls.join("\n")}
29
+
30
+ #{"private" if private_decls.any?}
31
+
32
+ #{private_decls.join("\n")}
33
+
34
+ #{footer(namespace)}
35
+ RBS
36
+ end.compact.join("\n")
37
+
38
+ return if definition.empty?
39
+
40
+ format(definition)
41
+ end
42
+
43
+ private
44
+
45
+ def format(rbs)
46
+ parsed = RBS::Parser.parse_signature(rbs)
47
+ StringIO.new.tap do |out|
48
+ RBS::Writer.new(out: out).write(parsed[1] + parsed[2])
49
+ end.string
50
+ end
51
+
52
+ def parse_source_code
53
+ parser = Parser.new
54
+ parser.parse(pathname.read)
55
+ parser.method_calls
56
+ end
57
+
58
+ def header(namespace)
59
+ context = +""
60
+ namespace.path.map do |mod_name|
61
+ context += "::#{mod_name}"
62
+ mod_object = Object.const_get(context)
63
+ case mod_object
64
+ when Class
65
+ # @type var superclass: Class
66
+ superclass = _ = mod_object.superclass
67
+ superclass_name = superclass.name || "Object"
68
+
69
+ "class #{mod_name} < ::#{superclass_name}"
70
+ when Module
71
+ "module #{mod_name}"
72
+ else
73
+ raise "unreachable"
74
+ end
75
+ end.join("\n")
76
+ end
77
+
78
+ def footer(namespace)
79
+ "end\n" * namespace.path.size
80
+ end
81
+ end
82
+ end