class RubyVM::AbstractSyntaxTree::Node
RubyVM::AbstractSyntaxTree::Node
的实例由 RubyVM::AbstractSyntaxTree
中的解析方法创建。
此类是 MRI 特有的。
公共实例方法
源代码
# File ast.rb, line 205 def all_tokens Primitive.ast_node_all_tokens end
返回输入脚本的所有 token,而无需考虑接收器节点。如果在调用解析方法时没有启用 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]], ...]
源代码
# File ast.rb, line 216 def children Primitive.ast_node_children end
返回此节点下的 AST 节点。每种类型的节点都有不同的子节点,具体取决于它是哪种类型的节点。
返回的数组可能包含其他节点或 nil
。
源代码
# File ast.rb, line 148 def first_column Primitive.ast_node_first_column end
此 AST 的文本在源代码中开始的列号。
源代码
# File ast.rb, line 140 def first_lineno Primitive.ast_node_first_lineno end
此 AST 的文本在源代码中开始的行号。
源代码
# File ast.rb, line 224 def inspect Primitive.ast_node_inspect end
返回关于此节点的调试信息的字符串。
源代码
# File ast.rb, line 164 def last_column Primitive.ast_node_last_column end
此 AST 的文本在源代码中结束的列号。
源代码
# File ast.rb, line 156 def last_lineno Primitive.ast_node_last_lineno end
此 AST 的文本在源代码中结束的行号。
源代码
# File ast.rb, line 280 def locations Primitive.ast_node_locations end
返回与 AST 节点关联的位置对象。返回的数组包含 RubyVM::AbstractSyntaxTree::Location
。
源代码
# File ast.rb, line 235 def node_id Primitive.ast_node_node_id end
返回内部 node_id
数字。请注意,这是一个用于 ruby 内部使用、调试和研究的 API。不要将其用于任何其他目的。不保证兼容性。
源代码
# File ast.rb, line 247 def script_lines Primitive.ast_node_script_lines end
将原始源代码作为行数组返回。
请注意,这是一个用于 ruby 内部使用、调试和研究的 API。不要将其用于任何其他目的。不保证兼容性。
源代码
# 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 文档可能会被删除。
源代码
# 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。如果在调用解析方法时没有启用 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
]
源代码
# File ast.rb, line 132 def type Primitive.ast_node_type end
以符号形式返回此节点的类型。
root = RubyVM::AbstractSyntaxTree.parse("x = 1 + 2") root.type # => :SCOPE lasgn = root.children[2] lasgn.type # => :LASGN call = lasgn.children[1] call.type # => :OPCALL