要約
構文解析の結果得られる構文木の各ノードを表す抽象基底クラスです。
Prism?.parse などが返す構文木は、このクラスのサブクラス
(150 種類以上)のインスタンスで構成されます。Prism::Node 自身のインスタンスが生成されることはありません。
個々のノードクラス(Prism::ProgramNode・Prism::CallNode など)に固有のフィールド(子ノードや値を取得するアクセサ)は、このページ末尾の ノードクラスの一覧 に名前だけを載せ、個別のエントリは作りません。このページで扱うのは、すべてのノードクラスに共通する
API です。個々のノードクラスの詳細は公式ドキュメントを参照してください。
- プロジェクトページ: https://github.com/ruby/prism
- リファレンス(YARD): https://www.rubydoc.info/gems/prism
- ドキュメントサイト: https://ruby.github.io/prism/
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
目次
- 特異メソッド
- インスタンスメソッド
-
- ===
- accept
- breadth_first_search
- breadth_first_search_all
- cached_end_code_units_column
- cached_end_code_units_offset
- cached_start_code_units_column
- cached_start_code_units_offset
- child_nodes
- comment_targets
- comments
- compact_child_nodes
- copy
- deconstruct
- deconstruct_keys
- deprecated
- each_child_node
- end_character_column
- end_character_offset
- end_column
- end_line
- end_offset
- find
- find_all
- inspect
- leading_comments
- location
- newline?
- node_id
- pretty_print
- save
- save_location
- script_lines
- slice
- slice_lines
- source_lines
- start_character_column
- start_character_offset
- start_column
- start_line
- start_offset
- static_literal?
- to_dot
- trailing_comments
- tunnel
- type
特異メソッド
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 - [PARAM]
accept(visitor) -> objectRuby 3.4 から[permalink][rdoc][edit]-
Visitor パターンの受け入れメソッドです。ノードの種類に応じた
visitor.visit_xxxを呼び出し、その戻り値を返します。- [PARAM]
visitor: -
Prism::Visitor(またはそのサブクラス)のインスタンスを指定します。
- [PARAM]
breadth_first_search {|node| ... } -> Prism::Node | nilRuby 3.4 から[permalink][rdoc][edit]-
自身を含めて構文木を幅優先で探索し、ブロックが真を返した最初のノードを返します。見つからない場合は 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 で得たキャッシュを指定します。
- [PARAM]
cached_end_code_units_offset(cache) -> IntegerRuby 3.4 から[permalink][rdoc][edit]-
キャッシュを使って、終了位置の、指定エンコーディングのコード単位でのオフセットを返します。
- [PARAM]
cache: - Prism::Result#code_units_cache で得たキャッシュを指定します。
- [PARAM]
cached_start_code_units_column(cache) -> IntegerRuby 3.4 から[permalink][rdoc][edit]-
キャッシュを使って、開始位置の、行頭からのコード単位での桁位置を返します。
- [PARAM]
cache: - Prism::Result#code_units_cache で得たキャッシュを指定します。
- [PARAM]
cached_start_code_units_offset(cache) -> IntegerRuby 3.4 から[permalink][rdoc][edit]-
キャッシュを使って、開始位置の、指定エンコーディングのコード単位でのオフセットを返します。
- [PARAM]
cache: - Prism::Result#code_units_cache で得たキャッシュを指定します。
- [PARAM]
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 を指定します。
- [PARAM]
deprecated(*replacements) -> ()Ruby 3.4 から[permalink][rdoc][edit]-
このノードの、別のフィールドに置き換えられた古いメソッドが呼び出されたときに、非推奨であることを示す警告を出力します。
生成された各ノードクラスの、名前が変更されたフィールドの読み出しメソッドが内部で使用するためのメソッドです。呼び出し元のメソッド名と、
replacementsに指定した代替メソッド名を含む警告メッセージを、:deprecatedカテゴリの警告として(Kernel のwarnを使って)出力します。- [PARAM]
replacements: - 代わりに使うべきメソッド名を文字列で 1 つ以上指定します。
- [PARAM]
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]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_locAliasMethodNodenew_name,old_name,keyword_locAlternationPatternNodeleft,right,operator_locAndNodeleft,right,operator_locArgumentsNodeargumentsArrayNodeelements,opening_loc,closing_locArrayPatternNodeconstant,requireds,rest,posts,opening_loc,closing_locAssocNodekey,value,operator_locAssocSplatNodevalue,operator_locBackReferenceReadNodenameBeginNodebegin_keyword_loc,statements,rescue_clause,else_clause,ensure_clause,end_keyword_locBlockArgumentNodeexpression,operator_locBlockLocalVariableNodenameBlockNodelocals,parameters,body,opening_loc,closing_locBlockParameterNodename,name_loc,operator_locBlockParametersNodeparameters,locals,opening_loc,closing_locBreakNodearguments,keyword_locCallAndWriteNodereceiver,call_operator_loc,message_loc,read_name,write_name,operator_loc,valueCallNodereceiver,call_operator_loc,name,message_loc,opening_loc,arguments,closing_loc,equal_loc,blockCallOperatorWriteNodereceiver,call_operator_loc,message_loc,read_name,write_name,binary_operator,binary_operator_loc,valueCallOrWriteNodereceiver,call_operator_loc,message_loc,read_name,write_name,operator_loc,valueCallTargetNodereceiver,call_operator_loc,name,message_locCapturePatternNodevalue,target,operator_locCaseMatchNodepredicate,conditions,else_clause,case_keyword_loc,end_keyword_locCaseNodepredicate,conditions,else_clause,case_keyword_loc,end_keyword_locClassNodelocals,class_keyword_loc,constant_path,inheritance_operator_loc,superclass,body,end_keyword_loc,nameClassVariableAndWriteNodename,name_loc,operator_loc,valueClassVariableOperatorWriteNodename,name_loc,binary_operator_loc,value,binary_operatorClassVariableOrWriteNodename,name_loc,operator_loc,valueClassVariableReadNodenameClassVariableTargetNodenameClassVariableWriteNodename,name_loc,value,operator_locConstantAndWriteNodename,name_loc,operator_loc,valueConstantOperatorWriteNodename,name_loc,binary_operator_loc,value,binary_operatorConstantOrWriteNodename,name_loc,operator_loc,valueConstantPathAndWriteNodetarget,operator_loc,valueConstantPathNodeparent,name,delimiter_loc,name_locConstantPathOperatorWriteNodetarget,binary_operator_loc,value,binary_operatorConstantPathOrWriteNodetarget,operator_loc,valueConstantPathTargetNodeparent,name,delimiter_loc,name_locConstantPathWriteNodetarget,operator_loc,valueConstantReadNodenameConstantTargetNodenameConstantWriteNodename,name_loc,value,operator_locDefNodename,name_loc,receiver,parameters,body,locals,def_keyword_loc,operator_loc,lparen_loc,rparen_loc,equal_loc,end_keyword_locDefinedNodelparen_loc,value,rparen_loc,keyword_locElseNodeelse_keyword_loc,statements,end_keyword_locEmbeddedStatementsNodeopening_loc,statements,closing_locEmbeddedVariableNodeoperator_loc,variableEnsureNodeensure_keyword_loc,statements,end_keyword_locFalseNode(なし) FindPatternNodeconstant,left,requireds,right,opening_loc,closing_locFlipFlopNodeleft,right,operator_locFloatNodevalueForNodeindex,collection,statements,for_keyword_loc,in_keyword_loc,do_keyword_loc,end_keyword_locForwardingArgumentsNode(なし) ForwardingParameterNode(なし) ForwardingSuperNodeblockGlobalVariableAndWriteNodename,name_loc,operator_loc,valueGlobalVariableOperatorWriteNodename,name_loc,binary_operator_loc,value,binary_operatorGlobalVariableOrWriteNodename,name_loc,operator_loc,valueGlobalVariableReadNodenameGlobalVariableTargetNodenameGlobalVariableWriteNodename,name_loc,value,operator_locHashNodeopening_loc,elements,closing_locHashPatternNodeconstant,elements,rest,opening_loc,closing_locIfNodeif_keyword_loc,predicate,then_keyword_loc,statements,subsequent,end_keyword_locImaginaryNodenumericImplicitNodevalueImplicitRestNode(なし) InNodepattern,statements,in_loc,then_locIndexAndWriteNodereceiver,call_operator_loc,opening_loc,arguments,closing_loc,block,operator_loc,valueIndexOperatorWriteNodereceiver,call_operator_loc,opening_loc,arguments,closing_loc,block,binary_operator,binary_operator_loc,valueIndexOrWriteNodereceiver,call_operator_loc,opening_loc,arguments,closing_loc,block,operator_loc,valueIndexTargetNodereceiver,opening_loc,arguments,closing_loc,blockInstanceVariableAndWriteNodename,name_loc,operator_loc,valueInstanceVariableOperatorWriteNodename,name_loc,binary_operator_loc,value,binary_operatorInstanceVariableOrWriteNodename,name_loc,operator_loc,valueInstanceVariableReadNodenameInstanceVariableTargetNodenameInstanceVariableWriteNodename,name_loc,value,operator_locIntegerNodevalueInterpolatedMatchLastLineNodeopening_loc,parts,closing_locInterpolatedRegularExpressionNodeopening_loc,parts,closing_locInterpolatedStringNodeopening_loc,parts,closing_locInterpolatedSymbolNodeopening_loc,parts,closing_locInterpolatedXStringNodeopening_loc,parts,closing_locItLocalVariableReadNode(なし) ItParametersNode(なし) KeywordHashNodeelementsKeywordRestParameterNodename,name_loc,operator_locLambdaNodelocals,operator_loc,opening_loc,closing_loc,parameters,bodyLocalVariableAndWriteNodename_loc,operator_loc,value,name,depthLocalVariableOperatorWriteNodename_loc,binary_operator_loc,value,name,binary_operator,depthLocalVariableOrWriteNodename_loc,operator_loc,value,name,depthLocalVariableReadNodename,depthLocalVariableTargetNodename,depthLocalVariableWriteNodename,depth,name_loc,value,operator_locMatchLastLineNodeopening_loc,content_loc,closing_loc,unescapedMatchPredicateNodevalue,pattern,operator_locMatchRequiredNodevalue,pattern,operator_locMatchWriteNodecall,targetsMissingNode(なし) ModuleNodelocals,module_keyword_loc,constant_path,body,end_keyword_loc,nameMultiTargetNodelefts,rest,rights,lparen_loc,rparen_locMultiWriteNodelefts,rest,rights,lparen_loc,rparen_loc,operator_loc,valueNextNodearguments,keyword_locNilNode(なし) NoKeywordsParameterNodeoperator_loc,keyword_locNumberedParametersNodemaximumNumberedReferenceReadNodenumberOptionalKeywordParameterNodename,name_loc,valueOptionalParameterNodename,name_loc,operator_loc,valueOrNodeleft,right,operator_locParametersNoderequireds,optionals,rest,posts,keywords,keyword_rest,blockParenthesesNodebody,opening_loc,closing_locPinnedExpressionNodeexpression,operator_loc,lparen_loc,rparen_locPinnedVariableNodevariable,operator_locPostExecutionNodestatements,keyword_loc,opening_loc,closing_locPreExecutionNodestatements,keyword_loc,opening_loc,closing_locProgramNodelocals,statementsRangeNodeleft,right,operator_locRationalNodenumerator,denominatorRedoNode(なし) RegularExpressionNodeopening_loc,content_loc,closing_loc,unescapedRequiredKeywordParameterNodename,name_locRequiredParameterNodenameRescueModifierNodeexpression,keyword_loc,rescue_expressionRescueNodekeyword_loc,exceptions,operator_loc,reference,then_keyword_loc,statements,subsequentRestParameterNodename,name_loc,operator_locRetryNode(なし) ReturnNodekeyword_loc,argumentsSelfNode(なし) ShareableConstantNodewriteSingletonClassNodelocals,class_keyword_loc,operator_loc,expression,body,end_keyword_locSourceEncodingNode(なし) SourceFileNodefilepathSourceLineNode(なし) SplatNodeoperator_loc,expressionStatementsNodebodyStringNodeopening_loc,content_loc,closing_loc,unescapedSuperNodekeyword_loc,lparen_loc,arguments,rparen_loc,blockSymbolNodeopening_loc,value_loc,closing_loc,unescapedTrueNode(なし) UndefNodenames,keyword_locUnlessNodekeyword_loc,predicate,then_keyword_loc,statements,else_clause,end_keyword_locUntilNodekeyword_loc,do_keyword_loc,closing_loc,predicate,statementsWhenNodekeyword_loc,conditions,then_keyword_loc,statementsWhileNodekeyword_loc,do_keyword_loc,closing_loc,predicate,statementsXStringNodeopening_loc,content_loc,closing_loc,unescapedYieldNodekeyword_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
- [PARAM]
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
- [PARAM]
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] - [PARAM]
type -> SymbolRuby 3.4 から[permalink][rdoc][edit]-
ノードの種類を表すシンボル(例
:program_node、:call_node)を返します。case 式や配列との比較でノードの種類を判定するときに使えます。