Skip to content

每日一报

JS的解析流程

JavaScript 的解析流程通常包括以下几个阶段:词法分析、语法分析、语义分析、优化和代码生成。以下是每个阶段的详细说明:

词法分析

词法分析是编译器和解释器的第一个阶段,其主要任务是将源代码转换为一系列的标记(tokens)。这些标记是代码中最小的语法单位,如关键字、标识符、运算符、字面量等。

词法分析的过程

  1. 输入: 源代码字符串。
  2. 输出: 标记序列(tokens)。
  3. 任务: 扫描源代码,识别并提取出有意义的词法单元。

词法分析的步骤

  1. 去除空白和注释: 忽略空格、换行符和注释,因为它们对语法结构没有影响。

  2. 识别标记: 根据语言的词法规则,识别出不同类型的标记。常见的标记类型包括:

    • 关键字: 如 if, else, while, return 等。
    • 标识符: 如 变量名函数名
    • 字面量: 如 数字字符串布尔值
    • 运算符: 如 +, -, *, /, == 等。
    • 分隔符: 如 ;, ,, (, ) 等。
  3. 生成标记: 为每个识别出的词法单元生成一个标记,通常包含标记的类型和其在源代码中的值。

词法分析器的实现

词法分析器通常使用有限状态机(FSM)来实现。它通过状态转换来识别不同的词法单元。

示例: 解析简单的赋值语句 let x = 10;

  • 输入: let x = 10;
  • 输出: 标记序列
    • let (关键字)
    • x (标识符)
    • = (运算符)
    • 10 (数字字面量)
    • ; (分隔符)

语法分析(Syntax Analysis)

目标: 将源代码转换为抽象语法树(AST),以便于进一步的分析和处理。

过程:

  • 输入: 词法分析器生成的标记(tokens)。
  • 输出: 抽象语法树(AST)。
  • 任务: 检查代码的语法结构是否符合语言的语法规则。语法分析器通过解析器(如递归下降解析器)来识别代码中的语法结构,并构建相应的 AST。

示例:

  • 识别变量声明、函数定义、控制结构(如 if、for)等。
  • 确保括号、花括号等符号正确匹配。

语义分析(Semantic Analysis)

目标: 确保代码的语义正确,即代码的逻辑和意义符合语言的语义规则。

过程:

  • 输入: 抽象语法树(AST)。
  • 输出: 经过验证和注释的 AST,或中间表示(IR)。
  • 任务: 检查代码的语义正确性,包括类型检查、作用域解析、变量绑定等。语义分析器通常会在 AST 上进行遍历,检查和注释节点。

示例:

  • 确保变量在使用前已声明。
  • 检查类型兼容性(如不能将字符串赋值给整数变量)。
  • 确保函数调用的参数和返回值类型正确。

语法分析和语义分析的区别

  • 语法分析关注代码的结构和形式,确保代码符合语言的语法规则。
  • 语义分析关注代码的逻辑和意义,确保代码的行为符合语言的语义规则。

在编译器的实现中,语法分析通常在语义分析之前进行,因为语义分析需要依赖于语法分析生成的 AST。

Contributors

Changelog

Discuss

Released under the CC BY-SA 4.0 License. (b3f0201)

Layout Switch

Adjust the layout style of VitePress to adapt to different reading needs and screens.

Expand all
The sidebar and content area occupy the entire width of the screen.
Expand sidebar with adjustable values
Expand sidebar width and add a new slider for user to choose and customize their desired width of the maximum width of sidebar can go, but the content area width will remain the same.
Expand all with adjustable values
Expand sidebar width and add a new slider for user to choose and customize their desired width of the maximum width of sidebar can go, but the content area width will remain the same.
Original width
The original layout width of VitePress

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.

Spotlight

Highlight the line where the mouse is currently hovering in the content to optimize for users who may have reading and focusing difficulties.

ONOn
Turn on Spotlight.
OFFOff
Turn off Spotlight.