Spec-Zone.ru › Ruby 4.0

модуль Prism

Парсер Ruby Prism.

«Парсить Ruby теперь проще простого!» — вы, надеемся

Константы

BACKEND

Расширение C — стандартный бэкенд в CRuby.

VERSION

Константа версии задаётся чтением результата вызова pm_version.

Публичные методы класса

dump (source, **options) Показать исходный код
# File lib/prism/ffi.rb, line 238
def dump(source, **options)
  LibRubyParser::PrismString.with_string(source) { |string| dump_common(string, options) }
end

Реализует API Prism.dump с помощью API сериализации.

dump_file (filepath, **options) Показать исходный код
# File lib/prism/ffi.rb, line 243
def dump_file(filepath, **options)
  options[:filepath] = filepath
  LibRubyParser::PrismString.with_file(filepath) { |string| dump_common(string, options) }
end

Реализует API Prism.dump_file с помощью API сериализации.

lex (code, **options) Показать исходный код
# File lib/prism/ffi.rb, line 249
def lex(code, **options)
  LibRubyParser::PrismString.with_string(code) { |string| lex_common(string, code, options) }
end

Реализует API Prism.lex с помощью API сериализации.

Prism::lex_compat(source, **options) → LexCompat::Result Показать исходный код
# File lib/prism.rb, line 68
def self.lex_compat(source, **options)
  LexCompat.new(source, **options).result # steep:ignore
end

Возвращает результат разбора, значением которого является массив токенов, очень похожий на возвращаемое значение Ripper::lex. Главное отличие состоит в том, что токен :on_sp не создаётся.

Список поддерживаемых параметров см. в описании Prism::parse.

lex_file (filepath, **options) Показать исходный код
# File lib/prism/ffi.rb, line 254
def lex_file(filepath, **options)
  options[:filepath] = filepath
  LibRubyParser::PrismString.with_file(filepath) { |string| lex_common(string, string.read, options) }
end

Реализует API Prism.lex_file с помощью API сериализации.

Prism::lex_ripper(source) → Array Показать исходный код
# File lib/prism.rb, line 78
def self.lex_ripper(source)
  LexRipper.new(source).result # steep:ignore
end

Выполняет лексический анализ с помощью лексера Ripper. Он отбрасывает события пробелов, но в остальном возвращает те же токены. Если синтаксис в исходном коде некорректен, вызывает SyntaxError.

Prism::load(source, serialized, freeze) → ParseResult Показать исходный код
# File lib/prism.rb, line 86
def self.load(source, serialized, freeze = false)
  Serialize.load_parse(source, serialized, freeze)
end

Загружает сериализованное AST в дерево, используя исходный код в качестве ссылки.

parse (code, **options) Показать исходный код
# File lib/prism/ffi.rb, line 260
def parse(code, **options)
  LibRubyParser::PrismString.with_string(code) { |string| parse_common(string, code, options) }
end

Реализует API Prism.parse с помощью API сериализации.

parse_comments (code, **options) Показать исходный код
# File lib/prism/ffi.rb, line 298
def parse_comments(code, **options)
  LibRubyParser::PrismString.with_string(code) { |string| parse_comments_common(string, code, options) }
end

Реализует API Prism.parse_comments с помощью API сериализации.

parse_failure? (code, **options) Показать исходный код
# File lib/prism/ffi.rb, line 327
def parse_failure?(code, **options)
  !parse_success?(code, **options)
end

Реализует API Prism.parse_failure? с помощью API сериализации.

parse_file (filepath, **options) Показать исходный код
# File lib/prism/ffi.rb, line 267
def parse_file(filepath, **options)
  options[:filepath] = filepath
  LibRubyParser::PrismString.with_file(filepath) { |string| parse_common(string, string.read, options) }
end

Реализует API Prism.parse_file с помощью API сериализации. Здесь используются нативные строки вместо строк Ruby, поскольку это позволяет применять mmap, если он доступен.

parse_file_comments (filepath, **options) Показать исходный код
# File lib/prism/ffi.rb, line 305
def parse_file_comments(filepath, **options)
  options[:filepath] = filepath
  LibRubyParser::PrismString.with_file(filepath) { |string| parse_comments_common(string, string.read, options) }
end

Реализует API Prism.parse_file_comments с помощью API сериализации. Здесь используются нативные строки вместо строк Ruby, поскольку это позволяет применять mmap, если он доступен.

parse_file_failure? (filepath, **options) Показать исходный код
# File lib/prism/ffi.rb, line 338
def parse_file_failure?(filepath, **options)
  !parse_file_success?(filepath, **options)
end

Реализует API Prism.parse_file_failure? с помощью API сериализации.

parse_file_success? (filepath, **options) Показать исходный код
# File lib/prism/ffi.rb, line 332
def parse_file_success?(filepath, **options)
  options[:filepath] = filepath
  LibRubyParser::PrismString.with_file(filepath) { |string| parse_file_success_common(string, options) }
end

Реализует API Prism.parse_file_success? с помощью API сериализации.

parse_lex (code, **options) Показать исходный код
# File lib/prism/ffi.rb, line 311
def parse_lex(code, **options)
  LibRubyParser::PrismString.with_string(code) { |string| parse_lex_common(string, code, options) }
end

Реализует API Prism.parse_lex с помощью API сериализации.

parse_lex_file (filepath, **options) Показать исходный код
# File lib/prism/ffi.rb, line 316
def parse_lex_file(filepath, **options)
  options[:filepath] = filepath
  LibRubyParser::PrismString.with_file(filepath) { |string| parse_lex_common(string, string.read, options) }
end

Реализует API Prism.parse_lex_file с помощью API сериализации.

parse_stream (stream, **options) Показать исходный код
# File lib/prism/ffi.rb, line 273
def parse_stream(stream, **options)
  LibRubyParser::PrismBuffer.with do |buffer|
    source = +""
    callback = -> (string, size, _) {
      raise "Expected size to be >= 0, got: #{size}" if size <= 0

      if !(line = stream.gets(size - 1)).nil?
        source << line
        string.write_string("#{line}\x00", line.bytesize + 1)
      end
    }

    eof_callback = -> (_) { stream.eof?  }

    # In the pm_serialize_parse_stream function it accepts a pointer to the
    # IO object as a void* and then passes it through to the callback as the
    # third argument, but it never touches it itself. As such, since we have
    # access to the IO object already through the closure of the lambda, we
    # can pass a null pointer here and not worry.
    LibRubyParser.pm_serialize_parse_stream(buffer.pointer, nil, callback, eof_callback, dump_options(options))
    Prism.load(source, buffer.read, options.fetch(:freeze, false))
  end
end

Реализует API Prism.parse_stream с помощью API сериализации.

parse_success? (code, **options) Показать исходный код
# File lib/prism/ffi.rb, line 322
def parse_success?(code, **options)
  LibRubyParser::PrismString.with_string(code) { |string| parse_file_success_common(string, options) }
end

Реализует API Prism.parse_success? с помощью API сериализации.

profile (source, **options) Показать исходный код
# File lib/prism/ffi.rb, line 343
def profile(source, **options)
  LibRubyParser::PrismString.with_string(source) do |string|
    LibRubyParser::PrismBuffer.with do |buffer|
      LibRubyParser.pm_serialize_parse(buffer.pointer, string.pointer, string.length, dump_options(options))
      nil
    end
  end
end

Реализует API Prism.profile с помощью API сериализации.

profile_file (filepath, **options) Показать исходный код
# File lib/prism/ffi.rb, line 353
def profile_file(filepath, **options)
  LibRubyParser::PrismString.with_file(filepath) do |string|
    LibRubyParser::PrismBuffer.with do |buffer|
      options[:filepath] = filepath
      LibRubyParser.pm_serialize_parse(buffer.pointer, string.pointer, string.length, dump_options(options))
      nil
    end
  end
end

Реализует API Prism.profile_file с помощью API сериализации.

scope (locals: [], forwarding: []) Показать исходный код
# File lib/prism/parse_result.rb, line 895
def self.scope(locals: [], forwarding: [])
  Scope.new(locals, forwarding)
end

Создаёт новую область видимости с заданными локальными переменными и параметрами перенаправления, подходящую для передачи одному из методов Prism.*, принимающих параметр scopes.

Приватные методы класса

dump_options (options) Показать исходный код
# File lib/prism/ffi.rb, line 449
def dump_options(options)
  template = +""
  values = []

  template << "L"
  if (filepath = options[:filepath])
    values.push(filepath.bytesize, filepath.b)
    template << "A*"
  else
    values << 0
  end

  template << "l"
  values << options.fetch(:line, 1)

  template << "L"
  if (encoding = options[:encoding])
    name = encoding.is_a?(Encoding) ? encoding.name : encoding
    values.push(name.bytesize, name.b)
    template << "A*"
  else
    values << 0
  end

  template << "C"
  values << (options.fetch(:frozen_string_literal, false) ? 1 : 0)

  template << "C"
  values << dump_options_command_line(options)

  template << "C"
  values << dump_options_version(options[:version])

  template << "C"
  values << (options[:encoding] == false ? 1 : 0)

  template << "C"
  values << (options.fetch(:main_script, false) ? 1 : 0)

  template << "C"
  values << (options.fetch(:partial_script, false) ? 1 : 0)

  template << "C"
  values << (options.fetch(:freeze, false) ? 1 : 0)

  template << "L"
  if (scopes = options[:scopes])
    values << scopes.length

    scopes.each do |scope|
      locals = nil
      forwarding = 0

      case scope
      when Array
        locals = scope
      when Scope
        locals = scope.locals

        scope.forwarding.each do |forward|
          case forward
          when :*     then forwarding |= 0x1
          when :**    then forwarding |= 0x2
          when :&     then forwarding |= 0x4
          when :"..." then forwarding |= 0x8
          else raise ArgumentError, "invalid forwarding value: #{forward}"
          end
        end
      else
        raise TypeError, "wrong argument type #{scope.class.inspect} (expected Array or Prism::Scope)"
      end

      template << "L"
      values << locals.length

      template << "C"
      values << forwarding

      locals.each do |local|
        name = local.name
        template << "L"
        values << name.bytesize

        template << "A*"
        values << name.b
      end
    end
  else
    values << 0
  end

  values.pack(template)
end

Преобразует заданные параметры в сериализованную строку параметров.

dump_options_command_line (options) Показать исходный код
# File lib/prism/ffi.rb, line 407
def dump_options_command_line(options)
  command_line = options.fetch(:command_line, "")
  raise ArgumentError, "command_line must be a string" unless command_line.is_a?(String)

  command_line.each_char.inject(0) do |value, char|
    case char
    when "a" then value | 0b000001
    when "e" then value | 0b000010
    when "l" then value | 0b000100
    when "n" then value | 0b001000
    when "p" then value | 0b010000
    when "x" then value | 0b100000
    else raise ArgumentError, "invalid command_line option: #{char}"
    end
  end
end

Возвращает значение, которое следует сериализовать для параметра command_line.

dump_options_version (version) Показать исходный код
# File lib/prism/ffi.rb, line 425
def dump_options_version(version)
  current = version == "current"

  case current ? RUBY_VERSION : version
  when nil, "latest"
    0 # Handled in pm_parser_init
  when /\A3\.3(\.\d+)?\z/
    1
  when /\A3\.4(\.\d+)?\z/
    2
  when /\A3\.5(\.\d+)?\z/, /\A4\.0(\.\d+)?\z/
    3
  when /\A4\.1(\.\d+)?\z/
    4
  else
    if current
      raise CurrentVersionError, RUBY_VERSION
    else
      raise ArgumentError, "invalid version: #{version}"
    end
  end
end

Возвращает значение, которое следует сериализовать для параметра version.

Ruby Core © 1993–2025 Yukihiro Matsumoto
Licensed under the Ruby License.
Ruby Standard Library © contributors
Licensed under their own licenses.

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API