Rubocop 如何静态检查 ruby 语法错误

How does Rubocop statically check for ruby syntax errors

Rubocop 如何静态检查 ruby 语法错误?由于 Ruby 是一种动态语言,如果您不使用 Rubocop 那么您是否只会在 运行 期间收到语法错误通知? IE。当你的 运行 你的程序会因为语法错误而崩溃?

您甚至不需要像 Rubocop 这样的工具。 Ruby 本身可以在不执行代码的情况下检查语法:

$ ruby --help
Usage: ruby [switches] [--] [programfile] [arguments]
[...]
-c              check syntax only
[...]

让我们检查它是否发现语法错误:

$ ruby -c -e "def; end"
-e:1: syntax error, unexpected ';'

Ruby先读取并解析源​​码,然后再执行。如果解析的第一步已经失败,因为代码没有任何意义,那么无论如何执行都是不可能的。发现语法错误的不是执行,而是代码的解析。

但是当然有一些错误是 Ruby 没有发现的,但是其他编程语言在编译代码时会检测到。例如 TypeError:

$ ruby -c -e "[1,2][:bar]"
Syntax OK

语法没问题,但这段代码真的有效吗?

$ ruby -e "[1,2][:bar]"
Traceback (most recent call last):
-e:1:in `<main>': no implicit conversion of Symbol into Integer (TypeError)

RuboCop 使用 parser gem. The gem provides some diagnostics information when it encounters syntax errors while parsing. RuboCop simply re-packages the parsing error inside the Lint/Syntax cop,并使用诊断信息来创建带有漂亮错误消息的 RuboCop 攻击。