Correctly output escapes in directives (#9501)

This commit is contained in:
Nicolò Ribaudo
2019-02-15 21:08:45 +01:00
committed by GitHub
parent 0f685d9b42
commit 83cbc11d46
4 changed files with 73 additions and 2 deletions

View File

@@ -50,8 +50,35 @@ export function Directive(node: Object) {
this.semicolon();
}
// These regexes match an even number of \ followed by a quote
const unescapedSingleQuoteRE = /(?:^|[^\\])(?:\\\\)*'/;
const unescapedDoubleQuoteRE = /(?:^|[^\\])(?:\\\\)*"/;
export function DirectiveLiteral(node: Object) {
const raw = this.getPossibleRaw(node);
if (raw != null) {
this.token(raw);
return;
}
const { value } = node;
// NOTE: In directives we can't change escapings,
// because they change the behavior.
// e.g. "us\x65 string" (\x65 is e) is not a "use strict" directive.
if (!unescapedDoubleQuoteRE.test(value)) {
this.token(`"${value}"`);
} else if (!unescapedSingleQuoteRE.test(value)) {
this.token(`'${value}'`);
} else {
throw new Error(
"Malformed AST: it is not possible to print a directive containing" +
" both unescaped single and double quotes.",
);
}
}
export function InterpreterDirective(node: Object) {
this.token(`#!${node.value}\n`);
}
export { StringLiteral as DirectiveLiteral } from "./types";