首页
/ Sourcify 项目技术文档

Sourcify 项目技术文档

2024-12-20 04:51:09作者:盛欣凯Ernestine

1. 安装指南

1.1 安装前提

  • Ruby 版本:Sourcify 是为 Ruby 1.9.x 编写的,不建议在更高版本的 Ruby 中使用。
  • 项目状态:Sourcify 已不再维护,使用时需自行承担风险,不保证修复任何 bug。

1.2 安装步骤

1.2.1 标准安装方式

在 Ruby 1.8.x 或更低版本中,使用以下命令安装:

$ gem install ParseTree sourcify

1.2.2 Ruby 1.9.x 或 JRuby 安装方式

在 Ruby 1.9.x 或 JRuby 中,使用以下命令安装:

$ gem install ruby_parser file-tail sourcify

2. 项目使用说明

2.1 概述

Sourcify 是一个用于提取 Proc 代码的统一解决方案。它可以在 ParseTree 可用时作为其薄包装器使用,否则使用自制的 Ragel 生成的扫描器来提取 Proc 代码。

2.2 主要功能

Sourcify 为 ProcMethod 类添加了多个方法,用于提取代码和 S-表达式。

2.2.1 Proc#to_source

返回 Proc 的代码表示:

require 'sourcify'

lambda { x + y }.to_source
# >> "proc { (x + y) }"

2.2.2 Proc#to_sexp

返回 Proc 的 S-表达式:

require 'sourcify'

lambda { x + y }.to_sexp
# >> s(:iter, s(:call, nil, :proc, s(:arglist)), nil, s(:call, s(:lvar, :x), :+, s(:arglist, s(:call, nil, :y, s(:arglist)))))

2.2.3 Proc#to_raw_source

返回 Proc 的原始代码,包括注释等:

lambda do |i|
  i+1 # (blah)
end.to_raw_source
# >> "proc do |i|
# >>   i+1 # (blah)
# >> end"

2.2.4 Proc#source_location

返回 Proc 的源代码位置(仅在 Ruby 1.9.x 中可用):

require 'sourcify'

lambda { x + y }.source_location
# >> ["/tmp/test.rb", 5]

2.3 Method 类扩展

Sourcify 还为 Method 类添加了类似的方法,但仅在 MRI-1.9.2 中支持。

2.3.1 Method#to_source

返回方法的代码表示:

require 'sourcify'

class MyMath
  def self.sum(x, y)
    x + y # (blah)
  end
end

MyMath.method(:sum).to_source
# >> "def sum(x, y)
# >>   (x + y)
# >> end"

2.3.2 Method#to_sexp

返回方法的 S-表达式:

MyMath.method(:sum).to_sexp
# >> s(:defn, :sum, s(:args, :x, :y), s(:scope, s(:block, s(:call, s(:lvar, :x), :+, s(:arglist, s(:lvar, :y))))))

2.3.3 Method#to_raw_source

返回方法的原始代码,包括注释等:

MyMath.method(:sum).to_raw_source
# >> "def sum(x, y)
# >>   x + y # (blah)
# >> end"

3. 项目API使用文档

3.1 Proc 类 API

  • Proc#to_source(options = {}):返回 Proc 的代码表示。
  • Proc#to_sexp(options = {}):返回 Proc 的 S-表达式。
  • Proc#to_raw_source(options = {}):返回 Proc 的原始代码。
  • Proc#source_location:返回 Proc 的源代码位置。

3.2 Method 类 API

  • Method#to_source(options = {}):返回方法的代码表示。
  • Method#to_sexp(options = {}):返回方法的 S-表达式。
  • Method#to_raw_source(options = {}):返回方法的原始代码。

4. 项目安装方式

4.1 标准安装

$ gem install ParseTree sourcify

4.2 Ruby 1.9.x 或 JRuby 安装

$ gem install ruby_parser file-tail sourcify

5. 注意事项

  • 性能:当前性能较差,尤其是在处理大量 Proc 时。
  • 已知问题:静态代码扫描存在一些限制,如无法处理 eval 生成的代码、同一行多个 Proc 等问题。

通过以上文档,您应该能够顺利安装和使用 Sourcify 项目,并了解其主要功能和 API 的使用方法。

登录后查看全文
热门项目推荐