Skip to content

Commit 913f65c

Browse files
authored
Remove most "import * as ts" imports, except for const enum reverse mapping and plugins (microsoft#53329)
1 parent 41474f9 commit 913f65c

File tree

14 files changed

+87
-76
lines changed

14 files changed

+87
-76
lines changed

src/compiler/builder.ts

+7-8
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import * as ts from "./_namespaces/ts";
21
import {
32
addRange,
43
AffectedFileResult,
@@ -453,23 +452,23 @@ function convertToDiagnostics(diagnostics: readonly ReusableDiagnostic[], newPro
453452
if (!diagnostics.length) return emptyArray;
454453
let buildInfoDirectory: string | undefined;
455454
return diagnostics.map(diagnostic => {
456-
const result: Diagnostic = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
455+
const result: Diagnostic = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPathInBuildInfoDirectory);
457456
result.reportsUnnecessary = diagnostic.reportsUnnecessary;
458457
result.reportsDeprecated = diagnostic.reportDeprecated;
459458
result.source = diagnostic.source;
460459
result.skippedOn = diagnostic.skippedOn;
461460
const { relatedInformation } = diagnostic;
462461
result.relatedInformation = relatedInformation ?
463462
relatedInformation.length ?
464-
relatedInformation.map(r => convertToDiagnosticRelatedInformation(r, newProgram, toPath)) :
463+
relatedInformation.map(r => convertToDiagnosticRelatedInformation(r, newProgram, toPathInBuildInfoDirectory)) :
465464
[] :
466465
undefined;
467466
return result;
468467
});
469468

470-
function toPath(path: string) {
469+
function toPathInBuildInfoDirectory(path: string) {
471470
buildInfoDirectory ??= getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions())!, newProgram.getCurrentDirectory()));
472-
return ts.toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName);
471+
return toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName);
473472
}
474473
}
475474

@@ -1697,7 +1696,7 @@ export function createBuilderProgramUsingProgramBuildInfo(buildInfo: BuildInfo,
16971696
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
16981697

16991698
let state: ReusableBuilderProgramState;
1700-
const filePaths = program.fileNames?.map(toPath);
1699+
const filePaths = program.fileNames?.map(toPathInBuildInfoDirectory);
17011700
let filePathsSetList: Set<Path>[] | undefined;
17021701
const latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : undefined;
17031702
if (isProgramBundleEmitBuildInfo(program)) {
@@ -1777,8 +1776,8 @@ export function createBuilderProgramUsingProgramBuildInfo(buildInfo: BuildInfo,
17771776
hasChangedEmitSignature: returnFalse,
17781777
};
17791778

1780-
function toPath(path: string) {
1781-
return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
1779+
function toPathInBuildInfoDirectory(path: string) {
1780+
return toPath(path, buildInfoDirectory, getCanonicalFileName);
17821781
}
17831782

17841783
function toAbsolutePath(path: string) {

src/compiler/emitter.ts

+10-9
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ import {
217217
isExportAssignment,
218218
isExportSpecifier,
219219
isExpression,
220+
isFileLevelUniqueName,
220221
isFunctionLike,
221222
isGeneratedIdentifier,
222223
isGeneratedPrivateIdentifier,
@@ -446,6 +447,7 @@ import {
446447
VariableDeclaration,
447448
VariableDeclarationList,
448449
VariableStatement,
450+
version,
449451
VoidExpression,
450452
WhileStatement,
451453
WithStatement,
@@ -1110,7 +1112,6 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi
11101112

11111113
/** @internal */
11121114
export function createBuildInfo(program: ProgramBuildInfo | undefined, bundle: BundleBuildInfo | undefined): BuildInfo {
1113-
const version = ts.version; // Extracted into a const so the form is stable between namespace and module
11141115
return { bundle, program, version };
11151116
}
11161117

@@ -1212,10 +1213,10 @@ export function emitUsingBuildInfo(
12121213
customTransformers?: CustomTransformers
12131214
): EmitUsingBuildInfoResult {
12141215
tracing?.push(tracing.Phase.Emit, "emitUsingBuildInfo", {}, /*separateBeginAndEnd*/ true);
1215-
ts.performance.mark("beforeEmit");
1216+
performance.mark("beforeEmit");
12161217
const result = emitUsingBuildInfoWorker(config, host, getCommandLine, customTransformers);
1217-
ts.performance.mark("afterEmit");
1218-
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
1218+
performance.mark("afterEmit");
1219+
performance.measure("Emit", "beforeEmit", "afterEmit");
12191220
tracing?.pop();
12201221
return result;
12211222
}
@@ -5758,7 +5759,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
57585759
* or within the NameGenerator.
57595760
*/
57605761
function isUniqueName(name: string, privateName: boolean): boolean {
5761-
return isFileLevelUniqueName(name, privateName)
5762+
return isFileLevelUniqueNameInCurrentFile(name, privateName)
57625763
&& !isReservedName(name, privateName)
57635764
&& !generatedNames.has(name);
57645765
}
@@ -5773,8 +5774,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
57735774
* @param _isPrivate (unused) this parameter exists to avoid an unnecessary adaptor frame in v8
57745775
* when `isfileLevelUniqueName` is passed as a callback to `makeUniqueName`.
57755776
*/
5776-
function isFileLevelUniqueName(name: string, _isPrivate: boolean) {
5777-
return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
5777+
function isFileLevelUniqueNameInCurrentFile(name: string, _isPrivate: boolean) {
5778+
return currentSourceFile ? isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
57785779
}
57795780

57805781
/**
@@ -5925,7 +5926,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
59255926
}
59265927

59275928
function makeFileLevelOptimisticUniqueName(name: string) {
5928-
return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ "");
5929+
return makeUniqueName(name, isFileLevelUniqueNameInCurrentFile, /*optimistic*/ true, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ "");
59295930
}
59305931

59315932
/**
@@ -6034,7 +6035,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
60346035
case GeneratedIdentifierFlags.Unique:
60356036
return makeUniqueName(
60366037
idText(name),
6037-
(autoGenerate.flags & GeneratedIdentifierFlags.FileLevel) ? isFileLevelUniqueName : isUniqueName,
6038+
(autoGenerate.flags & GeneratedIdentifierFlags.FileLevel) ? isFileLevelUniqueNameInCurrentFile : isUniqueName,
60386039
!!(autoGenerate.flags & GeneratedIdentifierFlags.Optimistic),
60396040
!!(autoGenerate.flags & GeneratedIdentifierFlags.ReservedInNestedScopes),
60406041
isPrivateIdentifier(name),

src/compiler/parser.ts

+9-8
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import * as ts from "./_namespaces/ts";
21
import {
32
AccessorDeclaration,
43
addRange,
@@ -139,6 +138,7 @@ import {
139138
isExpressionWithTypeArguments,
140139
isExternalModuleReference,
141140
isFunctionTypeNode,
141+
isIdentifier as isIdentifierNode,
142142
isIdentifierText,
143143
isImportDeclaration,
144144
isImportEqualsDeclaration,
@@ -264,6 +264,7 @@ import {
264264
NewExpression,
265265
Node,
266266
NodeArray,
267+
NodeFactory,
267268
NodeFactoryFlags,
268269
NodeFlags,
269270
nodeIsMissing,
@@ -427,7 +428,7 @@ export const parseBaseNodeFactory: BaseNodeFactory = {
427428
};
428429

429430
/** @internal */
430-
export const parseNodeFactory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules, parseBaseNodeFactory);
431+
export const parseNodeFactory: NodeFactory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules, parseBaseNodeFactory);
431432

432433
function visitNode<T>(cbNode: (node: Node) => T, node: Node | undefined): T | undefined {
433434
return node && cbNode(node);
@@ -2324,7 +2325,7 @@ namespace Parser {
23242325
}
23252326

23262327
// Otherwise, if this isn't a well-known keyword-like identifier, give the generic fallback message.
2327-
const expressionText = ts.isIdentifier(node) ? idText(node) : undefined;
2328+
const expressionText = isIdentifierNode(node) ? idText(node) : undefined;
23282329
if (!expressionText || !isIdentifierText(expressionText, languageVersion)) {
23292330
parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.SemicolonToken));
23302331
return;
@@ -6954,7 +6955,7 @@ namespace Parser {
69546955
let node: ExpressionStatement | LabeledStatement;
69556956
const hasParen = token() === SyntaxKind.OpenParenToken;
69566957
const expression = allowInAnd(parseExpression);
6957-
if (ts.isIdentifier(expression) && parseOptional(SyntaxKind.ColonToken)) {
6958+
if (isIdentifierNode(expression) && parseOptional(SyntaxKind.ColonToken)) {
69586959
node = factory.createLabeledStatement(expression, parseStatement());
69596960
}
69606961
else {
@@ -9070,7 +9071,7 @@ namespace Parser {
90709071
case SyntaxKind.ArrayType:
90719072
return isObjectOrObjectArrayTypeReference((node as ArrayTypeNode).elementType);
90729073
default:
9073-
return isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
9074+
return isTypeReferenceNode(node) && isIdentifierNode(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
90749075
}
90759076
}
90769077

@@ -9367,8 +9368,8 @@ namespace Parser {
93679368
}
93689369

93699370
function escapedTextsEqual(a: EntityName, b: EntityName): boolean {
9370-
while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
9371-
if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
9371+
while (!isIdentifierNode(a) || !isIdentifierNode(b)) {
9372+
if (!isIdentifierNode(a) && !isIdentifierNode(b) && a.right.escapedText === b.right.escapedText) {
93729373
a = a.left;
93739374
b = b.left;
93749375
}
@@ -9393,7 +9394,7 @@ namespace Parser {
93939394
const child = tryParseChildTag(target, indent);
93949395
if (child && (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) &&
93959396
target !== PropertyLikeParse.CallbackParameter &&
9396-
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
9397+
name && (isIdentifierNode(child.name) || !escapedTextsEqual(name, child.name.left))) {
93979398
return false;
93989399
}
93999400
return child;

src/compiler/program.ts

+10-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import * as ts from "./_namespaces/ts";
21
import {
32
__String,
43
addInternalEmitFlags,
@@ -104,12 +103,15 @@ import {
104103
forEachEmittedFile,
105104
forEachEntry,
106105
forEachKey,
106+
forEachResolvedProjectReference as ts_forEachResolvedProjectReference,
107107
FunctionLikeDeclaration,
108108
getAllowJSCompilerOption,
109109
getAutomaticTypeDirectiveNames,
110110
getBaseFileName,
111111
GetCanonicalFileName,
112+
getCommonSourceDirectory as ts_getCommonSourceDirectory,
112113
getCommonSourceDirectoryOfConfig,
114+
getDeclarationDiagnostics as ts_getDeclarationDiagnostics,
113115
getDefaultLibFileName,
114116
getDirectoryPath,
115117
getEmitDeclarations,
@@ -304,9 +306,11 @@ import {
304306
SymlinkCache,
305307
SyntaxKind,
306308
sys,
309+
System,
307310
targetOptionDeclaration,
308311
toFileNameLowerCase,
309312
tokenToString,
313+
toPath as ts_toPath,
310314
trace,
311315
tracing,
312316
trimStringEnd,
@@ -448,7 +452,7 @@ export function createWriteFileMeasuringIO(
448452
}
449453

450454
/** @internal */
451-
export function createCompilerHostWorker(options: CompilerOptions, setParentNodes?: boolean, system = sys): CompilerHost {
455+
export function createCompilerHostWorker(options: CompilerOptions, setParentNodes?: boolean, system: System = sys): CompilerHost {
452456
const existingDirectories = new Map<string, boolean>();
453457
const getCanonicalFileName = createGetCanonicalFileName(system.useCaseSensitiveFileNames);
454458
function directoryExists(directoryPath: string): boolean {
@@ -1951,13 +1955,13 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
19511955
}
19521956

19531957
function toPath(fileName: string): Path {
1954-
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
1958+
return ts_toPath(fileName, currentDirectory, getCanonicalFileName);
19551959
}
19561960

19571961
function getCommonSourceDirectory() {
19581962
if (commonSourceDirectory === undefined) {
19591963
const emittedFiles = filter(files, file => sourceFileMayBeEmitted(file, program));
1960-
commonSourceDirectory = ts.getCommonSourceDirectory(
1964+
commonSourceDirectory = ts_getCommonSourceDirectory(
19611965
options,
19621966
() => mapDefined(emittedFiles, file => file.isDeclarationFile ? undefined : file.fileName),
19631967
currentDirectory,
@@ -3092,7 +3096,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
30923096
return runWithCancellationToken(() => {
30933097
const resolver = getTypeChecker().getEmitResolver(sourceFile, cancellationToken);
30943098
// Don't actually write any files since we're just getting diagnostics.
3095-
return ts.getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile) || emptyArray;
3099+
return ts_getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile) || emptyArray;
30963100
});
30973101
}
30983102

@@ -3657,7 +3661,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
36573661
function forEachResolvedProjectReference<T>(
36583662
cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined
36593663
): T | undefined {
3660-
return ts.forEachResolvedProjectReference(resolvedProjectReferences, cb);
3664+
return ts_forEachResolvedProjectReference(resolvedProjectReferences, cb);
36613665
}
36623666

36633667
function getSourceOfProjectReferenceRedirect(path: Path) {

src/compiler/resolutionCache.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import * as ts from "./_namespaces/ts";
21
import {
32
arrayToMap,
43
CachedDirectoryStructureHost,
@@ -63,6 +62,7 @@ import {
6362
ResolvedModuleWithFailedLookupLocations,
6463
ResolvedProjectReference,
6564
ResolvedTypeReferenceDirectiveWithFailedLookupLocations,
65+
resolveModuleName as ts_resolveModuleName,
6666
returnTrue,
6767
some,
6868
SourceFile,
@@ -463,7 +463,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD
463463

464464
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, redirectedReference?: ResolvedProjectReference, mode?: ResolutionMode): CachedResolvedModuleWithFailedLookupLocations {
465465
const host = resolutionHost.getCompilerHost?.() || resolutionHost;
466-
const primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode);
466+
const primaryResult = ts_resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode);
467467
// return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
468468
if (!resolutionHost.getGlobalCache) {
469469
return primaryResult;

src/compiler/tsbuildPublic.ts

+9-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import * as ts from "./_namespaces/ts";
21
import {
32
AffectedFileResult,
43
arrayToMap,
@@ -52,6 +51,7 @@ import {
5251
ForegroundColorEscapeSequences,
5352
formatColorAndReset,
5453
getAllProjectOutputs,
54+
getBuildInfo as ts_getBuildInfo,
5555
getBuildInfoFileVersionMap,
5656
getConfigFileParsingDiagnostics,
5757
getDirectoryPath,
@@ -60,6 +60,7 @@ import {
6060
getFilesInErrorForSummary,
6161
getFirstProjectOutput,
6262
getLocaleTimeString,
63+
getModifiedTime as ts_getModifiedTime,
6364
getNormalizedAbsolutePath,
6465
getParsedCommandLineOfConfigFile,
6566
getPendingEmitKind,
@@ -108,6 +109,7 @@ import {
108109
Status,
109110
sys,
110111
System,
112+
toPath as ts_toPath,
111113
TypeReferenceDirectiveResolutionCache,
112114
unorderedRemoveItem,
113115
updateErrorForNoInputFiles,
@@ -525,7 +527,7 @@ function createSolutionBuilderState<T extends BuilderProgram>(watch: boolean, ho
525527
}
526528

527529
function toPath<T extends BuilderProgram>(state: SolutionBuilderState<T>, fileName: string) {
528-
return ts.toPath(fileName, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName);
530+
return ts_toPath(fileName, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName);
529531
}
530532

531533
function toResolvedConfigFilePath<T extends BuilderProgram>(state: SolutionBuilderState<T>, fileName: ResolvedConfigFileName): ResolvedConfigFilePath {
@@ -1150,7 +1152,7 @@ function createBuildOrUpdateInvalidedProject<T extends BuilderProgram>(
11501152
const path = toPath(state, name);
11511153
emittedOutputs.set(toPath(state, name), name);
11521154
if (data?.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, options, resultFlags);
1153-
const modifiedTime = data?.differsOnlyInMap ? ts.getModifiedTime(state.host, name) : undefined;
1155+
const modifiedTime = data?.differsOnlyInMap ? ts_getModifiedTime(state.host, name) : undefined;
11541156
writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
11551157
// Revert the timestamp for the d.ts that is same
11561158
if (data?.differsOnlyInMap) state.host.setModifiedTime(name, modifiedTime!);
@@ -1565,7 +1567,7 @@ function getModifiedTime<T extends BuilderProgram>(state: SolutionBuilderState<T
15651567
// In watch mode we store the modified times in the cache
15661568
// This is either Date | FileWatcherWithModifiedTime because we query modified times first and
15671569
// then after complete compilation of the project, watch the files so we dont want to loose these modified times.
1568-
const result = ts.getModifiedTime(state.host, fileName);
1570+
const result = ts_getModifiedTime(state.host, fileName);
15691571
if (state.watch) {
15701572
if (existing) (existing as FileWatcherWithModifiedTime).modifiedTime = result;
15711573
else state.filesWatched.set(path, result);
@@ -1657,7 +1659,7 @@ function getBuildInfo<T extends BuilderProgram>(state: SolutionBuilderState<T>,
16571659
return existing.buildInfo || undefined;
16581660
}
16591661
const value = state.readFileWithCache(buildInfoPath);
1660-
const buildInfo = value ? ts.getBuildInfo(buildInfoPath, value) : undefined;
1662+
const buildInfo = value ? ts_getBuildInfo(buildInfoPath, value) : undefined;
16611663
state.buildInfoCache.set(resolvedConfigPath, { path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || missingFileModifiedTime });
16621664
return buildInfo;
16631665
}
@@ -1732,7 +1734,7 @@ function getUpToDateStatusWorker<T extends BuilderProgram>(state: SolutionBuilde
17321734
let buildInfoVersionMap: ReturnType<typeof getBuildInfoFileVersionMap> | undefined;
17331735
if (buildInfoPath) {
17341736
const buildInfoCacheEntry = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath);
1735-
buildInfoTime = buildInfoCacheEntry?.modifiedTime || ts.getModifiedTime(host, buildInfoPath);
1737+
buildInfoTime = buildInfoCacheEntry?.modifiedTime || ts_getModifiedTime(host, buildInfoPath);
17361738
if (buildInfoTime === missingFileModifiedTime) {
17371739
if (!buildInfoCacheEntry) {
17381740
state.buildInfoCache.set(resolvedPath, {
@@ -1864,7 +1866,7 @@ function getUpToDateStatusWorker<T extends BuilderProgram>(state: SolutionBuilde
18641866
// Output is missing; can stop checking
18651867
let outputTime = outputTimeStampMap?.get(path);
18661868
if (!outputTime) {
1867-
outputTime = ts.getModifiedTime(state.host, output);
1869+
outputTime = ts_getModifiedTime(state.host, output);
18681870
outputTimeStampMap?.set(path, outputTime);
18691871
}
18701872

0 commit comments

Comments
 (0)