class RubyVM::AbstractSyntaxTree::Node
RubyVM::AbstractSyntaxTree::Node 实例由 RubyVM::AbstractSyntaxTree 中的 parse 方法创建。
此类是 MRI 特有的。
Public Instance Methods
Source
# File ast.rb, line 205 def all_tokens Primitive.ast_node_all_tokens end
返回输入脚本的所有 token,无论接收节点是什么。如果在调用 parse 方法时未启用 keep_tokens,则返回 nil。
root = RubyVM::AbstractSyntaxTree.parse("x = 1 + 2", keep_tokens: true) root.all_tokens # => [[0, :tIDENTIFIER, "x", [1, 0, 1, 1]], [1, :tSP, " ", [1, 1, 1, 2]], ...] root.children[-1].all_tokens # => [[0, :tIDENTIFIER, "x", [1, 0, 1, 1]], [1, :tSP, " ", [1, 1, 1, 2]], ...]
Source
# File ast.rb, line 216 def children Primitive.ast_node_children end
返回此节点下的 AST 节点。每种类型的节点都有不同的子节点,具体取决于它是哪种类型的节点。
返回的数组可能包含其他节点或 nil。
Source
# File ast.rb, line 148 def first_column Primitive.ast_node_first_column end
此 AST 文本开始处的源代码中的列号。
Source
# File ast.rb, line 140 def first_lineno Primitive.ast_node_first_lineno end
此 AST 文本开始处的源代码中的行号。
Source
# File ast.rb, line 224 def inspect Primitive.ast_node_inspect end
以字符串形式返回此节点的调试信息。
Source
# File ast.rb, line 164 def last_column Primitive.ast_node_last_column end
此 AST 文本结束处的源代码中的列号。
Source
# File ast.rb, line 156 def last_lineno Primitive.ast_node_last_lineno end
此 AST 文本结束处的源代码中的行号。
Source
# File ast.rb, line 280 def locations Primitive.ast_node_locations end
返回与 AST 节点关联的位置对象。返回的数组包含 RubyVM::AbstractSyntaxTree::Location。
Source
# File ast.rb, line 235 def node_id Primitive.ast_node_node_id end
返回内部 node_id 号。请注意,这是 ruby 内部使用、调试和研究的 API。请勿将其用于任何其他目的。不保证兼容性。
Source
# File ast.rb, line 247 def script_lines Primitive.ast_node_script_lines end
将原始源代码作为行数组返回。
请注意,这是 ruby 内部使用、调试和研究的 API。请勿将其用于任何其他目的。不保证兼容性。
Source
# File ast.rb, line 263 def source lines = script_lines if lines lines = lines[first_lineno - 1 .. last_lineno - 1] lines[-1] = lines[-1].byteslice(0...last_column) lines[0] = lines[0].byteslice(first_column..-1) lines.join else nil end end
返回与此 AST 对应的代码片段。
请注意,这是 ruby 内部使用、调试和研究的 API。请勿将其用于任何其他目的。不保证兼容性。
另请注意,此 API 可能返回不完整的代码片段,这些代码片段无法解析;例如,表达式后面的 here document 可能会被删除。
Source
# File ast.rb, line 184 def tokens return nil unless all_tokens all_tokens.each_with_object([]) do |token, a| loc = token.last if ([first_lineno, first_column] <=> [loc[0], loc[1]]) <= 0 && ([last_lineno, last_column] <=> [loc[2], loc[3]]) >= 0 a << token end end end
返回与节点位置对应的 token。如果在调用 parse 方法时未启用 keep_tokens,则返回 nil。
root = RubyVM::AbstractSyntaxTree.parse("x = 1 + 2", keep_tokens: true) root.tokens # => [[0, :tIDENTIFIER, "x", [1, 0, 1, 1]], [1, :tSP, " ", [1, 1, 1, 2]], ...] root.tokens.map{_1[2]}.join # => "x = 1 + 2"
Token 是一个数组,包含
-
id
-
token 类型
-
源代码文本
-
位置 [
first_lineno,first_column,last_lineno,last_column]
Source
# File ast.rb, line 132 def type Primitive.ast_node_type end
以 symbol 形式返回此节点的类型。
root = RubyVM::AbstractSyntaxTree.parse("x = 1 + 2") root.type # => :SCOPE lasgn = root.children[2] lasgn.type # => :LASGN call = lasgn.children[1] call.type # => :OPCALL