Skip to content

代码检查器架构

🌐 Linter Architecture

本文最初发表于 leaysgur.github.io/posts,作者为 @leaysgur

🌐 This article is originally posted on leaysgur.github.io/posts by @leaysgur.

apps/oxlint

oxlint 二进制文件是从 apps/oxlint crate 构建 main.rs 的结果。

🌐 The oxlint binary is the result of building main.rs from the apps/oxlint crate.

Cargo.toml 配置

这里,它解析参数然后运行 LintRunner

🌐 Here, it parses arguments and then runs the LintRunner.

Lint 执行流程

crates/oxc_diagnostics

LintServicempsc::channel 发送器传递给 oxc_diagnostics 以接收 lint 结果。

🌐 The LintService passes the mpsc::channel Sender to oxc_diagnostics to receive lint results.

接收 Lint 结果

它格式化并显示收到的消息。格式化由 miette crate 完成。

🌐 It formats and displays the received messages. The formatting is done by the miette crate.

miette Crate 参考

crates/oxc_linter

LintService 开始:

🌐 Starting with the LintService:

  • self.runtime 作为 Arc<Runtime> 使用
  • Runtime 保存用于 lint 的路径
  • 运行时,它使用 rayon 并行遍历 Runtime 路径
  • 它发送一个 None 来完成

LintService 实现

Runtime: process_path()

  • 从路径推断扩展名和内容
  • 支持“.[m|c]?[j|t]s”或“.[j|t]sx”扩展
  • .vue.astro.svelte 的例外,部分支持 script
  • 处理 JavaScript 和 TypeScript 源代码
  • 执行 linting 并将结果发送到 'DiagnosticService'

运行时路径处理

Runtimeprocess_source()

🌐 Runtime: process_source()

  • 使用解析器将源代码处理为抽象语法树
  • 从“SemanticBuilder”创建一个“LintContext”,并通过“Linter”运行

[运行时源处理](https://github.com/oxc-project/oxc/blob/oxlint_v0.2.0/crates/oxc_linter/src/service.rs#L206)

crates/oxc_semantic: SemanticBuilder

SemanticBuilder 构建从源中提取的语义信息。

语义构建器源

  • source_text:源代码
  • nodes:AST 节点
  • classes:课程
  • scopes:作用域
  • trivias:评论
  • jsdoc: JSDoc
  • 等等

SemanticBuilder 构建时,它会生成 SemanticBuilderReturn,但只有 Semantic 被传递给 LintContext

🌐 When SemanticBuilder builds, it generates SemanticBuilderReturn, but only Semantic is passed to LintContext.

语义构建器返回

crates/oxc_linter: LintContext

LintContext 来源

表示上下文,Semantic 为主体。它包括每条信息的 getter 方法,以及像 diagnostic() 这样的用于通知代码检查问题的方法。

🌐 Represents the context, with Semantic as the main body. It includes getters for each piece of information and methods like diagnostic() to notify of linting issues.

crates/oxc_linter: Linter

Linter 来源

这个 Linterrun() 功能是代码检查过程的核心。

🌐 The run() function of this Linter is the core of the linting process.

  • Linter 保存了在 self.rules 中针对目标源执行的规则
  • 每条规则可以根据特性实现三种类型的处理
  • 它按顺序执行这三种模式

有关当前实现的规则,请参阅此列表。

🌐 For the currently implemented rules, refer to this list.

[已实现规则](https://github.com/oxc-project/oxc/blob/oxlint_v0.2.0/crates/oxc_linter/src/rules.rs)

在添加新规则时,别忘了更新此列表。

🌐 For adding new rules, remember to update this list.

代码检查示例

🌐 Linter Example

该仓库提供了创建代码检查器的最小代码配置。

🌐 The repository provides the minimum code configuration for creating a linter.

最小化 Linter 代码