Skip to content

bug(Printer): LF newline in template strings is escaped when it shouldn't be #59150

Closed
@maxpatiiuk

Description

@maxpatiiuk

πŸ”Ž Search Terms

template strings new line newline escape LF backslash emit print

πŸ•— Version & Regression Information

⏯ Playground Link

https://github.com/maxpatiiuk/typescript-bug-needless-lf-escaping/tree/main

πŸ’» Code

import ts from 'typescript';

const expression = ts.factory.createNoSubstitutionTemplateLiteral('\n');

const printer = ts.createPrinter();
// LF new line gets escaped by the printer:
const printed = printer.printNode(
  ts.EmitHint.Unspecified,
  expression,
  ts.createSourceFile('index.ts', '', ts.ScriptTarget.Latest)
);

// Expected \n
// Received \\n
console.log(printed);
if (printed === '`\n`') console.log('Correct');
else if (printed === '`\\n`') console.error('Incorrect');

πŸ™ Actual behavior

LF new lines in template literal strings are escaped

πŸ™‚ Expected behavior

As the comment in TypeScript's source code states, LF new lines in backticks should not be escaped:

// Template strings preserve simple LF newlines, still encode CRLF (or CR)
const backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g;

https://github.com/microsoft/TypeScript/blame/3163fe7e3898c1f48cd9bc097b96e3426cd2a453/src/compiler/utilities.ts#L5925-L5926

However, that RegExp has a bug - the regex has a \u0000-\u001f character range, which includes the LF character (\u000a)

/[\u0000-\u001f]/.test('\n')
// -> true

The RegExp should be modified to not match \u000a (\n). Potentially like so:

- const backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g;
+ const backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u0009\u000b-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g;

Additional information about the issue

No response

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptDomain: TransformsRelates to the public transform APIFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

    Development

    Participants

    @DanielRosenwasser@andrewbranch@rbuckton@typescript-bot@maxpatiiuk

    Issue actions

      bug(Printer): LF newline in template strings is escaped when it shouldn't be Β· Issue #59150 Β· microsoft/TypeScript