compser 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: e91d16c77b4d59f8ce036475bb9f00d9d5c673b6c1d5ae83633189b76000ba68
4
+ data.tar.gz: 0ee49bea1a6235fc2d0da6840c920122cb58e394cd575a2739ce96a2fd9532d7
5
+ SHA512:
6
+ metadata.gz: 11eded3b70d584c53dc890f133b322e8485c43332c32c8694e40e91dd666bf64365014dc2b714ea94e5b0a25cee575f50479180829806b9a9fccbed4b084b5b6
7
+ data.tar.gz: 1055a219d1c8645739a891e049e5e0d598bf4643674ddde27807dda3b6efedbd3ffae0a4bd494e5fa84af6e751f5a4ad81b8d5071428e59e2607766137d68b35
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-10-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 luizpvasc@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,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in Compser.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
data/Gemfile.lock ADDED
@@ -0,0 +1,21 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ Compser (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ minitest (5.20.0)
10
+ rake (13.0.6)
11
+
12
+ PLATFORMS
13
+ x86_64-linux
14
+
15
+ DEPENDENCIES
16
+ Compser!
17
+ minitest (~> 5.0)
18
+ rake (~> 13.0)
19
+
20
+ BUNDLED WITH
21
+ 2.4.10
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Luiz Vasconcellos
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,221 @@
1
+ # Compser
2
+
3
+ Compser is a parser builder library for Ruby inspired by [elm-parser](https://package.elm-lang.org/packages/elm/parser/latest/).
4
+ Take a look at the [JSON parser](https://github.com/luizpvas/Compser/blob/main/examples/json.rb) to get a glimpse of the syntax
5
+ and available building blocks you can use to compose more complex and sophisticated parsers.
6
+
7
+ * Building blocks
8
+ * [`drop`](#drop)
9
+ * [`integer`](#integer)
10
+ * [`decimal`](#decimal)
11
+ * [`token`](#token)
12
+ * [`keyword`](#keyword)
13
+ * [`double_quoted_string`](#double_quoted_string)
14
+ * [`map`](#map)
15
+ * [`one_of`](#one_of)
16
+ * [`sequence`](#sequence)
17
+ * [`spaces`](#spaces)
18
+ * [`chomp_if`](#chomp_if)
19
+ * [`chomp_while`](#chomp_while)
20
+ * [Benchmark](#benchmark)
21
+
22
+ #### `drop`
23
+
24
+ Discard any result or chomped string produced by the parser.
25
+
26
+ ```ruby
27
+ parser = drop(:token, '[').take(:integer).drop(:token, ']')
28
+
29
+ parser.parse('[150]') # => Good<150>
30
+ parser.parse('[0]') # => Good<0>
31
+
32
+ parser.parse('1234') # => Bad<...>
33
+ parser.parse('[]') # => Bad<...>
34
+ parser.parse('[900') # => Bad<...>
35
+ ```
36
+
37
+ #### `integer`
38
+
39
+ Parse integers.
40
+
41
+ ```ruby
42
+ parser = take(:integer)
43
+
44
+ parser.parse('1') # => Good<1>
45
+ parser.parse('1234') # => Good<1234>
46
+
47
+ parser.parse('-500') # => Bad<...>
48
+ parser.parse('1.34') # => Bad<...>
49
+ parser.parse('1e31') # => Bad<...>
50
+ parser.parse('123a') # => Bad<...>
51
+ parser.parse('0x1A') # => Bad<...>
52
+
53
+
54
+ # negative integers with '-' prefix
55
+ def my_integer
56
+ take(:one_of, [
57
+ map(->(x) { x * -1 }).drop(:token, '-').take(:integer),
58
+ take(:integer)
59
+ ])
60
+ end
61
+ ```
62
+
63
+ #### `decimal`
64
+
65
+ Parse floating points as BigDecimal.
66
+
67
+ ```ruby
68
+ parser = take(:decimal)
69
+
70
+ parser.parse('0.00009') # => Good<0.00009>
71
+
72
+ parser.parse('-0.00009') # => Bad<...>
73
+ parser.parse('bad') # => Bad<...>
74
+ parser.parse('1e31') # => Bad<...>
75
+ parser.parse('123a') # => Bad<...>
76
+ ```
77
+
78
+ #### `token`
79
+
80
+ Parses the token from source.
81
+
82
+ ```ruby
83
+ parser = take(:token, 'module')
84
+
85
+
86
+ parser.parse('module') # => Good<'module'>
87
+ parser.parse('modules') # => Good<'module'> or use `keyword` if you want a failure in this case.
88
+ parser.parse('modu') # => Bad<...>
89
+ parser.parse('Module') # => Bad<...>
90
+ ```
91
+
92
+ #### `keyword`
93
+
94
+ Parses the keyword from source. The next character after the keyword must be a space, symbol or number.
95
+
96
+ ```ruby
97
+ parser = take(:keyword, 'let')
98
+
99
+ parser.parse('let') # => Good<'let'>
100
+
101
+ parser.parse('letter') # => Bad<...>
102
+ parser.parse('Let') # => Bad<...>
103
+ parser.parse('le') # => Bad<...>
104
+ ```
105
+
106
+ #### `double_quoted_string`
107
+
108
+ Parses a string between double quotes. Line breaks and tabs are supported.
109
+
110
+ ```ruby
111
+ parser = take(:double_quoted_string)
112
+
113
+ parser.parse('"Hello, world!"') # => Good<'Hello, world!'>
114
+ parser.parse('"line1\nline2"') # => Good<'line1\\nline2'>
115
+ parser.parse('"Hello, \\"world\\"!"') # => Good<'Hello, "world"!'>
116
+
117
+ parser.parse('foo') # => Bad<...>
118
+ parser.parse('foo "bar"') # => Bad<...>
119
+ parser.parse('"foo') # => Bad<...>
120
+ ```
121
+
122
+ #### `map`
123
+
124
+ Calls the map function with the taken values in the current pipeline if it succeeds. The output from map becomes the output of the parser,
125
+ that is, any parser with a map can be chained into other parsers.
126
+
127
+ Important: The arity of the map function should be equal to the amount of taken values in the pipeline.
128
+
129
+ ```ruby
130
+ Sum = ->(a, b) { a + b }
131
+
132
+ parser = map(Sum).take(:integer).drop(:token, '+').take(:integer)
133
+
134
+ parser.parse('1+1') # => Good<2>
135
+ parser.parse('1+') # => Bad<...>
136
+ ```
137
+
138
+ #### `one_of`
139
+
140
+ Attempts to parse each branch in the order they appear in the list. If all branches fail then the parser fails.
141
+ Important: `one_of` will fail on the current branch it had a partial success before failing. The branch has to fail
142
+ early without chomping any character from source .
143
+
144
+ ```ruby
145
+ parser = take(:one_of, [ take(:integer), take(:double_quoted_string) ])
146
+
147
+ parser.parse('2023') # => Good<2023>
148
+ parser.parse('"Hello, world!"') # => Good<'Hello, world!'>
149
+ parser.parse('true') # => Bad<...>
150
+ ```
151
+
152
+ #### `sequence`
153
+
154
+ Iterates over the parser until `done` is called. We don't know in advance how many values are gonna be taken,
155
+ so the `map` call should use single splat operator to receive a list with all values taken in the loop.
156
+
157
+ ```ruby
158
+
159
+ ToList = ->(*integers) { integers }
160
+
161
+ CommaSeparatedInteger = ->(continue, done) do
162
+ take(:integer)
163
+ .drop(:spaces)
164
+ .take(:one_of, [
165
+ drop(:token, ',').drop(:spaces).and_then(continue),
166
+ done
167
+ ])
168
+ end
169
+
170
+ parser = map(ToList).take(:sequence, CommaSeparatedInteger)
171
+
172
+ parser.parse('12, 23, 34') # => Good<[12, 23, 34]>
173
+ parser.parse('123') # => Good<[123]>
174
+
175
+ parser.parse('12,') # => Bad<...>
176
+ parser.parse(',12') # => Bad<...>
177
+ ```
178
+
179
+ #### `spaces`
180
+
181
+ Chompes zero or more blankspaces, line breaks and tabs. Always succeeds.
182
+
183
+ ```ruby
184
+ take(:spaces).parse(' \nfoo').state # => State<good?: true, offset: 5, chomped: ' \n'>
185
+ ```
186
+
187
+ #### `chomp_if`
188
+
189
+ Chomps a single character from source if predicate returns true. Otherwise, a bad result is pushed to state.
190
+
191
+ ```ruby
192
+ parser = take(:chomp_if, ->(ch) { ch == 'a' })
193
+
194
+ parser.parse('aaabb').state # => State<good?: true, offset: 1, chomped: 'a'>
195
+ parser.parse('cccdd').state # => State<good?: false, offset: 0, chomped: ''>
196
+ ```
197
+
198
+ #### `chomp_while`
199
+
200
+ Chomps characters from source as long as predicate returns true. This parser always succeeds even if predicate
201
+ returns false for the first character. It is a zero-or-more loop.
202
+
203
+ ```ruby
204
+ parser = take(:chomp_while, ->(ch) { ch == 'a' })
205
+
206
+ parser.parse('aaabb').state # => State<good?: true, offset: 3, chomped: 'aaa'>
207
+ parser.parse('cccdd').state # => State<good?: true, offset: 0, chomped: ''>
208
+ ```
209
+
210
+ ## Benchmark
211
+
212
+ The following result is a benchark of a [JSON parser](https://github.com/luizpvas/Compser/blob/main/examples/json.rb) I implemented
213
+ with this library. I ran the benchmark with and without YJIT, and compared the result against the native `JSON.parse`.
214
+
215
+ The benchmark parses a 1,5kb payload 5000 times.
216
+
217
+ Implementation | Time | Difference
218
+ :---:|:---:|:---:
219
+ `JSON.parse` | 0.019s | -
220
+ `MyJson.parse` (with YJIT) | 9.9s | 526x slower
221
+ `MyJSON.parse` | 12.3s | 654x slower
data/Rakefile ADDED
@@ -0,0 +1,12 @@
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
+ task default: :test
@@ -0,0 +1,16 @@
1
+ require_relative "json"
2
+ require "json"
3
+ require "benchmark"
4
+
5
+ json = File.read("./json-payload.json")
6
+
7
+ n = 5000
8
+
9
+ n.times do; MyJson.parse(json); end
10
+
11
+ Benchmark.bm do |x|
12
+ x.report("MyJson.parse") { n.times do; MyJson.parse(json); end }
13
+ x.report("JSON.parse") { n.times do; ::JSON.parse(json); end }
14
+ end
15
+
16
+ puts RubyVM::YJIT.runtime_stats
@@ -0,0 +1,32 @@
1
+ {
2
+ "product": "Live JSON generator",
3
+ "version": 3.1,
4
+ "releaseDate": "2014-06-25T00:00:00.000Z",
5
+ "demo": true,
6
+ "person": {
7
+ "id": 12345,
8
+ "name": "John Doe",
9
+ "phones": {
10
+ "home": "800-123-4567",
11
+ "mobile": "877-123-1234"
12
+ },
13
+ "email": [
14
+ "jd@example.com",
15
+ "jd@example.org"
16
+ ],
17
+ "dateOfBirth": "1980-01-02T00:00:00.000Z",
18
+ "registered": true,
19
+ "emergencyContacts": [
20
+ {
21
+ "name": "Jane Doe",
22
+ "phone": "888-555-1212",
23
+ "relationship": "spouse"
24
+ },
25
+ {
26
+ "name": "Justin Doe",
27
+ "phone": "877-123-1212",
28
+ "relationship": "parent"
29
+ }
30
+ ]
31
+ }
32
+ }
data/examples/json.rb ADDED
@@ -0,0 +1,73 @@
1
+ require_relative "../lib/compser"
2
+
3
+ module MyJson
4
+ extend Compser
5
+ extend self
6
+
7
+ def parse(str)
8
+ value.parse(str)
9
+ end
10
+
11
+ def value
12
+ take(:one_of, [
13
+ take(:double_quoted_string),
14
+ number,
15
+ boolean,
16
+ array,
17
+ object
18
+ ])
19
+ end
20
+
21
+ CommaSeparatedKeyValuePairs = ->(continue, done) do
22
+ map(->(key, value) { [key, value] })
23
+ .take(:double_quoted_string)
24
+ .drop(:spaces)
25
+ .drop(:token, ":")
26
+ .drop(:spaces)
27
+ .take(value)
28
+ .drop(:spaces)
29
+ .take(:one_of, [
30
+ drop(:token, ",").drop(:spaces).and_then(continue),
31
+ done
32
+ ])
33
+ end
34
+
35
+ def object
36
+ map(->(*pairs) { pairs.to_h })
37
+ .drop(:token, "{")
38
+ .drop(:spaces)
39
+ .take(:sequence, CommaSeparatedKeyValuePairs)
40
+ .drop(:token, "}")
41
+ end
42
+
43
+ CommaSeparatedValues = ->(continue, done) do
44
+ take(value)
45
+ .drop(:spaces)
46
+ .take(:one_of, [
47
+ succeed.drop(:token, ",").drop(:spaces).and_then(continue),
48
+ done
49
+ ])
50
+ end
51
+
52
+ def array
53
+ map(->(*values) { values })
54
+ .drop(:token, "[")
55
+ .drop(:spaces)
56
+ .take(:sequence, CommaSeparatedValues)
57
+ .drop(:token, "]")
58
+ end
59
+
60
+ def number
61
+ take(:one_of, [
62
+ map(->(x) { x * -1 }).drop(:token, "-").take(:decimal),
63
+ take(:decimal)
64
+ ])
65
+ end
66
+
67
+ def boolean
68
+ take(:one_of, [
69
+ map(-> { true }).drop(:token, "true"),
70
+ map(-> { false }).drop(:token, "false")
71
+ ])
72
+ end
73
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Compser::Result
4
+ Good = Data.define(:state, :value) do
5
+ def good? = true
6
+ def bad? = false
7
+ end
8
+
9
+ Bad = Data.define(:state, :message) do
10
+ def bad? = true
11
+ def good? = false
12
+ end
13
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Savepoint
4
+ def initialize(state)
5
+ @state = state
6
+
7
+ @offset = state.offset
8
+ @line = state.line
9
+ @column = state.column
10
+ @chomped = state.chomped
11
+ @result_stack = state.result_stack.dup
12
+ end
13
+
14
+ def has_changes?
15
+ @state.offset > @offset
16
+ end
17
+
18
+ def rollback_chomped_and_result_stack
19
+ @state.chomped = @chomped
20
+ @state.result_stack = @result_stack.dup
21
+ end
22
+
23
+ def rollback
24
+ @state.offset = @offset
25
+ @state.line = @line
26
+ @state.column = @column
27
+ @state.chomped = @chomped
28
+ @state.result_stack = @result_stack.dup
29
+ end
30
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::State
4
+ attr_accessor :source_code, :offset, :line, :column, :chomped, :result_stack, :__sequence__
5
+
6
+ def initialize(source_code)
7
+ @source_code = source_code
8
+ @offset = 0
9
+ @line = 0
10
+ @column = 0
11
+ @chomped = ::String.new("")
12
+ @result_stack = [Compser::Result::Good.new(self, nil)]
13
+ end
14
+
15
+ def result
16
+ @result_stack.last
17
+ end
18
+
19
+ def eof?
20
+ @offset >= @source_code.length
21
+ end
22
+
23
+ def peek(i = 0, n = 1)
24
+ peek_offset = @offset + i
25
+
26
+ return if peek_offset < 0
27
+ return if peek_offset + n - 1 >= @source_code.length
28
+
29
+ return @source_code[peek_offset, n]
30
+ end
31
+
32
+ def chomp
33
+ return if @offset >= @source_code.length
34
+
35
+ @chomped += @source_code[@offset]
36
+ @offset += 1
37
+
38
+ if peek(-1) == "\n"
39
+ @line += 1
40
+ @column = 0
41
+ else
42
+ @column += 1
43
+ end
44
+
45
+ self
46
+ end
47
+
48
+ def consume_chomped
49
+ chomped = @chomped
50
+
51
+ @chomped = ::String.new("")
52
+
53
+ chomped
54
+ end
55
+
56
+ def good?
57
+ @result_stack.last.good?
58
+ end
59
+
60
+ def bad?
61
+ !good?
62
+ end
63
+
64
+ def pop_results(n)
65
+ @result_stack.pop(n)
66
+ end
67
+
68
+ def good!(value)
69
+ @result_stack.push(good(value)) and return self
70
+ end
71
+
72
+ def bad!(message)
73
+ @result_stack.push(bad(message)) and return self
74
+ end
75
+
76
+ def good(value)
77
+ return value if value.is_a?(Compser::Result::Good)
78
+
79
+ Compser::Result::Good.new(self, value)
80
+ end
81
+
82
+ def bad(message)
83
+ return message if message.is_a?(Compser::Result::Bad)
84
+
85
+ Compser::Result::Bad.new(self, message)
86
+ end
87
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ ChompIf = ->(predicate, state) do
5
+ return state.bad!("unexpected eof") if state.eof?
6
+
7
+ return state.chomp if predicate.call(state.peek)
8
+
9
+ state.bad!("unexpected character")
10
+ end
11
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ ChompWhile = ->(predicate, state) do
5
+ state.chomp while !state.eof? && predicate.call(state.peek)
6
+
7
+ state
8
+ end
9
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+
5
+ class Compser::Step
6
+ Decimal = -> do
7
+ Compser::Step.new
8
+ .and_then(:chomp_if, IsDigit)
9
+ .and_then(:chomp_while, IsDigit)
10
+ .and_then(:one_of, [
11
+ Compser::Step.new
12
+ .and_then(:chomp_if, ->(ch) { ch == "." })
13
+ .and_then(:chomp_if, IsDigit)
14
+ .and_then(:chomp_while, IsDigit),
15
+ Compser::Step.new
16
+ ])
17
+ .and_then(NotFollowedByAlpha)
18
+ .and_then { |state| state.good!(BigDecimal(state.consume_chomped)) }
19
+ end
20
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ IsUninteresting = ->(ch) do
5
+ ch != "\\" && ch != "\""
6
+ end
7
+
8
+ AssertNotEof = ->(state) do
9
+ return state.bad!("unexpected eof") if state.eof?
10
+
11
+ state
12
+ end
13
+
14
+ DoubleQuotedStringHelper = ->(continue, done) do
15
+ Compser::Step.new
16
+ .and_then(:one_of, [
17
+ Compser::Step.new
18
+ .and_then(:chomp_if, ->(ch) { ch == "\\" })
19
+ .and_then(:chomp_if, ->(_) { true })
20
+ .and_then(continue),
21
+ Compser::Step.new
22
+ .drop(:chomp_if, ->(ch) { ch == "\"" })
23
+ .and_then(done),
24
+ Compser::Step.new
25
+ .and_then(:chomp_if, IsUninteresting)
26
+ .and_then(:chomp_while, IsUninteresting)
27
+ .and_then(AssertNotEof)
28
+ .and_then(continue)
29
+ ])
30
+ end
31
+
32
+ DoubleQuotedString = -> do
33
+ Compser::Step.new
34
+ .drop(:chomp_if, ->(ch) { ch == "\"" })
35
+ .and_then(:sequence, DoubleQuotedStringHelper)
36
+ .and_then { |state| state.good!(state.consume_chomped) }
37
+ end
38
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ Drop = ->(parser, state) do
5
+ savepoint = Compser::Savepoint.new(state)
6
+
7
+ parser.call(state)
8
+
9
+ savepoint.rollback_chomped_and_result_stack if state.good?
10
+
11
+ state
12
+ end.curry
13
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ IsDigit = ->(char) do
5
+ char =~ /\d/
6
+ end
7
+
8
+ NotFollowedByAlpha = ->(state) do
9
+ return state if state.eof?
10
+ return state if !state.peek.match?(/[[:alpha:]]/)
11
+
12
+ state.bad!("unexpected character")
13
+ end
14
+
15
+ Integer = -> do
16
+ Compser::Step.new
17
+ .and_then(:chomp_if, IsDigit)
18
+ .and_then(:chomp_while, IsDigit)
19
+ .and_then(NotFollowedByAlpha)
20
+ .and_then { |state| state.good!(state.consume_chomped.to_i) }
21
+ end
22
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ Keyword = ->(str, state) do
5
+ has_token = state.peek(0, str.size) == str
6
+
7
+ if has_token
8
+ str.size.times { state.chomp }
9
+
10
+ return state.good!(str) if state.eof? || !state.peek.match?(/[[:alpha:]]/)
11
+ end
12
+
13
+ state.bad!("expected keyword #{str.inspect}")
14
+ end
15
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ OneOf = ->(branches, state) do
5
+ return state.bad!(":one_of requires at least one branch") if branches.empty?
6
+
7
+ savepoint = Compser::Savepoint.new(state)
8
+
9
+ branches.each_with_index do |branch, index|
10
+ state = branch.call(state)
11
+
12
+ return state if state.good? || savepoint.has_changes?
13
+ return state if index == branches.size - 1 # is last
14
+
15
+ savepoint.rollback
16
+ end
17
+
18
+ state.bad!(":one_of failed all branches")
19
+ end
20
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ Problem = ->(message, state) do
5
+ state.bad!(message)
6
+ end
7
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ CONT = :continue
5
+ DONE = :done
6
+
7
+ Sequence = ->(helper, state) do
8
+ state.__sequence__ = nil
9
+
10
+ continue = ->(state) { state.__sequence__ = CONT; state }
11
+ done = ->(state) { state.__sequence__ = DONE; state }
12
+
13
+ state = helper.call(continue, done).call(state)
14
+
15
+ while state.good? && state.__sequence__ == CONT
16
+ state = helper.call(continue, done).call(state)
17
+ end
18
+
19
+ return state if state.bad?
20
+
21
+ if state.good? && state.__sequence__ == DONE
22
+ return state
23
+ end
24
+
25
+ state.bad!("unbound sequence")
26
+ end
27
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ Spaces = -> do
5
+ Compser::Step.new
6
+ .and_then(:chomp_while, ->(c) { c == " " || c == "\t" || c == "\n" || c == "\r" })
7
+ end
8
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ Token = ->(str, state) do
5
+ has_token = state.peek(0, str.size) == str
6
+
7
+ if has_token
8
+ str.size.times { state.chomp }
9
+
10
+ return state.good!(str)
11
+ end
12
+
13
+ state.bad!("expected #{str.inspect}")
14
+ end
15
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Compser::Step
4
+ STEPS = {
5
+ chomp_if: ChompIf.curry,
6
+ chomp_while: ChompWhile.curry,
7
+ decimal: Decimal,
8
+ double_quoted_string: DoubleQuotedString,
9
+ integer: Integer,
10
+ keyword: Keyword.curry,
11
+ one_of: OneOf.curry,
12
+ problem: Problem.curry,
13
+ sequence: Sequence.curry,
14
+ spaces: Spaces,
15
+ token: Token.curry
16
+ }.freeze
17
+
18
+ def initialize(mapper = nil)
19
+ @mapper = mapper
20
+ @steps = []
21
+ end
22
+
23
+ def parse(src)
24
+ call(Compser::State.new(src)).result
25
+ end
26
+
27
+ def call(state)
28
+ results_before = state.result_stack.size
29
+
30
+ state = @steps.reduce(state) do |state, step|
31
+ return state if state.bad?
32
+
33
+ step.call(state)
34
+ end
35
+
36
+ results_after = state.result_stack.size
37
+
38
+ if @mapper && state.good?
39
+ args = state.pop_results(results_after - results_before).map(&:value)
40
+
41
+ state.good!(@mapper.call(*args))
42
+ end
43
+
44
+ state
45
+ end
46
+
47
+ def and_then(*args, &block)
48
+ first, *rest = args
49
+
50
+ step =
51
+ case first
52
+ when Proc then first
53
+ when Compser::Step then first
54
+ when Symbol then STEPS.fetch(args.first).call(*rest)
55
+ when nil then block ? block : raise(ArgumentError, "expected a callable")
56
+ else raise ArgumentError, "expected a callable, got #{args.inspect}"
57
+ end
58
+
59
+ @steps << step
60
+
61
+ self
62
+ end
63
+
64
+ alias take and_then
65
+
66
+ def drop(*args, &block)
67
+ first, *rest = args
68
+
69
+ step =
70
+ case first
71
+ when Proc then Drop.(first)
72
+ when Compser::Step then Drop.(first)
73
+ when Symbol then Drop.(STEPS.fetch(first).call(*rest))
74
+ when nil then block ? Drop.(block) : raise(ArgumentError, "expected a callable")
75
+ else raise ArgumentError, "expected a callable"
76
+ end
77
+
78
+ @steps << step
79
+
80
+ self
81
+ end
82
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Compser
4
+ VERSION = "0.1.0"
5
+ end
data/lib/compser.rb ADDED
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "compser/version"
4
+ require_relative "compser/result"
5
+ require_relative "compser/savepoint"
6
+ require_relative "compser/state"
7
+ require_relative "compser/step/chomp_if"
8
+ require_relative "compser/step/chomp_while"
9
+ require_relative "compser/step/decimal"
10
+ require_relative "compser/step/double_quoted_string"
11
+ require_relative "compser/step/drop"
12
+ require_relative "compser/step/integer"
13
+ require_relative "compser/step/keyword"
14
+ require_relative "compser/step/one_of"
15
+ require_relative "compser/step/problem"
16
+ require_relative "compser/step/sequence"
17
+ require_relative "compser/step/spaces"
18
+ require_relative "compser/step/token"
19
+ require_relative "compser/step"
20
+
21
+ module Compser
22
+ def succeed
23
+ Step.new
24
+ end
25
+
26
+ def map(mapper)
27
+ Step.new(mapper)
28
+ end
29
+
30
+ def take(...)
31
+ Step.new.and_then(...)
32
+ end
33
+
34
+ def drop(...)
35
+ Step.new.drop(...)
36
+ end
37
+ end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: compser
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Luiz Vasconcellos
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-10-14 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description:
14
+ email:
15
+ - luizpvasc@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - CHANGELOG.md
21
+ - CODE_OF_CONDUCT.md
22
+ - Gemfile
23
+ - Gemfile.lock
24
+ - LICENSE.txt
25
+ - README.md
26
+ - Rakefile
27
+ - examples/json-benchmark.rb
28
+ - examples/json-payload.json
29
+ - examples/json.rb
30
+ - lib/compser.rb
31
+ - lib/compser/result.rb
32
+ - lib/compser/savepoint.rb
33
+ - lib/compser/state.rb
34
+ - lib/compser/step.rb
35
+ - lib/compser/step/chomp_if.rb
36
+ - lib/compser/step/chomp_while.rb
37
+ - lib/compser/step/decimal.rb
38
+ - lib/compser/step/double_quoted_string.rb
39
+ - lib/compser/step/drop.rb
40
+ - lib/compser/step/integer.rb
41
+ - lib/compser/step/keyword.rb
42
+ - lib/compser/step/one_of.rb
43
+ - lib/compser/step/problem.rb
44
+ - lib/compser/step/sequence.rb
45
+ - lib/compser/step/spaces.rb
46
+ - lib/compser/step/token.rb
47
+ - lib/compser/version.rb
48
+ homepage: https://github.com/luizpvas/compser
49
+ licenses:
50
+ - MIT
51
+ metadata:
52
+ homepage_uri: https://github.com/luizpvas/compser
53
+ source_code_uri: https://github.com/luizpvas/compser
54
+ changelog_uri: https://github.com/luizpvas/compser
55
+ post_install_message:
56
+ rdoc_options: []
57
+ require_paths:
58
+ - lib
59
+ required_ruby_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: 3.2.0
64
+ required_rubygems_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ requirements: []
70
+ rubygems_version: 3.4.10
71
+ signing_key:
72
+ specification_version: 4
73
+ summary: Parser combinator for Ruby.
74
+ test_files: []