Module: Prism
- Defined in:
- lib/prism.rb,
lib/prism/dsl.rb,
lib/prism/ffi.rb,
lib/prism/node.rb,
lib/prism/pattern.rb,
lib/prism/visitor.rb,
lib/prism/compiler.rb,
lib/prism/node_ext.rb,
lib/prism/node_find.rb,
lib/prism/serialize.rb,
lib/prism/dispatcher.rb,
lib/prism/lex_compat.rb,
lib/prism/reflection.rb,
lib/prism/relocation.rb,
lib/prism/dot_visitor.rb,
lib/prism/translation.rb,
lib/prism/parse_result.rb,
lib/prism/string_query.rb,
lib/prism/inspect_visitor.rb,
lib/prism/desugar_compiler.rb,
lib/prism/mutation_compiler.rb,
lib/prism/translation/parser.rb,
lib/prism/translation/ripper.rb,
lib/prism/parse_result/errors.rb,
lib/prism/parse_result/newlines.rb,
lib/prism/translation/ripper/sexp.rb,
lib/prism/translation/ruby_parser.rb,
lib/prism/translation/parser/lexer.rb,
lib/prism/translation/ripper/lexer.rb,
lib/prism/translation/ripper/filter.rb,
lib/prism/translation/parser/builder.rb,
lib/prism/translation/parser_current.rb,
lib/prism/translation/parser/compiler.rb,
lib/prism/translation/parser_versions.rb,
sig/generated/prism.rbs,
sig/generated/prism/dsl.rbs,
sig/generated/prism/node.rbs,
sig/generated/prism/pattern.rbs,
sig/generated/prism/visitor.rbs,
sig/generated/prism/compiler.rbs,
sig/generated/prism/node_ext.rbs,
sig/generated/prism/node_find.rbs,
sig/generated/prism/serialize.rbs,
sig/generated/prism/dispatcher.rbs,
sig/generated/prism/lex_compat.rbs,
sig/generated/prism/reflection.rbs,
sig/generated/prism/relocation.rbs,
sig/generated/prism/dot_visitor.rbs,
sig/generated/prism/translation.rbs,
sig/generated/prism/parse_result.rbs,
sig/generated/prism/string_query.rbs,
sig/generated/prism/inspect_visitor.rbs,
sig/generated/prism/desugar_compiler.rbs,
sig/generated/prism/mutation_compiler.rbs,
sig/generated/prism/parse_result/errors.rbs,
sig/generated/prism/parse_result/newlines.rbs,
ext/prism/extension.c
Overview
-- Here we are reopening the prism module to provide methods on nodes that aren't templated and are meant as convenience methods. ++
Defined Under Namespace
Modules: ArgumentsNodeFlags, ArrayNodeFlags, CallNodeFlags, DSL, EncodingFlags, IntegerBaseFlags, InterpolatedStringNodeFlags, KeywordHashNodeFlags, LoopFlags, NodeFlags, ParameterFlags, ParenthesesNodeFlags, RangeFlags, Reflection, RegularExpressionFlags, Relocation, ShareableConstantNodeFlags, StringFlags, SymbolFlags, Translation, _CodeUnitsCache, _Node, _Repository, _Stream, _Visitor Classes: ASCIISource, AliasGlobalVariableNode, AliasMethodNode, AlternationPatternNode, AndNode, ArgumentsNode, ArrayNode, ArrayPatternNode, AssocNode, AssocSplatNode, BackReferenceReadNode, BasicVisitor, BeginNode, BlockArgumentNode, BlockLocalVariableNode, BlockNode, BlockParameterNode, BlockParametersNode, BreakNode, CallAndWriteNode, CallNode, CallOperatorWriteNode, CallOrWriteNode, CallTargetNode, CapturePatternNode, CaseMatchNode, CaseNode, ClassNode, ClassVariableAndWriteNode, ClassVariableOperatorWriteNode, ClassVariableOrWriteNode, ClassVariableReadNode, ClassVariableTargetNode, ClassVariableWriteNode, CodeUnitsCache, Comment, ConstantAndWriteNode, ConstantOperatorWriteNode, ConstantOrWriteNode, ConstantPathAndWriteNode, ConstantPathNode, ConstantPathOperatorWriteNode, ConstantPathOrWriteNode, ConstantPathTargetNode, ConstantPathWriteNode, ConstantReadNode, ConstantTargetNode, ConstantWriteNode, CurrentVersionError, DefNode, DefinedNode, DesugarCompiler, Dispatcher, DotVisitor, ElseNode, EmbDocComment, EmbeddedStatementsNode, EmbeddedVariableNode, EnsureNode, ErrorRecoveryNode, FalseNode, FindPatternNode, FlipFlopNode, FloatNode, ForNode, ForwardingArgumentsNode, ForwardingParameterNode, ForwardingSuperNode, GlobalVariableAndWriteNode, GlobalVariableOperatorWriteNode, GlobalVariableOrWriteNode, GlobalVariableReadNode, GlobalVariableTargetNode, GlobalVariableWriteNode, HashNode, HashPatternNode, IfNode, ImaginaryNode, ImplicitNode, ImplicitRestNode, InNode, IndexAndWriteNode, IndexOperatorWriteNode, IndexOrWriteNode, IndexTargetNode, InlineComment, InspectVisitor, InstanceVariableAndWriteNode, InstanceVariableOperatorWriteNode, InstanceVariableOrWriteNode, InstanceVariableReadNode, InstanceVariableTargetNode, InstanceVariableWriteNode, IntegerNode, InterpolatedMatchLastLineNode, InterpolatedRegularExpressionNode, InterpolatedStringNode, InterpolatedSymbolNode, InterpolatedXStringNode, ItLocalVariableReadNode, ItParametersNode, KeywordHashNode, KeywordRestParameterNode, LambdaNode, LexResult, LocalVariableAndWriteNode, LocalVariableOperatorWriteNode, LocalVariableOrWriteNode, LocalVariableReadNode, LocalVariableTargetNode, LocalVariableWriteNode, Location, MagicComment, MatchLastLineNode, MatchPredicateNode, MatchRequiredNode, MatchWriteNode, ModuleNode, MultiTargetNode, MultiWriteNode, MutationCompiler, NextNode, NilNode, NoBlockParameterNode, NoKeywordsParameterNode, Node, NumberedParametersNode, NumberedReferenceReadNode, OptionalKeywordParameterNode, OptionalParameterNode, OrNode, ParametersNode, ParenthesesNode, ParseError, ParseLexResult, ParseResult, ParseWarning, Pattern, PinnedExpressionNode, PinnedVariableNode, PostExecutionNode, PreExecutionNode, ProgramNode, RangeNode, RationalNode, RedoNode, RegularExpressionNode, RequiredKeywordParameterNode, RequiredParameterNode, RescueModifierNode, RescueNode, RestParameterNode, Result, RetryNode, ReturnNode, Scope, SelfNode, ShareableConstantNode, SingletonClassNode, Source, SourceEncodingNode, SourceFileNode, SourceLineNode, SplatNode, StatementsNode, StringNode, StringQuery, SuperNode, SymbolNode, Token, TrueNode, UndefNode, UnlessNode, UntilNode, Visitor, WhenNode, WhileNode, XStringNode, YieldNode
Constant Summary collapse
- BACKEND =
The FFI backend is used on other Ruby implementations.
:FFI- VERSION =
The version of the prism library.
rb_str_freeze(rb_str_new_cstr(EXPECTED_PRISM_VERSION))
Class Method Summary collapse
-
.dump(*args) ⇒ Object
:markup: markdown call-seq: dump(source, **options) -> String.
-
.dump_file(*args) ⇒ Object
:markup: markdown call-seq: dump_file(filepath, **options) -> String.
-
.find(callable) ⇒ Node?
Given a Method, UnboundMethod, Proc, or Thread::Backtrace::Location, returns the Prism node representing it.
-
.lex(*args) ⇒ Object
:markup: markdown call-seq: lex(source, **options) -> LexResult.
-
.lex_compat(source, **options) ⇒ LexCompat::Result
:call-seq: lex_compat(source, **options) -> LexCompat::Result.
-
.lex_file(*args) ⇒ Object
:markup: markdown call-seq: lex_file(filepath, **options) -> LexResult.
-
.load(source, serialized, freeze = false) ⇒ ParseResult
:call-seq: load(source, serialized, freeze) -> ParseResult.
-
.parse(*args) ⇒ Object
:markup: markdown call-seq: parse(source, **options) -> ParseResult.
-
.parse_comments(*args) ⇒ Object
:markup: markdown call-seq: parse_comments(source, **options) -> Array.
-
.parse_failure?(*args) ⇒ Boolean
:markup: markdown call-seq: parse_failure?(source, **options) -> bool.
-
.parse_file(*args) ⇒ Object
:markup: markdown call-seq: parse_file(filepath, **options) -> ParseResult.
-
.parse_file_comments(*args) ⇒ Object
:markup: markdown call-seq: parse_file_comments(filepath, **options) -> Array.
-
.parse_file_failure?(*args) ⇒ Boolean
:markup: markdown call-seq: parse_file_failure?(filepath, **options) -> bool.
-
.parse_file_success?(*args) ⇒ Boolean
:markup: markdown call-seq: parse_file_success?(filepath, **options) -> bool.
-
.parse_lex(*args) ⇒ Object
:markup: markdown call-seq: parse_lex(source, **options) -> ParseLexResult.
-
.parse_lex_file(*args) ⇒ Object
:markup: markdown call-seq: parse_lex_file(filepath, **options) -> ParseLexResult.
-
.parse_stream(*args) ⇒ Object
:markup: markdown call-seq: parse_stream(stream, **options) -> ParseResult.
-
.parse_success?(*args) ⇒ Boolean
:markup: markdown call-seq: parse_success?(source, **options) -> bool.
-
.profile(*args) ⇒ Object
:markup: markdown call-seq: profile(source, **options) -> nil.
-
.profile_file(*args) ⇒ Object
:markup: markdown call-seq: profile_file(filepath, **options) -> nil.
-
.scope(locals: [], forwarding: []) ⇒ Scope
Create a new scope with the given locals and forwarding options that is suitable for passing into one of the Prism.* methods that accepts the
scopesoption.
Class Method Details
.dump(*args) ⇒ Object
:markup: markdown call-seq:
dump(source, **options) -> String
Dump the AST corresponding to the given string to a string. For supported options, see Prism.parse.
270 271 272 |
# File 'lib/prism/ffi.rb', line 270 def dump(source, **) LibRubyParser::PrismSource.with_string(source) { |string| dump_common(string, ) } end |
.dump_file(*args) ⇒ Object
:markup: markdown call-seq:
dump_file(filepath, **options) -> String
Dump the AST corresponding to the given file to a string. For supported options, see Prism.parse.
275 276 277 |
# File 'lib/prism/ffi.rb', line 275 def dump_file(filepath, **) LibRubyParser::PrismSource.with_file(filepath, ) { |string| dump_common(string, ) } end |
.find(callable) ⇒ Node?
Given a Method, UnboundMethod, Proc, or Thread::Backtrace::Location, returns the Prism node representing it. On CRuby, this uses node_id for an exact match. On other implementations, it falls back to best-effort matching by source location line number.
: (Method | UnboundMethod | Proc | Thread::Backtrace::Location callable) -> Node?
94 95 96 |
# File 'lib/prism.rb', line 94 def self.find(callable) NodeFind.find(callable) end |
.lex(*args) ⇒ Object
:markup: markdown call-seq:
lex(source, **options) -> LexResult
Return a LexResult instance that contains an array of Token instances corresponding to the given string. For supported options, see Prism.parse.
280 281 282 |
# File 'lib/prism/ffi.rb', line 280 def lex(code, **) LibRubyParser::PrismSource.with_string(code) { |string| lex_common(string, code, ) } end |
.lex_compat(source, **options) ⇒ LexCompat::Result
:call-seq:
lex_compat(source, **options) -> LexCompat::Result
Returns a parse result whose value is an array of tokens that closely resembles the return value of Ripper.lex.
For supported options, see Prism.parse.
: (String source, **untyped options) -> LexCompat::Result
74 75 76 |
# File 'lib/prism.rb', line 74 def self.lex_compat(source, **) LexCompat.new(source, **).result # steep:ignore end |
.lex_file(*args) ⇒ Object
:markup: markdown call-seq:
lex_file(filepath, **options) -> LexResult
Return a LexResult instance that contains an array of Token instances corresponding to the given file. For supported options, see Prism.parse.
285 286 287 |
# File 'lib/prism/ffi.rb', line 285 def lex_file(filepath, **) LibRubyParser::PrismSource.with_file(filepath, ) { |string| lex_common(string, string.read, ) } end |
.load(source, serialized, freeze = false) ⇒ ParseResult
:call-seq:
load(source, serialized, freeze) -> ParseResult
Load the serialized AST using the source as a reference into a tree.
: (String source, String serialized, ?bool freeze) -> ParseResult
84 85 86 |
# File 'lib/prism.rb', line 84 def self.load(source, serialized, freeze = false) Serialize.load_parse(source, serialized, freeze) end |
.parse(*args) ⇒ Object
:markup: markdown call-seq:
parse(source, **options) -> ParseResult
Parse the given string and return a ParseResult instance. The options that are supported are:
attach_comments- whether or not to attach each comment to the node that owns it. When set, the comments on the result are sorted by start offset. This should be a boolean or nil.command_line- either nil or a string of the various options that were set on the command line. Valid values are combinations of "a", "l", "n", "p", and "x".encoding- the encoding of the source being parsed. This should be an encoding or nil.filepath- the filepath of the source being parsed. This should be a string or nil.freeze- whether or not to deeply freeze the AST. This should be a boolean or nil.frozen_string_literal- whether or not the frozen string literal pragma has been set. This should be a boolean or nil.line- the line number that the parse starts on. This should be an integer or nil. Note that this is 1-indexed.main_script- a boolean indicating whether or not the source being parsed is the main script being run by the interpreter. This controls whether or not shebangs are parsed for additional flags and whether or not the parser will attempt to find a matching shebang if the first one does not contain the word "ruby".partial_script- when the file being parsed is considered a "partial" script, jumps will not be marked as errors if they are not contained within loops/blocks. This is used in the case that you're parsing a script that you know will be embedded inside another script later, but you do not have that context yet. For example, when parsing an ERB template that will be evaluated inside another script.raise_error- either nil, true, or a symbol indicating that an error should be raised if the source contains any errors. The message of the error will include the source of the lines that contain errors when possible, and the value of this option controls how those lines are formatted. Valid values are:plain(no formatting),:style(bold formatting), and:color(bold and color formatting). Whentrueis given, the formatting is determined by whether or not$stderris a terminal and whether or not theNO_COLORenvironment variable is set, mirroring the behavior of CRuby itself. Syntax-level errors raise SyntaxError, argument-level errors raise ArgumentError, and load-level errors raise LoadError. Note that this option is honored by every API that accepts these options, including predicates like Prism.parse_success?, which will raise instead of returning a boolean when the source contains errors.scopes- the locals that are in scope surrounding the code that is being parsed. This should be an array of arrays of symbols or nil. Scopes are ordered from the outermost scope to the innermost one.version- the version of Ruby syntax that prism should used to parse Ruby code. By default prism parses with the syntax version nearest to the current Ruby that is running (which you can trigger withnilor"nearest"): the running version if prism supports it, otherwise the closest version that it does support. You may also restrict the syntax to a specific version of Ruby, e.g., with"3.3.0". To parse with exactly the same syntax version that the current Ruby is running useversion: "current", which raises Prism::CurrentVersionError if prism does not support it. To parse with the latest version of Ruby syntax that prism supports, useversion: "latest". Raises ArgumentError if the version is not currently supported by Prism.
290 291 292 |
# File 'lib/prism/ffi.rb', line 290 def parse(code, **) LibRubyParser::PrismSource.with_string(code) { |string| parse_common(string, code, ) } end |
.parse_comments(*args) ⇒ Object
:markup: markdown call-seq:
parse_comments(source, **options) -> Array
Parse the given string and return an array of Comment objects. For supported options, see Prism.parse.
349 350 351 |
# File 'lib/prism/ffi.rb', line 349 def parse_comments(code, **) LibRubyParser::PrismSource.with_string(code) { |string| parse_comments_common(string, code, ) } end |
.parse_failure?(*args) ⇒ Boolean
:markup: markdown call-seq:
parse_failure?(source, **options) -> bool
Parse the given string and return true if it parses with errors. For supported options, see Prism.parse.
376 377 378 |
# File 'lib/prism/ffi.rb', line 376 def parse_failure?(code, **) !parse_success?(code, **) end |
.parse_file(*args) ⇒ Object
:markup: markdown call-seq:
parse_file(filepath, **options) -> ParseResult
Parse the given file and return a ParseResult instance. For supported options, see Prism.parse.
297 298 299 |
# File 'lib/prism/ffi.rb', line 297 def parse_file(filepath, **) LibRubyParser::PrismSource.with_file(filepath, ) { |string| parse_common(string, string.read, ) } end |
.parse_file_comments(*args) ⇒ Object
:markup: markdown call-seq:
parse_file_comments(filepath, **options) -> Array
Parse the given file and return an array of Comment objects. For supported options, see Prism.parse.
356 357 358 |
# File 'lib/prism/ffi.rb', line 356 def parse_file_comments(filepath, **) LibRubyParser::PrismSource.with_file(filepath, ) { |string| parse_comments_common(string, string.read, ) } end |
.parse_file_failure?(*args) ⇒ Boolean
:markup: markdown call-seq:
parse_file_failure?(filepath, **options) -> bool
Parse the given file and return true if it parses with errors. For supported options, see Prism.parse.
386 387 388 |
# File 'lib/prism/ffi.rb', line 386 def parse_file_failure?(filepath, **) !parse_file_success?(filepath, **) end |
.parse_file_success?(*args) ⇒ Boolean
:markup: markdown call-seq:
parse_file_success?(filepath, **options) -> bool
Parse the given file and return true if it parses without errors. For supported options, see Prism.parse.
381 382 383 |
# File 'lib/prism/ffi.rb', line 381 def parse_file_success?(filepath, **) LibRubyParser::PrismSource.with_file(filepath, ) { |string| parse_file_success_common(string, ) } end |
.parse_lex(*args) ⇒ Object
:markup: markdown call-seq:
parse_lex(source, **options) -> ParseLexResult
Parse the given string and return a ParseLexResult instance that contains a 2-element array, where the first element is the AST and the second element is an array of Token instances.
This API is only meant to be used in the case where you need both the AST and the tokens. If you only need one or the other, use either Prism.parse or Prism.lex.
For supported options, see Prism.parse.
361 362 363 |
# File 'lib/prism/ffi.rb', line 361 def parse_lex(code, **) LibRubyParser::PrismSource.with_string(code) { |string| parse_lex_common(string, code, ) } end |
.parse_lex_file(*args) ⇒ Object
:markup: markdown call-seq:
parse_lex_file(filepath, **options) -> ParseLexResult
Parse the given file and return a ParseLexResult instance that contains a 2-element array, where the first element is the AST and the second element is an array of Token instances.
This API is only meant to be used in the case where you need both the AST and the tokens. If you only need one or the other, use either Prism.parse_file or Prism.lex_file.
For supported options, see Prism.parse.
366 367 368 |
# File 'lib/prism/ffi.rb', line 366 def parse_lex_file(filepath, **) LibRubyParser::PrismSource.with_file(filepath, ) { |string| parse_lex_common(string, string.read, ) } end |
.parse_stream(*args) ⇒ Object
:markup: markdown call-seq:
parse_stream(stream, **options) -> ParseResult
Parse the given object that responds to gets and return a ParseResult
instance. The options that are supported are the same as Prism.parse.
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/prism/ffi.rb', line 302 def parse_stream(stream, **) format_type = raise_error_format_type() LibRubyParser::PrismBuffer.with do |buffer| # The largest number of bytes a single character can occupy in any # encoding Ruby supports. IO#gets(limit) may return up to # (max_enc_len - 1) bytes more than requested to avoid splitting a # multi-byte character, so we reserve that much headroom (plus the NUL # terminator) to guarantee the result fits in the caller's buffer. This # mirrors MAX_ENC_LEN in ext/prism/extension.c. max_enc_len = 6 source = +"" callback = -> (string, size, _) { raise "Expected size to be > #{max_enc_len}, got: #{size}" if size <= max_enc_len line = String.try_convert(stream.gets(size - max_enc_len)) if !line.nil? # A misbehaving `gets` may ignore the limit; never write past the # buffer (one byte is reserved for the NUL terminator). line = line.byteslice(0, size - 1) if line.bytesize > size - 1 source << line string.write_string("#{line}\x00", line.bytesize + 1) end } eof_callback = -> (_) { stream.eof? } pm_source = LibRubyParser.pm_source_stream_new(nil, callback, eof_callback) begin LibRubyParser.pm_serialize_parse_stream(buffer.pointer, pm_source, ()) result = Prism.load(source, buffer.read, .fetch(:freeze, false)) if format_type && result.failure? LibRubyParser::PrismSource.with_string(source) do |string| raise_error(string, , format_type) end end result ensure LibRubyParser.pm_source_free(pm_source) if pm_source && !pm_source.null? end end end |
.parse_success?(*args) ⇒ Boolean
:markup: markdown call-seq:
parse_success?(source, **options) -> bool
Parse the given string and return true if it parses without errors. For supported options, see Prism.parse.
371 372 373 |
# File 'lib/prism/ffi.rb', line 371 def parse_success?(code, **) LibRubyParser::PrismSource.with_string(code) { |string| parse_file_success_common(string, ) } end |
.profile(*args) ⇒ Object
:markup: markdown call-seq:
profile(source, **options) -> nil
Parse the given string and return nothing. This method is meant to allow profilers to avoid the overhead of reifying the AST to Ruby. For supported options, see Prism.parse.
391 392 393 394 395 396 397 398 399 400 401 402 |
# File 'lib/prism/ffi.rb', line 391 def profile(source, **) LibRubyParser::PrismSource.with_string(source) do |string| if (format_type = raise_error_format_type()) raise_error(string, , format_type) end LibRubyParser::PrismBuffer.with do |buffer| LibRubyParser.pm_serialize_parse(buffer.pointer, string.pointer, string.length, ()) nil end end end |
.profile_file(*args) ⇒ Object
:markup: markdown call-seq:
profile_file(filepath, **options) -> nil
Parse the given file and return nothing. This method is meant to allow profilers to avoid the overhead of reifying the AST to Ruby. For supported options, see Prism.parse.
405 406 407 408 409 410 411 412 413 414 415 416 |
# File 'lib/prism/ffi.rb', line 405 def profile_file(filepath, **) LibRubyParser::PrismSource.with_file(filepath, ) do |string| if (format_type = raise_error_format_type()) raise_error(string, , format_type) end LibRubyParser::PrismBuffer.with do |buffer| LibRubyParser.pm_serialize_parse(buffer.pointer, string.pointer, string.length, ()) nil end end end |