将 Ruby AST 转换为语义上等价的 Ruby 源代码
Generate equivalent source for ASTs from parser.
The following constraints apply:
Notable Users:
(if you want your tool to be mentioned here please PR the addition with a TLDR of your use case).
While unparser is in the 0.x versions its public API can change any moment.
I recommend to use ~> 0.x.y style version constraints that should give the best mileage.
require 'parser/current'
require 'unparser'
ast = Unparser.parse('your(ruby(code))')
Unparser.unparse(ast) # => 'your(ruby(code))'To preserve the comments from the source:
require 'parser/current'
require 'unparser'
ast, comments = Unparser.parser.parse_with_comments(Unparser.buffer('your(ruby(code)) # with comments'))
Unparser.unparse(ast, comments: comments) # => 'your(ruby(code)) # with comments'Passing in manually constructed AST:
require 'parser/current'
require 'unparser'
module YourHelper
def s(type, *children)
Parser::AST::Node.new(type, children)
end
end
include YourHelper
node = s(:def,
:foo,
s(:args,
s(:arg, :x)
),
s(:send,
s(:lvar, :x),
:+,
s(:int, 3)
)
)
Unparser.unparse(node) # => "def foo(x)\n x + 3\nend"Note: DO NOT attempt to pass in nodes generated via AST::Sexp#s, these ones return
API incompatible AST::Node instances, unparser needs Parser::AST::Node instances.
Equivalent vs identical:
…ruby
"\x98\x76\xAB\xCD\x45\x32\xEF\x01\x01\x23\x45\x67\x89\xAB\xCD\xEF"
Original-AST:(str "\x98v\xAB\xCDE2\xEF\x01\x01#Eg\x89\xAB\xCD\xEF")
Generated-Source:
```ruby
"\x98v\xAB\xCDE2\xEF\x01\x01#Eg\x89\xAB\xCD\xEF"Generated-AST:
(str "\x98v\xAB\xCDE2\xEF\u0001\u0001#Eg\x89\xAB\xCD\xEF")Diff:
@@ -1,2 +1,2 @@
-(str "\x98v\xAB\xCDE2\xEF\x01\x01#Eg\x89\xAB\xCD\xEF")
+(str "\x98v\xAB\xCDE2\xEF\u0001\u0001#Eg\x89\xAB\xCD\xEF")Install the gem unparser via your prefered method.
Various people contributed to this repository. See Contributors.
For dependency reduction reasons unparser ships vendored (and reduced) versions of:
See LICENSE file.
暂无开放 Issues,或尚未同步最近议题。