marshal-parser 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: 54bc27a08a2e25692ac3b0ccf449b6db7df3af095eff14a2c94c91545502721f
4
+ data.tar.gz: 0b803be1bde2b3d51d5023c51db1042b9b41eebc341f1d9c29e9c7c2e39e9aa8
5
+ SHA512:
6
+ metadata.gz: fca493db638e427e393d252b32e01a7be43bc4f9e2090d2b23492e5997c3b671d3734534054039dee19aeb8667b9291e74e098d4c85a3a1bbefaf79df7037fd4
7
+ data.tar.gz: cc2bcab736f4a53aec056e7d52dbe282100223641c8b57bff64e8fba3ea00995fddbdcfb3a8c5e1c848a148ebe784fb90937e8dff9b7bb3f9948d16e5b317528
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-02-27
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 andry.konchin@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 Andrew Konchin
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,202 @@
1
+ # marshal-parser
2
+
3
+ `marshal-parser` is a library that allows you to read and analyze data
4
+ that has been serialized in Ruby's Marshal format. It is built for
5
+ educational purposes, but can also be a handy tool for learning the
6
+ Marshal format or even for investigating bugs in its implementation.
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem 'marshal-parser'
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ $ bundle install
19
+
20
+ Or install it yourself as:
21
+
22
+ $ gem install marshal-parser
23
+
24
+ ## What is the Marshal format?
25
+
26
+ The Marshal format is a binary format used in Ruby to serialize Ruby
27
+ objects. The format can store arbitrary objects through three
28
+ user-defined extension mechanisms. The serialized data can be stored in
29
+ a file or transmitted over a network, and then deserialized back into a
30
+ Ruby object.
31
+
32
+ The Marshal format is described here <https://ruby-doc.org/core-3.1.0/doc/marshal_rdoc.html>.
33
+
34
+ There are also a lot of useful articles, for instance:
35
+ - <https://shopify.engineering/caching-without-marshal-part-one>
36
+ - <https://iliabylich.github.io/2016/01/25/ruby-marshalling-from-a-to-z.html>
37
+ - <http://jakegoulding.com/blog/categories/marshal/>
38
+
39
+ ## Features
40
+
41
+ There are a couple of uniq features that makes it stand out from the
42
+ croud:
43
+
44
+ - comprehensive support of the Marshal format
45
+ - CLI to parse existing dumps
46
+ - several output formats with different detalization levels
47
+
48
+ ## Usage
49
+
50
+ The primary way to use `marshal-parser` is to run the CLI script `marshal-cli`.
51
+
52
+ ### Tokens
53
+
54
+ To print tokens separated by whitespaces, use the `tokens` command,
55
+ followed by the `--evaluate` flag and a Ruby expression which value you
56
+ want to dump and parse:
57
+
58
+ marshal-cli tokens --evaluate '[true, false, 0]'
59
+
60
+ This will output:
61
+
62
+ "\x04\b" [ "\b" T F i "\x00"
63
+
64
+ To print descriptions for each token, use the `--annotate` flag:
65
+
66
+ marshal-cli tokens --evaluate '[true, false, 0]' --annotate
67
+
68
+ This will output:
69
+
70
+ "\x04\b" - Version (4.8)
71
+ "[" - Array beginning
72
+ "\b" - Integer encoded (3)
73
+ "T" - true
74
+ "F" - false
75
+ "i" - Integer beginning
76
+ "\x00" - Integer encoded (0)
77
+
78
+ ### AST
79
+
80
+ To print the AST or structure of a Marshal dump, use the `ast` command,
81
+ followed by the `--evaluate` flag:
82
+
83
+ marshal-cli ast --evaluate '[true, false, 0]'
84
+
85
+ This will output:
86
+
87
+ (array
88
+ (length 3)
89
+ (true)
90
+ (false)
91
+ (integer
92
+ (value 0)))
93
+
94
+ The AST is printed in a kind of S-expressions form. Both nodes (e.g. `array`,
95
+ `integer`...) and attributes (`length`) are printed.
96
+
97
+ To print only the nodes, use the `--compact` flag:
98
+
99
+ marshal-cli --evaluate '[true, false, 0]' --compact
100
+
101
+ This will output:
102
+
103
+ (array
104
+ true
105
+ false
106
+ (integer 0))
107
+
108
+ To print the AST as tokens, use the `--only-tokens` option:
109
+
110
+ marshal-cli ast --evaluate '[true, false, 0]' --only-tokens
111
+
112
+ This will output:
113
+
114
+ [
115
+ "\b"
116
+ T
117
+ F
118
+ i "\x00"
119
+
120
+ ### Other flags
121
+
122
+ To list all the available flags use the `--help` flag for each command:
123
+
124
+ marshal-cli tokens --help
125
+ marshal-cli ast --help
126
+ marshal-cli --help
127
+
128
+ ### Ruby library
129
+
130
+ To use `marshal-parser` as a Ruby library the following examples will be
131
+ useful:
132
+
133
+ Use `MarshalParser::Lexer` class to get tokens:
134
+
135
+ ```ruby
136
+ require 'marshal-parser'
137
+
138
+ dump = Marshal.dump(1)
139
+ lexer = MarshalParser::Lexer.new(dump)
140
+ lexer.run
141
+
142
+ pp lexer.tokens
143
+ ```
144
+
145
+ This will output:
146
+
147
+ [#<struct MarshalParser::Lexer::Token id=0, index=0, length=2, value="4.8">,
148
+ #<struct MarshalParser::Lexer::Token id=14, index=2, length=1, value=nil>,
149
+ #<struct MarshalParser::Lexer::Token id=25, index=3, length=1, value=1>]
150
+
151
+ Use `MarshalParser::Parser` class to get the AST:
152
+
153
+ ```ruby
154
+ require 'marshal-parser'
155
+
156
+ dump = Marshal.dump(1)
157
+ lexer = MarshalParser::Lexer.new(dump)
158
+ lexer.run
159
+
160
+ parser = MarshalParser::Parser.new(lexer)
161
+ ast = parser.parse
162
+
163
+ puts ast
164
+ ```
165
+
166
+ This will output:
167
+
168
+ #<MarshalParser::Parser::IntegerNode:0x000000010daba4d8
169
+ @prefix=#<struct MarshalParser::Lexer::Token id=14, index=2, length=1, value=nil>,
170
+ @value=#<struct MarshalParser::Lexer::Token id=25, index=3, length=1, value=1>>
171
+
172
+ ## Limitations
173
+
174
+ - Only supports current format version 4.8
175
+ - Does not support a deprecated node 'M' (that represents Class or Module)
176
+ - Does not support a 'd' node (Data object, that represents wrapped pointers from Ruby extensions)
177
+ - Doesn't print in annotations object indices (because Ruby is not consistent here and object indices assigning order may
178
+ vary depending on dumped class)
179
+
180
+ ## Similar projects
181
+
182
+ There are several projects that might be interesting as well:
183
+ - <https://github.com/iliabylich/pure_ruby_marshal>
184
+ - <https://github.com/drbrain/marshal-structure>
185
+
186
+ ## Development
187
+
188
+ 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.
189
+
190
+ 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).
191
+
192
+ ## Contributing
193
+
194
+ Bug reports and pull requests are welcome on GitHub at https://github.com/andrykonchin/marshal-parser. 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/andrykonchin/marshal-parser/blob/master/CODE_OF_CONDUCT.md).
195
+
196
+ ## License
197
+
198
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
199
+
200
+ ## Code of Conduct
201
+
202
+ Everyone interacting in the marshal-parser project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/andrykonchin/marshal-parser/blob/master/CODE_OF_CONDUCT.md).
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 "marshal-parser"
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/marshal-cli ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "marshal-parser"
5
+
6
+ Dry::CLI.new(MarshalParser::CLI::Commands).call
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,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MarshalParser
4
+ module Assertable
5
+ def assert(boolean, message)
6
+ raise "Assert failed: #{message}" unless boolean
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/cli"
4
+
5
+ module MarshalParser
6
+ module CLI
7
+ module Commands
8
+ extend Dry::CLI::Registry
9
+
10
+ class Tokens < Dry::CLI::Command
11
+ desc "Parse a dump and print tokens. By default reads dump from the stdin."
12
+ option :file, type: :string, aliases: ["-f"], desc: "Read a dump from file with provided name"
13
+ option :evaluate, type: :string, aliases: ["-e"], desc: "Ruby expression to dump"
14
+ option :annotate, type: :boolean, aliases: ["-a"], desc: "Print a table with annonated tokens"
15
+
16
+ def call(**options)
17
+ dump = \
18
+ if options[:file]
19
+ File.read(options[:file])
20
+ elsif options[:evaluate]
21
+ Marshal.dump(eval(options[:evaluate]))
22
+ else
23
+ $stdin.read
24
+ end
25
+
26
+ lexer = MarshalParser::Lexer.new(dump)
27
+ lexer.run
28
+
29
+ formatter = \
30
+ if options[:annotate]
31
+ MarshalParser::Formatters::Tokens::WithDescription.new(lexer.tokens, dump)
32
+ else
33
+ MarshalParser::Formatters::Tokens::OneLine.new(lexer.tokens, dump)
34
+ end
35
+
36
+ puts formatter.string
37
+ end
38
+ end
39
+
40
+ class AST < Dry::CLI::Command
41
+ desc "Parse a dump and print AST. By default reads dump from the stdin and uses S-expressions format."
42
+ option :file, type: :string, aliases: ["-f"], desc: "Read a dump from file with provided name"
43
+ option :evaluate, type: :string, aliases: ["-e"], desc: "Ruby expression to dump"
44
+ option :"only-tokens", type: :boolean, aliases: ["-o"], desc: "Print only tokens"
45
+ option :annotate, type: :boolean, aliases: ["-a"], desc: "Print annotations"
46
+ option :width, type: :string, aliases: ["-w"],
47
+ desc: "Width of the column with AST, used with --annotate"
48
+ option :symbols, type: :boolean, aliases: ["-s"], desc: "Print a table of symbols"
49
+ option :compact, type: :boolean, aliases: ["-c"], desc: "Don't print node attributes"
50
+
51
+ def call(**options)
52
+ dump = \
53
+ if options[:file]
54
+ File.read(options[:file])
55
+ elsif options[:evaluate]
56
+ Marshal.dump(eval(options[:evaluate]))
57
+ else
58
+ $stdin.read
59
+ end
60
+
61
+ lexer = Lexer.new(dump)
62
+ lexer.run
63
+
64
+ parser = Parser.new(lexer)
65
+ ast = parser.parse
66
+
67
+ renderer = \
68
+ if options[:annotate]
69
+ width = options[:width] ? Integer(options[:width]) : 50
70
+ MarshalParser::Formatters::AST::Renderers::RendererWithAnnotations.new(indent_size: 2, width: width)
71
+ else
72
+ MarshalParser::Formatters::AST::Renderers::Renderer.new(indent_size: 2)
73
+ end
74
+
75
+ formatter = \
76
+ if options[:"only-tokens"]
77
+ MarshalParser::Formatters::AST::OnlyTokens.new(ast, dump, renderer)
78
+ elsif options[:compact]
79
+ MarshalParser::Formatters::AST::SExpressionCompact.new(ast, dump, renderer)
80
+ else
81
+ MarshalParser::Formatters::AST::SExpression.new(ast, dump, renderer)
82
+ end
83
+
84
+ puts formatter.string
85
+
86
+ if options[:symbols]
87
+ symbols = parser.symbols
88
+ puts ""
89
+ puts "Symbols table:"
90
+ puts MarshalParser::Formatters::Symbols::Table.new(symbols).string
91
+ end
92
+ end
93
+ end
94
+
95
+ class Version < Dry::CLI::Command
96
+ desc "Print version"
97
+
98
+ def call(**)
99
+ puts MarshalParser::VERSION
100
+ end
101
+ end
102
+
103
+ register "tokens", Tokens, aliases: ["t"]
104
+ register "ast", AST, aliases: ["a"]
105
+ register "version", Version, aliases: ["v", "-v", "--version"]
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MarshalParser
4
+ module Formatters
5
+ module AST
6
+ class OnlyTokens
7
+ def initialize(node, source_string, renderer)
8
+ @node = node
9
+ @source_string = source_string
10
+ @renderer = renderer
11
+ end
12
+
13
+ def string
14
+ entries = node_to_entries(@node)
15
+ block = Renderers::EntriesBlock.new(entries)
16
+ @renderer.render(block)
17
+ end
18
+
19
+ private
20
+
21
+ def node_to_entries(node)
22
+ entries = node.child_entities.map do |child|
23
+ case child
24
+ when Lexer::Token
25
+ string = @source_string[child.index, child.length]
26
+ string = string.dump if string =~ /[^[:print:]]/ # TODO: How to detect \n, \r etc that may break formatting?
27
+
28
+ Renderers::Line.new(string)
29
+ when Parser::Node
30
+ node_to_entries(child)
31
+ else
32
+ raise "Unexpected node child entity #{child}"
33
+ end
34
+ end.flatten
35
+
36
+ # short oneline form, e.g. for Symbol - (: "\x06" E)
37
+ if node.children.empty?
38
+ # ignore "" as the last token and strip inserted whitespace
39
+ string = entries.map(&:string).join(" ").strip
40
+ entries = [Renderers::Line.new(string)]
41
+ end
42
+
43
+ raise "Expected 1st entry to be Line" unless entries[0].is_a?(Renderers::Line)
44
+
45
+ if node.is_a?(Parser::Annotatable)
46
+ string = entries[0].string
47
+ annotation = node.annotation
48
+ entries[0] = Renderers::LineAnnotated.new(string, annotation)
49
+ end
50
+
51
+ if entries.size > 1
52
+ [entries[0], Renderers::EntriesBlock.new(entries[1..])]
53
+ else
54
+ entries
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MarshalParser
4
+ module Formatters
5
+ module AST
6
+ module Renderers
7
+ class EntriesBlock
8
+ attr_reader :entries
9
+
10
+ def initialize(entries)
11
+ @entries = entries
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MarshalParser
4
+ module Formatters
5
+ module AST
6
+ module Renderers
7
+ class Line
8
+ attr_reader :string
9
+
10
+ def initialize(string)
11
+ @string = string
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MarshalParser
4
+ module Formatters
5
+ module AST
6
+ module Renderers
7
+ class LineAnnotated < Line
8
+ attr_reader :annotation
9
+
10
+ def initialize(string, annotation)
11
+ super(string)
12
+ @annotation = annotation
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MarshalParser
4
+ module Formatters
5
+ module AST
6
+ module Renderers
7
+ class Renderer
8
+ def initialize(indent_size:)
9
+ @indent_size = indent_size
10
+ end
11
+
12
+ def render(block)
13
+ lines = apply_indentation(block, 0)
14
+ strings = lines.map(&:string)
15
+ strings.join("\n")
16
+ end
17
+
18
+ private
19
+
20
+ def apply_indentation(block, level)
21
+ indentation = " " * @indent_size * level
22
+
23
+ block.entries.map do |e|
24
+ case e
25
+ when Line
26
+ Line.new(indentation + e.string)
27
+ when EntriesBlock
28
+ apply_indentation(e.entries, level + 1)
29
+ else
30
+ raise "Unexpected entry #{e} (#{e.class}), expected Line or EntriesBlock"
31
+ end
32
+ end.flatten
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MarshalParser
4
+ module Formatters
5
+ module AST
6
+ module Renderers
7
+ class RendererWithAnnotations
8
+ def initialize(indent_size:, width:)
9
+ @indent_size = indent_size
10
+ @width = width
11
+ end
12
+
13
+ def render(block)
14
+ # indent
15
+ lines = apply_indentation(block, 0)
16
+
17
+ # add annotations
18
+ strings = lines.map do |line|
19
+ case line
20
+ when LineAnnotated
21
+ "%-#{@width}s # %s" % [line.string, line.annotation]
22
+ when Line
23
+ line.string
24
+ else
25
+ raise "Unexpected line #{e} (#{e.class}), expected Line or LineAnnotated"
26
+ end
27
+ end
28
+
29
+ strings.join("\n")
30
+ end
31
+
32
+ private
33
+
34
+ def apply_indentation(block, level)
35
+ indentation = " " * @indent_size * level
36
+
37
+ block.entries.map do |e|
38
+ case e
39
+ when LineAnnotated
40
+ LineAnnotated.new(indentation + e.string, e.annotation)
41
+ when Line
42
+ Line.new(indentation + e.string)
43
+ when EntriesBlock
44
+ apply_indentation(e.entries, level + 1)
45
+ end
46
+ end.flatten
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end