Skip to content
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

fix(eslint-plugin): [switch-exhaustiveness-check] handle special characters in enum keys #2207

Merged
merged 4 commits into from Jul 10, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 20 additions & 2 deletions packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts
Expand Up @@ -42,7 +42,9 @@ export default createRule({
fixer: TSESLint.RuleFixer,
node: TSESTree.SwitchStatement,
missingBranchTypes: Array<ts.Type>,
symbolName?: string,
): TSESLint.RuleFix | null {
const identifierRegex = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem we've got is that a-zA-Z doesn't include all of the "letter-like" characters that are actually allowed in the spec (chinese/japanese/korean/cyrillic/etc characters, accented characters), etc. So for a large number of codebases this regex will actually cause a false match. A false match isn't the end of the world, but it's going to be annoying for non-english speakers.

This is the actual regex of allowed characters within a variable name: https://github.com/estools/esutils/blob/a825f91fd1d1e3a9fff84227cb06c011d8a0b9e8/lib/code.js#L39-L44

It's a mess.

TypeScript needs to parse identifiers itself, and thankfully they export two functions that we can use here: isIdentifierStart and isIdentifierPart.

You can use this function instead to determine if the name requires quoting:

const compilerOptions = service.program.getCompilerOptions();
function requiresQuoting(name: string): boolean {
  if (name.length === 0) {
    return true;
  }
  if (!ts.isIdentifierStart(name.charCodeAt(0), compilerOptions.target)) {
    return true;
  }

  for (let i = 1; i < name.length; i += 1) {
    if (!ts.isIdentifierPart(name.charCodeAt(i), compilerOptions.target)) {
      return true;
    }
  }

  return false;
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! Will make the changes as soon as I can find some time.

const lastCase =
node.cases.length > 0 ? node.cases[node.cases.length - 1] : null;
const caseIndent = lastCase
Expand All @@ -67,7 +69,17 @@ export default createRule({
continue;
}

const caseTest = checker.typeToString(missingBranchType);
const missingBranchName = missingBranchType.getSymbol()?.escapedName;
let caseTest = checker.typeToString(missingBranchType);

if (
symbolName &&
missingBranchName &&
!identifierRegex.test(missingBranchName.toString())
) {
caseTest = `${symbolName}['${missingBranchName}']`;
}

const errorMessage = `Not implemented yet: ${caseTest} case`;

missingCases.push(
Expand Down Expand Up @@ -101,6 +113,7 @@ export default createRule({

function checkSwitchExhaustive(node: TSESTree.SwitchStatement): void {
const discriminantType = getNodeType(node.discriminant);
const symbolName = discriminantType.getSymbol()?.escapedName;

if (discriminantType.isUnion()) {
const unionTypes = unionTypeParts(discriminantType);
Expand Down Expand Up @@ -139,7 +152,12 @@ export default createRule({
{
messageId: 'addMissingCases',
fix(fixer): TSESLint.RuleFix | null {
return fixSwitch(fixer, node, missingBranchTypes);
return fixSwitch(
fixer,
node,
missingBranchTypes,
symbolName?.toString(),
);
},
},
],
Expand Down
Expand Up @@ -483,6 +483,43 @@ function test(value: T): number {
case 1: { throw new Error('Not implemented yet: 1 case') }
case 2: { throw new Error('Not implemented yet: 2 case') }
}
}
`.trimRight(),
},
],
},
],
},
{
// keys include special characters
code: `
export enum Enum {
'test-test' = 'test-test',
'test' = 'test',
}

function test(arg: Enum): string {
switch (arg) {
}
}
`.trimRight(),
errors: [
{
messageId: 'switchIsNotExhaustive',
suggestions: [
{
messageId: 'addMissingCases',
output: noFormat`
export enum Enum {
'test-test' = 'test-test',
'test' = 'test',
}

function test(arg: Enum): string {
switch (arg) {
case Enum['test-test']: { throw new Error('Not implemented yet: Enum['test-test'] case') }
case Enum.test: { throw new Error('Not implemented yet: Enum.test case') }
}
}
`.trimRight(),
},
Expand Down