Typescript 源码核心流程
1. 命令行参数解析
文件: src/tsc/tsc.ts
功能: tsc.ts 是 TypeScript 编译器的入口文件,它负责解析命令行参数并启动编译过程。
// src/tsc/tsc.ts
import * as ts from "../compiler/_namespaces/ts";
import { executeCommandLine } from "../compiler/tsc";const commandLine = ts.parseCommandLine(ts.sys.args);
executeCommandLine(commandLine);
2. 配置文件解析
文件: src/compiler/commandLineParser.ts
功能: 该文件处理 tsconfig.json 配置文件的解析,并将解析结果转换为编译器选项。
// src/compiler/commandLineParser.ts
import { readJsonConfigFile, parseJsonSourceFileConfigFileContent } from "./tsconfig";export function parseCommandLine(args: string[]): ParsedCommandLine {// 解析 tsconfig.json 文件const configFile = readJsonConfigFile("tsconfig.json", sys.readFile);return parseJsonSourceFileConfigFileContent(configFile, sys, "./");
}
3. 文件解析
文件: src/compiler/program.ts
功能: program.ts 负责创建编译器的程序实例,解析所有输入文件并创建源文件对象。
// src/compiler/program.ts
export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program {// 创建并解析程序const program = new Program(rootNames, options, host);program.parse();return program;
}
4. 词法分析
文件:src/compiler/scanner.ts
功能:scanner.ts 负责将输入的 TypeScript 源代码转换为一系列的词法单元。
// src/compiler/scanner.ts
export function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean): Scanner {return new Scanner(languageVersion, skipTrivia);
}class Scanner {// 实现扫描器的核心逻辑
}
5. 语法分析
文件:src/compiler/parser.ts
功能:该文件包含将 TypeScript 代码转换为抽象语法树的逻辑,是 TypeScript 语法解析的核心。
// src/compiler/parser.ts
export function parseSourceFile(fileName: string, sourceText: string): SourceFile {// 将源码文本转换为 ASTreturn createSourceFile(fileName, sourceText, ScriptTarget.Latest);
}
6. 类型检查
文件:src/compiler/checker.ts
功能:checker.ts 包含类型检查器的主要逻辑,负责遍历 AST 并执行类型检查。
// src/compiler/checker.ts
export function getTypeChecker(program: Program): TypeChecker {// 返回类型检查器return new TypeChecker(program);
}export class TypeChecker {constructor(private program: Program) {}public checkSourceFile(sourceFile: SourceFile): void {// 对 AST 进行类型检查this.checkNode(sourceFile);}
}
7. 代码生成
文件:src/compiler/emitter.ts
功能:emitter.ts 负责将类型检査后的 AST 转换为 JavaScript 代码。
// src/compiler/emitter.ts
export function emitFiles(program: Program): EmitResult {const emitter = new Emitter(program);return emitter.emit();
}export class Emitter {constructor(private program: Program) {}public emit(): EmitResult {// 将 AST 转换为 JavaScript 代码return this.emitSourceFiles();}
}
8. 输出结果
文件:src/tsc/tsc.ts和src/compiler/sys.ts
功能:tsc.ts 负责输出编译结果, sys.ts 负责文件系统的交互,用于写入生成的 JavaScript 文件。
// src/tsc/tsc.ts
import * as ts from "../compiler/_namespaces/ts";
import { createProgram } from "../compiler/program";
import { sys } from "../compiler/sys";export function executeCommandLine(commandLine: ParsedCommandLine): void {const program = createProgram(commandLine.fileNames, commandLine.options);const emitResult = program.emit();sys.writeFile("output.js", emitResult.outputText);
}