Compiler Principle

What does compiler do ?

Map the source program to a semantically equivalent target program.

There are two stages in this mapping process:

  1. analysis: the frontend of compiler

  2. synthesis: the backend of compiler

https://cdn.jsdelivr.net/gh/gaohongy/cloudImages@master/202403122106578.png

词法分析(Lexical Analysis):

将源代码转换为标记(token)序列,识别出代码中的基本单位(如关键字、标识符、常量、运算符等),并移除注释和不必要的空白字符。此过程可通过构造有限自动机来实现。

1
<token-name, attribute-value>

example:

对赋值语句 position = initial + rate * 64 进行词法分析,形成词法单元序列 <id, 1> < = > <id, 2> < + > <id, 3> < * > <64>

语法分析(Syntax Analysis):

根据语法规则检查标记序列是否符合编程语言的语法结构。将标记序列转换为语法树(Parse Tree)或者抽象语法树(Abstract Syntax Tree),以便后续阶段的处理。此过程可通过递归下降算法实现。

关于 AST 的一个生活化示例:

表达式:“我喜欢又聪明又勇敢的你”,语法分析的结果如下图所示:

https://cdn.jsdelivr.net/gh/gaohongy/cloudImages@master/202405181703327.png

对于词法分析一节给出的表达式,语法分析的结果如下图所示

https://cdn.jsdelivr.net/gh/gaohongy/cloudImages@master/202405181714030.png

从上图不难看出,AST 对应的就是中缀表达式,转换为这种格式更加便于计算机进行处理。

语义分析(Semantic Analysis):

检查代码中的语义是否合法,即代码是否符合语言的语义规则。这包括类型检查、作用域检查、语义错误检查等,以确保代码在逻辑上是正确的。

消除语义模糊,生成属性信息标注在 AST 中,以便后续生成目标代码。

0%