棱镜解析器的 ruby 编码

问题描述 投票:0回答:1

我正在尝试检查该程序的 ruby prism AST (

input.rb
):

x = 8 + 55 * 14
# this is a comment ...
puts ">> the value is #{x}"

我的编码似乎错误,因为当我尝试这个时:

require "prism"
puts Prism.dump_file('input.rb')

我收到以下乱码:

$ ruby main.rb
PRISMUTF-8(D�wC�C`
                 RR
--�...0>>�@^@AB
               (
ruby
1个回答
0
投票

我想你想要的是打电话给

Prism.parse_file
而不是
dump_file

据我所知,

dump_file
的结果是内部专有表示,不用于打印。
parse_file
将为您提供语法树,我认为这就是您正在寻找的:

>> Prism.parse_file('input.rb')

#<Prism::ParseResult:0x00007f01d00bbd18
 @comments=
  [#<Prism::InlineComment @location=#<Prism::Location @start_offset=16 @length=23 start_line=2>>],
 @data_loc=nil,
 @errors=[],
 @magic_comments=[],
 @source=
  #<Prism::Source:0x00007f01d014fec8
   @offsets=[0, 16, 40, 68],
   @source="x = 8 + 55 * 14\n# this is a comment ...\nputs \">> the value is \#{x}\"\n",
   @start_line=1>,
 @value=
  @ ProgramNode (location: (1,0)-(3,27))
  ├── locals: [:x]
  └── statements:
      @ StatementsNode (location: (1,0)-(3,27))
      └── body: (length: 2)
          ├── @ LocalVariableWriteNode (location: (1,0)-(1,15))
          │   ├── name: :x
          │   ├── depth: 0
          │   ├── name_loc: (1,0)-(1,1) = "x"
          │   ├── value:
          │   │   @ CallNode (location: (1,4)-(1,15))
          │   │   ├── flags: ∅
          │   │   ├── receiver:
          │   │   │   @ IntegerNode (location: (1,4)-(1,5))
          │   │   │   └── flags: decimal
          │   │   ├── call_operator_loc: ∅
          │   │   ├── name: :+
          │   │   ├── message_loc: (1,6)-(1,7) = "+"
          │   │   ├── opening_loc: ∅
          │   │   ├── arguments:
          │   │   │   @ ArgumentsNode (location: (1,8)-(1,15))
          │   │   │   ├── flags: ∅
          │   │   │   └── arguments: (length: 1)
          │   │   │       └── @ CallNode (location: (1,8)-(1,15))
          │   │   │           ├── flags: ∅

   ....
© www.soinside.com 2019 - 2024. All rights reserved.