TypeScript AST 转换删除所有空行

TypeScript AST transformation removes all blank lines

我编写了一个 VS Code 扩展,它使用 TypeScrpt AST API 来组织 class 成员。我的问题是,在 运行 ts.transform(...) 之后,将转换后的语法树转换回文本,所有空行都丢失了,导致生成的源代码格式不正确。如何防止 AST API 删除空行?

我正在使用的代码示例:

let sourceFile: ts.SourceFile;
let sourceCode: string;

sourceCode = editor.document.getText();
sourceFile = ts.createSourceFile(editor.document.fileName, sourceCode, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
  transformation = ts.transform(sourceFile, [organizeTransformer]);
  sourceCode = transformation.transformed[0].getFullText();

解析器不是代码格式化的最佳工具:

  • 要求输入无误。
  • 它通常会跳过白色spaces + 注释,因为它们与解析无关。
  • AST/parse 树以最适合语言处理而非代码生成的方式表示输入结构。

事实上漂亮的打印根本不需要解析。它是源到源的转换,所需要的只是一个词法分析器,用于识别各种类型的输入元素(因为它们与格式相关,特别是 whitespaces + comments)。您可以在 my vscode extension vscode-antlr4 中看到一种实现代码格式化程序的方法。原理很简单:为列表(包括注释)中的每个非白色 space 元素收集源位置(不是源文本)。也添加格式 whitespaces。然后通过将原始文本复制到输出来从此列表生成新文本。这避免了引号、数字基数、注释类型等方面的麻烦,解析器可能会以使其处理更容易的方式进行转换,但不一定代表原始形式。

解决方法:

  • 用注释替换空行
  • 变换
  • 用空行替换注释

    import {decodeEmptyLines, encodeEmptyLines} from 'ts-empty-line-encoder';
    
    let sourceCode = editor.document.getText();
    //encode empty lines
    sourceCode = encodeEmptyLines(sourceCode);
    const sourceFile = ts.createSourceFile(editor.document.fileName, sourceCode, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
    const transformation = ts.transform(sourceFile, [organizeTransformer]);
    sourceCode = transformation.transformed[0].getFullText();
    //decode empty lines
    sourceCode = decodeEmptyLines(sourceCode);