10000 fix(eslint-plugin): [no-unnecessary-template-expression] do not render escaped strings in autofixes by auvred · Pull Request #8688 · typescript-eslint/typescript-eslint · GitHub
[go: up one dir, main page]

Skip to content

fix(eslint-plugin): [no-unnecessary-template-expression] do not render escaped strings in autofixes #8688

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jul 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
188 changes: 145 additions & 43 deletions packages/eslint-plugin/src/rules/no-unnecessary-template-expression.ts
8000
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,23 @@ import {
createRule,
getConstrainedTypeAtLocation,
getParserServices,
getStaticStringValue,
isTypeFlagSet,
isUndefinedIdentifier,
} from '../util';

type MessageId = 'noUnnecessaryTemplateExpression';

const evenNumOfBackslashesRegExp = /(?<!(?:[^\\]|^)(?:\\\\)*\\)/;

// '\\$' <- false
// '\\\\$' <- true
// '\\\\\\$' <- false
function endsWithUnescapedDollarSign(str: string): boolean {
return new RegExp(String(evenNumOfBackslashesRegExp.source) + '\\$$').test(
str,
);
}

export default createRule<[], MessageId>({
name: 'no-unnecessary-template-expression',
meta: {
Expand Down Expand Up @@ -53,11 +63,15 @@ export default createRule<[], MessageId>({
return isString(type);
}

function isLiteral(expression: TSESTree.Expression): boolean {
function isLiteral(
expression: TSESTree.Expression,
): expression is TSESTree.Literal {
return expression.type === AST_NODE_TYPES.Literal;
}

function isTemplateLiteral(expression: TSESTree.Expression): boolean {
function isTemplateLiteral(
expression: TSESTree.Expression,
): expression is TSESTree.TemplateLiteral {
return expression.type === AST_NODE_TYPES.TemplateLiteral;
}

Expand Down Expand Up @@ -113,62 +127,150 @@ export default createRule<[], MessageId>({
return;
}

const fixableExpressions = node.expressions.filter(
expression =>
isLiteral(expression) ||
isTemplateLiteral(expression) ||
isUndefinedIdentifier(expression) ||
isInfinityIdentifier(expression) ||
isNaNIdentifier(expression),
);
const fixableExpressions = node.expressions
.filter(
expression =>
isLiteral(expression) ||
isTemplateLiteral(expression) ||
isUndefinedIdentifier(expression) ||
isInfinityIdentifier(expression) ||
isNaNIdentifier(expression),
)
.reverse();

let nextCharacterIsOpeningCurlyBrace = false;

for (const expression of fixableExpressions) {
const fixers: ((fixer: TSESLint.RuleFixer) => TSESLint.RuleFix[])[] =
[];
const index = node.expressions.indexOf(expression);
const prevQuasi = node.quasis[index];
const nextQuasi = node.quasis[index + 1];

if (nextQuasi.value.raw.length !== 0) {
nextCharacterIsOpeningCurlyBrace =
nextQuasi.value.raw.startsWith('{');
}

if (isLiteral(expression)) {
let escapedValue = (
typeof expression.value === 'string'
? // The value is already a string, so we're removing quotes:
// "'va`lue'" -> "va`lue"
expression.raw.slice(1, -1)
: // The value may be one of number | bigint | boolean | RegExp | null.
// In regular expressions, we escape every backslash
String(expression.value).replace(/\\/g, '\\\\')
)
// The string or RegExp may contain ` or ${.
// We want both of these to be escaped in the final template expression.
//
// A pair of backslashes means "escaped backslash", so backslashes
// from this pair won't escape ` or ${. Therefore, to escape these
// sequences in the resulting template expression, we need to escape
// all sequences that are preceded by an even number of backslashes.
//
// This RegExp does the following transformations:
// \` -> \`
// \\` -> \\\`
// \${ -> \${
// \\${ -> \\\${
.replace(
new RegExp(
String(evenNumOfBackslashesRegExp.source) + '(`|\\${)',
'g',
),
'\\$1',
);

// `...${'...$'}{...`
// ^^^^
if (
nextCharacterIsOpeningCurlyBrace &&
endsWithUnescapedDollarSign(escapedValue)
) {
escapedValue = escapedValue.replaceAll(/\$$/g, '\\$');
}

if (escapedValue.length !== 0) {
nextCharacterIsOpeningCurlyBrace = escapedValue.startsWith('{');
}

fixers.push(fixer => [fixer.replaceText(expression, escapedValue)]);
} else if (isTemplateLiteral(expression)) {
// Since we iterate from the last expression to the first,
// a subsequent expression can tell the current expression
// that it starts with {.
//
// `... ${`... $`}${'{...'} ...`
// ^ ^ subsequent expression starts with {
// current expression ends with a dollar sign,
// so '$' + '{' === '${' (bad news for us).
// Let's escape the dollar sign at the end.
if (
nextCharacterIsOpeningCurlyBrace &&
endsWithUnescapedDollarSign(
expression.quasis[expression.quasis.length - 1].value.raw,
)
) {
fixers.push(fixer => [
fixer.replaceTextRange(
[expression.range[1] - 2, expression.range[1] - 2],
'\\',
),
]);
}
if (
expression.quasis.length === 1 &&
expression.quasis[0].value.raw.length !== 0
) {
nextCharacterIsOpeningCurlyBrace =
expression.quasis[0].value.raw.startsWith('{');
}

// Remove the beginning and trailing backtick characters.
fixers.push(fixer => [
fixer.removeRange([expression.range[0], expression.range[0] + 1]),
fixer.removeRange([expression.range[1] - 1, expression.range[1]]),
]);
} else {
nextCharacterIsOpeningCurlyBrace = false;
}

// `... $${'{...'} ...`
// ^^^^^
if (
nextCharacterIsOpeningCurlyBrace &&
endsWithUnescapedDollarSign(prevQuasi.value.raw)
) {
fixers.push(fixer => [
fixer.replaceTextRange(
[prevQuasi.range[1] - 3, prevQuasi.range[1] - 2],
'\\$',
),
]);
}

fixableExpressions.forEach(expression => {
context.report({
node: expression,
messageId: 'noUnnecessaryTemplateExpression',
fix(fixer): TSESLint.RuleFix[] {
const index = node.expressions.indexOf(expression);
const prevQuasi = node.quasis[index];
const nextQuasi = node.quasis[index + 1];

// Remove the quasis' parts that are related to the current expression.
const fixes = [
return [
// Remove the quasis' parts that are related to the current expression.
fixer.removeRange([
prevQuasi.range[1] - 2,
expression.range[0],
]),

fixer.removeRange([
expression.range[1],
nextQuasi.range[0] + 1,
]),
];

const stringValue = getStaticStringValue(expression);

if (stringValue != null) {
const escapedValue = stringValue.replace(/([`$\\])/g, '\\$1');

fixes.push(fixer.replaceText(expression, escapedValue));
} else if (isTemplateLiteral(expression)) {
// Note that some template literals get handled in the previous branch too.
// Remove the beginning and trailing backtick characters.
fixes.push(
fixer.removeRange([
expression.range[0],
expression.range[0] + 1,
]),
fixer.removeRange([
expression.range[1] - 1,
expression.range[1],
]),
);
}

return fixes;
...fixers.flatMap(cb => cb(fixer)),
];
},
});
});
}
},
};
},
Expand Down
Loading
Loading
0