claret 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: 86c0a750f84fc7c9b43896cc1b8129671d96e0de433fe99a8ee2b5097ade93e6
4
+ data.tar.gz: 6a08e47f63d6e7bdbba114a9192be6551f13ac308aef419061731c3bab220068
5
+ SHA512:
6
+ metadata.gz: 2e9f2009d9b790f0ffc76f33490bec46274a26a024d9a56497c1c5e7db9732718b2dd279b92e7f6ad89418582cbf5a41f3f7bc7d2383bc73029e0636aad25fd9
7
+ data.tar.gz: 2f4ad49a1046554c5072d6e6264bf2daeb4d3630f5a8be7573405a81d3574388410826541f73e2579e149606b96817c3be6280ddf33b2bb1173af0a8c3dfcff6
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/testdouble/standard
3
+ ruby_version: 2.6
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-12-27
4
+
5
+ - Initial release of experiment, only supports some of the final syntax.
@@ -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 stevegeek@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.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Stephen Ierodiaconou
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,218 @@
1
+ # claret
2
+
3
+ Ruby + RBS = claret
4
+
5
+ ```ruby
6
+ # examples/hello_world.rb
7
+
8
+ class HelloWorld
9
+ def initialize(String @name = "world")
10
+ end
11
+
12
+ def say_it_to(String name = @name, (Integer | Float) age = (1 + 2))
13
+ puts "Hello #{name}! You are #{age} years old."
14
+ end
15
+ end
16
+
17
+ # 42 should be an Integer or Float
18
+ HelloWorld.new.say_it_to("bob", "42")
19
+ ```
20
+
21
+ ```
22
+ $ ./exe/claret start examples/hello_world.rb
23
+ --- steep output ---
24
+ # Type checking files:
25
+
26
+ ............................................................................F........
27
+
28
+ lib/examples/hello_world.rb:13:32: [error] Cannot pass a value of type `::String` as an argument of type `(::Integer | ::Float)`
29
+ │ ::String <: (::Integer | ::Float)
30
+ │ ::String <: ::Integer
31
+ │ ::Object <: ::Integer
32
+ │ ::BasicObject <: ::Integer
33
+
34
+ │ Diagnostic ID: Ruby::ArgumentTypeMismatch
35
+
36
+ └ HelloWorld.new.say_it_to("bob", "42")
37
+ ~~~~
38
+
39
+ Detected 1 problem from 1 file
40
+ --- End steep output ---
41
+ 🚨 Something went wrong with steep!
42
+ ```
43
+
44
+
45
+ ### `claret` is:
46
+
47
+ - an attempt at creating a typed Ruby syntax that incorporates RBS like types directly into the Ruby source
48
+ - A CLI too that transpiles the typed Ruby to pure Ruby and an RBS file, thus allowing the existing Ruby runtime and type checker steep to do the heavy lifting
49
+
50
+ ### `claret` aims to be
51
+
52
+ - optional: you can type only some parts of your application (similarly to RBS) and mix typed and not typed code
53
+ - debugging friendly: runtime error source locations will map relatively well to their typed source counterpart
54
+ - runtime friendly: claret is built with Ruby-next meaning transpilation can happen at runtime too using the ruby-next require hook
55
+ - escape-able: you can use the CLI to erase the type information and emit the pure Ruby code should you wish to stop using it
56
+
57
+ ### `claret` future directions:
58
+
59
+ - build an AST based parser allowing for more accurate transpilation
60
+ - Ability to also emit Crystal code allowing for the possibility to create single code base Ruby/Crystal projects (assuming you only use language features which are comparable to both languages)
61
+
62
+
63
+
64
+ ## Warning: Experimental Tool
65
+
66
+ Please note that claret is currently an experimental tool, and as such, it is subject to change or may never reach a stable release. The syntax for inline type signatures could also evolve, potentially causing compatibility issues with certain Ruby codebases. Proceed with caution and be prepared for possible adjustments in the future.
67
+
68
+
69
+ ## Installation
70
+
71
+ Install the gem and add to the application's Gemfile by executing:
72
+
73
+ $ bundle add claret
74
+
75
+ If bundler is not being used to manage dependencies, install the gem by executing:
76
+
77
+ $ gem install claret
78
+
79
+ ## Usage
80
+
81
+ ```
82
+ claret help
83
+ Commands:
84
+ claret check [SCRIPT] # Check the given file for type errors, or all files if none given
85
+ claret execute SCRIPT # Run the typed Ruby SCRIPT
86
+ claret help [COMMAND] # Describe available commands or one specific command
87
+ claret remove # Remove all type annotations from the project
88
+ claret ruby SCRIPT # [Alias of 'execute']
89
+ claret start SCRIPT # Run type checking and then execute the SCRIPT
90
+ claret steep [SCRIPT] # [Alias of 'check']
91
+
92
+ Options:
93
+ [--debug], [--no-debug]
94
+ # Default: false
95
+ [--quiet], [--no-quiet]
96
+ # Default: false
97
+ [--time], [--no-time]
98
+ # Default: false
99
+ ```
100
+
101
+ ## Syntax
102
+
103
+
104
+ ### Methods
105
+
106
+ In claret's typed Ruby syntax, types are specified directly before the argument name (optionally enclosed in parentheses).
107
+ For return types, an arrow (->) is used after the method definition, followed by the type.
108
+
109
+ Here are a couple of examples to demonstrate this syntax:
110
+
111
+ ```ruby
112
+ def my_method(Integer a, String b = "hi") -> String
113
+ # method body
114
+ end
115
+
116
+ def another_method(untyped kwarg1:, (Alice | Bob[String]) kwarg2: nil)
117
+ # method body, note return type is implicitly untyped
118
+ end
119
+ ```
120
+
121
+ In the first example, `my_method` takes two arguments: an `Integer` named `a`, and a `String` named `b` with a
122
+ default value of "hi". The method returns a `String`.
123
+
124
+ The second example, `another_method`, has two keyword arguments: an untyped argument named `kwarg1`, and
125
+ an argument named `kwarg2` that can be either an instance of class `Alice` or a generic instance of class
126
+ `Bob` with its type parameter set to `String`. The default value for `kwarg2` is set to nil.
127
+ No return type means an implicit `untyped` return type.
128
+
129
+ **Note**:
130
+
131
+ when specifying method argument types in claret's typed Ruby syntax, you must enclose the type information in
132
+ parentheses if it consists of more than a single simple type. This is especially relevant when creating
133
+ union types or other complex type constructs.
134
+
135
+ ## Instance Variable Setting Short Hand Syntax
136
+
137
+ In `claret`'s typed Ruby syntax, you can simplify the process of setting instance variables from method arguments by
138
+ using a shorthand syntax inspired by Crystal lang. By prefixing the argument name with an `@` symbol in the
139
+ method definition, the corresponding instance variable will be automatically set to the argument value upon
140
+ method call.
141
+
142
+ Here's a Box example demonstrating this shorthand syntax:
143
+
144
+ ```ruby
145
+ class Box
146
+ def initialize(String @item) -> void
147
+ end
148
+ attr_reader :item: String
149
+ end
150
+
151
+ puts Box.new("Hello").item # “Hello”
152
+ ```
153
+
154
+ In this example, we've modified the `initialize` method definition to use the shorthand syntax for setting
155
+ the `@item` instance variable. By writing `String @item`, we're telling claret the type of `@item`, and to
156
+ automatically set `@item` to the value passed as an argument when calling the `initialize` method. This
157
+ eliminates the need for explicitly assigning `@item = item` within the method body.
158
+
159
+ **Note**:
160
+
161
+ This syntax will add one or more lines to the start of your `initialize` method and as such will
162
+ change line numbers between the output Ruby and your original typed Ruby source. Thus, your debugging
163
+ experience will be worse as error source line numbers will not map back to your original typed Ruby source file.
164
+
165
+
166
+ ## TODO:
167
+
168
+ - ivars typing
169
+ - Generics
170
+
171
+ In claret's typed Ruby syntax, generic types are included after types in a similar manner to RBS. The type parameters are enclosed within square brackets `[ ]` and separated by commas.&#x20;
172
+
173
+ Here's an example demonstrating the use of generic types:
174
+
175
+ ```ruby
176
+ def process_data(Array[Integer] numbers) -> Hash[String, Integer]
177
+ # method body
178
+ end
179
+ ```
180
+
181
+ In this example, `process_data` takes an argument named `numbers`, which is an `Array` of `Integer` elements. The method returns a `Hash` with keys of type `String` and values of type `Integer`.
182
+
183
+
184
+ Class Definitions with Generics
185
+
186
+ To define a class with generic types in claret's typed Ruby syntax, include the type parameters after the class name, enclosed within square brackets `[ ]`. Here's an example demonstrating this:
187
+
188
+ ```ruby
189
+ class Box[ItemType]
190
+ @item: ItemType
191
+ def initialize(ItemType item) -> void
192
+ @item = item
193
+ end
194
+ end
195
+
196
+ my_box = Box[String].new("Hello")
197
+ ```
198
+
199
+ In this example, we define a `Box` class with a generic type parameter `ItemType`. The instance variable and `initialize` method uses the generic type to ensure that the box can only store and return items of a specific type. When creating an instance of the `Box` class, we specify the desired type within square brackets, as seen with `Box[String].new("Hello")`.
200
+
201
+
202
+ ## Development
203
+
204
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
205
+
206
+ 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).
207
+
208
+ ## Contributing
209
+
210
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/claret. 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/[USERNAME]/claret/blob/master/CODE_OF_CONDUCT.md).
211
+
212
+ ## License
213
+
214
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
215
+
216
+ ## Code of Conduct
217
+
218
+ Everyone interacting in the Claret project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/claret/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "standard/rake"
13
+
14
+ task default: %i[test standard]
data/claret.gemspec ADDED
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/claret/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "claret"
7
+ spec.version = Claret::VERSION
8
+ spec.authors = ["Stephen Ierodiaconou"]
9
+ spec.email = ["stevegeek@gmail.com"]
10
+
11
+ spec.summary = "A Ruby dialect that includes types in the language. Transpiles to Ruby and RBS."
12
+ spec.description = "A Ruby dialect that includes types in the language. Transpiles to Ruby and RBS by leveraging the ruby-next and irbs gems. Type checks with steep."
13
+ spec.homepage = "https://github.com/stevegeek/claret"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.0.0"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = "https://github.com/stevegeek/claret"
19
+ spec.metadata["changelog_uri"] = "https://github.com/stevegeek/claret/blob/main/CHANGELOG.md"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(__dir__) do
24
+ `git ls-files -z`.split("\x0").reject do |f|
25
+ (File.expand_path(f) == __FILE__) ||
26
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile])
27
+ end
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ # Uncomment to register a new dependency of your gem
34
+ spec.add_dependency "thor", "~> 1.3"
35
+ spec.add_dependency "ruby-next", "~> 1.0"
36
+ spec.add_dependency "steep", "~> 1.6"
37
+ spec.add_dependency "irbs", "> 0.1", "< 1"
38
+
39
+ # For more information and examples about making a new gem, check out our
40
+ # guide at: https://bundler.io/guides/creating_gem.html
41
+ end
@@ -0,0 +1,18 @@
1
+ # examples/hello_world.rb
2
+
3
+ class HelloWorld
4
+ def initialize(String @name = "world")
5
+ end
6
+
7
+ def say_it_to(String name = @name, (Integer | Float) age = (1 + 2))
8
+ puts "Hello #{name}! You are #{age} years old."
9
+ end
10
+
11
+ def test
12
+ puts "test"
13
+ end
14
+ end
15
+
16
+ HelloWorld.new.say_it_to
17
+
18
+ HelloWorld.new.say_it_to("bob", "42")
data/exe/claret ADDED
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "claret"
5
+ require "thor"
6
+ require "open3"
7
+
8
+ class ClaretCLI < Thor
9
+ include Thor::Actions
10
+
11
+ option :debug, type: :boolean, default: false
12
+ option :quiet, type: :boolean, default: false
13
+ option :verbose, type: :boolean, default: false
14
+ option :time, type: :boolean, default: false # TODO: add timing to all commands
15
+ def initialize(*args)
16
+ super
17
+ end
18
+
19
+ desc "execute SCRIPT", "Run the typed Ruby SCRIPT"
20
+ def execute(relative_path)
21
+ # Run command - performs type to @sig comment conversion
22
+ require "ruby-next/language"
23
+
24
+ path = File.expand_path(File.join(Dir.pwd, relative_path))
25
+ RubyNext::Language.include_patterns << path
26
+
27
+ require "ruby-next/language/runtime"
28
+
29
+ require path
30
+ end
31
+
32
+ desc "ruby SCRIPT", "[Alias of 'execute']"
33
+ def ruby(relative_path)
34
+ invoke :execute, [relative_path]
35
+ end
36
+
37
+ desc "start SCRIPT", "Run type checking and then execute the SCRIPT"
38
+ def start(relative_path)
39
+ # Run steep and then run the application
40
+ invoke :check, [relative_path], options
41
+ say "\n>Check passed, run now...\n\n" if options[:verbose]
42
+ # TODO: we have the compiled code in .claret/lib, so we can just run that
43
+ invoke :execute, [relative_path], options
44
+ end
45
+
46
+ desc "check [SCRIPT]", "Check the given file for type errors, or all files if none given"
47
+ def check(relative_path = nil)
48
+ # Check command - include watch mode
49
+ # Run ruby next and get output files written to disk
50
+ # run irbs to extract the RBS (or call Irbs::Core (which loads from disk) directly?)
51
+ # then run steep on extracted RBS
52
+
53
+ config = options.transform_keys(&:to_sym)
54
+ empty_directory ".claret/lib", config
55
+ empty_directory ".claret/sig", config
56
+
57
+ create_file ".claret/Steepfile", config do
58
+ <<~STEEPFILE
59
+ D = Steep::Diagnostic
60
+ target :app do
61
+ signature "sig"
62
+ check "lib"
63
+ end
64
+ STEEPFILE
65
+ end
66
+
67
+ create_file ".claret/.rbnextrc", config do
68
+ # Get absolute path to lib/claret/rewriters which is relative to this files path but one level up
69
+ path = File.expand_path("../lib/claret/rewriters", __dir__)
70
+ imports = Dir.glob("#{path}/*.rb").map { File.expand_path(_1) }.map { " --import-rewriter=#{_1}" }.join("\n")
71
+ <<~RUBY_NEXT
72
+ nextify: |
73
+ --min-version=3.2
74
+ --single-version
75
+ #{imports}
76
+ --output=lib
77
+ RUBY_NEXT
78
+ end
79
+
80
+ inside ".claret", config do
81
+ input = File.expand_path("../#{relative_path}")
82
+ output = File.join("lib/", relative_path)
83
+ run_command("ruby-next", "bundle", "exec", "ruby-next", "nextify", input, "-o", output, "-V", "--no-refine")
84
+ run_command("irbs", "bundle", "exec", "irbs", output, "-o", "sig/#{File.basename(relative_path, ".rb")}.rbs")
85
+ run_command("steep", "bundle", "exec", "steep", "check")
86
+ end
87
+ end
88
+
89
+ desc "steep [SCRIPT]", "[Alias of 'check']"
90
+ def steep(relative_path = nil)
91
+ invoke :check, relative_path
92
+ end
93
+
94
+ desc "remove", "Remove all type annotations from the project"
95
+ def remove
96
+ # TODO: Remove command - remove all type annotations
97
+ end
98
+
99
+ private
100
+
101
+ def run_command(type, *args)
102
+ options[:debug] && say("Debug enabled for command #{type}.")
103
+ stdout, status = Open3.capture2({"DEBUG" => "1"}, *args)
104
+ if status != 0
105
+ say_output(type, stdout)
106
+ say_error "🚨 Something went wrong with #{type}!"
107
+ exit 1
108
+ else
109
+ say_output(type, stdout) if options[:debug]
110
+ say "🤘 all good with #{type}!" if options[:verbose]
111
+ end
112
+ end
113
+
114
+ def say_output(type, output)
115
+ say "--- #{type} output ---"
116
+ say output
117
+ say "--- End #{type} output ---"
118
+ end
119
+ end
120
+
121
+ ClaretCLI.start(ARGV)
@@ -0,0 +1,76 @@
1
+ module Claret
2
+ module Parsing
3
+ class Parens
4
+ def initialize(scanner)
5
+ @scanner = scanner
6
+ end
7
+
8
+ attr_reader :scanner
9
+
10
+ def parse
11
+ reset_parse_result
12
+ reset_buffer
13
+
14
+ continue_parsing = true
15
+ until scanner.eos? || continue_parsing == :stop
16
+ continue_parsing = handle_next_character
17
+ end
18
+
19
+ # Add anything remaining in current to result (ie after last closing parens)
20
+ append_buffer_to_result_if_not_empty unless continue_parsing == :stop
21
+ @result
22
+ end
23
+
24
+ def reset
25
+ reset_parse_result
26
+ reset_buffer
27
+ scanner.reset
28
+ end
29
+
30
+ private
31
+
32
+ def handle_next_character
33
+ case scanner.peek(1)
34
+ when "("
35
+ consume_and_append_buffer
36
+ parse_next
37
+ when ")"
38
+ consume_and_append_buffer
39
+ :stop
40
+ when ","
41
+ consume_and_append_buffer
42
+ parse_next
43
+ else
44
+ # append any other characters to current buffer
45
+ @current_buffer << scanner.getch
46
+ end
47
+ end
48
+
49
+ def consume_and_append_buffer
50
+ scanner.getch # consume the current character
51
+ append_buffer_to_result_if_not_empty
52
+ end
53
+
54
+ def parse_next
55
+ # recursive call for next argument when opening parens encountered. At every comma we also add to stack,
56
+ # which lets us know when we're at the end of an arg.
57
+ @result << Parens.new(scanner).parse
58
+ end
59
+
60
+ def append_buffer_to_result_if_not_empty
61
+ stripped = @current_buffer.strip
62
+ separator = stripped.empty?
63
+ @result << stripped unless separator
64
+ reset_buffer
65
+ end
66
+
67
+ def reset_parse_result
68
+ @result = []
69
+ end
70
+
71
+ def reset_buffer
72
+ @current_buffer = ""
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,85 @@
1
+ require "strscan"
2
+
3
+ require_relative "../utils/logging"
4
+ require_relative "../parsing/parens"
5
+
6
+ module Claret
7
+ module Rewriters
8
+ class MethodDefRewriter < RubyNext::Language::Rewriters::Text
9
+ include ::Claret::Utils::Logging
10
+
11
+ NAME = "claret-positional-arg-type"
12
+ SYNTAX_PROBE = "def foo(String a, (Integer | String) b, customType c, ivarType @ivar)"
13
+ MIN_SUPPORTED_VERSION = Gem::Version.new(RubyNext::NEXT_VERSION)
14
+
15
+ def safe_rewrite(source)
16
+ modified_source = source.dup
17
+
18
+ source.scan(/(def\s+[\w_]+)(.*)$/).each do |method_def_match|
19
+ debug "> Method def match: #{method_def_match.inspect}"
20
+ matched_def = method_def_match.join
21
+ scanner = StringScanner.new matched_def
22
+ stack = Claret::Parsing::Parens.new(scanner).parse
23
+
24
+ # TODO: we still need to handle return values
25
+ if stack.size < 2
26
+ add_sig_comment(modified_source, method_def_match, [])
27
+ next
28
+ end
29
+
30
+ debug "> Parsed arguments:"
31
+ debug stack.inspect
32
+
33
+ types = stack.last.map do |arg_def|
34
+ debug "> Arg def: #{arg_def}"
35
+
36
+ to_replace, type, arg = if arg_def.is_a?(String) && arg_def.match?(/[\w_]+\s+[\w_@=]+\s*/)
37
+ optional = arg_def.include?("=")
38
+ arg_def = arg_def.split("=").first
39
+ debug "> Arg def simple: #{arg_def}"
40
+
41
+ type, arg = arg_def.squeeze(" ").strip.split(" ")
42
+ type_for_sig = optional ? "?(#{type})" : type
43
+ [arg_def, type_for_sig, arg]
44
+ elsif arg_def.is_a?(Array)
45
+ # TODO: handle nested parens in type
46
+ type = arg_def.first.first
47
+ arg = arg_def[1]
48
+ optional = arg.include?("=")
49
+ type_for_sig = optional ? "?(#{type})" : type
50
+ [/\(\s*#{Regexp.escape(type)}\s*\)\s*#{Regexp.escape(arg)}/, type_for_sig, arg]
51
+ else
52
+ raise "Unexpected arg def: #{arg_def}"
53
+ end
54
+
55
+ debug "> Replace: #{to_replace} -- (Type: #{type}, Arg: #{arg})"
56
+
57
+ modified_source.gsub!(to_replace, arg)
58
+ type
59
+ end
60
+
61
+ # Mark file dirty
62
+ context.track! self
63
+
64
+ # TODO: handle return type
65
+ add_sig_comment(modified_source, method_def_match, types)
66
+ end
67
+
68
+ modified_source
69
+ end
70
+
71
+ private
72
+
73
+ def add_sig_comment(source, method_def_match, types)
74
+ method = method_def_match.first
75
+ sig_comment = "# @sig (#{types.join(", ")}) -> void"
76
+ debug "> Add sig comment to '#{method}': #{sig_comment}"
77
+ # Ensure to capture whole of line and add comment at end
78
+ source.gsub!(/#{method}(.*)$/, "#{method}\\1 #{sig_comment}")
79
+ end
80
+ end
81
+ end
82
+ end
83
+
84
+ # Add the rewriter to the list of rewriters
85
+ RubyNext::Language.rewriters << Claret::Rewriters::MethodDefRewriter
@@ -0,0 +1,73 @@
1
+ require "strscan"
2
+
3
+ require_relative "../utils/logging"
4
+ require_relative "../parsing/parens"
5
+
6
+ module Claret
7
+ module Rewriters
8
+ class MethodArgIvarRewriter < RubyNext::Language::Rewriters::Text
9
+ include ::Claret::Utils::Logging
10
+
11
+ NAME = "claret-ivar-arg"
12
+ # Must be run after the MethodDefRewriter
13
+ SYNTAX_PROBE = "def foo(@a, @b, @c = :foo)"
14
+ MIN_SUPPORTED_VERSION = Gem::Version.new(RubyNext::NEXT_VERSION)
15
+
16
+ def safe_rewrite(source)
17
+ modified_source = source.dup
18
+
19
+ source.scan(/(def\s+[\w_]+\s*)([^#]*)/).each do |method_def_match|
20
+ debug "> Method def match: #{method_def_match.inspect}"
21
+
22
+ method_def_match = method_def_match.join
23
+ scanner = StringScanner.new method_def_match
24
+ stack = Claret::Parsing::Parens.new(scanner).parse
25
+
26
+ next if stack.size < 2
27
+
28
+ debug "> Parsing arguments:"
29
+ debug stack.inspect
30
+
31
+ ivars_lines = stack.last.map do |arg_def|
32
+ debug "> Arg def: #{arg_def}"
33
+ arg_str = if arg_def.is_a?(String)
34
+ arg_def = arg_def.strip
35
+ if arg_def[0] == "@"
36
+ debug "> ivar def: #{arg_def}"
37
+ arg_def[1..-1]
38
+ end
39
+ elsif arg_def.is_a?(Array) && arg_def.first
40
+ arg_def = arg_def.first.strip
41
+ if arg_def[0] == "@"
42
+ debug "> ivar def: #{arg_def}"
43
+ arg_def.first[1..-1]
44
+ end
45
+ end
46
+ next unless arg_str
47
+ arg_name = arg_str.match(/[\w_]+/).to_s
48
+
49
+ debug "> Set: @#{arg_name}"
50
+
51
+ modified_source.gsub!(arg_def, arg_def[1..-1])
52
+ method_def_match.gsub!(arg_def, arg_def[1..-1])
53
+ "@#{arg_name} = #{arg_name}"
54
+ end
55
+
56
+ ivars_lines.compact!
57
+
58
+ # Mark file dirty
59
+ context.track! self
60
+
61
+ debug "> Add setters: #{ivars_lines.join("\n")}"
62
+ # Ensure to capture whole of line inc comments and then add ivar lines at end
63
+ modified_source.gsub!(/#{Regexp.escape(method_def_match)}(.*)$/, "#{method_def_match}\\1#{ivars_lines.map { "\n#{_1}" }.join}")
64
+ end
65
+
66
+ modified_source
67
+ end
68
+ end
69
+ end
70
+ end
71
+
72
+ # Add the rewriter to the list of rewriters
73
+ RubyNext::Language.rewriters << Claret::Rewriters::MethodArgIvarRewriter
@@ -0,0 +1,19 @@
1
+ require "logger"
2
+
3
+ module Claret
4
+ module Utils
5
+ module Logging
6
+ def say(msg)
7
+ logger.info("#{self.class.name} > #{msg}")
8
+ end
9
+
10
+ def debug(msg)
11
+ logger.debug("#{self.class.name} > #{msg}")
12
+ end
13
+
14
+ def logger
15
+ @logger ||= ::Logger.new($stdout, level: ENV.fetch("DEBUG", "").empty? ? Logger::INFO : Logger::DEBUG)
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Claret
4
+ VERSION = "0.1.0"
5
+ end
data/lib/claret.rb ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "claret/version"
4
+
5
+ require "ruby-next/language"
6
+ require "ruby-next/language/rewriters/text"
7
+
8
+ require_relative "claret/utils/logging"
9
+ require_relative "claret/parsing/parens"
10
+ require_relative "claret/rewriters/1_method_def_rewriter"
11
+ require_relative "claret/rewriters/2_method_arg_ivar_rewriter"
12
+
13
+ module Claret
14
+ class Error < StandardError; end
15
+ # Your code goes here...
16
+ end
data/sig/claret.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Claret
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,127 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: claret
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Stephen Ierodiaconou
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-12-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: thor
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.3'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.3'
27
+ - !ruby/object:Gem::Dependency
28
+ name: ruby-next
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: steep
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.6'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.6'
55
+ - !ruby/object:Gem::Dependency
56
+ name: irbs
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">"
60
+ - !ruby/object:Gem::Version
61
+ version: '0.1'
62
+ - - "<"
63
+ - !ruby/object:Gem::Version
64
+ version: '1'
65
+ type: :runtime
66
+ prerelease: false
67
+ version_requirements: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">"
70
+ - !ruby/object:Gem::Version
71
+ version: '0.1'
72
+ - - "<"
73
+ - !ruby/object:Gem::Version
74
+ version: '1'
75
+ description: A Ruby dialect that includes types in the language. Transpiles to Ruby
76
+ and RBS by leveraging the ruby-next and irbs gems. Type checks with steep.
77
+ email:
78
+ - stevegeek@gmail.com
79
+ executables:
80
+ - claret
81
+ extensions: []
82
+ extra_rdoc_files: []
83
+ files:
84
+ - ".standard.yml"
85
+ - CHANGELOG.md
86
+ - CODE_OF_CONDUCT.md
87
+ - LICENSE.txt
88
+ - README.md
89
+ - Rakefile
90
+ - claret.gemspec
91
+ - examples/hello_world.rb
92
+ - exe/claret
93
+ - lib/claret.rb
94
+ - lib/claret/parsing/parens.rb
95
+ - lib/claret/rewriters/1_method_def_rewriter.rb
96
+ - lib/claret/rewriters/2_method_arg_ivar_rewriter.rb
97
+ - lib/claret/utils/logging.rb
98
+ - lib/claret/version.rb
99
+ - sig/claret.rbs
100
+ homepage: https://github.com/stevegeek/claret
101
+ licenses:
102
+ - MIT
103
+ metadata:
104
+ homepage_uri: https://github.com/stevegeek/claret
105
+ source_code_uri: https://github.com/stevegeek/claret
106
+ changelog_uri: https://github.com/stevegeek/claret/blob/main/CHANGELOG.md
107
+ post_install_message:
108
+ rdoc_options: []
109
+ require_paths:
110
+ - lib
111
+ required_ruby_version: !ruby/object:Gem::Requirement
112
+ requirements:
113
+ - - ">="
114
+ - !ruby/object:Gem::Version
115
+ version: 3.0.0
116
+ required_rubygems_version: !ruby/object:Gem::Requirement
117
+ requirements:
118
+ - - ">="
119
+ - !ruby/object:Gem::Version
120
+ version: '0'
121
+ requirements: []
122
+ rubygems_version: 3.4.20
123
+ signing_key:
124
+ specification_version: 4
125
+ summary: A Ruby dialect that includes types in the language. Transpiles to Ruby and
126
+ RBS.
127
+ test_files: []