You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{type: "prog",prog: [// 第一个表达式:{type: "assign",operator: "=",left: {type: "var",value: "sum"},right: {type: "lambda",vars: ["a","b"],body: {// the body should be a "prog", but because// it contains a single expression, our parser// reduces it to the expression itself.type: "binary",operator: "+",left: {type: "var",value: "a"},right: {type: "var",value: "b"}}}},// 第二个表达式:{type: "call",func: {type: "var",value: "print"},args: [{type: "call",func: {type: "var",value: "sum"},args: [{type: "num",value: 1},{type: "num",value: 2}]}]}]}
整篇译文的目录章节如下:
写一个解析器(Parser)
编写一个语言解析器是一个相对稍复杂的任务。本质上,它是通过检测字符的方式将一块代码片段转化成抽象语法树(Abstract Syntax Tree,AST)。AST是程序在内存中的结构化展现,“抽象”意味着不用关心源代码具体是由什么字符组成,只需要把程序的语义表达出来即可。我写了一个单独的章节来描述我们的AST。
例如,对于下面的程序代码:
我们的解析器将会生成如下的AST(一个JavaScript对象):
写解析器的一个主要难点在于如何恰当的组织代码。解析器工作层面要更高,不仅仅是如何从字符串读取字符。下面是将复杂度做到可控的几点建议:
为了便于理解,会将实现代码分成三部分,各部分会进一步拆分成许多小的函数:
The text was updated successfully, but these errors were encountered: