Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
e9f0a1a
WIP
andrewbranch Jul 28, 2022
5f9cf9d
Add extension error back unless noEmit is set
andrewbranch Jul 29, 2022
2421cf5
Add non-relative tests
andrewbranch Jul 29, 2022
660026e
Add error for importing from declaration file
andrewbranch Jul 29, 2022
2daa136
Merge branch 'main' into module-resolution/minimal
andrewbranch Sep 14, 2022
f49a368
Update unit test
andrewbranch Sep 14, 2022
af03675
Add explicit flag for importing from .ts extensions
andrewbranch Sep 14, 2022
496ef99
Add module specifier resolution changes
andrewbranch Sep 15, 2022
458c125
Add auto-import tests
andrewbranch Sep 19, 2022
7d64928
Disallow relative imports into node_modules
andrewbranch Sep 26, 2022
0249e0a
Ensure auto-imports don’t suggest ./node_modules;
andrewbranch Sep 26, 2022
6242ee3
Test a non-portable declaration emit issue
andrewbranch Sep 26, 2022
6cc0e18
Test auto-importing TSX file
andrewbranch Sep 26, 2022
240533a
Update path completions
andrewbranch Sep 26, 2022
eb9a4bb
Merge branch 'main' into module-resolution/minimal
andrewbranch Sep 26, 2022
619843e
Fix lint due to merge
andrewbranch Sep 27, 2022
2ceb4bc
Remove minimal-specific stuff
andrewbranch Oct 13, 2022
aad7fe7
Remove minimal tests
andrewbranch Oct 13, 2022
7fd3e72
Update unit tests
andrewbranch Oct 13, 2022
7cca6f3
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Oct 14, 2022
ea12012
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Oct 25, 2022
8655cf9
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Nov 7, 2022
86dd5da
Add options
andrewbranch Oct 20, 2022
8846f31
Add customConditions option
andrewbranch Oct 21, 2022
9bc0f07
Add first tests
andrewbranch Oct 24, 2022
4545afb
CJS constructs are not allowed
andrewbranch Oct 24, 2022
e82e61d
Add another test
andrewbranch Oct 24, 2022
038783d
Fix extension adding/replacing priority
andrewbranch Oct 25, 2022
c55c454
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Nov 8, 2022
870d807
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Nov 8, 2022
6e1989e
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Nov 15, 2022
a482180
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Nov 15, 2022
89bcd01
Update test to reflect the choice not to block on unrecognized extens…
andrewbranch Nov 16, 2022
6074661
Add auto-imports and string completions tests
andrewbranch Nov 17, 2022
fa188b1
Revamp string completions ending preferences
andrewbranch Nov 18, 2022
9e03db2
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Nov 18, 2022
c4320a2
Comment test
andrewbranch Nov 18, 2022
f04f1b5
Auto-imports of declaration files cannot use .ts extension
andrewbranch Nov 18, 2022
29039de
Have declaration file auto imports default to extensionless instead
andrewbranch Nov 18, 2022
c6b963b
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Nov 18, 2022
e83ca2a
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Nov 18, 2022
f98730a
Add test for custom conditions
andrewbranch Nov 18, 2022
5a01dd6
Fix indentation
andrewbranch Nov 18, 2022
4dd6d01
Add baseline showing resolvePackageJsonImports/Exports compatibility
andrewbranch Nov 18, 2022
7225671
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Nov 28, 2022
81b9e70
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Nov 28, 2022
f6fa5f3
Fix test and prevent CJS require from resolving
andrewbranch Nov 28, 2022
aeb23be
Update unit test baselines
andrewbranch Nov 28, 2022
3b1d554
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Dec 5, 2022
e0c0375
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Dec 5, 2022
f9414aa
Fix bad merge conflict resolution
andrewbranch Dec 5, 2022
dadc1a8
Make resolvedUsingTsExtension optional
andrewbranch Dec 5, 2022
5909643
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Dec 5, 2022
5089aab
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Dec 5, 2022
a88b8ad
Update missed baselines
andrewbranch Dec 6, 2022
c3575de
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Dec 6, 2022
224bb10
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Dec 6, 2022
b2e283c
Revert now-unnecessary API implementation changes
andrewbranch Dec 6, 2022
30afa86
Clean up
andrewbranch Dec 9, 2022
c4ba4a5
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Dec 9, 2022
0baca5b
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Dec 9, 2022
6e763d9
Update baselines to es5 emit
andrewbranch Dec 9, 2022
4e73a46
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Dec 13, 2022
22fbb44
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Dec 13, 2022
d4a3b3c
Rename to `bundler`
andrewbranch Dec 13, 2022
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
10,897 changes: 79 additions & 10,818 deletions src/compiler/checker.ts

Large diffs are not rendered by default.

379 changes: 103 additions & 276 deletions src/compiler/commandLineParser.ts

Large diffs are not rendered by default.

1,478 changes: 225 additions & 1,253 deletions src/compiler/moduleNameResolver.ts

Large diffs are not rendered by default.

997 changes: 390 additions & 607 deletions src/compiler/moduleSpecifiers.ts

Large diffs are not rendered by default.

419 changes: 29 additions & 390 deletions src/compiler/program.ts

Large diffs are not rendered by default.

18,577 changes: 9,354 additions & 9,223 deletions src/compiler/types.ts

Large diffs are not rendered by default.

394 changes: 79 additions & 315 deletions src/compiler/utilities.ts

Large diffs are not rendered by default.

470 changes: 70 additions & 400 deletions src/harness/fourslashImpl.ts

Large diffs are not rendered by default.

393 changes: 6 additions & 387 deletions src/harness/fourslashInterfaceImpl.ts

Large diffs are not rendered by default.

247 changes: 17 additions & 230 deletions src/services/codefixes/importFixes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,235 +499,21 @@ function getImportFixes(
};
}

function getTargetModuleFromNamespaceLikeImport(declaration: AnyImportOrRequire, checker: TypeChecker) {
switch (declaration.kind) {
case SyntaxKind.VariableDeclaration:
return checker.resolveExternalModuleName(declaration.initializer.arguments[0]);
case SyntaxKind.ImportEqualsDeclaration:
return checker.getAliasedSymbol(declaration.symbol);
case SyntaxKind.ImportDeclaration:
const namespaceImport = tryCast(declaration.importClause?.namedBindings, isNamespaceImport);
return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol);
default:
return Debug.assertNever(declaration);
}
}

function getNamespaceLikeImportText(declaration: AnyImportOrRequire) {
switch (declaration.kind) {
case SyntaxKind.VariableDeclaration:
return tryCast(declaration.name, isIdentifier)?.text;
case SyntaxKind.ImportEqualsDeclaration:
return declaration.name.text;
case SyntaxKind.ImportDeclaration:
return tryCast(declaration.importClause?.namedBindings, isNamespaceImport)?.name.text;
default:
return Debug.assertNever(declaration);
}
}

function getAddAsTypeOnly(
isValidTypeOnlyUseSite: boolean,
isForNewImportDeclaration: boolean,
symbol: Symbol,
targetFlags: SymbolFlags,
checker: TypeChecker,
compilerOptions: CompilerOptions
) {
if (!isValidTypeOnlyUseSite) {
// Can't use a type-only import if the usage is an emitting position
return AddAsTypeOnly.NotAllowed;
}
if (isForNewImportDeclaration && compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error) {
// Not writing a (top-level) type-only import here would create an error because the runtime dependency is unnecessary
return AddAsTypeOnly.Required;
}
if (compilerOptions.isolatedModules && compilerOptions.preserveValueImports &&
(!(targetFlags & SymbolFlags.Value) || !!checker.getTypeOnlyAliasDeclaration(symbol))
) {
// A type-only import is required for this symbol if under these settings if the symbol will
// be erased, which will happen if the target symbol is purely a type or if it was exported/imported
// as type-only already somewhere between this import and the target.
return AddAsTypeOnly.Required;
}
return AddAsTypeOnly.Allowed;
}

function tryAddToExistingImport(existingImports: readonly FixAddToExistingImportInfo[], isValidTypeOnlyUseSite: boolean, checker: TypeChecker, compilerOptions: CompilerOptions): FixAddToExistingImport | undefined {
return firstDefined(existingImports, ({ declaration, importKind, symbol, targetFlags }): FixAddToExistingImport | undefined => {
if (importKind === ImportKind.CommonJS || importKind === ImportKind.Namespace || declaration.kind === SyntaxKind.ImportEqualsDeclaration) {
// These kinds of imports are not combinable with anything
return undefined;
}

if (declaration.kind === SyntaxKind.VariableDeclaration) {
return (importKind === ImportKind.Named || importKind === ImportKind.Default) && declaration.name.kind === SyntaxKind.ObjectBindingPattern
? { kind: ImportFixKind.AddToExisting, importClauseOrBindingPattern: declaration.name, importKind, moduleSpecifier: declaration.initializer.arguments[0].text, addAsTypeOnly: AddAsTypeOnly.NotAllowed }
: undefined;
}

const { importClause } = declaration;
if (!importClause || !isStringLiteralLike(declaration.moduleSpecifier)) return undefined;
const { name, namedBindings } = importClause;
// A type-only import may not have both a default and named imports, so the only way a name can
// be added to an existing type-only import is adding a named import to existing named bindings.
if (importClause.isTypeOnly && !(importKind === ImportKind.Named && namedBindings)) return undefined;

// N.B. we don't have to figure out whether to use the main program checker
// or the AutoImportProvider checker because we're adding to an existing import; the existence of
// the import guarantees the symbol came from the main program.
const addAsTypeOnly = getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ false, symbol, targetFlags, checker, compilerOptions);

if (importKind === ImportKind.Default && (
name || // Cannot add a default import to a declaration that already has one
addAsTypeOnly === AddAsTypeOnly.Required && namedBindings // Cannot add a default import as type-only if the import already has named bindings
)) return undefined;
if (
importKind === ImportKind.Named &&
namedBindings?.kind === SyntaxKind.NamespaceImport // Cannot add a named import to a declaration that has a namespace import
) return undefined;

return {
kind: ImportFixKind.AddToExisting,
importClauseOrBindingPattern: importClause,
importKind,
moduleSpecifier: declaration.moduleSpecifier.text,
addAsTypeOnly,
};
});
}

function createExistingImportMap(checker: TypeChecker, importingFile: SourceFile, compilerOptions: CompilerOptions) {
let importMap: MultiMap<SymbolId, AnyImportOrRequire> | undefined;
for (const moduleSpecifier of importingFile.imports) {
const i = importFromModuleSpecifier(moduleSpecifier);
if (isVariableDeclarationInitializedToRequire(i.parent)) {
const moduleSymbol = checker.resolveExternalModuleName(moduleSpecifier);
if (moduleSymbol) {
(importMap ||= createMultiMap()).add(getSymbolId(moduleSymbol), i.parent);
}
}
else if (i.kind === SyntaxKind.ImportDeclaration || i.kind === SyntaxKind.ImportEqualsDeclaration) {
const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
if (moduleSymbol) {
(importMap ||= createMultiMap()).add(getSymbolId(moduleSymbol), i);
}
}
}

return {
getImportsForExportInfo: ({ moduleSymbol, exportKind, targetFlags, symbol }: SymbolExportInfo): readonly FixAddToExistingImportInfo[] => {
// Can't use an es6 import for a type in JS.
if (!(targetFlags & SymbolFlags.Value) && isSourceFileJS(importingFile)) return emptyArray;
const matchingDeclarations = importMap?.get(getSymbolId(moduleSymbol));
if (!matchingDeclarations) return emptyArray;
const importKind = getImportKind(importingFile, exportKind, compilerOptions);
return matchingDeclarations.map(declaration => ({ declaration, importKind, symbol, targetFlags }));
}
};
}

function shouldUseRequire(sourceFile: SourceFile, program: Program): boolean {
// 1. TypeScript files don't use require variable declarations
if (!isSourceFileJS(sourceFile)) {
return false;
}

// 2. If the current source file is unambiguously CJS or ESM, go with that
if (sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator) return true;
if (sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) return false;

// 3. If there's a tsconfig/jsconfig, use its module setting
const compilerOptions = program.getCompilerOptions();
if (compilerOptions.configFile) {
return getEmitModuleKind(compilerOptions) < ModuleKind.ES2015;
}

// 4. Match the first other JS file in the program that's unambiguously CJS or ESM
for (const otherFile of program.getSourceFiles()) {
if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue;
if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) return true;
if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator) return false;
}

// 5. Literally nothing to go on
return true;
}

function createGetChecker(program: Program, host: LanguageServiceHost) {
return memoizeOne((isFromPackageJson: boolean) => isFromPackageJson ? host.getPackageJsonAutoImportProvider!()!.getTypeChecker() : program.getTypeChecker());
}

function getNewImportFixes(
program: Program,
sourceFile: SourceFile,
position: number | undefined,
isValidTypeOnlyUseSite: boolean,
useRequire: boolean,
exportInfo: readonly SymbolExportInfo[],
host: LanguageServiceHost,
preferences: UserPreferences,
fromCacheOnly?: boolean,
): { computedWithoutCacheCount: number, fixes: readonly (FixAddNewImport | FixAddJsdocTypeImport)[] } {
const isJs = isSourceFileJS(sourceFile);
const compilerOptions = program.getCompilerOptions();
const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host);
const getChecker = createGetChecker(program, host);
const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution);
const getModuleSpecifiers = fromCacheOnly
? (moduleSymbol: Symbol) => ({ moduleSpecifiers: moduleSpecifiers.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false })
: (moduleSymbol: Symbol, checker: TypeChecker) => moduleSpecifiers.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences);

let computedWithoutCacheCount = 0;
const fixes = flatMap(exportInfo, (exportInfo, i) => {
const checker = getChecker(exportInfo.isFromPackageJson);
const { computedWithoutCache, moduleSpecifiers } = getModuleSpecifiers(exportInfo.moduleSymbol, checker);
const importedSymbolHasValueMeaning = !!(exportInfo.targetFlags & SymbolFlags.Value);
const addAsTypeOnly = getAddAsTypeOnly(isValidTypeOnlyUseSite, /*isForNewImportDeclaration*/ true, exportInfo.symbol, exportInfo.targetFlags, checker, compilerOptions);
computedWithoutCacheCount += computedWithoutCache ? 1 : 0;
return mapDefined(moduleSpecifiers, (moduleSpecifier): FixAddNewImport | FixAddJsdocTypeImport | undefined =>
rejectNodeModulesRelativePaths && pathContainsNodeModules(moduleSpecifier) ? undefined :
// `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types.
!importedSymbolHasValueMeaning && isJs && position !== undefined ? { kind: ImportFixKind.JsdocTypeImport, moduleSpecifier, position, exportInfo, isReExport: i > 0 } :
{
kind: ImportFixKind.AddNew,
moduleSpecifier,
importKind: getImportKind(sourceFile, exportInfo.exportKind, compilerOptions),
useRequire,
addAsTypeOnly,
exportInfo,
isReExport: i > 0,
}
);
});

return { computedWithoutCacheCount, fixes };
}

function getFixesForAddImport(
exportInfos: readonly SymbolExportInfo[],
existingImports: readonly FixAddToExistingImportInfo[],
program: Program,
sourceFile: SourceFile,
position: number | undefined,
isValidTypeOnlyUseSite: boolean,
useRequire: boolean,
host: LanguageServiceHost,
preferences: UserPreferences,
fromCacheOnly?: boolean,
): { computedWithoutCacheCount?: number, fixes: readonly (FixAddNewImport | FixAddJsdocTypeImport)[] } {
const existingDeclaration = firstDefined(existingImports, info => newImportInfoFromExistingSpecifier(info, isValidTypeOnlyUseSite, useRequire, program.getTypeChecker(), program.getCompilerOptions()));
return existingDeclaration ? { fixes: [existingDeclaration] } : getNewImportFixes(program, sourceFile, position, isValidTypeOnlyUseSite, useRequire, exportInfos, host, preferences, fromCacheOnly);
}

function newImportInfoFromExistingSpecifier(
{ declaration, importKind, symbol, targetFlags }: FixAddToExistingImportInfo,
isValidTypeOnlyUseSite: boolean,
useRequire: boolean,
checker: TypeChecker,
compilerOptions: CompilerOptions
): FixAddNewImport | undefined {
function tryUseExistingNamespaceImport(existingImports: readonly FixAddToExistingImportInfo[], symbolName: string, position: number, checker: TypeChecker): FixUseNamespaceImport | undefined {
// It is possible that multiple import statements with the same specifier exist in the file.
// e.g.
//
// import * as ns from "foo";
// import { member1, member2 } from "foo";
//
// member3/**/ <-- cusor here
//
// in this case we should provie 2 actions:
// 1. change "member3" to "ns.member3"
// 2. add "member3" to the second import statement's import list
// and it is up to the user to decide which one fits best.
return firstDefined(existingImports, ({ declaration }): FixUseNamespaceImport | undefined => {
const namespacePrefix = getNamespaceLikeImportText(declaration);
const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(declaration)?.text;
if (namespacePrefix && moduleSpecifier) {
const moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker);
Expand Down Expand Up @@ -912,7 +698,8 @@ function getNewImportFixes(
const compilerOptions = program.getCompilerOptions();
const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host);
const getChecker = createGetChecker(program, host);
const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(getEmitModuleResolutionKind(compilerOptions));
const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution);
const getModuleSpecifiers = fromCacheOnly
? (moduleSymbol: Symbol) => ({ moduleSpecifiers: moduleSpecifiers.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false })
: (moduleSymbol: Symbol, checker: TypeChecker) => moduleSpecifiers.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences);
Expand Down
Loading