slimi 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: b30b237b1d1e68744ac90e65d148397a5099a4702482286768afd6db8409a484
4
+ data.tar.gz: 055a9e297a5467e35c01d7468ab5d5083df89ef8762bb8c92d3074956751675b
5
+ SHA512:
6
+ metadata.gz: 43d27cd7dc20e1de1d744ae87110bec52727d30786c252cd02de8f31cdc7f86fe4d7cc08d005b5c430c73d1ab68176dc0a73e5ae2376722febfb12f4193dfd68
7
+ data.tar.gz: 4ab35e06cb00a9b50cbca0dd34797ad281777fba885141cf41709c6e15f24c8c87a99b55d466ce8c31546a464d507e1a476a3b1d6aa5345a770572a9151b5cd0
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ NewCops: enable
3
+ SuggestExtensions: false
4
+ TargetRubyVersion: 2.6
5
+
6
+ Layout/LineLength:
7
+ Enabled: false
8
+
9
+ Metrics:
10
+ Enabled: false
11
+
12
+ Style/Documentation:
13
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.1.0 - 2021-12-20
6
+
7
+ - 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 r7kamura@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 slimi.gemspec
6
+ gemspec
7
+
8
+ gem 'rake', '~> 13.0'
9
+ gem 'rspec', '~> 3.0'
10
+ gem 'rubocop', '~> 1.21'
11
+ gem 'slim'
data/Gemfile.lock ADDED
@@ -0,0 +1,62 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ slimi (0.1.0)
5
+ temple
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ ast (2.4.2)
11
+ diff-lcs (1.4.4)
12
+ parallel (1.21.0)
13
+ parser (3.0.3.2)
14
+ ast (~> 2.4.1)
15
+ rainbow (3.0.0)
16
+ rake (13.0.6)
17
+ regexp_parser (2.2.0)
18
+ rexml (3.2.5)
19
+ rspec (3.10.0)
20
+ rspec-core (~> 3.10.0)
21
+ rspec-expectations (~> 3.10.0)
22
+ rspec-mocks (~> 3.10.0)
23
+ rspec-core (3.10.1)
24
+ rspec-support (~> 3.10.0)
25
+ rspec-expectations (3.10.1)
26
+ diff-lcs (>= 1.2.0, < 2.0)
27
+ rspec-support (~> 3.10.0)
28
+ rspec-mocks (3.10.2)
29
+ diff-lcs (>= 1.2.0, < 2.0)
30
+ rspec-support (~> 3.10.0)
31
+ rspec-support (3.10.3)
32
+ rubocop (1.23.0)
33
+ parallel (~> 1.10)
34
+ parser (>= 3.0.0.0)
35
+ rainbow (>= 2.2.2, < 4.0)
36
+ regexp_parser (>= 1.8, < 3.0)
37
+ rexml
38
+ rubocop-ast (>= 1.12.0, < 2.0)
39
+ ruby-progressbar (~> 1.7)
40
+ unicode-display_width (>= 1.4.0, < 3.0)
41
+ rubocop-ast (1.15.0)
42
+ parser (>= 3.0.1.1)
43
+ ruby-progressbar (1.11.0)
44
+ slim (4.1.0)
45
+ temple (>= 0.7.6, < 0.9)
46
+ tilt (>= 2.0.6, < 2.1)
47
+ temple (0.8.2)
48
+ tilt (2.0.10)
49
+ unicode-display_width (2.1.0)
50
+
51
+ PLATFORMS
52
+ x86_64-linux
53
+
54
+ DEPENDENCIES
55
+ rake (~> 13.0)
56
+ rspec (~> 3.0)
57
+ rubocop (~> 1.21)
58
+ slim
59
+ slimi!
60
+
61
+ BUNDLED WITH
62
+ 2.2.29
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Ryo Nakamura
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
+ # Slimi
2
+
3
+ [![test](https://github.com/r7kamura/slimi/actions/workflows/test.yml/badge.svg)](https://github.com/r7kamura/slimi/actions/workflows/test.yml)
4
+
5
+ Yet another implementation for [Slim](https://github.com/slim-template/slim) template language.
6
+
7
+ The current goal is to generate AST with detailed location information so that the embedded Ruby code in slim templates can be auto-corrected by Linter such as RuboCop.
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'slimi'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ ```
20
+ bundle install
21
+ ```
22
+
23
+ Or install it yourself as:
24
+
25
+ ```
26
+ gem install slimi
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ TBD.
32
+
33
+ ## Development
34
+
35
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
36
+
37
+ 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).
38
+
39
+ ## Contributing
40
+
41
+ Bug reports and pull requests are welcome on GitHub at https://github.com/r7kamura/slimi. 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/r7kamura/slimi/blob/main/CODE_OF_CONDUCT.md).
42
+
43
+ ## License
44
+
45
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
46
+
47
+ ## Code of Conduct
48
+
49
+ Everyone interacting in the Slimi project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/r7kamura/slimi/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'slimi'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Slimi
4
+ module Errors
5
+ class BaseError < StandardError
6
+ end
7
+
8
+ class ParserError < BaseError
9
+ end
10
+
11
+ class LineEndingNotFoundError < ParserError
12
+ end
13
+
14
+ class MalformedIndentationError < ParserError
15
+ end
16
+
17
+ class UnexpectedEosError < ParserError
18
+ end
19
+
20
+ class UnexpectedIndentationError < ParserError
21
+ end
22
+
23
+ class UnexpectedTextAfterClosedTagError < ParserError
24
+ end
25
+
26
+ class UnknownLineIndicator < ParserError
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'strscan'
4
+ require 'temple'
5
+
6
+ module Slimi
7
+ module Filters
8
+ class Interpolation < ::Temple::Filter
9
+ # @param [Integer] begin_
10
+ # @param [Integer] end_
11
+ # @return [Array] S-expression.
12
+ def on_slimi_interpolate(begin_, end_, string)
13
+ block = [:multi]
14
+ scanner = ::StringScanner.new(string)
15
+ until scanner.eos?
16
+ charpos = scanner.charpos
17
+ if (value = scanner.scan(/\\#\{/) || scanner.scan(/([#\\]?[^#\\]*([#\\][^\\\#{][^#\\]*)*)/))
18
+ block << [:static, value]
19
+ elsif scanner.scan(/#\{((?>[^{}]|(\{(?>[^{}]|\g<1>)*\}))*)\}/)
20
+ code = scanner[1]
21
+ begin2 = begin_ + charpos + 2
22
+ end2 = end_ + scanner.charpos - 1
23
+ if code.start_with?('{') && code.end_with?('}')
24
+ escape = true
25
+ code = code[1..-2]
26
+ begin2 -= 1
27
+ end2 -= 1
28
+ else
29
+ escape = false
30
+ end
31
+ block << [:slimi, :position, begin2, end2, [:slim, :output, escape, code, [:multi]]]
32
+ end
33
+ end
34
+ block
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Slimi
4
+ module Filters
5
+ class Unposition
6
+ def initialize(*); end
7
+
8
+ # @param [Array] node S-expression.
9
+ # @return [Array] S-expression.
10
+ def call(node)
11
+ convert(node)
12
+ end
13
+
14
+ private
15
+
16
+ def convert(value)
17
+ if value.instance_of?(::Array)
18
+ if value[0] == :slimi && value[1] == :position
19
+ call(value[4])
20
+ else
21
+ value.map do |element|
22
+ call(element)
23
+ end
24
+ end
25
+ else
26
+ value
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Slimi
4
+ module Filters
5
+ autoload :Interpolation, 'slimi/filters/interpolation'
6
+ autoload :Unposition, 'slimi/filters/unposition'
7
+ end
8
+ end
@@ -0,0 +1,550 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'strscan'
4
+ require 'temple'
5
+
6
+ module Slimi
7
+ class Parser < ::Temple::Parser
8
+ define_options(
9
+ attr_list_delims: {
10
+ '(' => ')',
11
+ '[' => ']',
12
+ '{' => '}'
13
+ },
14
+ shortcut: {
15
+ '#' => { attr: 'id' },
16
+ '.' => { attr: 'class' }
17
+ }
18
+ )
19
+
20
+ def initialize(options = {})
21
+ super
22
+ factory = Factory.new(
23
+ attribute_delimiters: options[:attr_list_delims] || {},
24
+ default_tag: options[:default_tag] || 'div',
25
+ shortcut: options[:shortcut] || {}
26
+ )
27
+ @attribute_delimiters = factory.attribute_delimiters
28
+ @attribute_shortcuts = factory.attribute_shortcuts
29
+ @tag_shortcuts = factory.tag_shortcuts
30
+ @attribute_shortcut_regexp = factory.attribute_shortcut_regexp
31
+ @attribute_delimiter_regexp = factory.attribute_delimiter_regexp
32
+ @quoted_attribute_regexp = factory.quoted_attribute_regexp
33
+ @tag_name_regexp = factory.tag_name_regexp
34
+ @attribute_name_regexp = factory.attribute_name_regexp
35
+ end
36
+
37
+ def call(source)
38
+ @stacks = [[:multi]]
39
+ @indents = []
40
+ @scanner = ::StringScanner.new(source)
41
+ parse_block until @scanner.eos?
42
+ @stacks[0]
43
+ end
44
+
45
+ private
46
+
47
+ def parse_block
48
+ parse_indent
49
+
50
+ parse_line_ending ||
51
+ parse_html_comment ||
52
+ parse_html_conditional_comment ||
53
+ parse_slim_comment_block ||
54
+ parse_verbatim_text_block ||
55
+ parse_inline_html ||
56
+ parse_code_block ||
57
+ parse_output_block ||
58
+ parse_doctype ||
59
+ parse_tag ||
60
+ raise(Errors::UnknownLineIndicatorError)
61
+ end
62
+
63
+ def parse_indent
64
+ @scanner.skip(/[ \t]*/)
65
+ indent = indent_from_last_match
66
+ @indents << indent if @indents.empty?
67
+
68
+ if indent > @indents.last
69
+ raise Errors::UnexpectedIndentationError unless expecting_indentation?
70
+
71
+ @indents << indent
72
+ else
73
+ @stacks.pop if expecting_indentation?
74
+
75
+ while indent < @indents.last && @indents.length > 1
76
+ @indents.pop
77
+ @stacks.pop
78
+ end
79
+
80
+ raise Errors::MalformedIndentationError if indent != @indents.last
81
+ end
82
+ end
83
+
84
+ # @return [Boolean]
85
+ def parse_tag
86
+ parse_tag_inner && expect_line_ending
87
+ end
88
+
89
+ # @return [Boolean]
90
+ def parse_tag_inner
91
+ tag_name = parse_tag_name
92
+ if tag_name
93
+ attributes = parse_attributes
94
+
95
+ white_space_marker = @scanner.scan(/[<>']*/)
96
+ with_trailing_white_space = white_space_marker.include?('<') || white_space_marker.include?("'")
97
+ with_leading_white_space = white_space_marker.include?('>')
98
+
99
+ tag = [:html, :tag, tag_name, attributes]
100
+ @stacks.last << [:static, ' '] if with_leading_white_space
101
+ @stacks.last << tag
102
+ @stacks.last << [:static, ' '] if with_trailing_white_space
103
+
104
+ if @scanner.skip(/[ \t]*$/)
105
+ content = [:multi]
106
+ tag << content
107
+ @stacks << content
108
+ elsif @scanner.skip(/[ \t]*=(=?)([<>'])*/)
109
+ escape = @scanner[1].empty?
110
+ white_space_marker = @scanner[2]
111
+ with_trailing_white_space2 = !with_trailing_white_space && white_space_marker && (white_space_marker.include?('<') || white_space_marker.include?("'"))
112
+ with_leading_white_space2 = !with_leading_white_space && white_space_marker && white_space_marker.include?('>')
113
+ block = [:multi]
114
+ @stacks.last.insert(-2, [:static, ' ']) if with_leading_white_space2
115
+ @scanner.skip(/[ \t]+/)
116
+ tag << with_position { [:slim, :output, escape, parse_broken_lines, block] }
117
+ @stacks.last << [:static, ' '] if with_trailing_white_space2
118
+ @stacks << block
119
+ elsif @scanner.skip(%r{[ \t]*/[ \t]*})
120
+ raise Errors::UnexpectedTextAfterClosedTagError unless @scanner.match?(/\r?\n/)
121
+ else
122
+ @scanner.skip(/[ \t]+/)
123
+ tag << [:slim, :text, :inline, parse_text_block]
124
+ end
125
+ true
126
+ else
127
+ false
128
+ end
129
+ end
130
+
131
+ # Parse tag name part.
132
+ # e.g. div.foo
133
+ # ^^^
134
+ # `- tag name
135
+ # e.g. .foo
136
+ # ^
137
+ # `- tag name shortcut (not consume input in this case)
138
+ # e.g. ?.foo
139
+ # ^
140
+ # `- tag name shortcut if `?` is registered as only-tag shortcut (consume input in this case)
141
+ # @return [String, nil] Tag name if found.
142
+ def parse_tag_name
143
+ return unless @scanner.match?(@tag_name_regexp)
144
+
145
+ if @scanner[1]
146
+ @scanner.pos += @scanner.matched_size
147
+ @scanner.matched
148
+ else
149
+ marker = @scanner.matched
150
+ @scanner.pos += @scanner.matched_size unless @attribute_shortcuts[marker]
151
+ @tag_shortcuts[marker]
152
+ end
153
+ end
154
+
155
+ # Parse attribute shortcuts part.
156
+ # e.g. div#foo.bar
157
+ # ^^^^^^^^
158
+ # `- attribute shortcuts
159
+ # @return [Array] Found attribute s-expressions.
160
+ def parse_tag_attribute_shortcuts
161
+ result = []
162
+ while @scanner.skip(@attribute_shortcut_regexp)
163
+ marker = @scanner[1]
164
+ attribute_value = @scanner[2]
165
+ attribute_names = @attribute_shortcuts[marker]
166
+ raise 'Illegal shortcut' unless attribute_names
167
+
168
+ attribute_names.map do |attribute_name|
169
+ result << [:html, :attr, attribute_name.to_s, [:static, attribute_value]]
170
+ end
171
+ end
172
+ result
173
+ end
174
+
175
+ # Parse quoted attribute value part.
176
+ # e.g. input type="text"
177
+ # ^^^^^^
178
+ # `- quoted attribute value
179
+ # @note Skip closing quote in {}.
180
+ # @param [String] quote `"'"` or `'"'`.
181
+ # @return [Array] S-expression.
182
+ def parse_quoted_attribute_value(quote)
183
+ begin_ = @scanner.charpos
184
+ end_ = nil
185
+ value = +''
186
+ count = 0
187
+ loop do
188
+ if @scanner.match?(/#{quote}/) && count.zero?
189
+ end_ = @scanner.charpos
190
+ @scanner.pos += @scanner.matched_size
191
+ break
192
+ end
193
+
194
+ if @scanner.skip(/\{/)
195
+ count += 1
196
+ elsif @scanner.skip(/\}/)
197
+ count -= 1
198
+ end
199
+ value << @scanner.scan(/[^{}#{quote}]*/)
200
+ end
201
+ [:slimi, :interpolate, begin_, end_, value]
202
+ end
203
+
204
+ # Parse attributes part.
205
+ # e.g. input type="text" value="a" autofocus
206
+ # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
207
+ # `- attributes part
208
+ # @return [Array] S-expression of attributes.
209
+ def parse_attributes
210
+ attributes = %i[html attrs]
211
+ attributes += parse_tag_attribute_shortcuts
212
+
213
+ if @scanner.scan(@attribute_delimiter_regexp)
214
+ attribute_delimiter_opening = @scanner[1]
215
+ attribute_delimiter_closing = @attribute_delimiters[attribute_delimiter_opening]
216
+ attribute_delimiter_closing_regexp = ::Regexp.escape(attribute_delimiter_closing)
217
+ boolean_attribute_regexp = /#{@attribute_name_regexp}(?=(?:[ \t]|#{attribute_delimiter_closing_regexp}|$))/
218
+ attribute_delimiter_closing_part_regexp = /[ \t]*#{attribute_delimiter_closing_regexp}/
219
+ end
220
+
221
+ loop do
222
+ if @scanner.skip(@quoted_attribute_regexp)
223
+ attribute_name = @scanner[1]
224
+ escape = @scanner[2].empty?
225
+ quote = @scanner[3]
226
+ attributes << [:html, :attr, attribute_name, [:escape, escape, parse_quoted_attribute_value(quote)]]
227
+ elsif !attribute_delimiter_closing_part_regexp
228
+ break
229
+ elsif @scanner.skip(boolean_attribute_regexp)
230
+ attributes << [:html, :attr, @scanner[1], [:multi]]
231
+ elsif @scanner.skip(attribute_delimiter_closing_part_regexp) # rubocop:disable Lint/DuplicateBranch
232
+ break
233
+ else
234
+ raise ::NotImplementedError
235
+ end
236
+ end
237
+
238
+ attributes
239
+ end
240
+
241
+ # @return [Boolean]
242
+ def parse_html_comment
243
+ if @scanner.skip(%r{/!})
244
+ text_block = parse_text_block
245
+ text = [:slim, :text, :verbatim, text_block]
246
+ @stacks.last << [:html, :comment, text]
247
+ true
248
+ else
249
+ false
250
+ end
251
+ end
252
+
253
+ # @return [Boolean]
254
+ def parse_html_conditional_comment
255
+ parse_html_conditional_comment_inner && expect_line_ending
256
+ end
257
+
258
+ # @return [Boolean]
259
+ def parse_html_conditional_comment_inner
260
+ if @scanner.skip(%r{/\[\s*(.*?)\s*\][ \t]*})
261
+ block = [:multi]
262
+ @stacks.last << [:html, :condcomment, @scanner[1], block]
263
+ @stacks << block
264
+ true
265
+ else
266
+ false
267
+ end
268
+ end
269
+
270
+ # @return [Boolean]
271
+ def parse_slim_comment_block
272
+ if @scanner.skip(%r{/.*})
273
+ while !@scanner.eos? && (@scanner.match?(/[ \t]*$/) || peek_indent > @indents.last)
274
+ @scanner.skip(/.*/)
275
+ parse_line_ending
276
+ end
277
+ true
278
+ else
279
+ false
280
+ end
281
+ end
282
+
283
+ # @return [Boolean]
284
+ def parse_verbatim_text_block
285
+ parse_verbatim_text_block_inner && expect_line_ending
286
+ end
287
+
288
+ # @return [Boolean]
289
+ def parse_verbatim_text_block_inner
290
+ if @scanner.skip(/([|']) ?/)
291
+ with_trailing_white_space = @scanner[1] == "'"
292
+ @stacks.last << [:slim, :text, :verbatim, parse_text_block]
293
+ @stacks.last << [:static, ' '] if with_trailing_white_space
294
+ true
295
+ else
296
+ false
297
+ end
298
+ end
299
+
300
+ # @return [Boolean]
301
+ def parse_inline_html
302
+ parse_inline_html_inner && expect_line_ending
303
+ end
304
+
305
+ # @return [Boolean]
306
+ def parse_inline_html_inner
307
+ if @scanner.match?(/<.*/)
308
+ begin_ = @scanner.charpos
309
+ value = @scanner.matched
310
+ @scanner.pos += @scanner.matched_size
311
+ end_ = @scanner.charpos
312
+ block = [:multi]
313
+ @stacks.last << [:multi, [:slimi, :interpolate, begin_, end_, value], block]
314
+ @stacks << block
315
+ true
316
+ else
317
+ false
318
+ end
319
+ end
320
+
321
+ # @return [Boolean]
322
+ def parse_code_block
323
+ parse_code_block_inner && expect_line_ending
324
+ end
325
+
326
+ # @return [Boolean]
327
+ def parse_code_block_inner
328
+ if @scanner.skip(/-/)
329
+ block = [:multi]
330
+ @scanner.skip(/[ \t]+/)
331
+ @stacks.last << with_position { [:slim, :control, parse_broken_lines, block] }
332
+ @stacks << block
333
+ true
334
+ else
335
+ false
336
+ end
337
+ end
338
+
339
+ # @return [Boolean]
340
+ def parse_output_block
341
+ parse_output_block_inner && expect_line_ending
342
+ end
343
+
344
+ # @return [Boolean]
345
+ def parse_output_block_inner
346
+ if @scanner.skip(/=(=?)([<>']*)/)
347
+ escape = @scanner[1].empty?
348
+ white_space_marker = @scanner[2]
349
+ with_trailing_white_space = white_space_marker.include?('<') || white_space_marker.include?("'")
350
+ with_leading_white_space = white_space_marker.include?('>')
351
+ block = [:multi]
352
+ @stacks.last << [:static, ' '] if with_trailing_white_space
353
+ @scanner.skip(/[ \t]+/)
354
+ @stacks.last << with_position { [:slim, :output, escape, parse_broken_lines, block] }
355
+ @stacks.last << [:static, ' '] if with_leading_white_space
356
+ @stacks << block
357
+ else
358
+ false
359
+ end
360
+ end
361
+
362
+ # @return [Boolean]
363
+ def parse_doctype
364
+ parse_doctype_inner && expect_line_ending
365
+ end
366
+
367
+ # @return [Boolean]
368
+ def parse_doctype_inner
369
+ if @scanner.skip(/doctype[ \t]*/)
370
+ @stacks.last << [:html, :doctype, @scanner.scan(/.*/).rstrip]
371
+ true
372
+ else
373
+ false
374
+ end
375
+ end
376
+
377
+ # @return [Boolean]
378
+ def expecting_indentation?
379
+ @stacks.length > @indents.length
380
+ end
381
+
382
+ # @raise
383
+ def expect_line_ending
384
+ parse_line_ending || @scanner.eos? || raise(LineEndingNotFoundError)
385
+ end
386
+
387
+ # @return [Integer] Indent level.
388
+ def peek_indent
389
+ @scanner.match?(/[ \t]*/)
390
+ indent_from_last_match
391
+ end
392
+
393
+ # @return [Integer]
394
+ def indent_from_last_match
395
+ @scanner.matched.chars.map do |char|
396
+ case char
397
+ when "\t"
398
+ 4
399
+ when ' '
400
+ 1
401
+ else
402
+ 0
403
+ end
404
+ end.sum(0)
405
+ end
406
+
407
+ # @return [Boolean]
408
+ def parse_line_ending
409
+ if @scanner.skip(/\r?\n/)
410
+ @stacks.last << [:newline]
411
+ true
412
+ else
413
+ false
414
+ end
415
+ end
416
+
417
+ # @todo Append new_line for each empty line.
418
+ def parse_text_block
419
+ result = [:multi]
420
+
421
+ interpolate = parse_interpolate_line
422
+ result << interpolate if interpolate
423
+
424
+ loop do
425
+ break unless @scanner.match?(/\r?\n[ \t]*/)
426
+
427
+ indent = indent_from_last_match
428
+ break if indent <= @indents.last
429
+
430
+ @scanner.pos += @scanner.matched_size
431
+ result << [:newline]
432
+ result << parse_interpolate_line
433
+ end
434
+
435
+ result
436
+ end
437
+
438
+ # @return [Array, nil] S-expression if found.
439
+ def parse_interpolate_line
440
+ return unless @scanner.match?(/.+/)
441
+
442
+ begin_ = @scanner.charpos
443
+ value = @scanner.matched
444
+ @scanner.pos += @scanner.matched_size
445
+ end_ = @scanner.charpos
446
+ [:slimi, :interpolate, begin_, end_, value]
447
+ end
448
+
449
+ # @note Broken line means line-breaked lines, separated by trailing "," or "\".
450
+ # @return [String]
451
+ def parse_broken_lines
452
+ result = +''
453
+ result << @scanner.scan(/.*/)
454
+ while result.end_with?(',') || result.end_with?('\\')
455
+ raise Errors::UnexpectedEosError unless @scanner.scan(/\r?\n/)
456
+
457
+ result << "\n"
458
+ result << @scanner.scan(/.*/)
459
+ end
460
+ result
461
+ end
462
+
463
+ # Wrap the result s-expression of given block with slimi-position s-expression.
464
+ def with_position(&block)
465
+ begin_ = @scanner.charpos
466
+ inner = block.call
467
+ end_ = @scanner.charpos
468
+ [:slimi, :position, begin_, end_, inner]
469
+ end
470
+
471
+ # Convert human-friendly options into machine-friendly objects.
472
+ class Factory
473
+ # @return [Hash]
474
+ attr_reader :attribute_delimiters
475
+
476
+ # @param [Hash] attribute_delimiters
477
+ # @param [String] default_tag
478
+ # @param [Hash] shortcut
479
+ def initialize(attribute_delimiters:, default_tag:, shortcut:)
480
+ @attribute_delimiters = attribute_delimiters
481
+ @default_tag = default_tag
482
+ @shortcut = shortcut
483
+ end
484
+
485
+ # @return [Hash] e.g. `{ "." => { "a" => "b" }}`
486
+ # ^^^ ^^^ ^^^
487
+ # | | `- attribute value
488
+ # | `- attribute key
489
+ # `- marker
490
+ def additional_attributes
491
+ @additional_attributes ||= @shortcut.each_with_object({}) do |(marker, details), result|
492
+ result[marker] = details[:additional_attrs] if details.key?(:additional_attrs)
493
+ end
494
+ end
495
+
496
+ # @return [Hash] e.g. `{ "." => ["class"] }`
497
+ # ^^^ ^^^^^^^
498
+ # | `- attribute name
499
+ # `- marker
500
+ def attribute_shortcuts
501
+ @attribute_shortcuts ||= @shortcut.each_with_object({}) do |(marker, details), result|
502
+ result[marker] = Array(details[:attr]) if details.key?(:attr)
503
+ end
504
+ end
505
+
506
+ # @return [Hash] e.g. `{ "." => "div" }`
507
+ # ^^^ ^^^^^
508
+ # | `- tag name
509
+ # `- marker
510
+ def tag_shortcuts
511
+ @tag_shortcuts ||= @shortcut.transform_values do |details|
512
+ details[:tag] || @default_tag
513
+ end
514
+ end
515
+
516
+ # @return [Regexp] Pattern that matches to attribute delimiter.
517
+ def attribute_delimiter_regexp
518
+ delimiters_regexp = ::Regexp.union(@attribute_delimiters.keys)
519
+ /[ \t]*(#{delimiters_regexp})/
520
+ end
521
+
522
+ # @return [Regexp]
523
+ def attribute_name_regexp
524
+ @attribute_name_regexp ||= begin
525
+ characters = ::Regexp.escape(@attribute_delimiters.flatten.uniq.join)
526
+ %r{[ \t]*([^\0 \t\r\n"'<>/=#{characters}]+)}
527
+ end
528
+ end
529
+
530
+ # @return [Regexp] Pattern that matches to attribute shortcuts part.
531
+ def attribute_shortcut_regexp
532
+ markers = attribute_shortcuts.keys.sort_by { |marker| -marker.size }
533
+ markers_regexp = ::Regexp.union(markers)
534
+ %r{(#{markers_regexp}+)((?:\p{Word}|-|/\d+|:(\w|-)+)*)}
535
+ end
536
+
537
+ # @return [Regexp]
538
+ def quoted_attribute_regexp
539
+ /#{attribute_name_regexp}[ \t]*=(=?)[ \t]*("|')/
540
+ end
541
+
542
+ # @return [Regexp] Pattern that matches to tag header part.
543
+ def tag_name_regexp
544
+ markers = tag_shortcuts.keys.sort_by { |marker| -marker.size }
545
+ markers_regexp = ::Regexp.union(markers)
546
+ /#{markers_regexp}|\*(?=[^ \t]+)|(\p{Word}(?:\p{Word}|:|-)*\p{Word}|\p{Word}+)/
547
+ end
548
+ end
549
+ end
550
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Slimi
4
+ VERSION = '0.1.0'
5
+ end
data/lib/slimi.rb ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'slimi/version'
4
+
5
+ module Slimi
6
+ autoload :Errors, 'slimi/errors'
7
+ autoload :Filters, 'slimi/filters'
8
+ autoload :Parser, 'slimi/parser'
9
+ end
data/slimi.gemspec ADDED
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/slimi/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'slimi'
7
+ spec.version = Slimi::VERSION
8
+ spec.authors = ['Ryo Nakamura']
9
+ spec.email = ['r7kamura@gmail.com']
10
+
11
+ spec.summary = 'Yet another implementation for Slim template language.'
12
+ spec.homepage = 'https://github.com/r7kamura/slimi'
13
+ spec.license = 'MIT'
14
+ spec.required_ruby_version = '>= 2.6.0'
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = spec.homepage
18
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/main/CHANGELOG.md"
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
23
+ `git ls-files -z`.split("\x0").reject do |f|
24
+ (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
25
+ end
26
+ end
27
+ spec.bindir = 'exe'
28
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
29
+ spec.require_paths = ['lib']
30
+ spec.metadata = {
31
+ 'rubygems_mfa_required' => 'true'
32
+ }
33
+
34
+ spec.add_dependency 'temple'
35
+ end
metadata ADDED
@@ -0,0 +1,77 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: slimi
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ryo Nakamura
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-12-19 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: temple
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description:
28
+ email:
29
+ - r7kamura@gmail.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rspec"
35
+ - ".rubocop.yml"
36
+ - CHANGELOG.md
37
+ - CODE_OF_CONDUCT.md
38
+ - Gemfile
39
+ - Gemfile.lock
40
+ - LICENSE.txt
41
+ - README.md
42
+ - Rakefile
43
+ - bin/console
44
+ - bin/setup
45
+ - lib/slimi.rb
46
+ - lib/slimi/errors.rb
47
+ - lib/slimi/filters.rb
48
+ - lib/slimi/filters/interpolation.rb
49
+ - lib/slimi/filters/unposition.rb
50
+ - lib/slimi/parser.rb
51
+ - lib/slimi/version.rb
52
+ - slimi.gemspec
53
+ homepage: https://github.com/r7kamura/slimi
54
+ licenses:
55
+ - MIT
56
+ metadata:
57
+ rubygems_mfa_required: 'true'
58
+ post_install_message:
59
+ rdoc_options: []
60
+ require_paths:
61
+ - lib
62
+ required_ruby_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: 2.6.0
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ requirements: []
73
+ rubygems_version: 3.1.4
74
+ signing_key:
75
+ specification_version: 4
76
+ summary: Yet another implementation for Slim template language.
77
+ test_files: []