Ruby 4.1 リファレンスマニュアル

class Prism::Node

[edit]

要約

構文解析の結果得られる構文木の各ノードを表す抽象基底クラスです。 Prism?.parse などが返す構文木は、このクラスのサブクラス (150 種類以上)のインスタンスで構成されます。Prism::Node 自身のインスタンスが生成されることはありません。

個々のノードクラス(Prism::ProgramNode・Prism::CallNode など)に固有のフィールド(子ノードや値を取得するアクセサ)は、このページ末尾の ノードクラスの一覧 に名前だけを載せ、個別のエントリは作りません。このページで扱うのは、すべてのノードクラスに共通する API です。個々のノードクラスの詳細は公式ドキュメントを参照してください。

例
require "prism"

node = Prism.parse("1 + 2").value
p node.type           # => :program_node
p node.class          # => Prism::ProgramNode
p node.location.slice # => "1 + 2"

call = node.statements.body[0]
p call.type                    # => :call_node
p call.child_nodes.size        # => 3
p call.compact_child_nodes.size # => 2

[SEE_ALSO] Prism::ParseResult, Prism::Location

目次

特異メソッド
インスタンスメソッド

特異メソッド

fields -> [Prism::Reflection::Field]Ruby 3.4 から[permalink][rdoc][edit]

このノードクラスが持つフィールド(子ノードや属性)を表す Prism::Reflection::Field の配列を返します。構文木の各ノード・各フィールドを再帰的に処理するツールを書くときのリフレクション用途に使えます。

Prism::Node 自身に対して呼び出すと NoMethodError が発生します。サブクラスに対して呼び出してください。

type -> SymbolRuby 3.4 から[permalink][rdoc][edit]

Prism::Node#type のクラスメソッド版です。インスタンスを作らずにノードクラス自体からノードの種類を表すシンボルを得られます。

インスタンスメソッド

self === other -> boolRuby 3.4 から[permalink][rdoc][edit]

other が自身と同じクラスで、位置情報を除く各フィールドの内容が (再帰的に === で)一致する場合に true を返します。位置情報は「存在するかどうか」だけが比較され、実際の値(オフセットなど)は比較されません。

[PARAM] other:
比較対象のオブジェクトを指定します。
例
require "prism"

a = Prism.parse("1 + 2").value
b = Prism.parse("1 + 2").value
p a === b # => true
accept(visitor) -> objectRuby 3.4 から[permalink][rdoc][edit]

Visitor パターンの受け入れメソッドです。ノードの種類に応じた visitor.visit_xxx を呼び出し、その戻り値を返します。

[PARAM] visitor:
Prism::Visitor (またはそのサブクラス)のインスタンスを指定します。

自身を含めて構文木を幅優先で探索し、ブロックが真を返した最初のノードを返します。見つからない場合は nil を返します。

例
require "prism"

node = Prism.parse("1 + 2").value
call = node.breadth_first_search { |n| n.is_a?(Prism::CallNode) }
p call&.type # => :call_node

[SEE_ALSO] Prism::Node#find

breadth_first_search_all {|node| ... } -> [Prism::Node]Ruby 4.1 から[permalink][rdoc][edit]

自身を含めて構文木を幅優先で探索し、ブロックが真を返したノードをすべて集めた配列を返します。

[SEE_ALSO] Prism::Node#find_all

cached_end_code_units_column(cache) -> IntegerRuby 3.4 から[permalink][rdoc][edit]

キャッシュを使って、終了位置の、行頭からのコード単位での桁位置を返します。

[PARAM] cache:
Prism::Result#code_units_cache で得たキャッシュを指定します。
cached_end_code_units_offset(cache) -> IntegerRuby 3.4 から[permalink][rdoc][edit]

キャッシュを使って、終了位置の、指定エンコーディングのコード単位でのオフセットを返します。

[PARAM] cache:
Prism::Result#code_units_cache で得たキャッシュを指定します。
cached_start_code_units_column(cache) -> IntegerRuby 3.4 から[permalink][rdoc][edit]

キャッシュを使って、開始位置の、行頭からのコード単位での桁位置を返します。

[PARAM] cache:
Prism::Result#code_units_cache で得たキャッシュを指定します。
cached_start_code_units_offset(cache) -> IntegerRuby 3.4 から[permalink][rdoc][edit]

キャッシュを使って、開始位置の、指定エンコーディングのコード単位でのオフセットを返します。

[PARAM] cache:
Prism::Result#code_units_cache で得たキャッシュを指定します。
child_nodes -> [Prism::Node | nil]Ruby 3.4 から[permalink][rdoc][edit]

子ノードの配列を返します。存在しないオプショナルな子ノードの位置には nil が入ります。

[SEE_ALSO] Prism::Node#compact_child_nodes

comment_targets -> [Prism::Node | Prism::Location]Ruby 3.4 から[permalink][rdoc][edit]

コメントの関連付け先になりうる子ノードや位置情報の配列を返します。 Prism::ParseResult#attach_comments! が内部で使用します。

comments -> [Prism::Comment]Ruby 3.4 から[permalink][rdoc][edit]

このノードに関連付けられた前後両方のコメントの配列を返します。 location.comments と同じです。

compact_child_nodes -> [Prism::Node]Ruby 3.4 から[permalink][rdoc][edit]

子ノードの配列を返します。Prism::Node#child_nodes と異なり、存在しないオプショナルな子ノードは含まれません(nil を含みません)。

copy(**params) -> Prism::NodeRuby 3.3 から[permalink][rdoc][edit]

自身と同じクラスの新しいノードを、指定したフィールドだけを差し替えて複製します。渡せるキーワードはノードクラスごとのフィールド名で、指定しなかったフィールドは自身の値を引き継ぎます。

例
require "prism"

call = Prism.parse("1 + 2").value.statements.body[0]
copied = call.copy
p copied.class        # => Prism::CallNode
p copied.equal?(call) # => false
deconstruct -> [Prism::Node | nil]Ruby 3.4 から[permalink][rdoc][edit]

Prism::Node#child_nodes のエイリアスです。パターンマッチの配列パターン(case node; in [a, b])で使われます。

deconstruct_keys(keys) -> HashRuby 3.3 から[permalink][rdoc][edit]

パターンマッチのハッシュパターン(case node; in {value:})で使われます。ノードの各フィールドをキーに持つハッシュを返します。

[PARAM] keys:
取り出したいキーの配列。すべて取り出す場合は nil を指定します。
deprecated(*replacements) -> ()Ruby 3.4 から[permalink][rdoc][edit]

このノードの、別のフィールドに置き換えられた古いメソッドが呼び出されたときに、非推奨であることを示す警告を出力します。

生成された各ノードクラスの、名前が変更されたフィールドの読み出しメソッドが内部で使用するためのメソッドです。呼び出し元のメソッド名と、replacements に指定した代替メソッド名を含む警告メッセージを、:deprecated カテゴリの警告として(Kernel の warn を使って)出力します。

[PARAM] replacements:
代わりに使うべきメソッド名を文字列で 1 つ以上指定します。
each_child_node -> EnumeratorRuby 4.0.1 から[permalink][rdoc][edit]
each_child_node {|node| ... } -> ()

ブロックを指定した場合、Prism::Node#compact_child_nodes の各要素を順に yield します。ブロックを指定しない場合は Enumerator を返します。

end_character_column -> IntegerRuby 3.4 から[permalink][rdoc][edit]

終了位置の、行頭からの文字単位の桁位置を返します。 location.end_character_column と同じです。

end_character_offset -> IntegerRuby 3.4 から[permalink][rdoc][edit]

終了位置の、ソースコード先頭からの文字単位のオフセットを返します。 location.end_character_offset と同じです。

end_column -> IntegerRuby 3.4 から[permalink][rdoc][edit]

終了位置の、行頭からのバイト単位の桁位置を返します。 location.end_column と同じです。

end_line -> IntegerRuby 3.4 から[permalink][rdoc][edit]

終了位置の行番号を返します。location.end_line と同じです。

end_offset -> IntegerRuby 3.4 から[permalink][rdoc][edit]

終了位置のバイトオフセットを返します。location.end_offset と同じです。

find {|node| ... } -> Prism::Node | nilRuby 4.1 から[permalink][rdoc][edit]

Prism::Node#breadth_first_search の別名です。

find_all {|node| ... } -> [Prism::Node]Ruby 4.1 から[permalink][rdoc][edit]

Prism::Node#breadth_first_search_all の別名です。

ノードクラスの一覧

prism の各ノードクラス(Prism::Node のサブクラス)と、そのフィールド(子ノードや値を取得するアクセサ)の名前の一覧です。 prism の config.yml(3.3= prism 0.19.0・3.4= 1.2.0・4.0= 1.7.0・4.1= 1.9.0)から機械的に生成しています。フィールドの構成が版によって異なるノードは、版ごとに行を分けています。各フィールドの意味は公式ドキュメントを参照してください。

ノードクラスフィールド
AliasGlobalVariableNodenew_name, old_name, keyword_loc
AliasMethodNodenew_name, old_name, keyword_loc
AlternationPatternNodeleft, right, operator_loc
AndNodeleft, right, operator_loc
ArgumentsNodearguments
ArrayNodeelements, opening_loc, closing_loc
ArrayPatternNodeconstant, requireds, rest, posts, opening_loc, closing_loc
AssocNodekey, value, operator_loc
AssocSplatNodevalue, operator_loc
BackReferenceReadNodename
BeginNodebegin_keyword_loc, statements, rescue_clause, else_clause, ensure_clause, end_keyword_loc
BlockArgumentNodeexpression, operator_loc
BlockLocalVariableNodename
BlockNodelocals, parameters, body, opening_loc, closing_loc
BlockParameterNodename, name_loc, operator_loc
BlockParametersNodeparameters, locals, opening_loc, closing_loc
BreakNodearguments, keyword_loc
CallAndWriteNodereceiver, call_operator_loc, message_loc, read_name, write_name, operator_loc, value
CallNodereceiver, call_operator_loc, name, message_loc, opening_loc, arguments, closing_loc, equal_loc, block
CallOperatorWriteNodereceiver, call_operator_loc, message_loc, read_name, write_name, binary_operator, binary_operator_loc, value
CallOrWriteNodereceiver, call_operator_loc, message_loc, read_name, write_name, operator_loc, value
CallTargetNodereceiver, call_operator_loc, name, message_loc
CapturePatternNodevalue, target, operator_loc
CaseMatchNodepredicate, conditions, else_clause, case_keyword_loc, end_keyword_loc
CaseNodepredicate, conditions, else_clause, case_keyword_loc, end_keyword_loc
ClassNodelocals, class_keyword_loc, constant_path, inheritance_operator_loc, superclass, body, end_keyword_loc, name
ClassVariableAndWriteNodename, name_loc, operator_loc, value
ClassVariableOperatorWriteNodename, name_loc, binary_operator_loc, value, binary_operator
ClassVariableOrWriteNodename, name_loc, operator_loc, value
ClassVariableReadNodename
ClassVariableTargetNodename
ClassVariableWriteNodename, name_loc, value, operator_loc
ConstantAndWriteNodename, name_loc, operator_loc, value
ConstantOperatorWriteNodename, name_loc, binary_operator_loc, value, binary_operator
ConstantOrWriteNodename, name_loc, operator_loc, value
ConstantPathAndWriteNodetarget, operator_loc, value
ConstantPathNodeparent, name, delimiter_loc, name_loc
ConstantPathOperatorWriteNodetarget, binary_operator_loc, value, binary_operator
ConstantPathOrWriteNodetarget, operator_loc, value
ConstantPathTargetNodeparent, name, delimiter_loc, name_loc
ConstantPathWriteNodetarget, operator_loc, value
ConstantReadNodename
ConstantTargetNodename
ConstantWriteNodename, name_loc, value, operator_loc
DefNodename, name_loc, receiver, parameters, body, locals, def_keyword_loc, operator_loc, lparen_loc, rparen_loc, equal_loc, end_keyword_loc
DefinedNodelparen_loc, value, rparen_loc, keyword_loc
ElseNodeelse_keyword_loc, statements, end_keyword_loc
EmbeddedStatementsNodeopening_loc, statements, closing_loc
EmbeddedVariableNodeoperator_loc, variable
EnsureNodeensure_keyword_loc, statements, end_keyword_loc
FalseNode(なし)
FindPatternNodeconstant, left, requireds, right, opening_loc, closing_loc
FlipFlopNodeleft, right, operator_loc
FloatNodevalue
ForNodeindex, collection, statements, for_keyword_loc, in_keyword_loc, do_keyword_loc, end_keyword_loc
ForwardingArgumentsNode(なし)
ForwardingParameterNode(なし)
ForwardingSuperNodeblock
GlobalVariableAndWriteNodename, name_loc, operator_loc, value
GlobalVariableOperatorWriteNodename, name_loc, binary_operator_loc, value, binary_operator
GlobalVariableOrWriteNodename, name_loc, operator_loc, value
GlobalVariableReadNodename
GlobalVariableTargetNodename
GlobalVariableWriteNodename, name_loc, value, operator_loc
HashNodeopening_loc, elements, closing_loc
HashPatternNodeconstant, elements, rest, opening_loc, closing_loc
IfNodeif_keyword_loc, predicate, then_keyword_loc, statements, subsequent, end_keyword_loc
ImaginaryNodenumeric
ImplicitNodevalue
ImplicitRestNode(なし)
InNodepattern, statements, in_loc, then_loc
IndexAndWriteNodereceiver, call_operator_loc, opening_loc, arguments, closing_loc, block, operator_loc, value
IndexOperatorWriteNodereceiver, call_operator_loc, opening_loc, arguments, closing_loc, block, binary_operator, binary_operator_loc, value
IndexOrWriteNodereceiver, call_operator_loc, opening_loc, arguments, closing_loc, block, operator_loc, value
IndexTargetNodereceiver, opening_loc, arguments, closing_loc, block
InstanceVariableAndWriteNodename, name_loc, operator_loc, value
InstanceVariableOperatorWriteNodename, name_loc, binary_operator_loc, value, binary_operator
InstanceVariableOrWriteNodename, name_loc, operator_loc, value
InstanceVariableReadNodename
InstanceVariableTargetNodename
InstanceVariableWriteNodename, name_loc, value, operator_loc
IntegerNodevalue
InterpolatedMatchLastLineNodeopening_loc, parts, closing_loc
InterpolatedRegularExpressionNodeopening_loc, parts, closing_loc
InterpolatedStringNodeopening_loc, parts, closing_loc
InterpolatedSymbolNodeopening_loc, parts, closing_loc
InterpolatedXStringNodeopening_loc, parts, closing_loc
ItLocalVariableReadNode(なし)
ItParametersNode(なし)
KeywordHashNodeelements
KeywordRestParameterNodename, name_loc, operator_loc
LambdaNodelocals, operator_loc, opening_loc, closing_loc, parameters, body
LocalVariableAndWriteNodename_loc, operator_loc, value, name, depth
LocalVariableOperatorWriteNodename_loc, binary_operator_loc, value, name, binary_operator, depth
LocalVariableOrWriteNodename_loc, operator_loc, value, name, depth
LocalVariableReadNodename, depth
LocalVariableTargetNodename, depth
LocalVariableWriteNodename, depth, name_loc, value, operator_loc
MatchLastLineNodeopening_loc, content_loc, closing_loc, unescaped
MatchPredicateNodevalue, pattern, operator_loc
MatchRequiredNodevalue, pattern, operator_loc
MatchWriteNodecall, targets
MissingNode(なし)
ModuleNodelocals, module_keyword_loc, constant_path, body, end_keyword_loc, name
MultiTargetNodelefts, rest, rights, lparen_loc, rparen_loc
MultiWriteNodelefts, rest, rights, lparen_loc, rparen_loc, operator_loc, value
NextNodearguments, keyword_loc
NilNode(なし)
NoKeywordsParameterNodeoperator_loc, keyword_loc
NumberedParametersNodemaximum
NumberedReferenceReadNodenumber
OptionalKeywordParameterNodename, name_loc, value
OptionalParameterNodename, name_loc, operator_loc, value
OrNodeleft, right, operator_loc
ParametersNoderequireds, optionals, rest, posts, keywords, keyword_rest, block
ParenthesesNodebody, opening_loc, closing_loc
PinnedExpressionNodeexpression, operator_loc, lparen_loc, rparen_loc
PinnedVariableNodevariable, operator_loc
PostExecutionNodestatements, keyword_loc, opening_loc, closing_loc
PreExecutionNodestatements, keyword_loc, opening_loc, closing_loc
ProgramNodelocals, statements
RangeNodeleft, right, operator_loc
RationalNodenumerator, denominator
RedoNode(なし)
RegularExpressionNodeopening_loc, content_loc, closing_loc, unescaped
RequiredKeywordParameterNodename, name_loc
RequiredParameterNodename
RescueModifierNodeexpression, keyword_loc, rescue_expression
RescueNodekeyword_loc, exceptions, operator_loc, reference, then_keyword_loc, statements, subsequent
RestParameterNodename, name_loc, operator_loc
RetryNode(なし)
ReturnNodekeyword_loc, arguments
SelfNode(なし)
ShareableConstantNodewrite
SingletonClassNodelocals, class_keyword_loc, operator_loc, expression, body, end_keyword_loc
SourceEncodingNode(なし)
SourceFileNodefilepath
SourceLineNode(なし)
SplatNodeoperator_loc, expression
StatementsNodebody
StringNodeopening_loc, content_loc, closing_loc, unescaped
SuperNodekeyword_loc, lparen_loc, arguments, rparen_loc, block
SymbolNodeopening_loc, value_loc, closing_loc, unescaped
TrueNode(なし)
UndefNodenames, keyword_loc
UnlessNodekeyword_loc, predicate, then_keyword_loc, statements, else_clause, end_keyword_loc
UntilNodekeyword_loc, do_keyword_loc, closing_loc, predicate, statements
WhenNodekeyword_loc, conditions, then_keyword_loc, statements
WhileNodekeyword_loc, do_keyword_loc, closing_loc, predicate, statements
XStringNodeopening_loc, content_loc, closing_loc, unescaped
YieldNodekeyword_loc, lparen_loc, arguments, rparen_loc
inspect -> StringRuby 3.3 から[permalink][rdoc][edit]

構文木をツリー形式で表した、人間が読みやすい文字列を返します。

例
require "prism"

puts Prism.parse("1 + 2").value.inspect
leading_comments -> [Prism::Comment]Ruby 3.4 から[permalink][rdoc][edit]

このノードの前に付くコメントの配列を返します。 location.leading_comments と同じです。 Prism::ParseResult#attach_comments! を呼び出す前は空配列です。

location -> Prism::LocationRuby 3.3 から[permalink][rdoc][edit]

ノードのソースコード上の位置を表す Prism::Location を返します。

newline? -> boolRuby 3.3 から[permalink][rdoc][edit]

このノードが、TracePoint の :line イベントを発生させる行の位置としてマークされているかどうかを返します。

node_id -> IntegerRuby 3.4 から[permalink][rdoc][edit]

このノード固有の識別子を返します。同じソースコードを同じバージョンで再度解析した場合、対応するノードには同じ識別子が割り当てられます。構文木全体をメモリ上に保持せずにノードを再特定するための仕組み (prism の Prism::Relocation)で使われます。

pretty_print(q) -> ()Ruby 3.3 から[permalink][rdoc][edit]

pp ライブラリからの呼び出しに対応します。Prism::Node#inspect の出力を、現在のインデントレベルを保ったまま表示します。

save(repository) -> Prism::Relocation::EntryRuby 3.4 から[permalink][rdoc][edit]

self を repository に保存し、後で参照するための Prism::Relocation::Entry を返します。

構文木全体をメモリ上に保持し続けることなく、Prism::Node#node_id を使ってノードを後から再特定するための仕組み(Prism::Relocation)で使われます。

[PARAM] repository:
保存先の Prism::Relocation::Repository を指定します。
例
require "prism"

result = Prism.parse("1 + 2")
node = result.value.statements.body[0]

repository = Prism::Relocation.filepath("sample.rb")
entry = node.save(repository)
p entry.class
# => Prism::Relocation::Entry

[SEE_ALSO] Prism::Node#save_location, Prism::Node#node_id

save_location(repository) -> Prism::Relocation::EntryRuby 3.4 から[permalink][rdoc][edit]

self の位置情報を repository に保存し、後で参照するための Prism::Relocation::Entry を返します。

Prism::Node#save とは異なり、ノードそのものではなく Prism::Node#location だけを保存します。

[PARAM] repository:
保存先の Prism::Relocation::Repository を指定します。
例
require "prism"

result = Prism.parse("1 + 2")
node = result.value.statements.body[0]

repository = Prism::Relocation.filepath("sample.rb")
entry = node.save_location(repository)
p entry.class
# => Prism::Relocation::Entry

[SEE_ALSO] Prism::Node#save

script_lines -> [String]Ruby 3.4 から[permalink][rdoc][edit]

Prism::Node#source_lines のエイリアスです。 RubyVM::AbstractSyntaxTree の API に合わせた名前で、そこからの移行を容易にするためのものです。

slice -> StringRuby 3.3 から[permalink][rdoc][edit]

ノードの位置に対応するソースコードの文字列を返します。 location.slice と同じです。

slice_lines -> StringRuby 3.4 から[permalink][rdoc][edit]

ノードの位置を含む行全体(開始行の行頭から終端行の行末まで)の文字列を返します。location.slice_lines と同じです。

source_lines -> [String]Ruby 3.4 から[permalink][rdoc][edit]

ソースコード全体を行ごとに分割した配列を返します。 location.source_lines と同じです。

start_character_column -> IntegerRuby 3.4 から[permalink][rdoc][edit]

開始位置の、行頭からの文字単位の桁位置を返します。 location.start_character_column と同じです。

start_character_offset -> IntegerRuby 3.4 から[permalink][rdoc][edit]

開始位置の、ソースコード先頭からの文字単位のオフセットを返します。 location.start_character_offset と同じです。

start_column -> IntegerRuby 3.4 から[permalink][rdoc][edit]

開始位置の、行頭からのバイト単位の桁位置を返します。 location.start_column と同じです。

start_line -> IntegerRuby 3.4 から[permalink][rdoc][edit]

開始位置の行番号を返します。location.start_line と同じです。

start_offset -> IntegerRuby 3.4 から[permalink][rdoc][edit]

開始位置のバイトオフセットを返します。location.start_offset と同じです。

static_literal? -> boolRuby 3.4 から[permalink][rdoc][edit]

このノードに静的リテラル(構文解析の時点で値が確定するリテラル) のフラグが立っているかどうかを返します。

to_dot -> StringRuby 3.3 から[permalink][rdoc][edit]

構文木を Graphviz の DOT 言語形式の文字列に変換します。

例
require "prism"

dot = Prism.parse("1 + 2").value.to_dot
p dot.start_with?("digraph") # => true
trailing_comments -> [Prism::Comment]Ruby 3.4 から[permalink][rdoc][edit]

このノードの後ろに付くコメントの配列を返します。 location.trailing_comments と同じです。

tunnel(line, column) -> [Prism::Node]Ruby 3.4 から[permalink][rdoc][edit]

指定した行・桁を位置に含むノードを、自分自身から子孫の方向へ順に並べた配列で返します。エディタ上のカーソル位置に対応するノードを特定するといった用途に使えます。

[PARAM] line:
行番号(1 始まり)を指定します。
[PARAM] column:
行頭からのバイト単位の桁位置(0 始まり)を指定します。
例
require "prism"

node = Prism.parse("x = 1 + 2").value
path = node.tunnel(1, 4)
p path.map(&:type)
# => [:program_node, :statements_node, :local_variable_write_node, :call_node, :integer_node]
type -> SymbolRuby 3.4 から[permalink][rdoc][edit]

ノードの種類を表すシンボル(例 :program_node、:call_node)を返します。case 式や配列との比較でノードの種類を判定するときに使えます。