Skip to content

Build parser-to-language mapping dynamically from getSupportInfo() #3940

@ntotten

Description

@ntotten

Problem

The extension maintains a hardcoded mapping from VS Code language IDs to Prettier parsers in src/util.ts:getParserFromLanguageId(). This mapping can get out of sync with Prettier's actual parser support, especially when:

  • New parsers are added to Prettier
  • Parser names change
  • Users have different Prettier versions with different parser support

Proposed Solution

Replace the hardcoded mapping with a dynamic lookup using Prettier's getSupportInfo() API. This API returns metadata about all supported languages, including their vscodeLanguageIds.

Current Implementation

// src/util.ts - hardcoded switch statement
export function getParserFromLanguageId(languageId: string): string | undefined {
  switch (languageId) {
    case "javascript":
      return "babel";
    case "typescript":
      return "typescript";
    // ... many more cases
  }
}

Proposed Implementation

async function getParserFromLanguageId(
  prettierInstance: PrettierInstance,
  languageId: string
): Promise<string | undefined> {
  const supportInfo = await prettierInstance.getSupportInfo();
  for (const lang of supportInfo.languages) {
    if (lang.vscodeLanguageIds?.includes(languageId)) {
      return lang.parsers[0]; // Use primary parser
    }
  }
  return undefined;
}

Benefits

  • Always in sync with the Prettier version being used
  • Supports plugins that register new languages automatically
  • Eliminates maintenance burden of keeping the mapping updated
  • Ensures CLI parity since the CLI uses the same getSupportInfo() data

Considerations

  • May need to cache the result of getSupportInfo() per Prettier instance
  • Function becomes async (minor change to call sites)

Relevant Files

  • src/util.ts - getParserFromLanguageId() function
  • src/PrettierEditService.ts - calls getParserFromLanguageId()

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions