steadfast 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4c7180221c50d5f0e81f1328dbc03aa33df4a71fc4effcdc429fde0bc5c54925
4
- data.tar.gz: 7a0af87cae2fb6f434e2d0b367cda46a6dd6f468e49ab4ccb3ed509f61279cbf
3
+ metadata.gz: 3856e55251f5e48be25a1cb9f03df36743ab36e8bfa18068b33045a977205cfc
4
+ data.tar.gz: f04e002ad7a9b54e3f80f848a82cbb8efd0fd71980b7066e581473a5512b4b9a
5
5
  SHA512:
6
- metadata.gz: 79761040dc7cd9eb03ff2ef37110dfdbf45de6a38ed6772b2d4054145610a735d849e05069d83de88caa5df1a6fa9b91ac03192829a5d7ac2a20c8ca3cc6d870
7
- data.tar.gz: 2757ce844329d3bd3a3c73252c8cb9728450321a887da1e26fb8bf6c3a29ee0a2428ca5263d028e4d27555ec3c721ee81ed94aeef94ad3c8891e9bbeab123d1e
6
+ metadata.gz: f31437cf5dd75e56eae0342d6055c50fcd82726130b22b07cbababa4dd45f7955b03497ca5ac572747a101d9bf6e5aced9b49c8c21c55bae9bf73e7c1e2b6f1c
7
+ data.tar.gz: 2cc985fff855606d568445392bbaf289eb12d0876bd6879dcad7a6d01686aad46f883e0c981254b686fabeddc4d9222b4358145f733e9ae69ccd572c96547cc2
data/CHANGELOG.md CHANGED
@@ -1,3 +1,20 @@
1
+ # 0.5.0 2026-11-26
2
+
3
+ - Add examples
4
+ - Sourcifier: fix source formatting for `ForwardingSuperNode`, `ImaginaryNode`, `ProgramNode`
5
+ - Add support for AlternationPatternNode
6
+ - Add `Steadfast.quote` - Include `Steadfast::Quote` methods in `Steadfast`
7
+ - `Steadfast.rewrite` - raise on invalid AST
8
+
9
+ # 0.4.0 2026-11-25
10
+
11
+ - Improve sourcifier output
12
+ - Implement `quote` and `unquote`
13
+ - Implement additional `make_xxx` methods
14
+ - Implement `make_statements`
15
+ - Implement `make_literal`
16
+ - Implement `make_node`
17
+
1
18
  # 0.3.0 2026-11-24
2
19
 
3
20
  - Implement `Steadfast.find_all`
data/README.md CHANGED
@@ -21,4 +21,206 @@
21
21
  <img src="./steadfast.png">
22
22
  </p>
23
23
 
24
- More information coming soon...
24
+ Steadfast is a gem for working with Ruby [Prism](https://github.com/ruby/prism/)
25
+ [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree). Steadfast provides a
26
+ convenient, rich API for generating and transforming ASTs.
27
+
28
+ ## Features
29
+
30
+ - Convert any proc or method to AST, convert any AST to source code.
31
+ - Rewrite, transform, compose and take apart ASTs.
32
+ - Comprehensive set of tools for creating synthetic AST nodes.
33
+ - Code quoting and templating using quote / unquote.
34
+ - Partial evaluation / specialization.
35
+ - Additional tools for iterating over ASTs and finding nodes.
36
+
37
+ ## Requirements
38
+
39
+ Steadfast requires Ruby 4.1 or newer.
40
+
41
+ ## Getting Started
42
+
43
+ Steadfast provides a variety of tools for working with ASTs. Here are the main
44
+ ones:
45
+
46
+ - `Steadfast.to_ast` - used to get the AST of a proc or a method.
47
+ - `Steadfast.rewrite` - used to create modified copies of ASTs.
48
+ - `Steadfast.quote` and `Steadfast.unquote` - used to generate ASTs and create
49
+ code templates.
50
+ - `Steadfast.eval_ast` - used to evaluate ASTs.
51
+
52
+ In the following example, we'll take a lambda that returns an integer, extract
53
+ its AST, and modify it to return an interpolated string instead.
54
+
55
+ ```ruby
56
+ require 'steadfast'
57
+
58
+ l = -> { 42 }
59
+ ast = Steadfast.to_ast(l)
60
+
61
+ msg = 'Hello'
62
+ ast2 = Steadfast.rewrite(ast) do |n|
63
+ next n if !(n in Ruby::Prism::IntegerNode(value: 42))
64
+
65
+ # Inject the value of a local variable into the string
66
+ Steadfast.quote(binding) { "#{unquote(msg)} from Steadfast!" }
67
+ end
68
+
69
+ l2 = Steadfast.eval_ast(ast2)
70
+ l2.() #=> "Hello from Steadfast!"
71
+ ```
72
+
73
+ ## Rewriting ASTs
74
+
75
+ The `Steadfast.rewrite` method is a general-purpose tool for modifying ASTs.
76
+ Since Prism ASTs are immutable, `Steadfast.rewrite` lets you modify an AST by
77
+ creating a copy of it with the requisite node replacements. You can replace
78
+ nodes by providing a hash with the replacements to be made. For example:
79
+
80
+ ```ruby
81
+ ast = Steadfast.to_ast(->() { foo() })
82
+ call_node = Steadfast.find(ast) { n in Ruby::Prism::CallNode(name: :foo)) }
83
+
84
+ # replace foo call with bar call
85
+ ast2 = Steadfast.rewrite(ast, call_node => quote { bar() })
86
+ ```
87
+
88
+ Another way to use Steadfast.rewrite is by providing a block that will be
89
+ invoked for each node in the AST. The block should return eith the node passed
90
+ to it, or a replacement node if it should be replaced. For example:
91
+
92
+ ```ruby
93
+ ast = Steadfast.to_ast(->() { foo() })
94
+
95
+ # replace foo call with bar call
96
+ ast2 = Steadfast.rewrite(ast) { |n|
97
+ # use next to allow the iteration to continue
98
+ next n if !(n in Ruby::Prism::CallNode(name: :foo))
99
+
100
+ Steadfast.quote { bar() }
101
+ }
102
+ ```
103
+
104
+ ### Recursive rewriting
105
+
106
+ When using the block form of `Steadfast.rewrite`, if a block returns a
107
+ replacement node, it will not be iterated on. In order to allow recursive
108
+ processing of replacement nodes, `Steadfast.rewrite` provides the block with a
109
+ reference to itself, as a block argument, which you can use to make recursive
110
+ calls to `Steadfast.rewrite`:
111
+
112
+ ```ruby
113
+ Steadfast.rewrite(ast) { |node, &block|
114
+ if (replacement = should_replace_node?(node))
115
+ Steadfast.rewrite(replacement, &block)
116
+ else
117
+ node
118
+ end
119
+ }
120
+ ```
121
+
122
+ ## Code Quoting and Templating
123
+
124
+ Steadfast provides a quote / unquote mechanism similar to that found in
125
+ languages such as Elixir or Lisp, to facilitate code generation and code
126
+ templating.
127
+
128
+ `Steadfast.quote` is used to quote code, returning an AST for the code block
129
+ provided to it:
130
+
131
+ ```ruby
132
+ Steadfast.quote(binding) { 42 } #=> IntegerNode
133
+ Steadfast.quote(binding) { foo(42) } #=> CallNode
134
+ Steadfast.quote(binding) { -> { 42 } } #=> LambdaNode
135
+ Steadfast.quote(binding) { foo; bar } #=> StatementsNode
136
+ ```
137
+
138
+ `Steadfast.unquote` is used to convert a literal value into an AST. Normally, it
139
+ is used inside a `quote` block in order to inject the result of an expression or
140
+ block. The `unquote` call lets you inject arbitrary values into the quoted code:
141
+
142
+ ```ruby
143
+ foo = 42
144
+ Steadfast.quote(binding) { x + unquote(foo) } #=> x + 42
145
+ ```
146
+
147
+ ## Creating Nodes
148
+
149
+ The easiest way to create new AST nodes is by using `Steadfast.quote`, as
150
+ explained above. Literal values can also be created using `Steadfast.unquote`:
151
+
152
+ ```ruby
153
+ Steadfast.unquote({ foo: 1, bar: 2 })
154
+ ```
155
+
156
+ Arbitrary types of nodescan be created by using `Steadfast.make_node` and
157
+ providing a string containing Ruby syntax:
158
+
159
+ ```ruby
160
+ Steadfast.make_node('foo.bar(:baz)') #=> CallNode
161
+ ```
162
+
163
+ The `Steadfast.make_node` method takes the following optional arguments:
164
+
165
+ - `location`: a Prism node or Prism location which will be used as the location
166
+ for the generated AST.
167
+ - `lvars`: an array containing local variable names used in the given code
168
+ snippet.
169
+ - `binding`: a binding for determining local variable names used in the given
170
+ code snippet.
171
+
172
+ In addition to `Steadfast.make_node`, additional methods allow the creation of
173
+ specific node types:
174
+
175
+ - `Steadfast.make_call(name:, receiver:, args:)` - create a call node.
176
+ - `Steadfast.make_def(name:, params:, :body)` - create a method definition.
177
+
178
+ ## Traversing ASTs and Finding Nodes
179
+
180
+ Use `Steadfast.walk` to visit each node in an AST:
181
+
182
+ ```ruby
183
+ Steadfast.walk(ast) { p it } #=> print out each node in the AST
184
+ ```
185
+
186
+ To find a node, use `Steadfast.find`. This method will return the first node for
187
+ which the given block returns true, or nil if none found:
188
+
189
+ ```ruby
190
+ # look for a call to foo
191
+ Steadfast.find(ast) { n in Ruby::CallNode(receiver: nil, name: :foo) }
192
+ ```
193
+
194
+ To find all nodes that respond to specific criteria, use `Steadfast.find_all`:
195
+
196
+ ```ruby
197
+ # find all method calls without a receiver
198
+ Steadfast.find_all(ast) { n in Ruby::CallNode(receiver: nil) }
199
+ ```
200
+
201
+ ## AST Conversion and Evaluation
202
+
203
+ Additional Steadfast allow you to convert a method or proc to AST, to convert an
204
+ AST to source code, and to evaluate ASTs. To get the AST for a proc or method,
205
+ use `Steadfast.to_ast`:
206
+
207
+ ```ruby
208
+ def foo
209
+ 42
210
+ end
211
+
212
+ foo_ast = Steadfast.to_ast(method(:foo))
213
+ ```
214
+
215
+ To convert an AST to source code, use `Steadfast.to_source`:
216
+
217
+ ```ruby
218
+ Steadfast.to_source(foo_ast) #=> "def foo..."
219
+ ```
220
+
221
+ To evaluate an AST use `Steadfast.eval_ast`:
222
+
223
+ ```ruby
224
+ ast = quote { puts 'Hi!' }
225
+ Steadfast.eval_ast(ast) #=> 'Hi!!!'
226
+ ```
@@ -0,0 +1,142 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Steadfast
4
+ module Make
5
+ # @param src [String]
6
+ # @param location [Ruby::Prism::Node, Ruby::Prism::Location]
7
+ # @param lvars [Array<Symbol>] optional local var list
8
+ # @param binding [Binding] optional binding
9
+ # @return [Ruby::Prism::Node]
10
+ def make_node(src, location: nil, lvars: nil, binding: nil)
11
+ loc = location && __make_get_source_location__(location)
12
+ scopes = [(binding&.local_variables || []), lvars].compact
13
+ opts = {
14
+ raise_error: true,
15
+ frozen_string_literal: true,
16
+ filepath: loc && loc[0],
17
+ line: loc && loc[1],
18
+ scopes: scopes
19
+ }
20
+ ast = Ruby::Prism.parse(src, **opts).value.statements.body[0]
21
+ ast.send(:source).__filename__ = loc[0] if loc
22
+ ast
23
+ end
24
+
25
+ IDENTIFIER_RE = /^[^\(\)\;\:\s]+$/
26
+
27
+ # Makes a def node.
28
+ #
29
+ # @param name [String, Symbol]
30
+ # @param params [Ruby::Prism::Node, nil]
31
+ # @param body [Ruby::Prism::StatementsNode]
32
+ # @param location [Ruby::Prism::Location]
33
+ # @return [Ruby::Prism::Node]
34
+ def make_def(name, params: nil, body:, location: nil)
35
+ raise SyntaxError, 'Invalid method name' if !(IDENTIFIER_RE === name)
36
+
37
+ n = make_node("def #{name}(x); 1; end", location:)
38
+ n.copy(body:, parameters: params)
39
+ end
40
+
41
+ # Makes a local variable read node.
42
+ #
43
+ # @param name [String, Symbol]
44
+ # @param location [Ruby::Prism::Location]
45
+ # @return [Ruby::Prism::Node]
46
+ def make_lvar_read(name, location: nil)
47
+ raise SyntaxError, 'Invalid identifier name' if !(IDENTIFIER_RE === name)
48
+
49
+ make_node(name.to_s, lvars: [name.to_sym], location:)
50
+ end
51
+
52
+ # Makes a literal array node.
53
+ #
54
+ # @param array [Array]
55
+ # @param location [Ruby::Prism::Location]
56
+ # @return [Ruby::Prism::Node]
57
+ def make_array(array, location: nil)
58
+ raise ArgumentError, "Not an array" if !array.is_a?(Array)
59
+
60
+ n = make_node('[]', location:)
61
+ Steadfast.rewrite(n, n => { elements: array.map { make_literal(it, location:) } })
62
+ end
63
+
64
+ # Makes a literal hash node.
65
+ #
66
+ # @param hash [Hash]
67
+ # @param location [Ruby::Prism::Location]
68
+ # @return [Ruby::Prism::Node]
69
+ def make_hash(hash, location: nil)
70
+ raise ArgumentError, "Not a hash" if !hash.is_a?(Hash)
71
+
72
+ n = make_node('{ x => 1 }', location:)
73
+ assoc_node = n.elements[0]
74
+ elements = hash.map { |k, v|
75
+ Steadfast.rewrite(
76
+ assoc_node,
77
+ assoc_node => {
78
+ key: make_literal(k, location:),
79
+ value: make_literal(v, location:)
80
+ }
81
+ )
82
+ }
83
+ Steadfast.rewrite(n, n => { elements: })
84
+ end
85
+
86
+ # Makes a literal value node.
87
+ #
88
+ # @param value [any]
89
+ # @param location [Ruby::Prism::Location]
90
+ # @return [Ruby::Prism::Node]
91
+ def make_literal(value, location: nil)
92
+ case value
93
+ when Integer, Float, String, Symbol, Range, Regexp, nil, true, false, Class, Module
94
+ make_node(value.inspect, location:)
95
+ when Array
96
+ make_array(value, location:)
97
+ when Hash
98
+ make_hash(value, location:)
99
+ else
100
+ raise ArgumentError, "Can't make AST node for #{value.inspect}"
101
+ end
102
+ end
103
+
104
+ # Makes a StatementsNode containing the given statement.
105
+ #
106
+ # @param statements [Array<Ruby::Prism::Node>]
107
+ # @param location [Ruby::Prism::Location]
108
+ # @return [Ruby::Prism::Node]
109
+ def make_statements(statements, location: nil)
110
+ raise ArgumentError, "Not an array" if !statements.is_a?(Array)
111
+ raise ArgumentError, "Empty array given" if statements.size == 0
112
+ raise ArgumentError, "Invalid array given" if statements.any? { !it.is_a?(Ruby::Prism::Node) }
113
+
114
+ n = make_node('(1)', location:)
115
+ Steadfast.rewrite(n.body, n.body => { body: statements })
116
+ end
117
+
118
+ # Makes a constant node.
119
+ #
120
+ # @param name [String, Symbol]
121
+ # @param location [Ruby::Prism::Location]
122
+ # @return [Ruby::Prism::Node]
123
+ def make_constant(name, location: nil)
124
+ raise SyntaxError, 'Invalid identifier name' if name !~ /^[A-Z][A-Za-z_\d]*$/
125
+
126
+ make_node(name.to_s, location:)
127
+ end
128
+
129
+ private
130
+
131
+ # Returns the source location information (filename, line) for the given
132
+ # location.
133
+ #
134
+ # @param location [Ruby::Prism::Node, Ruby::Prism::Location]
135
+ # @return [Array] [filename, lineno]
136
+ def __make_get_source_location__(location)
137
+ filename = location.send(:source).__filename__ || raise('No filename set')
138
+ lineno = location.start_line
139
+ [filename, lineno]
140
+ end
141
+ end
142
+ end
@@ -0,0 +1,173 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Steadfast
4
+ # Quote implements the quote / unquote code quoting tools. The quote/unquote
5
+ # pair of coding tools permits creation of code templates.
6
+ module Quote
7
+ extend self
8
+
9
+ # Quotes the code in the given block, interpolating all unquote expressions.
10
+ # Returns the resulting AST. The unquote call is used to perform a
11
+ # computation at the time of building the AST. The result of unquote is an
12
+ # object that can be literalized (See #unquote). A call to unquote can also
13
+ # be used to inject an AST into the code. The quote method takes a binding,
14
+ # which is then used for any unquote computations.
15
+ #
16
+ # Example:
17
+ #
18
+ # i = 4
19
+ # ast = Steadfast.quote(binding) { ->(x) { unquote(i) + x } }
20
+ # l = Steadfast.eval_ast(ast) #=> ->(x) { 4 + x }
21
+ # l + 3 #=> 7
22
+ #
23
+ # A call to unquote can also be in the form of a block, e.g. if the
24
+ # computation consists of more than one statement. Nested quote calls can be
25
+ # made in order to compute an AST that can be injected into the quoted code.
26
+ # Alternating calls to unquote and quote can be nested arbitrarily.
27
+ #
28
+ # Example:
29
+ #
30
+ # i = 4
31
+ # ast = Steadfast.quote(binding) {
32
+ # x = unquote {
33
+ # j = i + 3
34
+ # quote { (x + unquote(j)) }
35
+ # }
36
+ # }
37
+ #
38
+ # Nested calls to unquote and quote should be unqualified (i.e. quote
39
+ # instead of Steadfast.quote). In addition, nested calls to quote should not
40
+ # provide a binding, just a block. They will automatically inherit the
41
+ # binding of the outermost quote.
42
+ #
43
+ # @param binding [Binding, nil] binding for unquote computation
44
+ # @return [Ruby::Prism::Node] quoted code
45
+ def quote(binding, &block)
46
+ raise Steadfast::Error, "No block given" if !block
47
+
48
+ ast = Steadfast.to_ast(block)
49
+ statements = __quote_select_statements_node__(statements)
50
+ raise Steadfast::Error, "Block can't be quoted" if !ast
51
+
52
+ quoted = Steadfast.rewrite(ast) { |n|
53
+ next n if !(n in Ruby::Prism::CallNode(receiver: nil, name: :unquote))
54
+
55
+ __unquote_evaluate__(n, binding)
56
+ }
57
+
58
+ __quote_normalize_return_value__(quoted)
59
+ end
60
+
61
+ # Returns the AST for the given literal value. The value should be one of
62
+ # the builtin types: true, false, nil, String, Float, Integer, Symbol,
63
+ # Array, Hash, Module, Class, or Ruby::Prism::Node (an AST). If value is an
64
+ # AST, unquote will return it. All other values are converted to an AST
65
+ # representation as literal values.
66
+ #
67
+ # If a node location is provided, the resulting AST will use that location
68
+ # information (filename + lineno), for purposes of providing correct
69
+ # backtraces.
70
+ #
71
+ # The return value is an AST. If the unquote computation's result is an
72
+ # array of AST nodes, it is returned wrapped in a StatementsNode.
73
+ #
74
+ # @param value [expr] expression to evaluate and inject into surrounding code
75
+ # @return [Ruby::Prism::Node]
76
+ def unquote(value, location = nil)
77
+ __unquote_convert_value__(value, location)
78
+ end
79
+
80
+ private
81
+
82
+ # Selects the StatementsNode out of the given AST node. If the
83
+ # statementsNode contains a single statement, returns that statement.
84
+ # Otherwise, returns the StatementsNode.
85
+ #
86
+ # @param node [Ruby::Prism::Node]
87
+ # @return [Ruby::Prism::Node]
88
+ def __quote_normalize_return_value__(node)
89
+ statements = __quote_select_statements_node__(node)
90
+ return node if !statements
91
+
92
+ (statements.body.size == 1) ? statements.body[0] : statements
93
+ end
94
+
95
+ # Selects the outermost StatementsNode for the given AST, according to the
96
+ # node type.
97
+ #
98
+ # @param node [Ruby::Prism::Node]
99
+ # @return [Ruby::Prism::StatementsNode, nil]
100
+ def __quote_select_statements_node__(node)
101
+ case node
102
+ when Ruby::Prism::StatementsNode
103
+ node
104
+ when Ruby::Prism::BlockNode
105
+ node.body
106
+ when Ruby::Prism::CallNode
107
+ node.block.body
108
+ else
109
+ nil
110
+ end
111
+ end
112
+
113
+ # Evaluates the given AST node by sourcifying it and eval'ing the resulting
114
+ # code with the given binding. The resulting value is rendered into an AST
115
+ # and returned.
116
+ #
117
+ # @param node [Ruby::Prism::Node]
118
+ # @param binding [Binding]
119
+ # @return [Ruby::Prism::Node]
120
+ def __unquote_evaluate__(node, binding)
121
+ if node.arguments && (node.arguments.arguments.size == 1) && !node.block
122
+ arg = __unquote_rewrite_nested_quote__(node.arguments.arguments[0], binding)
123
+ v = Steadfast.eval_ast(arg, nil, binding)
124
+ __unquote_convert_value__(v, node)
125
+ elsif node.block && !node.arguments
126
+ ast = __unquote_rewrite_nested_quote__(node.block.body, binding)
127
+ v = Steadfast.eval_ast(node.block.body, nil, binding)
128
+ __unquote_convert_value__(v, node)
129
+ else
130
+ raise ArgumentError, "Invalid unquote arguments"
131
+ end
132
+ end
133
+
134
+ # Rewrites nested calls to quote inside an unquote block or expression.
135
+ #
136
+ # @param node [Ruby::Prism::Node]
137
+ # @param binding [Binding]
138
+ # @return [Ruby::Prism::Node]
139
+ def __unquote_rewrite_nested_quote__(node, binding)
140
+ Steadfast.rewrite(node) { |n2|
141
+ next n2 if !(n2 in Ruby::Prism::CallNode(receiver: nil, name: :quote))
142
+
143
+ raise ArgumentError, "Invalid arguments in call to quote" if n2.arguments
144
+ raise ArgumentError, "Missing block in call to quote" if !n2.block
145
+
146
+ n3 = Steadfast.make_node("Steadfast::Quote.quote(binding) do\nnil \nend", location: n2)
147
+ Steadfast.rewrite(n3, n3.block.body => n2.block.body)
148
+ }
149
+ end
150
+
151
+ # Returns an AST for the given value. This method converts the result of the
152
+ # unquote computation into an AST.
153
+ #
154
+ # @param value [any]
155
+ # @param location [Ruby::Prism::Location]
156
+ # @return [Ruby::Prism::Node]
157
+ def __unquote_convert_value__(value, location)
158
+ case value
159
+ when Integer, Float, String, Symbol, Range, Regexp, nil, true, false, Hash, Class, Module
160
+ Steadfast.make_literal(value, location:)
161
+ when Array
162
+ if value.first.is_a?(Ruby::Prism::Node)
163
+ return Steadfast.make_statements(value)
164
+ end
165
+ Steadfast.make_literal(value, location:)
166
+ when Ruby::Prism::Node
167
+ value
168
+ else
169
+ raise Steadfast::Error, "Don't know how to unquote #{value.inspect}"
170
+ end
171
+ end
172
+ end
173
+ end
@@ -13,6 +13,8 @@ module Steadfast
13
13
  # @replacements [Hash] replacements
14
14
  # @return [Ruby::Prism::Node]
15
15
  def self.rewrite(ast, **replacements, &rewrite_block)
16
+ raise ArgumentError, "Not an AST" if !ast.is_a?(Ruby::Prism::Node)
17
+
16
18
  rewrite_block ||= ->(n) do
17
19
  if (v = replacements[n]) && v.is_a?(Hash)
18
20
  n.copy(**v)
@@ -17,7 +17,7 @@ module Steadfast
17
17
  def set(path1, line1, path2, line2)
18
18
  (@map ||= {})["#{path1}:#{line1}"] ||= "#{path2}:#{line2}"
19
19
  end
20
-
20
+
21
21
  # Translates entries in the given backtrace according to the global source
22
22
  # map.
23
23
  #
@@ -36,7 +36,7 @@ module Steadfast
36
36
  end
37
37
 
38
38
  private
39
-
39
+
40
40
  # Returns a mapped location for the given location entry.
41
41
  #
42
42
  # @param loc [String] location string of the form file:line
@@ -44,9 +44,9 @@ module Steadfast
44
44
  def find_sourcemap_entry(loc)
45
45
  loc = @map[loc]
46
46
  return nil if !loc
47
-
47
+
48
48
  (loc =~ /^\(steadfast-[0-9a-f]+\)\:\d+$/) ? find_sourcemap_entry(loc) : loc
49
- end
49
+ end
50
50
  end
51
51
  end
52
52
  end
@@ -17,8 +17,8 @@ module Steadfast
17
17
  VISIT_PLANS = {
18
18
  alias_global_variable: [:keyword_loc, :whitespace, :new_name, :whitespace, :old_name],
19
19
  alias_method: [:keyword_loc, :whitespace, :new_name, :whitespace, :old_name],
20
+ alternation_pattern: [:left, :whitespace, :operator_loc, :whitespace, :right],
20
21
  and: [:left, :whitespace, :operator_loc, :whitespace, :right],
21
- assoc: [:key, :whitespace, :operator_loc, :whitespace, :value],
22
22
  assoc_splat: [:operator_loc, :value],
23
23
  back_reference_read: :emit_verbatim,
24
24
  block: [:opening_loc, :parameters, :newline, :body, :newline, :closing_loc],
@@ -51,11 +51,10 @@ module Steadfast
51
51
  :statements, :newline, :end_keyword_loc],
52
52
  forwarding_arguments: :emit_verbatim,
53
53
  forwarding_parameter: :emit_verbatim,
54
- forwarding_super: :emit_verbatim,
54
+ forwarding_super: [:keyword_loc, :block],
55
55
  global_variable_read: :emit_verbatim,
56
56
  global_variable_target: :emit_verbatim,
57
57
  global_variable_write: [:name_loc, :operator_loc, :value],
58
- imaginary: :emit_verbatim,
59
58
  implicit: :nop,
60
59
  implicit_rest: :nop,
61
60
  in: [:in_loc, :whitespace, :pattern, :whitespace, :then_loc],
@@ -89,7 +88,7 @@ module Steadfast
89
88
  optional_keyword_parameter: [:name_loc, :whitespace, :value],
90
89
  or: [:left, :whitespace, :operator_loc, :whitespace, :right],
91
90
  parentheses: [:opening_loc, :body, :closing_loc],
92
- program: :emit_verbatim,
91
+ program: [:statements],
93
92
  pinned_expression: [:operator_loc, :lparen_loc, :expression, :rparen_loc],
94
93
  pinned_variable: [:operator_loc, :variable],
95
94
  rational: :emit_verbatim,
@@ -174,6 +173,12 @@ module Steadfast
174
173
  visit_comma_separated_nodes(node.arguments[subscript])
175
174
  end
176
175
 
176
+ def visit_assoc_node(node)
177
+ emit_code(node.key)
178
+ node.operator_loc ? emit(' => ') : emit_whitespace
179
+ emit_code(node.value)
180
+ end
181
+
177
182
  def visit_begin_node(node)
178
183
  emit_code(node.begin_keyword_loc)
179
184
  emit_newline
@@ -211,8 +216,8 @@ module Steadfast
211
216
  if (ml = node.message_loc)
212
217
  ol = node.opening_loc
213
218
  emit_message_loc = !ol || (ol.start_line != ml.start_line) || (ol.start_column != ml.start_column)
214
- emit_whitespace if node.name =~ /^\+|\-|\*|\/|\&|\|\*\*|\&\&|\|\||\%$/
215
- emit_code(node.message_loc) if emit_message_loc
219
+ emit_whitespace if node.name =~ /^\+|\-|\*|\/|\&|\|\*\*|\&\&|\|\||\%|={2,3}$/
220
+ emit_code(node.message_loc, inhibit_new_line: true) if emit_message_loc
216
221
  end
217
222
  emit_code(node.opening_loc)
218
223
  emit_whitespace if !node.opening_loc && node.arguments
@@ -355,6 +360,11 @@ module Steadfast
355
360
  emit_code(node.subsequent)
356
361
  end
357
362
 
363
+ def visit_imaginary_node(node)
364
+ emit_code(node.numeric)
365
+ emit('i')
366
+ end
367
+
358
368
  def visit_interpolated_symbol_node(node)
359
369
  heredoc = node.opening_loc && node.opening_loc.slice =~ /\<\</
360
370
  emit_code(node.opening_loc)
@@ -667,6 +677,16 @@ module Steadfast
667
677
  # @param node [Ruby::Prism::Node]
668
678
  # @return [void]
669
679
  def emit_verbatim(node)
680
+ if node.child_nodes.size > 0
681
+ puts
682
+ puts '*' * 40
683
+ pp node
684
+ puts
685
+ pp node.child_nodes
686
+ puts
687
+ puts caller.join("\n")
688
+ exit!
689
+ end
670
690
  emit_code(node.location)
671
691
  end
672
692
 
@@ -674,11 +694,11 @@ module Steadfast
674
694
  #
675
695
  # @param loc [Ruby::Prism::Location, Ruby::Prism::Node, nil]
676
696
  # @return [void]
677
- def emit_code(loc)
697
+ def emit_code(loc, inhibit_new_line: false)
678
698
  return if !loc
679
699
  return visit(loc) if loc.is_a?(Ruby::Prism::Node)
680
700
 
681
- record_loc_source_mapping(loc) if @sourcemap
701
+ record_loc_source_mapping(loc, inhibit_new_line:) if @sourcemap
682
702
  emit(loc.slice.chomp)
683
703
  end
684
704
 
@@ -689,7 +709,8 @@ module Steadfast
689
709
  #
690
710
  # @param loc [Ruby::Prism::Location] code location
691
711
  # @return [void]
692
- def record_loc_source_mapping(loc)
712
+ def record_loc_source_mapping(loc, inhibit_new_line:)
713
+ last_loc = loc
693
714
  source = loc.send(:source)
694
715
  last_source = @last_loc&.send(:source)
695
716
  different_source = source.__filename__ && source != last_source
@@ -698,7 +719,7 @@ module Steadfast
698
719
  return if !changed
699
720
 
700
721
  if (filename = source.__filename__) && (filename || last_source.__filename__)
701
- emit_newline if different_source && last_source
722
+ emit_newline if !inhibit_new_line && different_source && last_source
702
723
  Steadfast::SourceMapping.set(
703
724
  @filename, @line, filename, loc.start_line
704
725
  )
@@ -1,4 +1,4 @@
1
1
  module Steadfast
2
2
  # Steadfast version
3
- VERSION = '0.3.0'
3
+ VERSION = '0.5.0'
4
4
  end
data/lib/steadfast.rb CHANGED
@@ -1,9 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'securerandom'
4
+
3
5
  require 'steadfast/source_mapping'
4
6
  require 'steadfast/sourcifier'
5
7
  require 'steadfast/visitor'
6
8
  require 'steadfast/rewriter'
9
+ require 'steadfast/make'
10
+ require 'steadfast/quote'
7
11
 
8
12
  # Tell Ruby to keep script lines in memory, so calling Proc#syntax_tree or
9
13
  # Method#syntax_tree will work.
@@ -26,6 +30,9 @@ module Steadfast
26
30
  end
27
31
 
28
32
  class << self
33
+ include Steadfast::Make
34
+ include Steadfast::Quote
35
+
29
36
  # Returns an AST for the given object.
30
37
  #
31
38
  # @param obj [Proc, Method, UnboundedMethod, Ruby::Prism::Node]
@@ -33,7 +40,11 @@ module Steadfast
33
40
  def to_ast(obj)
34
41
  case obj
35
42
  when Proc, Method, UnboundMethod
36
- obj.syntax_tree.tap { set_source_filename(it, obj) }
43
+ ast = obj.syntax_tree
44
+ raise Steadfast::Error, "AST not found for given object" if !ast
45
+
46
+ set_source_filename(ast, obj)
47
+ ast
37
48
  when Ruby::Prism::Node
38
49
  obj
39
50
  else
@@ -76,7 +87,7 @@ module Steadfast
76
87
  # However, while `eval` respects a starting lineno set to 0, Prism does
77
88
  # not, which can lead to off-by-one line nos in exception backtraces for
78
89
  # synthetic ASTs.
79
- #
90
+ #
80
91
  # Note that when source_location is not nil, we do decrement the start
81
92
  # lineno. Hopefully some day this wart will be removed from Ruby.G
82
93
  source_location = ["(steadfast-#{SecureRandom.hex(4)})", 1]
@@ -88,22 +99,36 @@ module Steadfast
88
99
  end
89
100
  src = to_source(ast, source_location:, sourcemap: true, frozen_string_literal: true)
90
101
  if eval_receiver
91
- eval_receiver.instance_eval(src)
102
+ eval_receiver.instance_eval(src, source_location[0], source_location[1])
92
103
  else
93
104
  eval(src, eval_binding || binding, source_location[0], source_location[1])
94
105
  end
95
106
  end
96
107
 
108
+ # Visits the given AST, passing each node in the AST to the given block.
109
+ #
110
+ # @param ast [Ruby::Prism::Node]
111
+ # @return [void]
97
112
  def walk(ast, &)
98
113
  ast.accept(Visitor.new(&))
99
114
  ast
100
115
  end
101
116
 
117
+ # Visits the given AST, passing each node in the AST to the given block.
118
+ # Returns the first node for which the block returns true.
119
+ #
120
+ # @param ast [Ruby::Prism::Node]
121
+ # @return [Ruby::Prism::Node, nil]
102
122
  def find(ast, &block)
103
123
  ast.accept(Visitor.new { return it if block.(it) })
104
124
  nil
105
125
  end
106
126
 
127
+ # Visits the given AST, passing each node in the AST to the given block.
128
+ # Returns all nodes for which the block returns true.
129
+ #
130
+ # @param ast [Ruby::Prism::Node]
131
+ # @return [Array<Ruby::Prism::Node>]
107
132
  def find_all(ast, &block)
108
133
  nodes = []
109
134
  ast.accept(Visitor.new { nodes << it if block.(it) })
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: steadfast
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sharon Rosner
@@ -9,22 +9,6 @@ bindir: bin
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
- - !ruby/object:Gem::Dependency
13
- name: debug_inspector
14
- requirement: !ruby/object:Gem::Requirement
15
- requirements:
16
- -
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
- - ">="
26
- - !ruby/object:Gem::Version
27
- version: "0"
28
12
  - !ruby/object:Gem::Dependency
29
13
  name: minitest
30
14
  requirement: !ruby/object:Gem::Requirement
@@ -82,6 +66,8 @@ files:
82
66
  - CHANGELOG.md
83
67
  - README.md
84
68
  - lib/steadfast.rb
69
+ - lib/steadfast/make.rb
70
+ - lib/steadfast/quote.rb
85
71
  - lib/steadfast/rewriter.rb
86
72
  - lib/steadfast/source_mapping.rb
87
73
  - lib/steadfast/sourcifier.rb