Skip to content

Remove most "import * as ts" imports, except for const enum reverse mapping and plugins #53329

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 6 commits into from
Mar 20, 2023
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
15 changes: 7 additions & 8 deletions src/compiler/builder.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as ts from "./_namespaces/ts";
import {
addRange,
AffectedFileResult,
Expand Down Expand Up @@ -453,23 +452,23 @@ function convertToDiagnostics(diagnostics: readonly ReusableDiagnostic[], newPro
if (!diagnostics.length) return emptyArray;
let buildInfoDirectory: string | undefined;
return diagnostics.map(diagnostic => {
const result: Diagnostic = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
const result: Diagnostic = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPathInBuildInfoDirectory);
result.reportsUnnecessary = diagnostic.reportsUnnecessary;
result.reportsDeprecated = diagnostic.reportDeprecated;
result.source = diagnostic.source;
result.skippedOn = diagnostic.skippedOn;
const { relatedInformation } = diagnostic;
result.relatedInformation = relatedInformation ?
relatedInformation.length ?
relatedInformation.map(r => convertToDiagnosticRelatedInformation(r, newProgram, toPath)) :
relatedInformation.map(r => convertToDiagnosticRelatedInformation(r, newProgram, toPathInBuildInfoDirectory)) :
[] :
undefined;
return result;
});

function toPath(path: string) {
function toPathInBuildInfoDirectory(path: string) {
buildInfoDirectory ??= getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions())!, newProgram.getCurrentDirectory()));
return ts.toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName);
return toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName);
}
}

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

let state: ReusableBuilderProgramState;
const filePaths = program.fileNames?.map(toPath);
const filePaths = program.fileNames?.map(toPathInBuildInfoDirectory);
let filePathsSetList: Set<Path>[] | undefined;
const latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : undefined;
if (isProgramBundleEmitBuildInfo(program)) {
Expand Down Expand Up @@ -1777,8 +1776,8 @@ export function createBuilderProgramUsingProgramBuildInfo(buildInfo: BuildInfo,
hasChangedEmitSignature: returnFalse,
};

function toPath(path: string) {
return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
function toPathInBuildInfoDirectory(path: string) {
return toPath(path, buildInfoDirectory, getCanonicalFileName);
}

function toAbsolutePath(path: string) {
Expand Down
19 changes: 10 additions & 9 deletions src/compiler/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ import {
isExportAssignment,
isExportSpecifier,
isExpression,
isFileLevelUniqueName,
isFunctionLike,
isGeneratedIdentifier,
isGeneratedPrivateIdentifier,
Expand Down Expand Up @@ -446,6 +447,7 @@ import {
VariableDeclaration,
VariableDeclarationList,
VariableStatement,
version,
VoidExpression,
WhileStatement,
WithStatement,
Expand Down Expand Up @@ -1110,7 +1112,6 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi

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

Expand Down Expand Up @@ -1212,10 +1213,10 @@ export function emitUsingBuildInfo(
customTransformers?: CustomTransformers
): EmitUsingBuildInfoResult {
tracing?.push(tracing.Phase.Emit, "emitUsingBuildInfo", {}, /*separateBeginAndEnd*/ true);
ts.performance.mark("beforeEmit");
performance.mark("beforeEmit");
const result = emitUsingBuildInfoWorker(config, host, getCommandLine, customTransformers);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
performance.mark("afterEmit");
performance.measure("Emit", "beforeEmit", "afterEmit");
tracing?.pop();
return result;
}
Expand Down Expand Up @@ -5758,7 +5759,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
* or within the NameGenerator.
*/
function isUniqueName(name: string, privateName: boolean): boolean {
return isFileLevelUniqueName(name, privateName)
return isFileLevelUniqueNameInCurrentFile(name, privateName)
&& !isReservedName(name, privateName)
&& !generatedNames.has(name);
}
Expand All @@ -5773,8 +5774,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
* @param _isPrivate (unused) this parameter exists to avoid an unnecessary adaptor frame in v8
* when `isfileLevelUniqueName` is passed as a callback to `makeUniqueName`.
*/
function isFileLevelUniqueName(name: string, _isPrivate: boolean) {
return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
function isFileLevelUniqueNameInCurrentFile(name: string, _isPrivate: boolean) {
return currentSourceFile ? isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
}

/**
Expand Down Expand Up @@ -5925,7 +5926,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
}

function makeFileLevelOptimisticUniqueName(name: string) {
return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ "");
return makeUniqueName(name, isFileLevelUniqueNameInCurrentFile, /*optimistic*/ true, /*scoped*/ false, /*privateName*/ false, /*prefix*/ "", /*suffix*/ "");
}

/**
Expand Down Expand Up @@ -6034,7 +6035,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
case GeneratedIdentifierFlags.Unique:
return makeUniqueName(
idText(name),
(autoGenerate.flags & GeneratedIdentifierFlags.FileLevel) ? isFileLevelUniqueName : isUniqueName,
(autoGenerate.flags & GeneratedIdentifierFlags.FileLevel) ? isFileLevelUniqueNameInCurrentFile : isUniqueName,
!!(autoGenerate.flags & GeneratedIdentifierFlags.Optimistic),
!!(autoGenerate.flags & GeneratedIdentifierFlags.ReservedInNestedScopes),
isPrivateIdentifier(name),
Expand Down
17 changes: 9 additions & 8 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as ts from "./_namespaces/ts";
import {
AccessorDeclaration,
addRange,
Expand Down Expand Up @@ -139,6 +138,7 @@ import {
isExpressionWithTypeArguments,
isExternalModuleReference,
isFunctionTypeNode,
isIdentifier as isIdentifierNode,
isIdentifierText,
isImportDeclaration,
isImportEqualsDeclaration,
Expand Down Expand Up @@ -264,6 +264,7 @@ import {
NewExpression,
Node,
NodeArray,
NodeFactory,
NodeFactoryFlags,
NodeFlags,
nodeIsMissing,
Expand Down Expand Up @@ -427,7 +428,7 @@ export const parseBaseNodeFactory: BaseNodeFactory = {
};

/** @internal */
export const parseNodeFactory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules, parseBaseNodeFactory);
export const parseNodeFactory: NodeFactory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules, parseBaseNodeFactory);

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

// Otherwise, if this isn't a well-known keyword-like identifier, give the generic fallback message.
const expressionText = ts.isIdentifier(node) ? idText(node) : undefined;
const expressionText = isIdentifierNode(node) ? idText(node) : undefined;
if (!expressionText || !isIdentifierText(expressionText, languageVersion)) {
parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.SemicolonToken));
return;
Expand Down Expand Up @@ -6954,7 +6955,7 @@ namespace Parser {
let node: ExpressionStatement | LabeledStatement;
const hasParen = token() === SyntaxKind.OpenParenToken;
const expression = allowInAnd(parseExpression);
if (ts.isIdentifier(expression) && parseOptional(SyntaxKind.ColonToken)) {
if (isIdentifierNode(expression) && parseOptional(SyntaxKind.ColonToken)) {
node = factory.createLabeledStatement(expression, parseStatement());
}
else {
Expand Down Expand Up @@ -9070,7 +9071,7 @@ namespace Parser {
case SyntaxKind.ArrayType:
return isObjectOrObjectArrayTypeReference((node as ArrayTypeNode).elementType);
default:
return isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
return isTypeReferenceNode(node) && isIdentifierNode(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
}
}

Expand Down Expand Up @@ -9367,8 +9368,8 @@ namespace Parser {
}

function escapedTextsEqual(a: EntityName, b: EntityName): boolean {
while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
while (!isIdentifierNode(a) || !isIdentifierNode(b)) {
if (!isIdentifierNode(a) && !isIdentifierNode(b) && a.right.escapedText === b.right.escapedText) {
a = a.left;
b = b.left;
}
Expand All @@ -9393,7 +9394,7 @@ namespace Parser {
const child = tryParseChildTag(target, indent);
if (child && (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) &&
target !== PropertyLikeParse.CallbackParameter &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
name && (isIdentifierNode(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
}
return child;
Expand Down
16 changes: 10 additions & 6 deletions src/compiler/program.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as ts from "./_namespaces/ts";
import {
__String,
addInternalEmitFlags,
Expand Down Expand Up @@ -104,12 +103,15 @@ import {
forEachEmittedFile,
forEachEntry,
forEachKey,
forEachResolvedProjectReference as ts_forEachResolvedProjectReference,
FunctionLikeDeclaration,
getAllowJSCompilerOption,
getAutomaticTypeDirectiveNames,
getBaseFileName,
GetCanonicalFileName,
getCommonSourceDirectory as ts_getCommonSourceDirectory,
getCommonSourceDirectoryOfConfig,
getDeclarationDiagnostics as ts_getDeclarationDiagnostics,
getDefaultLibFileName,
getDirectoryPath,
getEmitDeclarations,
Expand Down Expand Up @@ -304,9 +306,11 @@ import {
SymlinkCache,
SyntaxKind,
sys,
System,
targetOptionDeclaration,
toFileNameLowerCase,
tokenToString,
toPath as ts_toPath,
trace,
tracing,
trimStringEnd,
Expand Down Expand Up @@ -448,7 +452,7 @@ export function createWriteFileMeasuringIO(
}

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

function toPath(fileName: string): Path {
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
return ts_toPath(fileName, currentDirectory, getCanonicalFileName);
}

function getCommonSourceDirectory() {
if (commonSourceDirectory === undefined) {
const emittedFiles = filter(files, file => sourceFileMayBeEmitted(file, program));
commonSourceDirectory = ts.getCommonSourceDirectory(
commonSourceDirectory = ts_getCommonSourceDirectory(
options,
() => mapDefined(emittedFiles, file => file.isDeclarationFile ? undefined : file.fileName),
currentDirectory,
Expand Down Expand Up @@ -3092,7 +3096,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
return runWithCancellationToken(() => {
const resolver = getTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
return ts.getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile) || emptyArray;
return ts_getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile) || emptyArray;
});
}

Expand Down Expand Up @@ -3657,7 +3661,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
function forEachResolvedProjectReference<T>(
cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined
): T | undefined {
return ts.forEachResolvedProjectReference(resolvedProjectReferences, cb);
return ts_forEachResolvedProjectReference(resolvedProjectReferences, cb);
}

function getSourceOfProjectReferenceRedirect(path: Path) {
Expand Down
4 changes: 2 additions & 2 deletions src/compiler/resolutionCache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as ts from "./_namespaces/ts";
import {
arrayToMap,
CachedDirectoryStructureHost,
Expand Down Expand Up @@ -63,6 +62,7 @@ import {
ResolvedModuleWithFailedLookupLocations,
ResolvedProjectReference,
ResolvedTypeReferenceDirectiveWithFailedLookupLocations,
resolveModuleName as ts_resolveModuleName,
returnTrue,
some,
SourceFile,
Expand Down Expand Up @@ -463,7 +463,7 @@ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootD

function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, redirectedReference?: ResolvedProjectReference, mode?: ResolutionMode): CachedResolvedModuleWithFailedLookupLocations {
const host = resolutionHost.getCompilerHost?.() || resolutionHost;
const primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode);
const primaryResult = ts_resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode);
// return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
if (!resolutionHost.getGlobalCache) {
return primaryResult;
Expand Down
16 changes: 9 additions & 7 deletions src/compiler/tsbuildPublic.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as ts from "./_namespaces/ts";
import {
AffectedFileResult,
arrayToMap,
Expand Down Expand Up @@ -52,6 +51,7 @@ import {
ForegroundColorEscapeSequences,
formatColorAndReset,
getAllProjectOutputs,
getBuildInfo as ts_getBuildInfo,
getBuildInfoFileVersionMap,
getConfigFileParsingDiagnostics,
getDirectoryPath,
Expand All @@ -60,6 +60,7 @@ import {
getFilesInErrorForSummary,
getFirstProjectOutput,
getLocaleTimeString,
getModifiedTime as ts_getModifiedTime,
getNormalizedAbsolutePath,
getParsedCommandLineOfConfigFile,
getPendingEmitKind,
Expand Down Expand Up @@ -108,6 +109,7 @@ import {
Status,
sys,
System,
toPath as ts_toPath,
TypeReferenceDirectiveResolutionCache,
unorderedRemoveItem,
updateErrorForNoInputFiles,
Expand Down Expand Up @@ -525,7 +527,7 @@ function createSolutionBuilderState<T extends BuilderProgram>(watch: boolean, ho
}

function toPath<T extends BuilderProgram>(state: SolutionBuilderState<T>, fileName: string) {
return ts.toPath(fileName, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName);
return ts_toPath(fileName, state.compilerHost.getCurrentDirectory(), state.compilerHost.getCanonicalFileName);
}

function toResolvedConfigFilePath<T extends BuilderProgram>(state: SolutionBuilderState<T>, fileName: ResolvedConfigFileName): ResolvedConfigFilePath {
Expand Down Expand Up @@ -1150,7 +1152,7 @@ function createBuildOrUpdateInvalidedProject<T extends BuilderProgram>(
const path = toPath(state, name);
emittedOutputs.set(toPath(state, name), name);
if (data?.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, options, resultFlags);
const modifiedTime = data?.differsOnlyInMap ? ts.getModifiedTime(state.host, name) : undefined;
const modifiedTime = data?.differsOnlyInMap ? ts_getModifiedTime(state.host, name) : undefined;
writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
// Revert the timestamp for the d.ts that is same
if (data?.differsOnlyInMap) state.host.setModifiedTime(name, modifiedTime!);
Expand Down Expand Up @@ -1565,7 +1567,7 @@ function getModifiedTime<T extends BuilderProgram>(state: SolutionBuilderState<T
// In watch mode we store the modified times in the cache
// This is either Date | FileWatcherWithModifiedTime because we query modified times first and
// then after complete compilation of the project, watch the files so we dont want to loose these modified times.
const result = ts.getModifiedTime(state.host, fileName);
const result = ts_getModifiedTime(state.host, fileName);
if (state.watch) {
if (existing) (existing as FileWatcherWithModifiedTime).modifiedTime = result;
else state.filesWatched.set(path, result);
Expand Down Expand Up @@ -1657,7 +1659,7 @@ function getBuildInfo<T extends BuilderProgram>(state: SolutionBuilderState<T>,
return existing.buildInfo || undefined;
}
const value = state.readFileWithCache(buildInfoPath);
const buildInfo = value ? ts.getBuildInfo(buildInfoPath, value) : undefined;
const buildInfo = value ? ts_getBuildInfo(buildInfoPath, value) : undefined;
state.buildInfoCache.set(resolvedConfigPath, { path, buildInfo: buildInfo || false, modifiedTime: modifiedTime || missingFileModifiedTime });
return buildInfo;
}
Expand Down Expand Up @@ -1732,7 +1734,7 @@ function getUpToDateStatusWorker<T extends BuilderProgram>(state: SolutionBuilde
let buildInfoVersionMap: ReturnType<typeof getBuildInfoFileVersionMap> | undefined;
if (buildInfoPath) {
const buildInfoCacheEntry = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath);
buildInfoTime = buildInfoCacheEntry?.modifiedTime || ts.getModifiedTime(host, buildInfoPath);
buildInfoTime = buildInfoCacheEntry?.modifiedTime || ts_getModifiedTime(host, buildInfoPath);
if (buildInfoTime === missingFileModifiedTime) {
if (!buildInfoCacheEntry) {
state.buildInfoCache.set(resolvedPath, {
Expand Down Expand Up @@ -1864,7 +1866,7 @@ function getUpToDateStatusWorker<T extends BuilderProgram>(state: SolutionBuilde
// Output is missing; can stop checking
let outputTime = outputTimeStampMap?.get(path);
if (!outputTime) {
outputTime = ts.getModifiedTime(state.host, output);
outputTime = ts_getModifiedTime(state.host, output);
outputTimeStampMap?.set(path, outputTime);
}

Expand Down
Loading