Skip to main content

0

解析器 TypeScript 解析器的源代码完全位于 parser.tsScanner 由内部控制 Parser 以将源代码转换为 AST 。这是对期望结果的回顾。

SourceCode ~~ scanner ~~> Token Stream ~~ parser ~~> AST 解析器被实现为单例(类似的原因 scanner,如果我们可以重新初始化它,就不想重新创建它)。它实际上被实现为 namespace Parser 其中包含 Parser 的状态变量以及单例 scanner。如前所述,它包含一个 const scanner. 解析器函数管理这个扫描器。

按程序使用 Parser 是由 Program 间接驱动的(正如 CompilerHost 我们之前提到的那样,它实际上是间接驱动的)。基本上这是简化的调用堆栈:

Program -> CompilerHost.getSourceFile -> (global function parser.ts).createSourceFile -> Parser.parseSourceFile parseSourceFile 不仅为 Parser 初始化状态,而且还通过调用为初始化 scanner 状态 initializeState。然后它继续使用 parseSourceFileWorker.

示例使用

在我们深入研究解析器内部之前,这里有一个示例代码,它使用 TypeScript 的解析器获取源文件的 AST (使用 ts.createSourceFile),然后打印它。

code/compiler/parser/runParser.ts
import * as ts from "ntypescript";

function printAllChildren(node: ts.Node, depth = 0) {
console.log(
new Array(depth + 1).join("----"),
ts.syntaxKindToName(node.kind),
node.pos,
node.end
);
depth++;
node.getChildren().forEach((c) => printAllChildren(c, depth));
}

var sourceCode = `var foo = 123;`.trim();

var sourceFile = ts.createSourceFile(
"foo.ts",
sourceCode,
ts.ScriptTarget.ES5,
true
);
printAllChildren(sourceFile);

这将打印出以下内容:

SourceFile 0 14
---- SyntaxList 0 14
-------- VariableStatement 0 14
------------ VariableDeclarationList 0 13
---------------- VarKeyword 0 3
---------------- SyntaxList 3 13
-------------------- VariableDeclaration 3 13
------------------------ Identifier 3 7
------------------------ FirstAssignment 7 9
------------------------ FirstLiteralToken 9 13
------------ SemicolonToken 13 14
---- EndOfFileToken 14 14

如果您将头向左倾斜,这看起来像一棵(非常右侧的)树。