Class: R3EXS::StringsExtractor

Inherits:
Prism::Visitor
  • Object
show all
Defined in:
lib/R3EXS/ast.rb

Overview

用来提取源码生成的 AST 中的字符串和符号

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(script, with_symbol) ⇒ StringsExtractor

初始化 StringsExtractor

Parameters:

  • script (String)

    Ruby 源码

  • with_symbol (Boolean)

    是否包含脚本中的符号



29
30
31
32
33
34
# File 'lib/R3EXS/ast.rb', line 29

def initialize(script, with_symbol)
  super()
  @strings = []
  @with_symbol = with_symbol
  @root_node = Prism.parse(script).value
end

Instance Attribute Details

#root_nodePrism::Node (readonly)

AST 根节点

Returns:

  • (Prism::Node)


21
22
23
# File 'lib/R3EXS/ast.rb', line 21

def root_node
  @root_node
end

#stringsArray<String> (readonly)

提取后存储的字符串数组

Returns:



11
12
13
# File 'lib/R3EXS/ast.rb', line 11

def strings
  @strings
end

#with_symbolBoolean (readonly)

是否包含脚本中的符号

Returns:

  • (Boolean)


16
17
18
# File 'lib/R3EXS/ast.rb', line 16

def with_symbol
  @with_symbol
end

Class Method Details

.extract(script, with_symbol) ⇒ Array<String>

提取 script 源码中的字符串

Parameters:

  • script (String)

    Ruby 源码

  • with_symbol (Boolean)

    是否包含脚本中的符号

Returns:



69
70
71
72
# File 'lib/R3EXS/ast.rb', line 69

def self.extract(script, with_symbol)
  extractor = new(script, with_symbol)
  extractor.extract
end

Instance Method Details

#extractArray<String>

提取 script 源码中的字符串

Returns:



59
60
61
62
# File 'lib/R3EXS/ast.rb', line 59

def extract
  visit(@root_node)
  @strings
end

#visit_string_node(node) ⇒ void

This method returns an undefined value.

处理类型为 StringNode 的节点

Parameters:

  • node (Prism::StringNode)

    AST 节点



41
42
43
44
# File 'lib/R3EXS/ast.rb', line 41

def visit_string_node(node)
  @strings << node.content
  super
end

#visit_symbol_node(node) ⇒ void

This method returns an undefined value.

处理类型为 SymbolNode 的节点

Parameters:

  • node (Prism::SymbolNode)

    AST 节点



51
52
53
54
# File 'lib/R3EXS/ast.rb', line 51

def visit_symbol_node(node)
  @strings << node.value if @with_symbol
  super
end