orthoses 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (45) hide show
  1. checksums.yaml +7 -0
  2. data/CODE_OF_CONDUCT.md +84 -0
  3. data/Gemfile +11 -0
  4. data/LICENSE.txt +21 -0
  5. data/README.md +123 -0
  6. data/lib/orthoses/builder.rb +55 -0
  7. data/lib/orthoses/call_tracer.rb +53 -0
  8. data/lib/orthoses/constant.rb +47 -0
  9. data/lib/orthoses/content.rb +113 -0
  10. data/lib/orthoses/create_file_by_name.rb +44 -0
  11. data/lib/orthoses/delegate_class.rb +45 -0
  12. data/lib/orthoses/filter.rb +24 -0
  13. data/lib/orthoses/include_extend_prepend.rb +58 -0
  14. data/lib/orthoses/load_rbs.rb +89 -0
  15. data/lib/orthoses/object_space_all.rb +25 -0
  16. data/lib/orthoses/pp.rb +15 -0
  17. data/lib/orthoses/store.rb +16 -0
  18. data/lib/orthoses/tap.rb +19 -0
  19. data/lib/orthoses/utils.rb +166 -0
  20. data/lib/orthoses/version.rb +5 -0
  21. data/lib/orthoses/walk.rb +25 -0
  22. data/lib/orthoses.rb +46 -0
  23. data/orthoses.gemspec +36 -0
  24. data/sig/orthoses/_call.rbs +5 -0
  25. data/sig/orthoses/_middle_ware.rbs +5 -0
  26. data/sig/orthoses/builder/call_logable.rbs +4 -0
  27. data/sig/orthoses/builder.rbs +5 -0
  28. data/sig/orthoses/call_tracer.rbs +5 -0
  29. data/sig/orthoses/const_load_error.rbs +8 -0
  30. data/sig/orthoses/constant.rbs +7 -0
  31. data/sig/orthoses/content.rbs +11 -0
  32. data/sig/orthoses/create_file_by_name.rbs +7 -0
  33. data/sig/orthoses/delegate_class.rbs +4 -0
  34. data/sig/orthoses/filter.rbs +7 -0
  35. data/sig/orthoses/include_extend_prepend.rbs +4 -0
  36. data/sig/orthoses/load_rbs.rbs +4 -0
  37. data/sig/orthoses/name_space_error.rbs +4 -0
  38. data/sig/orthoses/object_space_all.rbs +4 -0
  39. data/sig/orthoses/pp.rbs +4 -0
  40. data/sig/orthoses/store.rbs +4 -0
  41. data/sig/orthoses/tap.rbs +4 -0
  42. data/sig/orthoses/utils.rbs +27 -0
  43. data/sig/orthoses/walk.rbs +8 -0
  44. data/sig/orthoses.rbs +9 -0
  45. metadata +102 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 64cbbb058a7d4dc7c5f6f0d8cc66a23a1b2026253ad20add3cc63777a1c42227
4
+ data.tar.gz: 15742e8389d7fc4e129bca6ab48203f13dad5b2338eff73a2b4c530ba239d327
5
+ SHA512:
6
+ metadata.gz: 276874fcb60ce45b3b2ffe3388e963b596f65a466c4f36f5b3986b561f756f721d797e8217a27b6a292f988343fe8f4209886b876ba03e4512466b51903e4996
7
+ data.tar.gz: 73b2a614b599980d20d2d0334d87f4f508b163beff9a766979d67f39f49213a634c9e907725efd1f7a51e1552b5db90e80f3d766bba024ff050d50c5d5522b5c
@@ -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 co000ri@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/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in orthoses.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+ gem "rgot", "~> 1.1"
10
+ gem "steep"
11
+ gem "activesupport"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 ksss
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,123 @@
1
+ # Orthoses
2
+
3
+ Orthoses is a framework for RBS generation.
4
+ The Rack architecture keeps your code organized and extensible.
5
+
6
+ ## PoC
7
+
8
+ https://gist.github.com/ksss/00592da24f28774bf8fc5db08331666e
9
+
10
+ ## Installation
11
+
12
+ Install the gem and add to the application's Gemfile by executing:
13
+
14
+ $ bundle add orthoses
15
+
16
+ If bundler is not being used to manage dependencies, install the gem by executing:
17
+
18
+ $ gem install orthoses
19
+
20
+ ## Usage
21
+
22
+ ```rb
23
+ Orthoses::Builder.new do
24
+ use Orthoses::CreateFileByName
25
+ base_dir: Rails.root.join("sig/out"),
26
+ header: "# !!! GENERATED CODE !!!"
27
+ use Orthoses::Filter,
28
+ if: -> (name, _content) {
29
+ path, _lineno = Object.const_source_location(name)
30
+ return false unless path
31
+ %r{app/models}.match?(path)
32
+ }
33
+ use YourCustom::Middleware
34
+ use Orthoses::IncludeExtendPrepend
35
+ use Orthoses::Constant
36
+ use Orthoses::Walk,
37
+ root: "Foo"
38
+ run -> () {
39
+ # load library or application
40
+ }
41
+ end.call
42
+ ```
43
+
44
+ ## Middlewares
45
+
46
+ ### Orthoses::Constant
47
+
48
+ Add constant signature to class/module.
49
+ Signatures are predicted from constant values.
50
+
51
+ ### Orthoses::IncludeExtendPrepend
52
+
53
+ Add module include/extend/prepend definition.
54
+ It use `Module#{includeed,extended,prepended}` for capture.
55
+
56
+ ### Orthoses::ObjectSpaceAll
57
+
58
+ Add module/class by `ObjectSpace.each_object(Module)`
59
+
60
+ ### Orthoses::CreateFileByName
61
+
62
+ Separate directories for each module name and output RBS files.
63
+
64
+ ### Orthoses::Filter
65
+
66
+ Filter stored value by name and content.
67
+
68
+ ### Orthoses::PP
69
+
70
+ Debug pring current stored values
71
+
72
+ ### Orthoses::LoadRBS
73
+
74
+ Load RBS from `paths`.
75
+ And loaded RBS will write to output.
76
+
77
+ ### Orthoses::Walk
78
+
79
+ Load class/module recersive from `root` constant.
80
+ If set String to `root`, It get constant after loading.
81
+
82
+ ### Orthoses::Tap
83
+
84
+ Get the current store in the block as an argument.
85
+ This is very useful for middleware development and debugging.
86
+
87
+ ### Orthoses::DelegateClass
88
+
89
+ If a class is defined using the `DelegateClass` method
90
+ RBS is automatically generated as inherited.
91
+
92
+ .rb
93
+
94
+ ```rb
95
+ class Tempfile < DelegateClass(File)
96
+ end
97
+ ```
98
+
99
+ .rbs
100
+
101
+ ```rbs
102
+ class Tempfile < File
103
+ end
104
+ ```
105
+
106
+
107
+ ## Development
108
+
109
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
110
+
111
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
112
+
113
+ ## Contributing
114
+
115
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ksss/orthoses. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/ksss/orthoses/blob/main/CODE_OF_CONDUCT.md).
116
+
117
+ ## License
118
+
119
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
120
+
121
+ ## Code of Conduct
122
+
123
+ Everyone interacting in the Orthoses project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/ksss/orthoses/blob/main/CODE_OF_CONDUCT.md).
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Orthoses
4
+ # Middleware builder like the Rack
5
+ # Builder.new do
6
+ # use Orthoses::CreateFileByName
7
+ # use Orthoses::Constant
8
+ # use Orthoses::IncludeExtendPrepend
9
+ # use Orthoses::Walk,
10
+ # root: "Foo"
11
+ # run ->() { require 'foo' }
12
+ # end
13
+ class Builder
14
+ def initialize(&block)
15
+ @use = []
16
+ @run = nil
17
+ instance_eval(&block) if block
18
+ end
19
+
20
+ module CallLogable
21
+ def call()
22
+ Orthoses.logger.info("[#{self.class}]#call start")
23
+ super.tap do
24
+ Orthoses.logger.info("[#{self.class}]#call end")
25
+ end
26
+ end
27
+ end
28
+
29
+ def use(middleware, *args, **key, &block)
30
+ @use << proc do |loader|
31
+ middleware.new(loader, *args, **key, &block).tap do |m|
32
+ m.extend CallLogable
33
+ end
34
+ end
35
+ end
36
+
37
+ def run(loader)
38
+ use Store
39
+ @run = proc do
40
+ Orthoses.logger.info("[loader].call start")
41
+ loader.call.tap do
42
+ Orthoses.logger.info("[loader].call end")
43
+ end
44
+ end
45
+ end
46
+
47
+ def to_loader
48
+ @use.reverse.inject(@run) { |current, next_proc| next_proc[current] }
49
+ end
50
+
51
+ def call
52
+ to_loader.call
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Orthoses
4
+ # Trace :call event by TracePoint and capture arguments.
5
+ # def call
6
+ # scope = CallTracer.new
7
+ # scope.trace(ActiveRecord::Base.method(:scope)) do
8
+ # @loader.call
9
+ # end
10
+ # scope.result.each do |method, argument|
11
+ # argument[:name]
12
+ # argument[:body]
13
+ # argument[:block]
14
+ # end
15
+ class CallTracer
16
+ attr_accessor :result
17
+
18
+ def initialize
19
+ @result = []
20
+ end
21
+
22
+ def trace(target, &block)
23
+ TracePoint.new(:call) do |tp|
24
+ called_method = tp.self.method(tp.method_id)
25
+ argument = tp.parameters.each_with_object({}) do |op_name, hash|
26
+ name = op_name[1]
27
+ case name
28
+ when :*, :**, :&, nil
29
+ # skip
30
+ else
31
+ hash[name] = tp.binding.local_variable_get(name).then do |var|
32
+ case var
33
+ when Module
34
+ var # avoid missing name
35
+ else
36
+ var.dup
37
+ end
38
+ rescue => err
39
+ case var
40
+ when Thread::Backtrace::Location
41
+ # known
42
+ else
43
+ warn("#dup fail (#{err.class}) #{err.message}")
44
+ end
45
+ var
46
+ end
47
+ end
48
+ end
49
+ @result << [called_method, argument]
50
+ end.enable(target: target, &block)
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Orthoses
4
+ class Constant
5
+ def initialize(loader, strict:, if: nil, on_error: nil)
6
+ @loader = loader
7
+ @strict = strict
8
+ @if = binding.local_variable_get(:if)
9
+ @on_error = on_error
10
+ end
11
+
12
+ def call
13
+ cache = {}
14
+ @loader.call.tap do |store|
15
+ will_add_key_and_content = []
16
+ store.each do |name, _|
17
+ next if name == :Module
18
+ next if name.start_with?('#<')
19
+
20
+ begin
21
+ base = Object.const_get(name)
22
+ rescue NameError, ArgumentError, LoadError
23
+ # i18n/tests raise ArgumentError
24
+ next
25
+ end
26
+ next unless base.kind_of?(Module)
27
+ Orthoses::Utils.each_const_recursive(base, on_error: @on_error) do |current, const, val|
28
+ next if current.singleton_class?
29
+ next if Utils.module_name(current).nil?
30
+ next if val.kind_of?(Module)
31
+ next if cache[[current, const]]
32
+ cache[[current, const]] = true
33
+
34
+ rbs = Orthoses::Utils.object_to_rbs(val, strict: @strict)
35
+ next unless rbs
36
+ next unless @if.nil? || @if.call(current, const, val, rbs)
37
+
38
+ will_add_key_and_content << [Utils.module_name(current), "#{const}: #{rbs}"]
39
+ end
40
+ end
41
+ will_add_key_and_content.each do |name, line|
42
+ store[name] << line
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Orthoses
4
+ # Common interface for output.
5
+ # Orthoses::Content expect to use result of middleware.
6
+ # store = @loader.call
7
+ # store["Foo::Bar"] << "def baz: () -> void"
8
+ # By default, Orthoses::Content search constant of keys.
9
+ # and decide class or module declaration.
10
+ # Also declaraion can specify directly.
11
+ # store["Foo::Bar"].header = "class Foo::Bar < Baz"
12
+ # Orthoses::Content can generate RBS.
13
+ # store["Foo::Bar"].to_rbs
14
+ class Content
15
+ attr_reader :name
16
+ attr_reader :body
17
+ attr_accessor :header
18
+
19
+ def initialize(name:)
20
+ @name = name
21
+ @body = []
22
+ @header = nil
23
+ end
24
+
25
+ def <<(line)
26
+ Orthoses.logger.debug("[#{name}] << #{line} on #{__FILE__}:#{__LINE__}")
27
+ @body << line
28
+ end
29
+
30
+ def concat(other)
31
+ Orthoses.logger.debug("[#{name}] concat #{other} on #{__FILE__}:#{__LINE__}")
32
+ @body.concat(other)
33
+ end
34
+
35
+ def to_rbs
36
+ if @header.nil?
37
+ auto_header
38
+ end
39
+ body_uniq("#{@header}\n#{@body.map { |b| " #{b}\n" }.join}end\n")
40
+ end
41
+
42
+ private
43
+
44
+ def auto_header
45
+ val = Object.const_get(name)
46
+
47
+ case val
48
+ when Class
49
+ superclass =
50
+ if val.superclass && val.superclass != Object
51
+ super_module_name = Utils.module_name(val.superclass)
52
+
53
+ if super_module_name && super_module_name != "Random::Base" # https://github.com/ruby/rbs/pull/977
54
+ " < ::#{super_module_name}#{temporary_type_params(super_module_name)}"
55
+ else
56
+ nil
57
+ end
58
+ else
59
+ nil
60
+ end
61
+ self.header = "class #{Utils.module_name(val)}#{type_params(name)}#{superclass}"
62
+ when Module
63
+ self.header = "module #{Utils.module_name(val)}#{type_params(name)}"
64
+ else
65
+ raise "#{val.inspect} is not class/module"
66
+ end
67
+ end
68
+
69
+ def temporary_type_params(name)
70
+ Utils.known_type_params(name)&.then do |params|
71
+ if params.empty?
72
+ nil
73
+ else
74
+ "[#{params.map { :untyped }.join(', ')}]"
75
+ end
76
+ end
77
+ end
78
+
79
+ def type_params(name)
80
+ Utils.known_type_params(name)&.then do |type_params|
81
+ if type_params.empty?
82
+ nil
83
+ else
84
+ "[#{type_params.join(', ')}]"
85
+ end
86
+ end
87
+ end
88
+
89
+ def body_uniq(rbs)
90
+ buffer = RBS::Buffer.new(
91
+ name: "orthoses/content.rb",
92
+ content: rbs
93
+ )
94
+ out = StringIO.new
95
+ writer = RBS::Writer.new(out: out)
96
+ decls = RBS::Parser.parse_signature(buffer).map do |parsed_decl|
97
+ before_members = parsed_decl.members.dup
98
+ parsed_decl.members.uniq! { |m| [m.class, m.respond_to?(:name) ? m.name : nil] }
99
+ (before_members - parsed_decl.members).each do |droped_member|
100
+ Orthoses.logger.warn("#{parsed_decl.name}::#{droped_member.name.to_s}: #{droped_member.to_s} was droped since duplication")
101
+ end
102
+ parsed_decl
103
+ end
104
+ writer.write(decls)
105
+ out.string
106
+ rescue RBS::ParsingError
107
+ puts "```rbs"
108
+ puts rbs
109
+ puts "```"
110
+ raise
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Orthoses
4
+ class CreateFileByName
5
+ def initialize(loader, base_dir:, header: nil)
6
+ @loader = loader
7
+ @base_dir = base_dir
8
+ @header = header
9
+ end
10
+
11
+ using(Module.new {
12
+ refine String do
13
+ # avoid load active_support
14
+ def underscore
15
+ return self unless /[A-Z-]|::/.match?(self)
16
+ word = self.to_s.gsub("::", "/")
17
+ word.gsub!(/(?:(?<=([A-Za-z\d]))|\b)((?-mix:(?=a)b))(?=\b|[^a-z])/) { "#{$1 && '_' }#{$2.downcase}" }
18
+ word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
19
+ word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
20
+ word.tr!("-", "_")
21
+ word.downcase!
22
+ word
23
+ end
24
+ end
25
+ })
26
+
27
+ def call
28
+ store = @loader.call
29
+
30
+ store.each do |name, content|
31
+ file_path = Pathname("#{@base_dir}/#{name.to_s.split('::').map(&:underscore).join('/')}.rbs")
32
+ file_path.dirname.mkpath
33
+ file_path.open('w+') do |out|
34
+ if @header
35
+ out.puts @header
36
+ out.puts
37
+ end
38
+ out.puts content.to_rbs
39
+ end
40
+ Orthoses.logger.info("Generate file to #{file_path.to_s}")
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Orthoses
4
+ class DelegateClass
5
+ def initialize(loader)
6
+ @loader = loader
7
+ end
8
+
9
+ def call
10
+ require 'delegate'
11
+ classes = []
12
+ Class.class_eval do
13
+ define_method(:inherited) do |subclass|
14
+ classes << [subclass, self]
15
+ end
16
+ end
17
+ delegate_class_super_map = {}
18
+ delegate_class_tracer = TracePoint.new(:return) do |tp|
19
+ return_value = tp.return_value
20
+ superclass = tp.binding.local_variable_get(:superclass)
21
+ delegate_class_super_map[return_value] = superclass
22
+ end
23
+ store = delegate_class_tracer.enable(target: method(:DelegateClass)) do
24
+ @loader.call
25
+ end
26
+ classes.each do |subclass, superclass|
27
+ if delegate_to_class = delegate_class_super_map[superclass]
28
+ subclass_name = Utils.module_name(subclass)
29
+ next unless subclass_name
30
+ delegate_to_class_name = Utils.module_name(delegate_to_class)
31
+ next unless delegate_to_class_name
32
+ store[subclass_name].header = "class #{subclass_name} < #{delegate_to_class_name}"
33
+ end
34
+ end
35
+ store
36
+ end
37
+
38
+ def from_DelegateClass?(klass)
39
+ klass.name.nil? &&
40
+ klass.superclass == Delegator &&
41
+ klass.instance_methods.include?(:__setobj__) &&
42
+ klass.instance_method(:__setobj__).source_location.first.end_with?("delegate.rb")
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Orthoses
4
+ # Filter current store.
5
+ # use Orthoses::Filter,
6
+ # # filter stored key and value if proc return true
7
+ # if: -> (name, content) { Orthoses.rbs_defined_class?(name) }
8
+ class Filter
9
+ def initialize(loader, if:)
10
+ @loader = loader
11
+ @if = binding.local_variable_get(:if)
12
+ end
13
+
14
+ def call
15
+ @loader.call.tap do |store|
16
+ store.filter! do |name, content|
17
+ @if.call(name, content).tap do
18
+ Orthoses.logger.debug("Filter pass [#{name}]")
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Orthoses
4
+ class IncludeExtendPrepend
5
+ def initialize(loader, if: nil)
6
+ @loader = loader
7
+ @if = binding.local_variable_get(:if)
8
+ end
9
+
10
+ def call
11
+ modules = Hash.new { |h, k| h[k] = [] }
12
+ ::Module.module_eval do
13
+ define_method(:included) do |mod|
14
+ modules[mod] << [:include, self]
15
+ end
16
+
17
+ define_method(:extended) do |mod|
18
+ modules[mod] << [:extend, self]
19
+ end
20
+
21
+ define_method(:prepended) do |mod|
22
+ modules[mod] << [:prepend, self]
23
+ end
24
+ end
25
+
26
+ store = @loader.call
27
+
28
+ modules.each do |base_mod, how_mods|
29
+ next unless base_mod.kind_of?(Module)
30
+ base_mod_name = Utils.module_name(base_mod)
31
+ next unless base_mod_name
32
+
33
+ lines = how_mods.filter.map do |how, mod|
34
+ mod_name = Utils.module_name(mod)
35
+ next unless mod_name
36
+ known_type_params = Utils.known_type_params(mod)
37
+ next unless known_type_params.nil? || known_type_params.empty?
38
+ next unless @if.nil? || @if.call(base_mod, how, mod)
39
+
40
+ if base_mod_name == "Object"
41
+ # avoid RecursiveAncestorError
42
+ content = store[mod_name]
43
+ if content.header.nil?
44
+ content.header = "module #{Utils.module_to_type_name(mod)} : ::BasicObject"
45
+ end
46
+ else
47
+ store[mod_name]
48
+ end
49
+
50
+ "#{how} #{mod_name}"
51
+ end
52
+ store[base_mod_name].concat(lines)
53
+ end
54
+
55
+ store
56
+ end
57
+ end
58
+ end