如何检查ruby代码中的ruby语法错误

cim*_*4gt 10 ruby

我现在用以下来检查语法错误:

system "ruby -wc path/to/file.rb"
Run Code Online (Sandbox Code Playgroud)

但是如果有太多的文件(例如,我的重构代码),它非常浪费时间,所以我的问题是:有没有办法在ruby代码中进行ruby语法检查?

Chr*_*ald 6

在MRI下,您可以使用RubyVM::InstructionSequence#compile(相关文档)编译Ruby代码(如果有错误,将抛出异常):

2.1.0 :001 > RubyVM::InstructionSequence.compile "a = 1 + 2"
 => <RubyVM::InstructionSequence:<compiled>@<compiled>>

2.1.0 :002 > RubyVM::InstructionSequence.compile "a = 1 + "
<compiled>:1: syntax error, unexpected end-of-input
a = 1 +
        ^
SyntaxError: compile error
        from (irb):2:in `compile'
        from (irb):2
        from /usr/local/rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'
Run Code Online (Sandbox Code Playgroud)


Mus*_*ify 5

我的经验是,检查我的代码是否正确编译的最简单方法是运行自动化测试。编译器将执行相同的工作,无论是编译运行测试还是仅检查文件在词法上是否正确。

核磁共振

MRI 的解析器是用 C 编写的。我找不到关于如何访问它的具体参考,但我确信有一种方法可以做到这一点。如果有人花一些时间让 Ruby 更加了解 Ruby 就好了……

鲁比纽斯

在 Rubinius 中,可以通过墨尔本直接访问解析器:

rbx-2.2.10 :039 > Rubinius::ToolSets::Runtime::Melbourne.parse_file("./todo.txt")
SyntaxError: expecting keyword_do or '{' or '(': ./todo.txt:2:17
Run Code Online (Sandbox Code Playgroud)

对于有效的 ruby​​ 文件:

rbx-2.2.10 :044 > Rubinius::ToolSets::Runtime::Melbourne.parse_file('./valid.rb')
=> #<Rubinius::ToolSets::Runtime::AST::Class:0x1e6b4 @name=#    <Rubinius::ToolSets::Runtime::AST::ClassName:0x1e6b8 @name=:RubyStuff @line=1 @superclass=#<Rubinius::ToolSets::Runtime::AST::NilLiteral:0x1e6bc @line=1>> @body=#<Rubinius::ToolSets::Runtime::AST::EmptyBody:0x1e6c8 @line=1> @line=1 @superclass=#<Rubinius::ToolSets::Runtime::AST::NilLiteral:0x1e6bc @line=1>>
Run Code Online (Sandbox Code Playgroud)

命令行

您目前正在使用命令行工具来解析 ruby​​。如果您在 Ruby 中循环遍历文件,也许您也应该将其带到命令行并执行以下操作:

jw@logopolis:/projects/open/compile-test$ find . | grep ".rb$" | xargs ruby -c
Syntax OK

jw@logopolis:/projects/open/compile-test$ find . | grep ".rb$" | xargs ruby -c
./invalid.rb:2: expecting $end: ./invalid.rb:2:3
Run Code Online (Sandbox Code Playgroud)

在 Ruby 中看起来像这样:

 system "find . | grep ".rb$" | xargs ruby -c"
Run Code Online (Sandbox Code Playgroud)

参考

http://rubini.us/doc/en/bytecode-compiler/parser/