mirror of
https://github.com/microsoft/TypeScript.git
synced 2026-11-18 20:11:14 +00:00
Merge branch 'main' into release-5.0
This commit is contained in:
commit
d3815df94e
1859 files changed
+43378
-10665
No files matched your search
+11
-6
@@ -11,7 +11,7 @@
|
||||
"es6": true
|
||||
},
|
||||
"plugins": [
|
||||
"@typescript-eslint", "no-null", "import", "eslint-plugin-local"
|
||||
"@typescript-eslint", "no-null", "import", "eslint-plugin-local", "simple-import-sort"
|
||||
],
|
||||
"ignorePatterns": [
|
||||
"**/node_modules/**",
|
||||
@@ -25,11 +25,8 @@
|
||||
"/coverage/**"
|
||||
],
|
||||
"rules": {
|
||||
"sort-imports": ["error", {
|
||||
"ignoreCase": true,
|
||||
"ignoreDeclarationSort": true,
|
||||
"allowSeparatedGroups": true
|
||||
}],
|
||||
"simple-import-sort/imports": "error",
|
||||
"simple-import-sort/exports": "error",
|
||||
|
||||
"@typescript-eslint/adjacent-overload-signatures": "error",
|
||||
"@typescript-eslint/array-type": "error",
|
||||
@@ -180,6 +177,14 @@
|
||||
{ "name": "exports" }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
// These files contain imports in a specific order that are generally unsafe to modify.
|
||||
"files": ["**/_namespaces/**"],
|
||||
"rules": {
|
||||
"simple-import-sort/imports": "off",
|
||||
"simple-import-sort/exports": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+6
@@ -40,6 +40,12 @@
|
||||
"env": {
|
||||
"NODE_ENV": "testing"
|
||||
},
|
||||
"outFiles": [
|
||||
"${workspaceFolder}/built/**/*.js",
|
||||
"${workspaceFolder}/built/**/*.mjs",
|
||||
"${workspaceFolder}/built/**/*.cjs",
|
||||
"!**/node_modules/**"
|
||||
],
|
||||
"sourceMaps": true,
|
||||
"smartStep": true,
|
||||
"preLaunchTask": "npm: build:tests",
|
||||
|
||||
Vendored
+8
@@ -13,6 +13,14 @@
|
||||
// ".git-blame-ignore-revs"
|
||||
// ]
|
||||
|
||||
// Match eslint-plugin-simple-import-sort in organize/auto-imports.
|
||||
"typescript.unstable": {
|
||||
"organizeImportsCollation": "unicode",
|
||||
"organizeImportsCaseFirst": "upper",
|
||||
"organizeImportsIgnoreCase": false,
|
||||
"organizeImportsNumericCollation": true
|
||||
},
|
||||
|
||||
// These options search the repo recursively and slow down
|
||||
// the build task menu. We define our own in tasks.json.
|
||||
"typescript.tsc.autoDetect": "off",
|
||||
|
||||
+40
-39
@@ -1,21 +1,22 @@
|
||||
// @ts-check
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import del from "del";
|
||||
import { task } from "hereby";
|
||||
import _glob from "glob";
|
||||
import util from "util";
|
||||
import { CancelToken } from "@esfx/canceltoken";
|
||||
import chalk from "chalk";
|
||||
import chokidar from "chokidar";
|
||||
import del from "del";
|
||||
import esbuild from "esbuild";
|
||||
import { EventEmitter } from "events";
|
||||
import fs from "fs";
|
||||
import fsExtra from "fs-extra";
|
||||
import { Debouncer, Deferred, exec, getDiffTool, getDirSize, memoize, needsUpdate, readJson } from "./scripts/build/utils.mjs";
|
||||
import { localBaseline, localRwcBaseline, refBaseline, refRwcBaseline, runConsoleTests } from "./scripts/build/tests.mjs";
|
||||
import { buildProject, cleanProject, watchProject } from "./scripts/build/projects.mjs";
|
||||
import _glob from "glob";
|
||||
import { task } from "hereby";
|
||||
import path from "path";
|
||||
import util from "util";
|
||||
|
||||
import { localizationDirectories } from "./scripts/build/localization.mjs";
|
||||
import cmdLineOptions from "./scripts/build/options.mjs";
|
||||
import esbuild from "esbuild";
|
||||
import chokidar from "chokidar";
|
||||
import { EventEmitter } from "events";
|
||||
import { CancelToken } from "@esfx/canceltoken";
|
||||
import { buildProject, cleanProject, watchProject } from "./scripts/build/projects.mjs";
|
||||
import { localBaseline, localRwcBaseline, refBaseline, refRwcBaseline, runConsoleTests } from "./scripts/build/tests.mjs";
|
||||
import { Debouncer, Deferred, exec, getDiffTool, getDirSize, memoize, needsUpdate, readJson } from "./scripts/build/utils.mjs";
|
||||
|
||||
const glob = util.promisify(_glob);
|
||||
|
||||
@@ -59,10 +60,7 @@ export const generateLibs = task({
|
||||
|
||||
for (const source of lib.sources) {
|
||||
const contents = await fs.promises.readFile(source, "utf-8");
|
||||
// TODO(jakebailey): "\n\n" is for compatibility with our current tests; our test baselines
|
||||
// are sensitive to the positions of things in the lib files. Eventually remove this,
|
||||
// or remove lib.d.ts line numbers from our baselines.
|
||||
output += "\n\n" + contents.replace(/\r\n/g, "\n");
|
||||
output += "\n" + contents.replace(/\r\n/g, "\n");
|
||||
}
|
||||
|
||||
await fs.promises.writeFile(lib.target, output);
|
||||
@@ -182,28 +180,6 @@ function createBundler(entrypoint, outfile, taskOptions = {}) {
|
||||
packages: "external",
|
||||
logLevel: "warning",
|
||||
// legalComments: "none", // If we add copyright headers to the source files, uncomment.
|
||||
plugins: [
|
||||
{
|
||||
name: "fix-require",
|
||||
setup: (build) => {
|
||||
build.onEnd(async () => {
|
||||
// esbuild converts calls to "require" to "__require"; this function
|
||||
// calls the real require if it exists, or throws if it does not (rather than
|
||||
// throwing an error like "require not defined"). But, since we want typescript
|
||||
// to be consumable by other bundlers, we need to convert these calls back to
|
||||
// require so our imports are visible again.
|
||||
//
|
||||
// The leading spaces are to keep the offsets the same within the files to keep
|
||||
// source maps working (though this only really matters for the line the require is on).
|
||||
//
|
||||
// See: https://github.com/evanw/esbuild/issues/1905
|
||||
let contents = await fs.promises.readFile(outfile, "utf-8");
|
||||
contents = contents.replace(/__require\(/g, " require(");
|
||||
await fs.promises.writeFile(outfile, contents);
|
||||
});
|
||||
},
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
if (taskOptions.exportIsTsObject) {
|
||||
@@ -213,6 +189,30 @@ function createBundler(entrypoint, outfile, taskOptions = {}) {
|
||||
options.globalName = "ts";
|
||||
// If we are in a CJS context, export the ts namespace.
|
||||
options.footer = { js: `\nif (typeof module !== "undefined" && module.exports) { module.exports = ts; }` };
|
||||
|
||||
// esbuild converts calls to "require" to "__require"; this function
|
||||
// calls the real require if it exists, or throws if it does not (rather than
|
||||
// throwing an error like "require not defined"). But, since we want typescript
|
||||
// to be consumable by other bundlers, we need to convert these calls back to
|
||||
// require so our imports are visible again.
|
||||
//
|
||||
// The leading spaces are to keep the offsets the same within the files to keep
|
||||
// source maps working (though this only really matters for the line the require is on).
|
||||
//
|
||||
// See: https://github.com/evanw/esbuild/issues/1905
|
||||
options.define = { require: "$$require" };
|
||||
options.plugins = [
|
||||
{
|
||||
name: "fix-require",
|
||||
setup: (build) => {
|
||||
build.onEnd(async () => {
|
||||
let contents = await fs.promises.readFile(outfile, "utf-8");
|
||||
contents = contents.replace(/\$\$require/g, " require");
|
||||
await fs.promises.writeFile(outfile, contents);
|
||||
});
|
||||
},
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
return options;
|
||||
@@ -515,6 +515,7 @@ const { main: watchGuard, watch: watchWatchGuard } = entrypointBuildTask({
|
||||
export const generateTypesMap = task({
|
||||
name: "generate-types-map",
|
||||
run: async () => {
|
||||
await fs.promises.mkdir("./built/local", { recursive: true });
|
||||
const source = "src/server/typesMap.json";
|
||||
const target = "built/local/typesMap.json";
|
||||
const contents = await fs.promises.readFile(source, "utf-8");
|
||||
|
||||
Generated
+355
-336
File diff suppressed because it is too large.
Load diff
@@ -66,6 +66,7 @@
|
||||
"eslint-plugin-import": "^2.26.0",
|
||||
"eslint-plugin-local": "^1.0.0",
|
||||
"eslint-plugin-no-null": "^1.0.2",
|
||||
"eslint-plugin-simple-import-sort": "^10.0.0",
|
||||
"fast-xml-parser": "^4.0.11",
|
||||
"fs-extra": "^9.1.0",
|
||||
"glob": "latest",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import chalk from "chalk";
|
||||
import { join } from "path";
|
||||
import { readFileSync } from "fs";
|
||||
import { join } from "path";
|
||||
|
||||
let playwright;
|
||||
try {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { dirname, join, resolve } from "path";
|
||||
import { existsSync } from "fs";
|
||||
import { dirname, join, resolve } from "path";
|
||||
import url from "url";
|
||||
|
||||
const __filename = url.fileURLToPath(new URL(import.meta.url));
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Debouncer, exec } from "./utils.mjs";
|
||||
import { resolve } from "path";
|
||||
|
||||
import { findUpRoot } from "./findUpDir.mjs";
|
||||
import cmdLineOptions from "./options.mjs";
|
||||
import { Debouncer, exec } from "./utils.mjs";
|
||||
|
||||
class ProjectQueue {
|
||||
/**
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { CancelError } from "@esfx/canceltoken";
|
||||
import chalk from "chalk";
|
||||
import del from "del";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import chalk from "chalk";
|
||||
|
||||
import { findUpFile, findUpRoot } from "./findUpDir.mjs";
|
||||
import cmdLineOptions from "./options.mjs";
|
||||
import { exec } from "./utils.mjs";
|
||||
import { findUpFile, findUpRoot } from "./findUpDir.mjs";
|
||||
import { CancelError } from "@esfx/canceltoken";
|
||||
|
||||
const mochaJs = path.resolve(findUpRoot(), "node_modules", "mocha", "bin", "_mocha");
|
||||
export const localBaseline = "tests/baselines/local/";
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
/* eslint-disable no-restricted-globals */
|
||||
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import chalk from "chalk";
|
||||
import which from "which";
|
||||
import { spawn } from "child_process";
|
||||
import assert from "assert";
|
||||
import JSONC from "jsonc-parser";
|
||||
import { CancelError } from "@esfx/canceltoken";
|
||||
import assert from "assert";
|
||||
import chalk from "chalk";
|
||||
import { spawn } from "child_process";
|
||||
import fs from "fs";
|
||||
import JSONC from "jsonc-parser";
|
||||
import path from "path";
|
||||
import which from "which";
|
||||
|
||||
/**
|
||||
* Executes the provided command once with the supplied arguments.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { normalize, relative } from "path";
|
||||
import assert from "assert";
|
||||
import { readFileSync, writeFileSync } from "fs";
|
||||
import { normalize, relative } from "path";
|
||||
import url from "url";
|
||||
|
||||
const __filename = url.fileURLToPath(new URL(import.meta.url));
|
||||
|
||||
@@ -5,12 +5,13 @@
|
||||
* bundle as namespaces again, even though the project is modules.
|
||||
*/
|
||||
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import minimist from "minimist";
|
||||
import url from "url";
|
||||
import ts from "../lib/typescript.js";
|
||||
import assert, { fail } from "assert";
|
||||
import fs from "fs";
|
||||
import minimist from "minimist";
|
||||
import path from "path";
|
||||
import url from "url";
|
||||
|
||||
import ts from "../lib/typescript.js";
|
||||
|
||||
const __filename = url.fileURLToPath(new URL(import.meta.url));
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// This file requires a modern version of node 14+, and grep to be available.
|
||||
|
||||
// node scripts/find-unused-diagnostic-messages.mjs
|
||||
import { execSync } from "child_process";
|
||||
import { readFileSync } from "fs";
|
||||
import { EOL } from "os";
|
||||
import { execSync } from "child_process";
|
||||
|
||||
const diags = readFileSync("src/compiler/diagnosticInformationMap.generated.ts", "utf8");
|
||||
const startOfDiags = diags.split("export const Diagnostics")[1];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { XMLParser } from "fast-xml-parser";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { XMLParser } from "fast-xml-parser";
|
||||
|
||||
/** @typedef {{
|
||||
LCX: {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import * as os from "os";
|
||||
import * as childProcess from "child_process";
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import url from "url";
|
||||
|
||||
const __filename = url.fileURLToPath(new URL(import.meta.url));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import url from "url";
|
||||
|
||||
import { findUpRoot } from "./build/findUpDir.mjs";
|
||||
|
||||
const __filename = url.fileURLToPath(new URL(import.meta.url));
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import { runSequence } from "./run-sequence.mjs";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import url from "url";
|
||||
|
||||
import { runSequence } from "./run-sequence.mjs";
|
||||
|
||||
const __filename = url.fileURLToPath(new URL(import.meta.url));
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Octokit } from "@octokit/rest";
|
||||
|
||||
import { runSequence } from "./run-sequence.mjs";
|
||||
|
||||
const userName = process.env.GH_USERNAME || "typescript-bot";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import fs from "fs";
|
||||
import ado from "azure-devops-node-api";
|
||||
import fetch from "node-fetch";
|
||||
import assert from "assert";
|
||||
import ado from "azure-devops-node-api";
|
||||
import fs from "fs";
|
||||
import fetch from "node-fetch";
|
||||
|
||||
|
||||
async function main() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
/** @typedef {{
|
||||
category: string;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import fs from "fs-extra";
|
||||
import path from "path";
|
||||
import glob from "glob";
|
||||
import url from "url";
|
||||
import del from "del";
|
||||
import fs from "fs-extra";
|
||||
import glob from "glob";
|
||||
import path from "path";
|
||||
import url from "url";
|
||||
|
||||
import { localizationDirectories } from "./build/localization.mjs";
|
||||
|
||||
const __filename = url.fileURLToPath(new URL(import.meta.url));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Octokit } from "@octokit/rest";
|
||||
|
||||
import { runSequence } from "./run-sequence.mjs";
|
||||
|
||||
// The first is used by bot-based kickoffs, the second by automatic triggers
|
||||
|
||||
+35
-31
@@ -501,49 +501,55 @@ export function bindSourceFile(file: SourceFile, options: CompilerOptions) {
|
||||
}
|
||||
|
||||
function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
|
||||
let file: SourceFile;
|
||||
let options: CompilerOptions;
|
||||
let languageVersion: ScriptTarget;
|
||||
let parent: Node;
|
||||
let container: IsContainer | EntityNameExpression;
|
||||
let thisParentContainer: IsContainer | EntityNameExpression; // Container one level up
|
||||
let blockScopeContainer: IsBlockScopedContainer;
|
||||
let lastContainer: HasLocals;
|
||||
let delayedTypeAliases: (JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag)[];
|
||||
let seenThisKeyword: boolean;
|
||||
// Why var? It avoids TDZ checks in the runtime which can be costly.
|
||||
// See: https://github.com/microsoft/TypeScript/issues/52924
|
||||
/* eslint-disable no-var */
|
||||
var file: SourceFile;
|
||||
var options: CompilerOptions;
|
||||
var languageVersion: ScriptTarget;
|
||||
var parent: Node;
|
||||
var container: IsContainer | EntityNameExpression;
|
||||
var thisParentContainer: IsContainer | EntityNameExpression; // Container one level up
|
||||
var blockScopeContainer: IsBlockScopedContainer;
|
||||
var lastContainer: HasLocals;
|
||||
var delayedTypeAliases: (JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag)[];
|
||||
var seenThisKeyword: boolean;
|
||||
|
||||
// state used by control flow analysis
|
||||
let currentFlow: FlowNode;
|
||||
let currentBreakTarget: FlowLabel | undefined;
|
||||
let currentContinueTarget: FlowLabel | undefined;
|
||||
let currentReturnTarget: FlowLabel | undefined;
|
||||
let currentTrueTarget: FlowLabel | undefined;
|
||||
let currentFalseTarget: FlowLabel | undefined;
|
||||
let currentExceptionTarget: FlowLabel | undefined;
|
||||
let preSwitchCaseFlow: FlowNode | undefined;
|
||||
let activeLabelList: ActiveLabel | undefined;
|
||||
let hasExplicitReturn: boolean;
|
||||
var currentFlow: FlowNode;
|
||||
var currentBreakTarget: FlowLabel | undefined;
|
||||
var currentContinueTarget: FlowLabel | undefined;
|
||||
var currentReturnTarget: FlowLabel | undefined;
|
||||
var currentTrueTarget: FlowLabel | undefined;
|
||||
var currentFalseTarget: FlowLabel | undefined;
|
||||
var currentExceptionTarget: FlowLabel | undefined;
|
||||
var preSwitchCaseFlow: FlowNode | undefined;
|
||||
var activeLabelList: ActiveLabel | undefined;
|
||||
var hasExplicitReturn: boolean;
|
||||
|
||||
// state used for emit helpers
|
||||
let emitFlags: NodeFlags;
|
||||
var emitFlags: NodeFlags;
|
||||
|
||||
// If this file is an external module, then it is automatically in strict-mode according to
|
||||
// ES6. If it is not an external module, then we'll determine if it is in strict mode or
|
||||
// not depending on if we see "use strict" in certain places or if we hit a class/namespace
|
||||
// or if compiler options contain alwaysStrict.
|
||||
let inStrictMode: boolean;
|
||||
var inStrictMode: boolean;
|
||||
|
||||
// If we are binding an assignment pattern, we will bind certain expressions differently.
|
||||
let inAssignmentPattern = false;
|
||||
var inAssignmentPattern = false;
|
||||
|
||||
let symbolCount = 0;
|
||||
var symbolCount = 0;
|
||||
|
||||
let Symbol: new (flags: SymbolFlags, name: __String) => Symbol;
|
||||
let classifiableNames: Set<__String>;
|
||||
var Symbol: new (flags: SymbolFlags, name: __String) => Symbol;
|
||||
var classifiableNames: Set<__String>;
|
||||
|
||||
const unreachableFlow: FlowNode = { flags: FlowFlags.Unreachable };
|
||||
const reportedUnreachableFlow: FlowNode = { flags: FlowFlags.Unreachable };
|
||||
const bindBinaryExpressionFlow = createBindBinaryExpressionFlow();
|
||||
var unreachableFlow: FlowNode = { flags: FlowFlags.Unreachable };
|
||||
var reportedUnreachableFlow: FlowNode = { flags: FlowFlags.Unreachable };
|
||||
var bindBinaryExpressionFlow = createBindBinaryExpressionFlow();
|
||||
/* eslint-enable no-var */
|
||||
|
||||
return bindSourceFile;
|
||||
|
||||
/**
|
||||
* Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
|
||||
@@ -600,8 +606,6 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
|
||||
emitFlags = NodeFlags.None;
|
||||
}
|
||||
|
||||
return bindSourceFile;
|
||||
|
||||
function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean {
|
||||
if (getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
|
||||
// bind in strict mode source files with alwaysStrict option
|
||||
|
||||
+55
-4
@@ -37,6 +37,7 @@ import {
|
||||
emitSkippedWithNoDiagnostics,
|
||||
emptyArray,
|
||||
ensurePathIsNonModuleName,
|
||||
FileIncludeKind,
|
||||
filterSemanticDiagnostics,
|
||||
forEach,
|
||||
forEachEntry,
|
||||
@@ -44,6 +45,7 @@ import {
|
||||
generateDjb2Hash,
|
||||
getDirectoryPath,
|
||||
getEmitDeclarations,
|
||||
getIsolatedModules,
|
||||
getNormalizedAbsolutePath,
|
||||
getOptionsNameMap,
|
||||
getOwnKeys,
|
||||
@@ -762,7 +764,7 @@ function handleDtsMayChangeOfReferencingExportOfAffectedFile(
|
||||
|
||||
// Since isolated modules dont change js files, files affected by change in signature is itself
|
||||
// But we need to cleanup semantic diagnostics and queue dts emit for affected files
|
||||
if (state.compilerOptions.isolatedModules) {
|
||||
if (getIsolatedModules(state.compilerOptions)) {
|
||||
const seenFileNamesMap = new Map<Path, true>();
|
||||
seenFileNamesMap.set(affectedFile.resolvedPath, true);
|
||||
const queue = BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
|
||||
@@ -911,9 +913,17 @@ export type ProgramBuildInfoEmitSignature = ProgramBuildInfoFileId | [fileId: Pr
|
||||
*/
|
||||
export type ProgramMultiFileEmitBuildInfoFileInfo = string | ProgramMultiFileEmitBuildInfoBuilderStateFileInfo;
|
||||
/** @internal */
|
||||
export type ProgramBuildInfoRootStartEnd = [start: ProgramBuildInfoFileId, end: ProgramBuildInfoFileId];
|
||||
/**
|
||||
* Either start and end of FileId for consecutive fileIds to be included as root or single fileId that is root
|
||||
* @internal
|
||||
*/
|
||||
export type ProgramBuildInfoRoot = ProgramBuildInfoRootStartEnd | ProgramBuildInfoFileId;
|
||||
/** @internal */
|
||||
export interface ProgramMultiFileEmitBuildInfo {
|
||||
fileNames: readonly string[];
|
||||
fileInfos: readonly ProgramMultiFileEmitBuildInfoFileInfo[];
|
||||
root: readonly ProgramBuildInfoRoot[];
|
||||
options: CompilerOptions | undefined;
|
||||
fileIdsList: readonly (readonly ProgramBuildInfoFileId[])[] | undefined;
|
||||
referencedMap: ProgramBuildInfoReferencedMap | undefined;
|
||||
@@ -942,6 +952,7 @@ export type ProgramBuildInfoBundlePendingEmit = BuilderFileEmit | false;
|
||||
export interface ProgramBundleEmitBuildInfo {
|
||||
fileNames: readonly string[];
|
||||
fileInfos: readonly ProgramBundleEmitBuildInfoFileInfo[];
|
||||
root: readonly ProgramBuildInfoRoot[];
|
||||
options: CompilerOptions | undefined;
|
||||
outSignature: EmitSignature | undefined;
|
||||
latestChangedDtsFile: string | undefined;
|
||||
@@ -966,12 +977,14 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde
|
||||
const latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : undefined;
|
||||
const fileNames: string[] = [];
|
||||
const fileNameToFileId = new Map<string, ProgramBuildInfoFileId>();
|
||||
const root: ProgramBuildInfoRoot[] = [];
|
||||
if (outFile(state.compilerOptions)) {
|
||||
// Copy all fileInfo, version and impliedFormat
|
||||
// Affects global scope and signature doesnt matter because with --out they arent calculated or needed to determine upto date ness
|
||||
const fileInfos = arrayFrom(state.fileInfos.entries(), ([key, value]): ProgramBundleEmitBuildInfoFileInfo => {
|
||||
// Ensure fileId
|
||||
toFileId(key);
|
||||
const fileId = toFileId(key);
|
||||
tryAddRoot(key, fileId);
|
||||
return value.impliedFormat ?
|
||||
{ version: value.version, impliedFormat: value.impliedFormat, signature: undefined, affectsGlobalScope: undefined } :
|
||||
value.version;
|
||||
@@ -979,6 +992,7 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde
|
||||
const program: ProgramBundleEmitBuildInfo = {
|
||||
fileNames,
|
||||
fileInfos,
|
||||
root,
|
||||
options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions),
|
||||
outSignature: state.outSignature,
|
||||
latestChangedDtsFile,
|
||||
@@ -1005,6 +1019,7 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde
|
||||
const fileInfos = arrayFrom(state.fileInfos.entries(), ([key, value]): ProgramMultiFileEmitBuildInfoFileInfo => {
|
||||
// Ensure fileId
|
||||
const fileId = toFileId(key);
|
||||
tryAddRoot(key, fileId);
|
||||
Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key));
|
||||
const oldSignature = state.oldSignatures?.get(key);
|
||||
const actualSignature = oldSignature !== undefined ? oldSignature || undefined : value.signature;
|
||||
@@ -1100,6 +1115,7 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde
|
||||
const program: ProgramMultiFileEmitBuildInfo = {
|
||||
fileNames,
|
||||
fileInfos,
|
||||
root,
|
||||
options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions),
|
||||
fileIdsList,
|
||||
referencedMap,
|
||||
@@ -1140,6 +1156,25 @@ function getBuildInfo(state: BuilderProgramState, bundle: BundleBuildInfo | unde
|
||||
return fileIdListId;
|
||||
}
|
||||
|
||||
function tryAddRoot(path: Path, fileId: ProgramBuildInfoFileId) {
|
||||
const file = state.program!.getSourceFile(path)!;
|
||||
if (!state.program!.getFileIncludeReasons().get(file.path)!.some(r => r.kind === FileIncludeKind.RootFile)) return;
|
||||
// First fileId as is
|
||||
if (!root.length) return root.push(fileId);
|
||||
const last = root[root.length - 1];
|
||||
const isLastStartEnd = isArray(last);
|
||||
// If its [..., last = [start, end = fileId - 1]], update last to [start, fileId]
|
||||
if (isLastStartEnd && last[1] === fileId - 1) return last[1] = fileId;
|
||||
// If its [..., last = [start, end !== fileId - 1]] or [last] or [..., last !== fileId - 1], push the fileId
|
||||
if (isLastStartEnd || root.length === 1 || last !== fileId - 1) return root.push(fileId);
|
||||
const lastButOne = root[root.length - 2];
|
||||
// If [..., lastButOne = [start, end], lastFileId] or [..., lastButOne !== lastFileId - 1, lastFileId], push the fileId
|
||||
if (!isNumber(lastButOne) || lastButOne !== last - 1) return root.push(fileId);
|
||||
// Convert lastButOne as [lastButOne, fileId]
|
||||
root[root.length - 2] = [lastButOne, fileId];
|
||||
return root.length = root.length - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param optionKey key of CommandLineOption to use to determine if the option should be serialized in tsbuildinfo
|
||||
*/
|
||||
@@ -1776,16 +1811,32 @@ export function getBuildInfoFileVersionMap(
|
||||
program: ProgramBuildInfo,
|
||||
buildInfoPath: string,
|
||||
host: Pick<ReadBuildProgramHost, "useCaseSensitiveFileNames" | "getCurrentDirectory">
|
||||
): Map<Path, string> {
|
||||
) {
|
||||
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
|
||||
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
|
||||
const fileInfos = new Map<Path, string>();
|
||||
let rootIndex = 0;
|
||||
const roots: Path[] = [];
|
||||
program.fileInfos.forEach((fileInfo, index) => {
|
||||
const path = toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName);
|
||||
const version = isString(fileInfo) ? fileInfo : fileInfo.version;
|
||||
fileInfos.set(path, version);
|
||||
if (rootIndex < program.root.length) {
|
||||
const current = program.root[rootIndex];
|
||||
const fileId = (index + 1) as ProgramBuildInfoFileId;
|
||||
if (isArray(current)) {
|
||||
if (current[0] <= fileId && fileId <= current[1]) {
|
||||
roots.push(path);
|
||||
if (current[1] === fileId) rootIndex++;
|
||||
}
|
||||
}
|
||||
else if (current === fileId) {
|
||||
roots.push(path);
|
||||
rootIndex++;
|
||||
}
|
||||
}
|
||||
});
|
||||
return fileInfos;
|
||||
return { fileInfos, roots };
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
ExportedModulesFromDeclarationEmit,
|
||||
GetCanonicalFileName,
|
||||
getDirectoryPath,
|
||||
getIsolatedModules,
|
||||
getSourceFileOfNode,
|
||||
HostForComputeHash,
|
||||
isDeclarationFileName,
|
||||
@@ -635,7 +636,7 @@ export namespace BuilderState {
|
||||
}
|
||||
|
||||
const compilerOptions = programOfThisState.getCompilerOptions();
|
||||
if (compilerOptions && (compilerOptions.isolatedModules || outFile(compilerOptions))) {
|
||||
if (compilerOptions && (getIsolatedModules(compilerOptions) || outFile(compilerOptions))) {
|
||||
return [sourceFileWithUpdatedShape];
|
||||
}
|
||||
|
||||
|
||||
+812
-541
File diff suppressed because it is too large.
Load diff
@@ -1221,7 +1221,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [
|
||||
{
|
||||
name: "allowArbitraryExtensions",
|
||||
type: "boolean",
|
||||
affectsModuleResolution: true,
|
||||
affectsProgramStructure: true,
|
||||
category: Diagnostics.Modules,
|
||||
description: Diagnostics.Enable_importing_files_with_any_extension_provided_a_declaration_file_is_present,
|
||||
defaultValueDescription: false,
|
||||
|
||||
@@ -1076,10 +1076,6 @@
|
||||
"category": "Error",
|
||||
"code": 1341
|
||||
},
|
||||
"Type arguments cannot be used here.": {
|
||||
"category": "Error",
|
||||
"code": 1342
|
||||
},
|
||||
"The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.": {
|
||||
"category": "Error",
|
||||
"code": 1343
|
||||
@@ -1593,6 +1589,10 @@
|
||||
"category": "Error",
|
||||
"code": 1485
|
||||
},
|
||||
"Decorator used before 'export' here.": {
|
||||
"category": "Error",
|
||||
"code": 1486
|
||||
},
|
||||
|
||||
"The types of '{0}' are incompatible between these types.": {
|
||||
"category": "Error",
|
||||
@@ -3030,10 +3030,6 @@
|
||||
"category": "Error",
|
||||
"code": 2690
|
||||
},
|
||||
"An import path cannot end with a '{0}' extension. Consider importing '{1}' instead.": {
|
||||
"category": "Error",
|
||||
"code": 2691
|
||||
},
|
||||
"'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible.": {
|
||||
"category": "Error",
|
||||
"code": 2692
|
||||
@@ -3499,7 +3495,7 @@
|
||||
"category": "Error",
|
||||
"code": 2808
|
||||
},
|
||||
"Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses.": {
|
||||
"Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the whole assignment in parentheses.": {
|
||||
"category": "Error",
|
||||
"code": 2809
|
||||
},
|
||||
@@ -4269,7 +4265,7 @@
|
||||
"category": "Error",
|
||||
"code": 5094
|
||||
},
|
||||
"Option 'preserveValueImports' can only be used when 'module' is set to 'es2015' or later.": {
|
||||
"Option '{0}' can only be used when 'module' is set to 'es2015' or later.": {
|
||||
"category": "Error",
|
||||
"code": 5095
|
||||
},
|
||||
@@ -4285,15 +4281,7 @@
|
||||
"category": "Error",
|
||||
"code": 5098
|
||||
},
|
||||
"Import assignment is not allowed when 'moduleResolution' is set to 'bundler'. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead.": {
|
||||
"category": "Error",
|
||||
"code": 5099
|
||||
},
|
||||
"Export assignment cannot be used when 'moduleResolution' is set to 'bundler'. Consider using 'export default' or another module format instead.": {
|
||||
"category": "Error",
|
||||
"code": 5100
|
||||
},
|
||||
"Flag '{0}' is deprecated and will stop functioning in TypeScript {1}. Specify 'ignoreDeprecations: \"{2}\"' to silence this error.": {
|
||||
"Flag '{0}' is deprecated and will stop functioning in TypeScript {1}. Specify compilerOption '\"ignoreDeprecations\": \"{2}\"' to silence this error.": {
|
||||
"category": "Error",
|
||||
"code": 5101
|
||||
},
|
||||
@@ -4647,7 +4635,7 @@
|
||||
"category": "Message",
|
||||
"code": 6096
|
||||
},
|
||||
"File '{0}' exist - use it as a name resolution result.": {
|
||||
"File '{0}' exists - use it as a name resolution result.": {
|
||||
"category": "Message",
|
||||
"code": 6097
|
||||
},
|
||||
@@ -5562,6 +5550,26 @@
|
||||
"category": "Message",
|
||||
"code": 6411
|
||||
},
|
||||
"Project '{0}' is out of date because buildinfo file '{1}' indicates that file '{2}' was root file of compilation but not any more.": {
|
||||
"category": "Message",
|
||||
"code": 6412
|
||||
},
|
||||
"Entering conditional exports.": {
|
||||
"category": "Message",
|
||||
"code": 6413
|
||||
},
|
||||
"Resolved under condition '{0}'.": {
|
||||
"category": "Message",
|
||||
"code": 6414
|
||||
},
|
||||
"Failed to resolve under condition '{0}'.": {
|
||||
"category": "Message",
|
||||
"code": 6415
|
||||
},
|
||||
"Exiting conditional exports.": {
|
||||
"category": "Message",
|
||||
"code": 6416
|
||||
},
|
||||
|
||||
"The expected type comes from property '{0}' which is declared here on type '{1}'": {
|
||||
"category": "Message",
|
||||
@@ -6209,6 +6217,10 @@
|
||||
"category": "Error",
|
||||
"code": 7011
|
||||
},
|
||||
"This overload implicitly returns the type '{0}' because it lacks a return type annotation.": {
|
||||
"category": "Error",
|
||||
"code": 7012
|
||||
},
|
||||
"Construct signature, which lacks return-type annotation, implicitly has an 'any' return type.": {
|
||||
"category": "Error",
|
||||
"code": 7013
|
||||
@@ -6544,7 +6556,7 @@
|
||||
"category": "Error",
|
||||
"code": 8037
|
||||
},
|
||||
"Decorators must come after 'export' or 'export default' in JavaScript files.": {
|
||||
"Decorators may not appear after 'export' or 'export default' if they also appear before 'export'.": {
|
||||
"category": "Error",
|
||||
"code": 8038
|
||||
},
|
||||
|
||||
+72
-64
@@ -737,15 +737,19 @@ export function getFirstProjectOutput(configFile: ParsedCommandLine, ignoreCase:
|
||||
/** @internal */
|
||||
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
|
||||
export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile | undefined, { scriptTransformers, declarationTransformers }: EmitTransformers, emitOnly?: boolean | EmitOnly, onlyBuildInfo?: boolean, forceDtsEmit?: boolean): EmitResult {
|
||||
const compilerOptions = host.getCompilerOptions();
|
||||
const sourceMapDataList: SourceMapEmitResult[] | undefined = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
|
||||
const emittedFilesList: string[] | undefined = compilerOptions.listEmittedFiles ? [] : undefined;
|
||||
const emitterDiagnostics = createDiagnosticCollection();
|
||||
const newLine = getNewLineCharacter(compilerOptions);
|
||||
const writer = createTextWriter(newLine);
|
||||
const { enter, exit } = performance.createTimer("printTime", "beforePrint", "afterPrint");
|
||||
let bundleBuildInfo: BundleBuildInfo | undefined;
|
||||
let emitSkipped = false;
|
||||
// Why var? It avoids TDZ checks in the runtime which can be costly.
|
||||
// See: https://github.com/microsoft/TypeScript/issues/52924
|
||||
/* eslint-disable no-var */
|
||||
var compilerOptions = host.getCompilerOptions();
|
||||
var sourceMapDataList: SourceMapEmitResult[] | undefined = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
|
||||
var emittedFilesList: string[] | undefined = compilerOptions.listEmittedFiles ? [] : undefined;
|
||||
var emitterDiagnostics = createDiagnosticCollection();
|
||||
var newLine = getNewLineCharacter(compilerOptions);
|
||||
var writer = createTextWriter(newLine);
|
||||
var { enter, exit } = performance.createTimer("printTime", "beforePrint", "afterPrint");
|
||||
var bundleBuildInfo: BundleBuildInfo | undefined;
|
||||
var emitSkipped = false;
|
||||
/* eslint-enable no-var */
|
||||
|
||||
// Emit each output file
|
||||
enter();
|
||||
@@ -1344,19 +1348,22 @@ const enum PipelinePhase {
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const createPrinterWithDefaults = memoize(() => createPrinter({}));
|
||||
export const createPrinterWithDefaults = /* @__PURE__ */ memoize(() => createPrinter({}));
|
||||
|
||||
/** @internal */
|
||||
export const createPrinterWithRemoveComments = memoize(() => createPrinter({ removeComments: true }));
|
||||
export const createPrinterWithRemoveComments = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true }));
|
||||
|
||||
/** @internal */
|
||||
export const createPrinterWithRemoveCommentsNeverAsciiEscape = memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true }));
|
||||
export const createPrinterWithRemoveCommentsNeverAsciiEscape = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, neverAsciiEscape: true }));
|
||||
|
||||
/** @internal */
|
||||
export const createPrinterWithRemoveCommentsOmitTrailingSemicolon = memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true }));
|
||||
export const createPrinterWithRemoveCommentsOmitTrailingSemicolon = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true, omitTrailingSemicolon: true }));
|
||||
|
||||
export function createPrinter(printerOptions: PrinterOptions = {}, handlers: PrintHandlers = {}): Printer {
|
||||
const {
|
||||
// Why var? It avoids TDZ checks in the runtime which can be costly.
|
||||
// See: https://github.com/microsoft/TypeScript/issues/52924
|
||||
/* eslint-disable no-var */
|
||||
var {
|
||||
hasGlobalName,
|
||||
onEmitNode = noEmitNotification,
|
||||
isEmitNotificationEnabled,
|
||||
@@ -1369,63 +1376,64 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
|
||||
onAfterEmitToken
|
||||
} = handlers;
|
||||
|
||||
const extendedDiagnostics = !!printerOptions.extendedDiagnostics;
|
||||
const newLine = getNewLineCharacter(printerOptions);
|
||||
const moduleKind = getEmitModuleKind(printerOptions);
|
||||
const bundledHelpers = new Map<string, boolean>();
|
||||
var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
|
||||
var newLine = getNewLineCharacter(printerOptions);
|
||||
var moduleKind = getEmitModuleKind(printerOptions);
|
||||
var bundledHelpers = new Map<string, boolean>();
|
||||
|
||||
let currentSourceFile: SourceFile | undefined;
|
||||
let nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes.
|
||||
let nodeIdToGeneratedPrivateName: string[]; // Map of generated names for specific nodes.
|
||||
let autoGeneratedIdToGeneratedName: string[]; // Map of generated names for temp and loop variables.
|
||||
let generatedNames: Set<string>; // Set of names generated by the NameGenerator.
|
||||
let formattedNameTempFlagsStack: (Map<string, TempFlags> | undefined)[];
|
||||
let formattedNameTempFlags: Map<string, TempFlags> | undefined;
|
||||
let privateNameTempFlagsStack: TempFlags[]; // Stack of enclosing name generation scopes.
|
||||
let privateNameTempFlags: TempFlags; // TempFlags for the current name generation scope.
|
||||
let tempFlagsStack: TempFlags[]; // Stack of enclosing name generation scopes.
|
||||
let tempFlags: TempFlags; // TempFlags for the current name generation scope.
|
||||
let reservedNamesStack: (Set<string> | undefined)[]; // Stack of reserved names in enclosing name generation scopes.
|
||||
let reservedNames: Set<string> | undefined; // Names reserved in nested name generation scopes.
|
||||
let reservedPrivateNamesStack: (Set<string> | undefined)[]; // Stack of reserved member names in enclosing name generation scopes.
|
||||
let reservedPrivateNames: Set<string> | undefined; // Member names reserved in nested name generation scopes.
|
||||
let preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
|
||||
let nextListElementPos: number | undefined; // See comment in `getLeadingLineTerminatorCount`.
|
||||
var currentSourceFile: SourceFile | undefined;
|
||||
var nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes.
|
||||
var nodeIdToGeneratedPrivateName: string[]; // Map of generated names for specific nodes.
|
||||
var autoGeneratedIdToGeneratedName: string[]; // Map of generated names for temp and loop variables.
|
||||
var generatedNames: Set<string>; // Set of names generated by the NameGenerator.
|
||||
var formattedNameTempFlagsStack: (Map<string, TempFlags> | undefined)[];
|
||||
var formattedNameTempFlags: Map<string, TempFlags> | undefined;
|
||||
var privateNameTempFlagsStack: TempFlags[]; // Stack of enclosing name generation scopes.
|
||||
var privateNameTempFlags: TempFlags; // TempFlags for the current name generation scope.
|
||||
var tempFlagsStack: TempFlags[]; // Stack of enclosing name generation scopes.
|
||||
var tempFlags: TempFlags; // TempFlags for the current name generation scope.
|
||||
var reservedNamesStack: (Set<string> | undefined)[]; // Stack of reserved names in enclosing name generation scopes.
|
||||
var reservedNames: Set<string> | undefined; // Names reserved in nested name generation scopes.
|
||||
var reservedPrivateNamesStack: (Set<string> | undefined)[]; // Stack of reserved member names in enclosing name generation scopes.
|
||||
var reservedPrivateNames: Set<string> | undefined; // Member names reserved in nested name generation scopes.
|
||||
var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
|
||||
var nextListElementPos: number | undefined; // See comment in `getLeadingLineTerminatorCount`.
|
||||
|
||||
let writer: EmitTextWriter;
|
||||
let ownWriter: EmitTextWriter; // Reusable `EmitTextWriter` for basic printing.
|
||||
let write = writeBase;
|
||||
let isOwnFileEmit: boolean;
|
||||
const bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } as BundleFileInfo : undefined;
|
||||
const relativeToBuildInfo = bundleFileInfo ? Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
|
||||
const recordInternalSection = printerOptions.recordInternalSection;
|
||||
let sourceFileTextPos = 0;
|
||||
let sourceFileTextKind: BundleFileTextLikeKind = BundleFileSectionKind.Text;
|
||||
var writer: EmitTextWriter;
|
||||
var ownWriter: EmitTextWriter; // Reusable `EmitTextWriter` for basic printing.
|
||||
var write = writeBase;
|
||||
var isOwnFileEmit: boolean;
|
||||
var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } as BundleFileInfo : undefined;
|
||||
var relativeToBuildInfo = bundleFileInfo ? Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
|
||||
var recordInternalSection = printerOptions.recordInternalSection;
|
||||
var sourceFileTextPos = 0;
|
||||
var sourceFileTextKind: BundleFileTextLikeKind = BundleFileSectionKind.Text;
|
||||
|
||||
// Source Maps
|
||||
let sourceMapsDisabled = true;
|
||||
let sourceMapGenerator: SourceMapGenerator | undefined;
|
||||
let sourceMapSource: SourceMapSource;
|
||||
let sourceMapSourceIndex = -1;
|
||||
let mostRecentlyAddedSourceMapSource: SourceMapSource;
|
||||
let mostRecentlyAddedSourceMapSourceIndex = -1;
|
||||
var sourceMapsDisabled = true;
|
||||
var sourceMapGenerator: SourceMapGenerator | undefined;
|
||||
var sourceMapSource: SourceMapSource;
|
||||
var sourceMapSourceIndex = -1;
|
||||
var mostRecentlyAddedSourceMapSource: SourceMapSource;
|
||||
var mostRecentlyAddedSourceMapSourceIndex = -1;
|
||||
|
||||
// Comments
|
||||
let containerPos = -1;
|
||||
let containerEnd = -1;
|
||||
let declarationListContainerEnd = -1;
|
||||
let currentLineMap: readonly number[] | undefined;
|
||||
let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number }[] | undefined;
|
||||
let hasWrittenComment = false;
|
||||
let commentsDisabled = !!printerOptions.removeComments;
|
||||
let lastSubstitution: Node | undefined;
|
||||
let currentParenthesizerRule: ParenthesizerRule<any> | undefined;
|
||||
const { enter: enterComment, exit: exitComment } = performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment");
|
||||
const parenthesizer = factory.parenthesizer;
|
||||
const typeArgumentParenthesizerRuleSelector: OrdinalParentheizerRuleSelector<TypeNode> = {
|
||||
var containerPos = -1;
|
||||
var containerEnd = -1;
|
||||
var declarationListContainerEnd = -1;
|
||||
var currentLineMap: readonly number[] | undefined;
|
||||
var detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number }[] | undefined;
|
||||
var hasWrittenComment = false;
|
||||
var commentsDisabled = !!printerOptions.removeComments;
|
||||
var lastSubstitution: Node | undefined;
|
||||
var currentParenthesizerRule: ParenthesizerRule<any> | undefined;
|
||||
var { enter: enterComment, exit: exitComment } = performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment");
|
||||
var parenthesizer = factory.parenthesizer;
|
||||
var typeArgumentParenthesizerRuleSelector: OrdinalParentheizerRuleSelector<TypeNode> = {
|
||||
select: index => index === 0 ? parenthesizer.parenthesizeLeadingTypeArgument : undefined
|
||||
};
|
||||
const emitBinaryExpression = createEmitBinaryExpression();
|
||||
var emitBinaryExpression = createEmitBinaryExpression();
|
||||
/* eslint-enable no-var */
|
||||
|
||||
reset();
|
||||
return {
|
||||
@@ -1567,7 +1575,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
|
||||
writeLine();
|
||||
const pos = writer.getTextPos();
|
||||
const savedSections = bundleFileInfo && bundleFileInfo.sections;
|
||||
if (savedSections) bundleFileInfo.sections = [];
|
||||
if (savedSections) bundleFileInfo!.sections = [];
|
||||
print(EmitHint.Unspecified, prepend, /*sourceFile*/ undefined);
|
||||
if (bundleFileInfo) {
|
||||
const newSections = bundleFileInfo.sections;
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
isComputedPropertyName,
|
||||
isIdentifier,
|
||||
memoize,
|
||||
ObjectLiteralElementLike,
|
||||
PrivateIdentifier,
|
||||
ScriptTarget,
|
||||
setEmitFlags,
|
||||
@@ -250,155 +251,97 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel
|
||||
]);
|
||||
}
|
||||
|
||||
// Per https://github.com/tc39/proposal-decorators/issues/494, we may need to change the emit for the `access` object
|
||||
// so that it does not need to be used via `.call`. The following two sections represent the options presented in
|
||||
// tc39/proposal-decorators#494
|
||||
//
|
||||
// === Current approach (`access.get.call(obj)`, `access.set.call(obj, value)`) ===
|
||||
//
|
||||
// function createESDecorateClassElementAccessGetMethod(elementName: ESDecorateName) {
|
||||
// const accessor = elementName.computed ?
|
||||
// factory.createElementAccessExpression(factory.createThis(), elementName.name) :
|
||||
// factory.createPropertyAccessExpression(factory.createThis(), elementName.name);
|
||||
//
|
||||
// return factory.createMethodDeclaration(
|
||||
// /*modifiers*/ undefined,
|
||||
// /*asteriskToken*/ undefined,
|
||||
// "get",
|
||||
// /*questionToken*/ undefined,
|
||||
// /*typeParameters*/ undefined,
|
||||
// [],
|
||||
// /*type*/ undefined,
|
||||
// factory.createBlock([factory.createReturnStatement(accessor)])
|
||||
// );
|
||||
// }
|
||||
//
|
||||
// function createESDecorateClassElementAccessSetMethod(elementName: ESDecorateName) {
|
||||
// const accessor = elementName.computed ?
|
||||
// factory.createElementAccessExpression(factory.createThis(), elementName.name) :
|
||||
// factory.createPropertyAccessExpression(factory.createThis(), elementName.name);
|
||||
//
|
||||
// return factory.createMethodDeclaration(
|
||||
// /*modifiers*/ undefined,
|
||||
// /*asteriskToken*/ undefined,
|
||||
// "set",
|
||||
// /*questionToken*/ undefined,
|
||||
// /*typeParameters*/ undefined,
|
||||
// [factory.createParameterDeclaration(
|
||||
// /*modifiers*/ undefined,
|
||||
// /*dotDotDotToken*/ undefined,
|
||||
// factory.createIdentifier("value")
|
||||
// )],
|
||||
// /*type*/ undefined,
|
||||
// factory.createBlock([
|
||||
// factory.createExpressionStatement(
|
||||
// factory.createAssignment(
|
||||
// accessor,
|
||||
// factory.createIdentifier("value")
|
||||
// )
|
||||
// )
|
||||
// ])
|
||||
// );
|
||||
// }
|
||||
//
|
||||
// function createESDecorateClassElementAccessObject(name: ESDecorateName, access: ESDecorateClassElementAccess) {
|
||||
// const properties: ObjectLiteralElementLike[] = [];
|
||||
// if (access.get) properties.push(createESDecorateClassElementAccessGetMethod(name));
|
||||
// if (access.set) properties.push(createESDecorateClassElementAccessSetMethod(name));
|
||||
// return factory.createObjectLiteralExpression(properties);
|
||||
// }
|
||||
//
|
||||
// === Suggested approach (`access.get(obj)`, `access.set(obj, value)`, `access.has(obj)`) ===
|
||||
//
|
||||
// function createESDecorateClassElementAccessGetMethod(elementName: ESDecorateName) {
|
||||
// const accessor = elementName.computed ?
|
||||
// factory.createElementAccessExpression(factory.createIdentifier("obj"), elementName.name) :
|
||||
// factory.createPropertyAccessExpression(factory.createIdentifier("obj"), elementName.name);
|
||||
//
|
||||
// return factory.createMethodDeclaration(
|
||||
// /*modifiers*/ undefined,
|
||||
// /*asteriskToken*/ undefined,
|
||||
// "get",
|
||||
// /*questionToken*/ undefined,
|
||||
// /*typeParameters*/ undefined,
|
||||
// [factory.createParameterDeclaration(
|
||||
// /*modifiers*/ undefined,
|
||||
// /*dotDotDotToken*/ undefined,
|
||||
// factory.createIdentifier("obj")
|
||||
// )],
|
||||
// /*type*/ undefined,
|
||||
// factory.createBlock([factory.createReturnStatement(accessor)])
|
||||
// );
|
||||
// }
|
||||
//
|
||||
// function createESDecorateClassElementAccessSetMethod(elementName: ESDecorateName) {
|
||||
// const accessor = elementName.computed ?
|
||||
// factory.createElementAccessExpression(factory.createIdentifier("obj"), elementName.name) :
|
||||
// factory.createPropertyAccessExpression(factory.createIdentifier("obj"), elementName.name);
|
||||
//
|
||||
// return factory.createMethodDeclaration(
|
||||
// /*modifiers*/ undefined,
|
||||
// /*asteriskToken*/ undefined,
|
||||
// "set",
|
||||
// /*questionToken*/ undefined,
|
||||
// /*typeParameters*/ undefined,
|
||||
// [factory.createParameterDeclaration(
|
||||
// /*modifiers*/ undefined,
|
||||
// /*dotDotDotToken*/ undefined,
|
||||
// factory.createIdentifier("obj")
|
||||
// ),
|
||||
// factory.createParameterDeclaration(
|
||||
// /*modifiers*/ undefined,
|
||||
// /*dotDotDotToken*/ undefined,
|
||||
// factory.createIdentifier("value")
|
||||
// )],
|
||||
// /*type*/ undefined,
|
||||
// factory.createBlock([
|
||||
// factory.createExpressionStatement(
|
||||
// factory.createAssignment(
|
||||
// accessor,
|
||||
// factory.createIdentifier("value")
|
||||
// )
|
||||
// )
|
||||
// ])
|
||||
// );
|
||||
// }
|
||||
//
|
||||
// function createESDecorateClassElementAccessHasMethod(elementName: ESDecorateName) {
|
||||
// const propertyName =
|
||||
// elementName.computed ? elementName.name :
|
||||
// isIdentifier(elementName.name) ? factory.createStringLiteralFromNode(elementName.name) :
|
||||
// elementName.name;
|
||||
//
|
||||
// return factory.createMethodDeclaration(
|
||||
// /*modifiers*/ undefined,
|
||||
// /*asteriskToken*/ undefined,
|
||||
// "has",
|
||||
// /*questionToken*/ undefined,
|
||||
// /*typeParameters*/ undefined,
|
||||
// [factory.createParameterDeclaration(
|
||||
// /*modifiers*/ undefined,
|
||||
// /*dotDotDotToken*/ undefined,
|
||||
// factory.createIdentifier("obj")
|
||||
// )],
|
||||
// /*type*/ undefined,
|
||||
// factory.createBlock([factory.createReturnStatement(
|
||||
// factory.createBinaryExpression(
|
||||
// propertyName,
|
||||
// SyntaxKind.InKeyword,
|
||||
// factory.createIdentifier("obj")
|
||||
// )
|
||||
// )])
|
||||
// );
|
||||
// }
|
||||
//
|
||||
// function createESDecorateClassElementAccessObject(name: ESDecorateName, access: ESDecorateClassElementAccess) {
|
||||
// const properties: ObjectLiteralElementLike[] = [];
|
||||
// if (access.get) properties.push(createESDecorateClassElementAccessGetMethod(name));
|
||||
// if (access.set) properties.push(createESDecorateClassElementAccessSetMethod(name));
|
||||
// property.push(createESDecorateClassElementAccessHasMethod(name));
|
||||
// return factory.createObjectLiteralExpression(properties);
|
||||
// }
|
||||
|
||||
function createESDecorateClassElementAccessGetMethod(elementName: ESDecorateName) {
|
||||
const accessor = elementName.computed ?
|
||||
factory.createElementAccessExpression(factory.createIdentifier("obj"), elementName.name) :
|
||||
factory.createPropertyAccessExpression(factory.createIdentifier("obj"), elementName.name);
|
||||
|
||||
return factory.createPropertyAssignment(
|
||||
"get",
|
||||
factory.createArrowFunction(
|
||||
/*modifiers*/ undefined,
|
||||
/*typeParameters*/ undefined,
|
||||
[factory.createParameterDeclaration(
|
||||
/*modifiers*/ undefined,
|
||||
/*dotDotDotToken*/ undefined,
|
||||
factory.createIdentifier("obj")
|
||||
)],
|
||||
/*type*/ undefined,
|
||||
/*equalsGreaterThanToken*/ undefined,
|
||||
accessor
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function createESDecorateClassElementAccessSetMethod(elementName: ESDecorateName) {
|
||||
const accessor = elementName.computed ?
|
||||
factory.createElementAccessExpression(factory.createIdentifier("obj"), elementName.name) :
|
||||
factory.createPropertyAccessExpression(factory.createIdentifier("obj"), elementName.name);
|
||||
|
||||
return factory.createPropertyAssignment(
|
||||
"set",
|
||||
factory.createArrowFunction(
|
||||
/*modifiers*/ undefined,
|
||||
/*typeParameters*/ undefined,
|
||||
[factory.createParameterDeclaration(
|
||||
/*modifiers*/ undefined,
|
||||
/*dotDotDotToken*/ undefined,
|
||||
factory.createIdentifier("obj")
|
||||
),
|
||||
factory.createParameterDeclaration(
|
||||
/*modifiers*/ undefined,
|
||||
/*dotDotDotToken*/ undefined,
|
||||
factory.createIdentifier("value")
|
||||
)],
|
||||
/*type*/ undefined,
|
||||
/*equalsGreaterThanToken*/ undefined,
|
||||
factory.createBlock([
|
||||
factory.createExpressionStatement(
|
||||
factory.createAssignment(
|
||||
accessor,
|
||||
factory.createIdentifier("value")
|
||||
)
|
||||
)
|
||||
])
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function createESDecorateClassElementAccessHasMethod(elementName: ESDecorateName) {
|
||||
const propertyName =
|
||||
elementName.computed ? elementName.name :
|
||||
isIdentifier(elementName.name) ? factory.createStringLiteralFromNode(elementName.name) :
|
||||
elementName.name;
|
||||
|
||||
return factory.createPropertyAssignment(
|
||||
"has",
|
||||
factory.createArrowFunction(
|
||||
/*modifiers*/ undefined,
|
||||
/*typeParameters*/ undefined,
|
||||
[factory.createParameterDeclaration(
|
||||
/*modifiers*/ undefined,
|
||||
/*dotDotDotToken*/ undefined,
|
||||
factory.createIdentifier("obj")
|
||||
)],
|
||||
/*type*/ undefined,
|
||||
/*equalsGreaterThanToken*/ undefined,
|
||||
factory.createBinaryExpression(
|
||||
propertyName,
|
||||
SyntaxKind.InKeyword,
|
||||
factory.createIdentifier("obj")
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function createESDecorateClassElementAccessObject(name: ESDecorateName, access: ESDecorateClassElementAccess) {
|
||||
const properties: ObjectLiteralElementLike[] = [];
|
||||
properties.push(createESDecorateClassElementAccessHasMethod(name));
|
||||
if (access.get) properties.push(createESDecorateClassElementAccessGetMethod(name));
|
||||
if (access.set) properties.push(createESDecorateClassElementAccessSetMethod(name));
|
||||
return factory.createObjectLiteralExpression(properties);
|
||||
}
|
||||
|
||||
function createESDecorateClassElementContextObject(contextIn: ESDecorateClassElementContext) {
|
||||
return factory.createObjectLiteralExpression([
|
||||
@@ -406,9 +349,7 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel
|
||||
factory.createPropertyAssignment(factory.createIdentifier("name"), contextIn.name.computed ? contextIn.name.name : factory.createStringLiteralFromNode(contextIn.name.name)),
|
||||
factory.createPropertyAssignment(factory.createIdentifier("static"), contextIn.static ? factory.createTrue() : factory.createFalse()),
|
||||
factory.createPropertyAssignment(factory.createIdentifier("private"), contextIn.private ? factory.createTrue() : factory.createFalse()),
|
||||
|
||||
// Disabled, pending resolution of https://github.com/tc39/proposal-decorators/issues/494
|
||||
// factory.createPropertyAssignment(factory.createIdentifier("access"), createESDecorateClassElementAccessObject(contextIn.name, contextIn.access))
|
||||
factory.createPropertyAssignment(factory.createIdentifier("access"), createESDecorateClassElementAccessObject(contextIn.name, contextIn.access))
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ import {
|
||||
ConstructorDeclaration,
|
||||
ConstructorTypeNode,
|
||||
ConstructSignatureDeclaration,
|
||||
containsObjectRestOrSpread,
|
||||
ContinueStatement,
|
||||
createBaseNodeFactory,
|
||||
createNodeConverters,
|
||||
@@ -114,7 +115,6 @@ import {
|
||||
getAllUnscopedEmitHelpers,
|
||||
getBuildInfo,
|
||||
getCommentRange,
|
||||
getElementsOfBindingOrAssignmentPattern,
|
||||
getEmitFlags,
|
||||
getIdentifierTypeArguments,
|
||||
getJSDocTypeAliasName,
|
||||
@@ -124,7 +124,6 @@ import {
|
||||
getSourceMapRange,
|
||||
getSyntheticLeadingComments,
|
||||
getSyntheticTrailingComments,
|
||||
getTargetOfBindingOrAssignmentElement,
|
||||
getTextOfIdentifierOrLiteral,
|
||||
hasInvalidEscape,
|
||||
HasModifiers,
|
||||
@@ -150,7 +149,6 @@ import {
|
||||
isArray,
|
||||
isArrayLiteralExpression,
|
||||
isArrowFunction,
|
||||
isAssignmentPattern,
|
||||
isBinaryExpression,
|
||||
isCallChain,
|
||||
isClassDeclaration,
|
||||
@@ -3326,24 +3324,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode
|
||||
}
|
||||
|
||||
function propagateAssignmentPatternFlags(node: AssignmentPattern): TransformFlags {
|
||||
if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) return TransformFlags.ContainsObjectRestOrSpread;
|
||||
if (node.transformFlags & TransformFlags.ContainsES2018) {
|
||||
// check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c'
|
||||
// will not be correctly interpreted by the ES2018 transformer
|
||||
for (const element of getElementsOfBindingOrAssignmentPattern(node)) {
|
||||
const target = getTargetOfBindingOrAssignmentElement(element);
|
||||
if (target && isAssignmentPattern(target)) {
|
||||
if (target.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
return TransformFlags.ContainsObjectRestOrSpread;
|
||||
}
|
||||
if (target.transformFlags & TransformFlags.ContainsES2018) {
|
||||
const flags = propagateAssignmentPatternFlags(target);
|
||||
if (flags) return flags;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return TransformFlags.None;
|
||||
return containsObjectRestOrSpread(node) ? TransformFlags.ContainsObjectRestOrSpread : TransformFlags.None;
|
||||
}
|
||||
|
||||
// @api
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
AssertionLevel,
|
||||
AssignmentExpression,
|
||||
AssignmentOperatorOrHigher,
|
||||
AssignmentPattern,
|
||||
BinaryExpression,
|
||||
BinaryOperator,
|
||||
BinaryOperatorToken,
|
||||
@@ -76,6 +77,7 @@ import {
|
||||
InternalEmitFlags,
|
||||
isAssignmentExpression,
|
||||
isAssignmentOperator,
|
||||
isAssignmentPattern,
|
||||
isBlock,
|
||||
isCommaListExpression,
|
||||
isComputedPropertyName,
|
||||
@@ -174,6 +176,7 @@ import {
|
||||
TextRange,
|
||||
ThisTypeNode,
|
||||
Token,
|
||||
TransformFlags,
|
||||
TypeNode,
|
||||
} from "../_namespaces/ts";
|
||||
|
||||
@@ -1151,7 +1154,6 @@ export function canHaveIllegalModifiers(node: Node): node is HasIllegalModifiers
|
||||
return kind === SyntaxKind.ClassStaticBlockDeclaration
|
||||
|| kind === SyntaxKind.PropertyAssignment
|
||||
|| kind === SyntaxKind.ShorthandPropertyAssignment
|
||||
|| kind === SyntaxKind.FunctionType
|
||||
|| kind === SyntaxKind.MissingDeclaration
|
||||
|| kind === SyntaxKind.NamespaceExportDeclaration;
|
||||
}
|
||||
@@ -1743,3 +1745,31 @@ export function flattenCommaList(node: Expression) {
|
||||
flattenCommaListWorker(node, expressions);
|
||||
return expressions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk an AssignmentPattern to determine if it contains object rest (`...`) syntax. We cannot rely on
|
||||
* propagation of `TransformFlags.ContainsObjectRestOrSpread` since it isn't propagated by default in
|
||||
* ObjectLiteralExpression and ArrayLiteralExpression since we do not know whether they belong to an
|
||||
* AssignmentPattern at the time the nodes are parsed.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export function containsObjectRestOrSpread(node: AssignmentPattern): boolean {
|
||||
if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) return true;
|
||||
if (node.transformFlags & TransformFlags.ContainsES2018) {
|
||||
// check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c'
|
||||
// will not be correctly interpreted by the ES2018 transformer
|
||||
for (const element of getElementsOfBindingOrAssignmentPattern(node)) {
|
||||
const target = getTargetOfBindingOrAssignmentElement(element);
|
||||
if (target && isAssignmentPattern(target)) {
|
||||
if (target.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
return true;
|
||||
}
|
||||
if (target.transformFlags & TransformFlags.ContainsES2018) {
|
||||
if (containsObjectRestOrSpread(target)) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -70,6 +70,7 @@ import {
|
||||
ModuleResolutionHost,
|
||||
ModuleResolutionKind,
|
||||
moduleResolutionOptionDeclarations,
|
||||
moduleResolutionSupportsPackageJsonExportsAndImports,
|
||||
noop,
|
||||
noopPush,
|
||||
normalizePath,
|
||||
@@ -103,8 +104,8 @@ import {
|
||||
tryExtractTSExtension,
|
||||
tryGetExtensionFromPath,
|
||||
tryParsePatterns,
|
||||
version,
|
||||
Version,
|
||||
version,
|
||||
versionMajorMinor,
|
||||
VersionRange,
|
||||
} from "./_namespaces/ts";
|
||||
@@ -206,6 +207,38 @@ function resolvedTypeScriptOnly(resolved: Resolved | undefined): PathAndPackageI
|
||||
return { fileName: resolved.path, packageId: resolved.packageId };
|
||||
}
|
||||
|
||||
function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(
|
||||
moduleName: string,
|
||||
resolved: Resolved | undefined,
|
||||
isExternalLibraryImport: boolean | undefined,
|
||||
failedLookupLocations: string[],
|
||||
affectingLocations: string[],
|
||||
diagnostics: Diagnostic[],
|
||||
state: ModuleResolutionState,
|
||||
legacyResult?: string,
|
||||
): ResolvedModuleWithFailedLookupLocations {
|
||||
// If this is from node_modules for non relative name, always respect preserveSymlinks
|
||||
if (!state.resultFromCache &&
|
||||
!state.compilerOptions.preserveSymlinks &&
|
||||
resolved &&
|
||||
isExternalLibraryImport &&
|
||||
!resolved.originalPath &&
|
||||
!isExternalModuleNameRelative(moduleName)
|
||||
) {
|
||||
const { resolvedFileName, originalPath } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled);
|
||||
if (originalPath) resolved = { ...resolved, path: resolvedFileName, originalPath };
|
||||
}
|
||||
return createResolvedModuleWithFailedLookupLocations(
|
||||
resolved,
|
||||
isExternalLibraryImport,
|
||||
failedLookupLocations,
|
||||
affectingLocations,
|
||||
diagnostics,
|
||||
state.resultFromCache,
|
||||
legacyResult,
|
||||
);
|
||||
}
|
||||
|
||||
function createResolvedModuleWithFailedLookupLocations(
|
||||
resolved: Resolved | undefined,
|
||||
isExternalLibraryImport: boolean | undefined,
|
||||
@@ -450,6 +483,16 @@ function arePathsEqual(path1: string, path2: string, host: ModuleResolutionHost)
|
||||
return comparePaths(path1, path2, !useCaseSensitiveFileNames) === Comparison.EqualTo;
|
||||
}
|
||||
|
||||
function getOriginalAndResolvedFileName(fileName: string, host: ModuleResolutionHost, traceEnabled: boolean) {
|
||||
const resolvedFileName = realPath(fileName, host, traceEnabled);
|
||||
const pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host);
|
||||
return {
|
||||
// If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames
|
||||
resolvedFileName: pathsAreEqual ? fileName : resolvedFileName,
|
||||
originalPath: pathsAreEqual ? undefined : fileName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
|
||||
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
|
||||
@@ -541,13 +584,12 @@ export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string
|
||||
let resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined;
|
||||
if (resolved) {
|
||||
const { fileName, packageId } = resolved;
|
||||
const resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
|
||||
const pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host);
|
||||
let resolvedFileName = fileName, originalPath: string | undefined;
|
||||
if (!options.preserveSymlinks) ({ resolvedFileName, originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled));
|
||||
resolvedTypeReferenceDirective = {
|
||||
primary,
|
||||
// If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames
|
||||
resolvedFileName: pathsAreEqual ? fileName : resolvedFileName,
|
||||
originalPath: pathsAreEqual ? undefined : fileName,
|
||||
resolvedFileName,
|
||||
originalPath,
|
||||
packageId,
|
||||
isExternalLibraryImport: pathContainsNodeModules(fileName),
|
||||
};
|
||||
@@ -659,15 +701,19 @@ function getNodeResolutionFeatures(options: CompilerOptions) {
|
||||
return features;
|
||||
}
|
||||
|
||||
function getConditions(options: CompilerOptions, esmMode?: boolean) {
|
||||
/** @internal */
|
||||
export function getConditions(options: CompilerOptions, esmMode?: boolean) {
|
||||
// conditions are only used by the node16/nodenext/bundler resolvers - there's no priority order in the list,
|
||||
// it's essentially a set (priority is determined by object insertion order in the object we look at).
|
||||
const conditions = esmMode || getEmitModuleResolutionKind(options) === ModuleResolutionKind.Bundler
|
||||
? ["node", "import"]
|
||||
: ["node", "require"];
|
||||
? ["import"]
|
||||
: ["require"];
|
||||
if (!options.noDtsResolution) {
|
||||
conditions.push("types");
|
||||
}
|
||||
if (getEmitModuleResolutionKind(options) !== ModuleResolutionKind.Bundler) {
|
||||
conditions.push("node");
|
||||
}
|
||||
return concatenate(conditions, options.customConditions);
|
||||
}
|
||||
|
||||
@@ -1659,7 +1705,7 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa
|
||||
candidateIsFromPackageJsonField: false,
|
||||
};
|
||||
|
||||
if (traceEnabled && getEmitModuleResolutionKind(compilerOptions) >= ModuleResolutionKind.Node16 && getEmitModuleResolutionKind(compilerOptions) <= ModuleResolutionKind.NodeNext) {
|
||||
if (traceEnabled && moduleResolutionSupportsPackageJsonExportsAndImports(getEmitModuleResolutionKind(compilerOptions))) {
|
||||
trace(host, Diagnostics.Resolving_in_0_mode_with_conditions_1, features & NodeResolutionFeatures.EsmMode ? "ESM" : "CJS", conditions.map(c => `'${c}'`).join(", "));
|
||||
}
|
||||
|
||||
@@ -1701,13 +1747,14 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa
|
||||
}
|
||||
}
|
||||
|
||||
return createResolvedModuleWithFailedLookupLocations(
|
||||
return createResolvedModuleWithFailedLookupLocationsHandlingSymlink(
|
||||
moduleName,
|
||||
result?.value?.resolved,
|
||||
result?.value?.isExternalLibraryImport,
|
||||
failedLookupLocations,
|
||||
affectingLocations,
|
||||
diagnostics,
|
||||
state.resultFromCache,
|
||||
state,
|
||||
legacyResult,
|
||||
);
|
||||
|
||||
@@ -1732,18 +1779,8 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa
|
||||
}
|
||||
resolved = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
|
||||
}
|
||||
if (!resolved) return undefined;
|
||||
|
||||
let resolvedValue = resolved.value;
|
||||
if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
|
||||
const path = realPath(resolvedValue.path, host, traceEnabled);
|
||||
const pathsAreEqual = arePathsEqual(path, resolvedValue.path, host);
|
||||
const originalPath = pathsAreEqual ? undefined : resolvedValue.path;
|
||||
// If the path and realpath are differing only in casing prefer path so that we can issue correct errors for casing under forceConsistentCasingInFileNames
|
||||
resolvedValue = { ...resolvedValue, path: pathsAreEqual ? resolvedValue.path : path, originalPath };
|
||||
}
|
||||
// For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
|
||||
return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
|
||||
return resolved && { value: resolved.value && { resolved: resolved.value, isExternalLibraryImport: true } };
|
||||
}
|
||||
else {
|
||||
const { path: candidate, parts } = normalizePathForCJSResolution(containingDirectory, moduleName);
|
||||
@@ -1998,7 +2035,7 @@ function tryFileLookup(fileName: string, onlyRecordFailures: boolean, state: Mod
|
||||
if (!onlyRecordFailures) {
|
||||
if (state.host.fileExists(fileName)) {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
|
||||
trace(state.host, Diagnostics.File_0_exists_use_it_as_a_name_resolution_result, fileName);
|
||||
}
|
||||
return fileName;
|
||||
}
|
||||
@@ -2551,19 +2588,26 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
|
||||
}
|
||||
else if (typeof target === "object" && target !== null) { // eslint-disable-line no-null/no-null
|
||||
if (!Array.isArray(target)) {
|
||||
traceIfEnabled(state, Diagnostics.Entering_conditional_exports);
|
||||
for (const condition of getOwnKeys(target as MapLike<unknown>)) {
|
||||
if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) {
|
||||
traceIfEnabled(state, Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition);
|
||||
const subTarget = (target as MapLike<unknown>)[condition];
|
||||
const result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key);
|
||||
if (result) {
|
||||
traceIfEnabled(state, Diagnostics.Resolved_under_condition_0, condition);
|
||||
traceIfEnabled(state, Diagnostics.Exiting_conditional_exports);
|
||||
return result;
|
||||
}
|
||||
else {
|
||||
traceIfEnabled(state, Diagnostics.Failed_to_resolve_under_condition_0, condition);
|
||||
}
|
||||
}
|
||||
else {
|
||||
traceIfEnabled(state, Diagnostics.Saw_non_matching_condition_0, condition);
|
||||
}
|
||||
}
|
||||
traceIfEnabled(state, Diagnostics.Exiting_conditional_exports);
|
||||
return undefined;
|
||||
}
|
||||
else {
|
||||
@@ -2990,13 +3034,14 @@ export function classicNameResolver(moduleName: string, containingFile: string,
|
||||
tryResolve(Extensions.TypeScript | Extensions.Declaration) ||
|
||||
tryResolve(Extensions.JavaScript | (compilerOptions.resolveJsonModule ? Extensions.Json : 0));
|
||||
// No originalPath because classic resolution doesn't resolve realPath
|
||||
return createResolvedModuleWithFailedLookupLocations(
|
||||
return createResolvedModuleWithFailedLookupLocationsHandlingSymlink(
|
||||
moduleName,
|
||||
resolved && resolved.value,
|
||||
resolved?.value && pathContainsNodeModules(resolved.value.path),
|
||||
failedLookupLocations,
|
||||
affectingLocations,
|
||||
diagnostics,
|
||||
state.resultFromCache
|
||||
state,
|
||||
);
|
||||
|
||||
function tryResolve(extensions: Extensions): SearchResult<Resolved> {
|
||||
@@ -3032,6 +3077,7 @@ export function classicNameResolver(moduleName: string, containingFile: string,
|
||||
|
||||
// Program errors validate that `noEmit` or `emitDeclarationOnly` is also set,
|
||||
// so this function doesn't check them to avoid propagating errors.
|
||||
/** @internal */
|
||||
export function shouldAllowImportingTsExtension(compilerOptions: CompilerOptions, fromFileName?: string) {
|
||||
return !!compilerOptions.allowImportingTsExtensions || fromFileName && isDeclarationFileName(fromFileName);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
forEachAncestorDirectory,
|
||||
getBaseFileName,
|
||||
GetCanonicalFileName,
|
||||
getConditions,
|
||||
getDirectoryPath,
|
||||
getEmitModuleResolutionKind,
|
||||
getModeForResolutionAtIndex,
|
||||
@@ -46,6 +47,7 @@ import {
|
||||
getPathsBasePath,
|
||||
getRelativePathFromDirectory,
|
||||
getRelativePathToDirectoryOrUrl,
|
||||
getResolvePackageJsonExports,
|
||||
getSourceFileOfModule,
|
||||
getSupportedExtensions,
|
||||
getTextOfIdentifierOrLiteral,
|
||||
@@ -369,7 +371,9 @@ function computeModuleSpecifiers(
|
||||
let redirectPathsSpecifiers: string[] | undefined;
|
||||
let relativeSpecifiers: string[] | undefined;
|
||||
for (const modulePath of modulePaths) {
|
||||
const specifier = tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode);
|
||||
const specifier = modulePath.isInNodeModules
|
||||
? tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode)
|
||||
: undefined;
|
||||
nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier);
|
||||
if (specifier && modulePath.isRedirect) {
|
||||
// If we got a specifier for a redirect, it was a bare package specifier (e.g. "@foo/bar",
|
||||
@@ -945,10 +949,15 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCan
|
||||
if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
|
||||
const packageJsonContent = cachedPackageJson?.contents.packageJsonContent || JSON.parse(host.readFile!(packageJsonPath)!);
|
||||
const importMode = overrideMode || importingSourceFile.impliedNodeFormat;
|
||||
if (getEmitModuleResolutionKind(options) === ModuleResolutionKind.Node16 || getEmitModuleResolutionKind(options) === ModuleResolutionKind.NodeNext) {
|
||||
const conditions = ["node", importMode === ModuleKind.ESNext ? "import" : "require", "types"];
|
||||
const fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string"
|
||||
? tryGetModuleNameFromExports(options, path, packageRootPath, getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions)
|
||||
if (getResolvePackageJsonExports(options)) {
|
||||
// The package name that we found in node_modules could be different from the package
|
||||
// name in the package.json content via url/filepath dependency specifiers. We need to
|
||||
// use the actual directory name, so don't look at `packageJsonContent.name` here.
|
||||
const nodeModulesDirectoryName = packageRootPath.substring(parts.topLevelPackageNameIndex + 1);
|
||||
const packageName = getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
|
||||
const conditions = getConditions(options, importMode === ModuleKind.ESNext);
|
||||
const fromExports = packageJsonContent.exports
|
||||
? tryGetModuleNameFromExports(options, path, packageRootPath, packageName, packageJsonContent.exports, conditions)
|
||||
: undefined;
|
||||
if (fromExports) {
|
||||
const withJsExtension = !hasTSFileExtension(fromExports.moduleFileToTry)
|
||||
|
||||
+141
-88
@@ -1401,18 +1401,22 @@ export function parseJSDocTypeExpressionForTests(content: string, start?: number
|
||||
// parser instances can actually be expensive enough to impact us on projects with many source
|
||||
// files.
|
||||
namespace Parser {
|
||||
// Why var? It avoids TDZ checks in the runtime which can be costly.
|
||||
// See: https://github.com/microsoft/TypeScript/issues/52924
|
||||
/* eslint-disable no-var */
|
||||
|
||||
// Share a single scanner across all calls to parse a source file. This helps speed things
|
||||
// up by avoiding the cost of creating/compiling scanners over and over again.
|
||||
const scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true);
|
||||
var scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true);
|
||||
|
||||
const disallowInAndDecoratorContext = NodeFlags.DisallowInContext | NodeFlags.DecoratorContext;
|
||||
var disallowInAndDecoratorContext = NodeFlags.DisallowInContext | NodeFlags.DecoratorContext;
|
||||
|
||||
// capture constructors in 'initializeState' to avoid null checks
|
||||
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
|
||||
let TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
|
||||
let IdentifierConstructor: new (kind: SyntaxKind.Identifier, pos: number, end: number) => Identifier;
|
||||
let PrivateIdentifierConstructor: new (kind: SyntaxKind.PrivateIdentifier, pos: number, end: number) => PrivateIdentifier;
|
||||
let SourceFileConstructor: new (kind: SyntaxKind.SourceFile, pos: number, end: number) => SourceFile;
|
||||
var NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
|
||||
var TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
|
||||
var IdentifierConstructor: new (kind: SyntaxKind.Identifier, pos: number, end: number) => Identifier;
|
||||
var PrivateIdentifierConstructor: new (kind: SyntaxKind.PrivateIdentifier, pos: number, end: number) => PrivateIdentifier;
|
||||
var SourceFileConstructor: new (kind: SyntaxKind.SourceFile, pos: number, end: number) => SourceFile;
|
||||
|
||||
function countNode(node: Node) {
|
||||
nodeCount++;
|
||||
@@ -1421,7 +1425,7 @@ namespace Parser {
|
||||
|
||||
// Rather than using `createBaseNodeFactory` here, we establish a `BaseNodeFactory` that closes over the
|
||||
// constructors above, which are reset each time `initializeState` is called.
|
||||
const baseNodeFactory: BaseNodeFactory = {
|
||||
var baseNodeFactory: BaseNodeFactory = {
|
||||
createBaseSourceFileNode: kind => countNode(new SourceFileConstructor(kind, /*pos*/ 0, /*end*/ 0)),
|
||||
createBaseIdentifierNode: kind => countNode(new IdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)),
|
||||
createBasePrivateIdentifierNode: kind => countNode(new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)),
|
||||
@@ -1429,26 +1433,55 @@ namespace Parser {
|
||||
createBaseNode: kind => countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0))
|
||||
};
|
||||
|
||||
const factory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules | NodeFactoryFlags.NoNodeConverters | NodeFactoryFlags.NoOriginalNode, baseNodeFactory);
|
||||
var factory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules | NodeFactoryFlags.NoNodeConverters | NodeFactoryFlags.NoOriginalNode, baseNodeFactory);
|
||||
|
||||
let fileName: string;
|
||||
let sourceFlags: NodeFlags;
|
||||
let sourceText: string;
|
||||
let languageVersion: ScriptTarget;
|
||||
let scriptKind: ScriptKind;
|
||||
let languageVariant: LanguageVariant;
|
||||
let parseDiagnostics: DiagnosticWithDetachedLocation[];
|
||||
let jsDocDiagnostics: DiagnosticWithDetachedLocation[];
|
||||
let syntaxCursor: IncrementalParser.SyntaxCursor | undefined;
|
||||
var {
|
||||
createNodeArray: factoryCreateNodeArray,
|
||||
createNumericLiteral: factoryCreateNumericLiteral,
|
||||
createStringLiteral: factoryCreateStringLiteral,
|
||||
createLiteralLikeNode: factoryCreateLiteralLikeNode,
|
||||
createIdentifier: factoryCreateIdentifier,
|
||||
createPrivateIdentifier: factoryCreatePrivateIdentifier,
|
||||
createToken: factoryCreateToken,
|
||||
createArrayLiteralExpression: factoryCreateArrayLiteralExpression,
|
||||
createObjectLiteralExpression: factoryCreateObjectLiteralExpression,
|
||||
createPropertyAccessExpression: factoryCreatePropertyAccessExpression,
|
||||
createPropertyAccessChain: factoryCreatePropertyAccessChain,
|
||||
createElementAccessExpression: factoryCreateElementAccessExpression,
|
||||
createElementAccessChain: factoryCreateElementAccessChain,
|
||||
createCallExpression: factoryCreateCallExpression,
|
||||
createCallChain: factoryCreateCallChain,
|
||||
createNewExpression: factoryCreateNewExpression,
|
||||
createParenthesizedExpression: factoryCreateParenthesizedExpression,
|
||||
createBlock: factoryCreateBlock,
|
||||
createVariableStatement: factoryCreateVariableStatement,
|
||||
createExpressionStatement: factoryCreateExpressionStatement,
|
||||
createIfStatement: factoryCreateIfStatement,
|
||||
createWhileStatement: factoryCreateWhileStatement,
|
||||
createForStatement: factoryCreateForStatement,
|
||||
createForOfStatement: factoryCreateForOfStatement,
|
||||
createVariableDeclaration: factoryCreateVariableDeclaration,
|
||||
createVariableDeclarationList: factoryCreateVariableDeclarationList,
|
||||
} = factory;
|
||||
|
||||
let currentToken: SyntaxKind;
|
||||
let nodeCount: number;
|
||||
let identifiers: Map<string, string>;
|
||||
let identifierCount: number;
|
||||
var fileName: string;
|
||||
var sourceFlags: NodeFlags;
|
||||
var sourceText: string;
|
||||
var languageVersion: ScriptTarget;
|
||||
var scriptKind: ScriptKind;
|
||||
var languageVariant: LanguageVariant;
|
||||
var parseDiagnostics: DiagnosticWithDetachedLocation[];
|
||||
var jsDocDiagnostics: DiagnosticWithDetachedLocation[];
|
||||
var syntaxCursor: IncrementalParser.SyntaxCursor | undefined;
|
||||
|
||||
let parsingContext: ParsingContext;
|
||||
var currentToken: SyntaxKind;
|
||||
var nodeCount: number;
|
||||
var identifiers: Map<string, string>;
|
||||
var identifierCount: number;
|
||||
|
||||
let notParenthesizedArrow: Set<number> | undefined;
|
||||
var parsingContext: ParsingContext;
|
||||
|
||||
var notParenthesizedArrow: Set<number> | undefined;
|
||||
|
||||
// Flags that dictate what parsing context we're in. For example:
|
||||
// Whether or not we are in strict parsing mode. All that changes in strict parsing mode is
|
||||
@@ -1496,10 +1529,10 @@ namespace Parser {
|
||||
// Note: it should not be necessary to save/restore these flags during speculative/lookahead
|
||||
// parsing. These context flags are naturally stored and restored through normal recursive
|
||||
// descent parsing and unwinding.
|
||||
let contextFlags: NodeFlags;
|
||||
var contextFlags: NodeFlags;
|
||||
|
||||
// Indicates whether we are currently parsing top-level statements.
|
||||
let topLevel = true;
|
||||
var topLevel = true;
|
||||
|
||||
// Whether or not we've had a parse error since creating the last AST node. If we have
|
||||
// encountered an error, it will be stored on the next AST node we create. Parse errors
|
||||
@@ -1528,7 +1561,8 @@ namespace Parser {
|
||||
//
|
||||
// Note: any errors at the end of the file that do not precede a regular node, should get
|
||||
// attached to the EOF token.
|
||||
let parseErrorBeforeNextFinishedNode = false;
|
||||
var parseErrorBeforeNextFinishedNode = false;
|
||||
/* eslint-enable no-var */
|
||||
|
||||
export function parseSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, syntaxCursor: IncrementalParser.SyntaxCursor | undefined, setParentNodes = false, scriptKind?: ScriptKind, setExternalModuleIndicatorOverride?: (file: SourceFile) => void): SourceFile {
|
||||
scriptKind = ensureScriptKind(fileName, scriptKind);
|
||||
@@ -1626,8 +1660,8 @@ namespace Parser {
|
||||
}
|
||||
}
|
||||
|
||||
const expression = isArray(expressions) ? finishNode(factory.createArrayLiteralExpression(expressions), pos) : Debug.checkDefined(expressions);
|
||||
const statement = factory.createExpressionStatement(expression) as JsonObjectExpressionStatement;
|
||||
const expression = isArray(expressions) ? finishNode(factoryCreateArrayLiteralExpression(expressions), pos) : Debug.checkDefined(expressions);
|
||||
const statement = factoryCreateExpressionStatement(expression) as JsonObjectExpressionStatement;
|
||||
finishNode(statement, pos);
|
||||
statements = createNodeArray([statement], pos);
|
||||
endOfFileToken = parseExpectedToken(SyntaxKind.EndOfFileToken, Diagnostics.Unexpected_token) as EndOfFileToken;
|
||||
@@ -1848,7 +1882,7 @@ namespace Parser {
|
||||
}
|
||||
|
||||
syntaxCursor = savedSyntaxCursor;
|
||||
return factory.updateSourceFile(sourceFile, setTextRange(factory.createNodeArray(statements), sourceFile.statements));
|
||||
return factory.updateSourceFile(sourceFile, setTextRange(factoryCreateNodeArray(statements), sourceFile.statements));
|
||||
|
||||
function containsPossibleTopLevelAwait(node: Node) {
|
||||
return !(node.flags & NodeFlags.AwaitContext)
|
||||
@@ -2465,14 +2499,14 @@ namespace Parser {
|
||||
const pos = getNodePos();
|
||||
const kind = token();
|
||||
nextToken();
|
||||
return finishNode(factory.createToken(kind), pos) as T;
|
||||
return finishNode(factoryCreateToken(kind), pos) as T;
|
||||
}
|
||||
|
||||
function parseTokenNodeJSDoc<T extends Node>(): T {
|
||||
const pos = getNodePos();
|
||||
const kind = token();
|
||||
nextTokenJSDoc();
|
||||
return finishNode(factory.createToken(kind), pos) as T;
|
||||
return finishNode(factoryCreateToken(kind), pos) as T;
|
||||
}
|
||||
|
||||
function canParseSemicolon() {
|
||||
@@ -2503,7 +2537,7 @@ namespace Parser {
|
||||
}
|
||||
|
||||
function createNodeArray<T extends Node>(elements: T[], pos: number, end?: number, hasTrailingComma?: boolean): NodeArray<T> {
|
||||
const array = factory.createNodeArray(elements, hasTrailingComma);
|
||||
const array = factoryCreateNodeArray(elements, hasTrailingComma);
|
||||
setTextRangePosEnd(array, pos, end ?? scanner.getStartPos());
|
||||
return array;
|
||||
}
|
||||
@@ -2537,12 +2571,12 @@ namespace Parser {
|
||||
|
||||
const pos = getNodePos();
|
||||
const result =
|
||||
kind === SyntaxKind.Identifier ? factory.createIdentifier("", /*originalKeywordKind*/ undefined) :
|
||||
kind === SyntaxKind.Identifier ? factoryCreateIdentifier("", /*originalKeywordKind*/ undefined) :
|
||||
isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) :
|
||||
kind === SyntaxKind.NumericLiteral ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) :
|
||||
kind === SyntaxKind.StringLiteral ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) :
|
||||
kind === SyntaxKind.NumericLiteral ? factoryCreateNumericLiteral("", /*numericLiteralFlags*/ undefined) :
|
||||
kind === SyntaxKind.StringLiteral ? factoryCreateStringLiteral("", /*isSingleQuote*/ undefined) :
|
||||
kind === SyntaxKind.MissingDeclaration ? factory.createMissingDeclaration() :
|
||||
factory.createToken(kind);
|
||||
factoryCreateToken(kind);
|
||||
return finishNode(result, pos) as T;
|
||||
}
|
||||
|
||||
@@ -2566,7 +2600,7 @@ namespace Parser {
|
||||
const text = internIdentifier(scanner.getTokenValue());
|
||||
const hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape();
|
||||
nextTokenWithoutCheck();
|
||||
return finishNode(factory.createIdentifier(text, originalKeywordKind, hasExtendedUnicodeEscape), pos);
|
||||
return finishNode(factoryCreateIdentifier(text, originalKeywordKind, hasExtendedUnicodeEscape), pos);
|
||||
}
|
||||
|
||||
if (token() === SyntaxKind.PrivateIdentifier) {
|
||||
@@ -2651,7 +2685,7 @@ namespace Parser {
|
||||
|
||||
function parsePrivateIdentifier(): PrivateIdentifier {
|
||||
const pos = getNodePos();
|
||||
const node = factory.createPrivateIdentifier(internIdentifier(scanner.getTokenValue()));
|
||||
const node = factoryCreatePrivateIdentifier(internIdentifier(scanner.getTokenValue()));
|
||||
nextToken();
|
||||
return finishNode(node, pos);
|
||||
}
|
||||
@@ -2684,7 +2718,6 @@ namespace Parser {
|
||||
return canFollowExportModifier();
|
||||
case SyntaxKind.DefaultKeyword:
|
||||
return nextTokenCanFollowDefaultKeyword();
|
||||
case SyntaxKind.AccessorKeyword:
|
||||
case SyntaxKind.StaticKeyword:
|
||||
case SyntaxKind.GetKeyword:
|
||||
case SyntaxKind.SetKeyword:
|
||||
@@ -3619,9 +3652,9 @@ namespace Parser {
|
||||
// never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
|
||||
// We also do not need to check for negatives because any prefix operator would be part of a
|
||||
// parent unary expression.
|
||||
kind === SyntaxKind.NumericLiteral ? factory.createNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) :
|
||||
kind === SyntaxKind.StringLiteral ? factory.createStringLiteral(scanner.getTokenValue(), /*isSingleQuote*/ undefined, scanner.hasExtendedUnicodeEscape()) :
|
||||
isLiteralKind(kind) ? factory.createLiteralLikeNode(kind, scanner.getTokenValue()) :
|
||||
kind === SyntaxKind.NumericLiteral ? factoryCreateNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) :
|
||||
kind === SyntaxKind.StringLiteral ? factoryCreateStringLiteral(scanner.getTokenValue(), /*isSingleQuote*/ undefined, scanner.hasExtendedUnicodeEscape()) :
|
||||
isLiteralKind(kind) ? factoryCreateLiteralLikeNode(kind, scanner.getTokenValue()) :
|
||||
Debug.fail();
|
||||
|
||||
if (scanner.hasExtendedUnicodeEscape()) {
|
||||
@@ -4349,7 +4382,7 @@ namespace Parser {
|
||||
if (token() === SyntaxKind.AbstractKeyword) {
|
||||
const pos = getNodePos();
|
||||
nextToken();
|
||||
const modifier = finishNode(factory.createToken(SyntaxKind.AbstractKeyword), pos);
|
||||
const modifier = finishNode(factoryCreateToken(SyntaxKind.AbstractKeyword), pos);
|
||||
modifiers = createNodeArray<Modifier>([modifier], pos);
|
||||
}
|
||||
return modifiers;
|
||||
@@ -4360,13 +4393,13 @@ namespace Parser {
|
||||
const hasJSDoc = hasPrecedingJSDocComment();
|
||||
const modifiers = parseModifiersForConstructorType();
|
||||
const isConstructorType = parseOptional(SyntaxKind.NewKeyword);
|
||||
Debug.assert(!modifiers || isConstructorType, "Per isStartOfFunctionOrConstructorType, a function type cannot have modifiers.");
|
||||
const typeParameters = parseTypeParameters();
|
||||
const parameters = parseParameters(SignatureFlags.Type);
|
||||
const type = parseReturnType(SyntaxKind.EqualsGreaterThanToken, /*isType*/ false);
|
||||
const node = isConstructorType
|
||||
? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, type)
|
||||
: factory.createFunctionTypeNode(typeParameters, parameters, type);
|
||||
if (!isConstructorType) (node as Mutable<FunctionTypeNode>).modifiers = modifiers;
|
||||
return withJSDoc(finishNode(node, pos), hasJSDoc);
|
||||
}
|
||||
|
||||
@@ -5201,6 +5234,7 @@ namespace Parser {
|
||||
switch (fourth) {
|
||||
case SyntaxKind.EqualsToken:
|
||||
case SyntaxKind.GreaterThanToken:
|
||||
case SyntaxKind.SlashToken:
|
||||
return false;
|
||||
default:
|
||||
return true;
|
||||
@@ -5647,6 +5681,11 @@ namespace Parser {
|
||||
case SyntaxKind.VoidKeyword:
|
||||
return parseVoidExpression();
|
||||
case SyntaxKind.LessThanToken:
|
||||
// Just like in parseUpdateExpression, we need to avoid parsing type assertions when
|
||||
// in JSX and we see an expression like "+ <foo> bar".
|
||||
if (languageVariant === LanguageVariant.JSX) {
|
||||
return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
|
||||
}
|
||||
// This is modified UnaryExpression grammar in TypeScript
|
||||
// UnaryExpression (modified):
|
||||
// < type > UnaryExpression
|
||||
@@ -5869,7 +5908,7 @@ namespace Parser {
|
||||
// If it wasn't then just try to parse out a '.' and report an error.
|
||||
parseExpectedToken(SyntaxKind.DotToken, Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
|
||||
// private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
|
||||
return finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true)), pos);
|
||||
return finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true)), pos);
|
||||
}
|
||||
|
||||
function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext: boolean, topInvalidNodePosition?: number, openingTag?: JsxOpeningElement | JsxOpeningFragment): JsxElement | JsxSelfClosingElement | JsxFragment {
|
||||
@@ -5891,7 +5930,7 @@ namespace Parser {
|
||||
const newLast = finishNode(factory.createJsxElement(
|
||||
lastChild.openingElement,
|
||||
lastChild.children,
|
||||
finishNode(factory.createJsxClosingElement(finishNode(factory.createIdentifier(""), end, end)), end, end)),
|
||||
finishNode(factory.createJsxClosingElement(finishNode(factoryCreateIdentifier(""), end, end)), end, end)),
|
||||
lastChild.openingElement.pos,
|
||||
end);
|
||||
|
||||
@@ -6060,7 +6099,7 @@ namespace Parser {
|
||||
let expression: JsxTagNameExpression = token() === SyntaxKind.ThisKeyword ?
|
||||
parseTokenNode<ThisExpression>() : parseIdentifierName();
|
||||
while (parseOptional(SyntaxKind.DotToken)) {
|
||||
expression = finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false)), pos) as JsxTagNamePropertyAccess;
|
||||
expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false)), pos) as JsxTagNamePropertyAccess;
|
||||
}
|
||||
return expression;
|
||||
}
|
||||
@@ -6146,10 +6185,7 @@ namespace Parser {
|
||||
function parseJsxClosingFragment(inExpressionContext: boolean): JsxClosingFragment {
|
||||
const pos = getNodePos();
|
||||
parseExpected(SyntaxKind.LessThanSlashToken);
|
||||
if (tokenIsIdentifierOrKeyword(token())) {
|
||||
parseErrorAtRange(parseJsxElementName(), Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
|
||||
}
|
||||
if (parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*shouldAdvance*/ false)) {
|
||||
if (parseExpected(SyntaxKind.GreaterThanToken, Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment, /*shouldAdvance*/ false)) {
|
||||
// manually advance the scanner in order to look for jsx text inside jsx
|
||||
if (inExpressionContext) {
|
||||
nextToken();
|
||||
@@ -6162,6 +6198,7 @@ namespace Parser {
|
||||
}
|
||||
|
||||
function parseTypeAssertion(): TypeAssertion {
|
||||
Debug.assert(languageVariant !== LanguageVariant.JSX, "Type assertions should never be parsed in JSX; they should be parsed as comparisons or JSX elements/fragments.");
|
||||
const pos = getNodePos();
|
||||
parseExpected(SyntaxKind.LessThanToken);
|
||||
const type = parseType();
|
||||
@@ -6208,8 +6245,8 @@ namespace Parser {
|
||||
const name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
|
||||
const isOptionalChain = questionDotToken || tryReparseOptionalChain(expression);
|
||||
const propertyAccess = isOptionalChain ?
|
||||
factory.createPropertyAccessChain(expression, questionDotToken, name) :
|
||||
factory.createPropertyAccessExpression(expression, name);
|
||||
factoryCreatePropertyAccessChain(expression, questionDotToken, name) :
|
||||
factoryCreatePropertyAccessExpression(expression, name);
|
||||
if (isOptionalChain && isPrivateIdentifier(propertyAccess.name)) {
|
||||
parseErrorAtRange(propertyAccess.name, Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
|
||||
}
|
||||
@@ -6237,8 +6274,8 @@ namespace Parser {
|
||||
parseExpected(SyntaxKind.CloseBracketToken);
|
||||
|
||||
const indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ?
|
||||
factory.createElementAccessChain(expression, questionDotToken, argumentExpression) :
|
||||
factory.createElementAccessExpression(expression, argumentExpression);
|
||||
factoryCreateElementAccessChain(expression, questionDotToken, argumentExpression) :
|
||||
factoryCreateElementAccessExpression(expression, argumentExpression);
|
||||
return finishNode(indexedAccess, pos);
|
||||
}
|
||||
|
||||
@@ -6329,15 +6366,15 @@ namespace Parser {
|
||||
}
|
||||
const argumentList = parseArgumentList();
|
||||
const callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
|
||||
factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) :
|
||||
factory.createCallExpression(expression, typeArguments, argumentList);
|
||||
factoryCreateCallChain(expression, questionDotToken, typeArguments, argumentList) :
|
||||
factoryCreateCallExpression(expression, typeArguments, argumentList);
|
||||
expression = finishNode(callExpr, pos);
|
||||
continue;
|
||||
}
|
||||
if (questionDotToken) {
|
||||
// We parsed `?.` but then failed to parse anything, so report a missing identifier here.
|
||||
const name = createMissingNode<Identifier>(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false, Diagnostics.Identifier_expected);
|
||||
expression = finishNode(factory.createPropertyAccessChain(expression, questionDotToken, name), pos);
|
||||
expression = finishNode(factoryCreatePropertyAccessChain(expression, questionDotToken, name), pos);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -6454,7 +6491,7 @@ namespace Parser {
|
||||
parseExpected(SyntaxKind.OpenParenToken);
|
||||
const expression = allowInAnd(parseExpression);
|
||||
parseExpected(SyntaxKind.CloseParenToken);
|
||||
return withJSDoc(finishNode(factory.createParenthesizedExpression(expression), pos), hasJSDoc);
|
||||
return withJSDoc(finishNode(factoryCreateParenthesizedExpression(expression), pos), hasJSDoc);
|
||||
}
|
||||
|
||||
function parseSpreadElement(): Expression {
|
||||
@@ -6481,7 +6518,7 @@ namespace Parser {
|
||||
const multiLine = scanner.hasPrecedingLineBreak();
|
||||
const elements = parseDelimitedList(ParsingContext.ArrayLiteralMembers, parseArgumentOrArrayLiteralElement);
|
||||
parseExpectedMatchingBrackets(SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken, openBracketParsed, openBracketPosition);
|
||||
return finishNode(factory.createArrayLiteralExpression(elements, multiLine), pos);
|
||||
return finishNode(factoryCreateArrayLiteralExpression(elements, multiLine), pos);
|
||||
}
|
||||
|
||||
function parseObjectLiteralElement(): ObjectLiteralElementLike {
|
||||
@@ -6547,7 +6584,7 @@ namespace Parser {
|
||||
const multiLine = scanner.hasPrecedingLineBreak();
|
||||
const properties = parseDelimitedList(ParsingContext.ObjectLiteralMembers, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
|
||||
parseExpectedMatchingBrackets(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, openBraceParsed, openBracePosition);
|
||||
return finishNode(factory.createObjectLiteralExpression(properties, multiLine), pos);
|
||||
return finishNode(factoryCreateObjectLiteralExpression(properties, multiLine), pos);
|
||||
}
|
||||
|
||||
function parseFunctionExpression(): FunctionExpression {
|
||||
@@ -6605,7 +6642,7 @@ namespace Parser {
|
||||
parseErrorAtCurrentToken(Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, getTextOfNodeFromSourceText(sourceText, expression));
|
||||
}
|
||||
const argumentList = token() === SyntaxKind.OpenParenToken ? parseArgumentList() : undefined;
|
||||
return finishNode(factory.createNewExpression(expression, typeArguments, argumentList), pos);
|
||||
return finishNode(factoryCreateNewExpression(expression, typeArguments, argumentList), pos);
|
||||
}
|
||||
|
||||
// STATEMENTS
|
||||
@@ -6618,9 +6655,9 @@ namespace Parser {
|
||||
const multiLine = scanner.hasPrecedingLineBreak();
|
||||
const statements = parseList(ParsingContext.BlockStatements, parseStatement);
|
||||
parseExpectedMatchingBrackets(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, openBraceParsed, openBracePosition);
|
||||
const result = withJSDoc(finishNode(factory.createBlock(statements, multiLine), pos), hasJSDoc);
|
||||
const result = withJSDoc(finishNode(factoryCreateBlock(statements, multiLine), pos), hasJSDoc);
|
||||
if (token() === SyntaxKind.EqualsToken) {
|
||||
parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses);
|
||||
parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_whole_assignment_in_parentheses);
|
||||
nextToken();
|
||||
}
|
||||
|
||||
@@ -6628,7 +6665,7 @@ namespace Parser {
|
||||
}
|
||||
else {
|
||||
const statements = createMissingList<Statement>();
|
||||
return withJSDoc(finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc);
|
||||
return withJSDoc(finishNode(factoryCreateBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6679,7 +6716,7 @@ namespace Parser {
|
||||
parseExpectedMatchingBrackets(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, openParenParsed, openParenPosition);
|
||||
const thenStatement = parseStatement();
|
||||
const elseStatement = parseOptional(SyntaxKind.ElseKeyword) ? parseStatement() : undefined;
|
||||
return withJSDoc(finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc);
|
||||
return withJSDoc(finishNode(factoryCreateIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc);
|
||||
}
|
||||
|
||||
function parseDoStatement(): DoStatement {
|
||||
@@ -6710,7 +6747,7 @@ namespace Parser {
|
||||
const expression = allowInAnd(parseExpression);
|
||||
parseExpectedMatchingBrackets(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, openParenParsed, openParenPosition);
|
||||
const statement = parseStatement();
|
||||
return withJSDoc(finishNode(factory.createWhileStatement(expression, statement), pos), hasJSDoc);
|
||||
return withJSDoc(finishNode(factoryCreateWhileStatement(expression, statement), pos), hasJSDoc);
|
||||
}
|
||||
|
||||
function parseForOrForInOrForOfStatement(): Statement {
|
||||
@@ -6734,7 +6771,7 @@ namespace Parser {
|
||||
if (awaitToken ? parseExpected(SyntaxKind.OfKeyword) : parseOptional(SyntaxKind.OfKeyword)) {
|
||||
const expression = allowInAnd(() => parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true));
|
||||
parseExpected(SyntaxKind.CloseParenToken);
|
||||
node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement());
|
||||
node = factoryCreateForOfStatement(awaitToken, initializer, expression, parseStatement());
|
||||
}
|
||||
else if (parseOptional(SyntaxKind.InKeyword)) {
|
||||
const expression = allowInAnd(parseExpression);
|
||||
@@ -6751,7 +6788,7 @@ namespace Parser {
|
||||
? allowInAnd(parseExpression)
|
||||
: undefined;
|
||||
parseExpected(SyntaxKind.CloseParenToken);
|
||||
node = factory.createForStatement(initializer, condition, incrementor, parseStatement());
|
||||
node = factoryCreateForStatement(initializer, condition, incrementor, parseStatement());
|
||||
}
|
||||
|
||||
return withJSDoc(finishNode(node, pos) as ForStatement | ForInOrOfStatement, hasJSDoc);
|
||||
@@ -6849,7 +6886,7 @@ namespace Parser {
|
||||
let expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
|
||||
if (expression === undefined) {
|
||||
identifierCount++;
|
||||
expression = finishNode(factory.createIdentifier(""), getNodePos());
|
||||
expression = finishNode(factoryCreateIdentifier(""), getNodePos());
|
||||
}
|
||||
if (!tryParseSemicolon()) {
|
||||
parseErrorForMissingSemicolonAfter(expression);
|
||||
@@ -6919,7 +6956,7 @@ namespace Parser {
|
||||
if (!tryParseSemicolon()) {
|
||||
parseErrorForMissingSemicolonAfter(expression);
|
||||
}
|
||||
node = factory.createExpressionStatement(expression);
|
||||
node = factoryCreateExpressionStatement(expression);
|
||||
if (hasParen) {
|
||||
// do not parse the same jsdoc twice
|
||||
hasJSDoc = false;
|
||||
@@ -7360,7 +7397,7 @@ namespace Parser {
|
||||
}
|
||||
const type = parseTypeAnnotation();
|
||||
const initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer();
|
||||
const node = factory.createVariableDeclaration(name, exclamationToken, type, initializer);
|
||||
const node = factoryCreateVariableDeclaration(name, exclamationToken, type, initializer);
|
||||
return withJSDoc(finishNode(node, pos), hasJSDoc);
|
||||
}
|
||||
|
||||
@@ -7406,7 +7443,7 @@ namespace Parser {
|
||||
setDisallowInContext(savedDisallowIn);
|
||||
}
|
||||
|
||||
return finishNode(factory.createVariableDeclarationList(declarations, flags), pos);
|
||||
return finishNode(factoryCreateVariableDeclarationList(declarations, flags), pos);
|
||||
}
|
||||
|
||||
function canFollowContextualOfKeyword(): boolean {
|
||||
@@ -7416,7 +7453,7 @@ namespace Parser {
|
||||
function parseVariableStatement(pos: number, hasJSDoc: boolean, modifiers: NodeArray<ModifierLike> | undefined): VariableStatement {
|
||||
const declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
|
||||
parseSemicolon();
|
||||
const node = factory.createVariableStatement(modifiers, declarationList);
|
||||
const node = factoryCreateVariableStatement(modifiers, declarationList);
|
||||
return withJSDoc(finishNode(node, pos), hasJSDoc);
|
||||
}
|
||||
|
||||
@@ -7688,7 +7725,7 @@ namespace Parser {
|
||||
}
|
||||
}
|
||||
|
||||
return finishNode(factory.createToken(kind as Modifier["kind"]), pos);
|
||||
return finishNode(factoryCreateToken(kind as Modifier["kind"]), pos);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -7703,20 +7740,36 @@ namespace Parser {
|
||||
function parseModifiers(allowDecorators: boolean, permitConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean): NodeArray<ModifierLike> | undefined {
|
||||
const pos = getNodePos();
|
||||
let list: ModifierLike[] | undefined;
|
||||
let modifier, hasSeenStaticModifier = false;
|
||||
while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) {
|
||||
if (modifier.kind === SyntaxKind.StaticKeyword) hasSeenStaticModifier = true;
|
||||
list = append(list, modifier);
|
||||
}
|
||||
let decorator, modifier, hasSeenStaticModifier = false, hasLeadingModifier = false, hasTrailingDecorator = false;
|
||||
|
||||
// Decorators should be contiguous in a list of modifiers (i.e., `[...leadingModifiers, ...decorators, ...trailingModifiers]`).
|
||||
// The leading modifiers *should* only contain `export` and `default` when decorators are present, but we'll handle errors for any other leading modifiers in the checker.
|
||||
// Decorators should be contiguous in a list of modifiers but can potentially appear in two places (i.e., `[...leadingDecorators, ...leadingModifiers, ...trailingDecorators, ...trailingModifiers]`).
|
||||
// The leading modifiers *should* only contain `export` and `default` when trailingDecorators are present, but we'll handle errors for any other leading modifiers in the checker.
|
||||
// It is illegal to have both leadingDecorators and trailingDecorators, but we will report that as a grammar check in the checker.
|
||||
|
||||
// parse leading decorators
|
||||
if (allowDecorators && token() === SyntaxKind.AtToken) {
|
||||
let decorator;
|
||||
while (decorator = tryParseDecorator()) {
|
||||
list = append(list, decorator);
|
||||
}
|
||||
}
|
||||
|
||||
// parse leading modifiers
|
||||
while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) {
|
||||
if (modifier.kind === SyntaxKind.StaticKeyword) hasSeenStaticModifier = true;
|
||||
list = append(list, modifier);
|
||||
hasLeadingModifier = true;
|
||||
}
|
||||
|
||||
// parse trailing decorators, but only if we parsed any leading modifiers
|
||||
if (hasLeadingModifier && allowDecorators && token() === SyntaxKind.AtToken) {
|
||||
while (decorator = tryParseDecorator()) {
|
||||
list = append(list, decorator);
|
||||
hasTrailingDecorator = true;
|
||||
}
|
||||
}
|
||||
|
||||
// parse trailing modifiers, but only if we parsed any trailing decorators
|
||||
if (hasTrailingDecorator) {
|
||||
while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) {
|
||||
if (modifier.kind === SyntaxKind.StaticKeyword) hasSeenStaticModifier = true;
|
||||
list = append(list, modifier);
|
||||
@@ -7731,7 +7784,7 @@ namespace Parser {
|
||||
if (token() === SyntaxKind.AsyncKeyword) {
|
||||
const pos = getNodePos();
|
||||
nextToken();
|
||||
const modifier = finishNode(factory.createToken(SyntaxKind.AsyncKeyword), pos);
|
||||
const modifier = finishNode(factoryCreateToken(SyntaxKind.AsyncKeyword), pos);
|
||||
modifiers = createNodeArray<Modifier>([modifier], pos);
|
||||
}
|
||||
return modifiers;
|
||||
@@ -8413,7 +8466,7 @@ namespace Parser {
|
||||
currentToken = scanner.scan();
|
||||
const jsDocTypeExpression = parseJSDocTypeExpression();
|
||||
|
||||
const sourceFile = createSourceFile("file.js", ScriptTarget.Latest, ScriptKind.JS, /*isDeclarationFile*/ false, [], factory.createToken(SyntaxKind.EndOfFileToken), NodeFlags.None, noop);
|
||||
const sourceFile = createSourceFile("file.js", ScriptTarget.Latest, ScriptKind.JS, /*isDeclarationFile*/ false, [], factoryCreateToken(SyntaxKind.EndOfFileToken), NodeFlags.None, noop);
|
||||
const diagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile);
|
||||
if (jsDocDiagnostics) {
|
||||
sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
|
||||
@@ -9154,7 +9207,7 @@ namespace Parser {
|
||||
let node: Identifier | PropertyAccessEntityNameExpression = parseJSDocIdentifierName();
|
||||
while (parseOptional(SyntaxKind.DotToken)) {
|
||||
const name = parseJSDocIdentifierName();
|
||||
node = finishNode(factory.createPropertyAccessExpression(node, name), pos) as PropertyAccessEntityNameExpression;
|
||||
node = finishNode(factoryCreatePropertyAccessExpression(node, name), pos) as PropertyAccessEntityNameExpression;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
@@ -9471,7 +9524,7 @@ namespace Parser {
|
||||
const end = scanner.getTextPos();
|
||||
const originalKeywordKind = token();
|
||||
const text = internIdentifier(scanner.getTokenValue());
|
||||
const result = finishNode(factory.createIdentifier(text, originalKeywordKind), pos, end);
|
||||
const result = finishNode(factoryCreateIdentifier(text, originalKeywordKind), pos, end);
|
||||
nextTokenJSDoc();
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,9 @@ import {
|
||||
|
||||
/** Performance measurements for the compiler. */
|
||||
|
||||
// NOTE: declared global is injected by ts-perf to monitor profiler marks to generate heap snapshots.
|
||||
declare let onProfilerEvent: ((eventName: string) => void) | undefined;
|
||||
|
||||
let perfHooks: PerformanceHooks | undefined;
|
||||
// when set, indicates the implementation of `Performance` to use for user timing.
|
||||
// when unset, indicates user timing is unavailable or disabled.
|
||||
@@ -74,6 +77,9 @@ export function mark(markName: string) {
|
||||
counts.set(markName, count + 1);
|
||||
marks.set(markName, timestamp());
|
||||
performanceImpl?.mark(markName);
|
||||
if (typeof onProfilerEvent === "function") {
|
||||
onProfilerEvent(markName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+34
-20
@@ -3,6 +3,7 @@ import {
|
||||
__String,
|
||||
addInternalEmitFlags,
|
||||
addRange,
|
||||
addRelatedInfo,
|
||||
append,
|
||||
arrayFrom,
|
||||
arrayIsEqualTo,
|
||||
@@ -68,6 +69,7 @@ import {
|
||||
DirectoryStructureHost,
|
||||
emitFiles,
|
||||
EmitHost,
|
||||
emitModuleKindIsNonNodeESM,
|
||||
EmitOnly,
|
||||
EmitResult,
|
||||
emptyArray,
|
||||
@@ -117,6 +119,7 @@ import {
|
||||
getEmitScriptTarget,
|
||||
getErrorSpanForNode,
|
||||
getExternalModuleName,
|
||||
getIsolatedModules,
|
||||
getJSXImplicitImportBase,
|
||||
getJSXRuntimeImport,
|
||||
getLineAndCharacterOfPosition,
|
||||
@@ -961,14 +964,14 @@ export function createModuleResolutionLoader(
|
||||
): ResolutionLoader<StringLiteralLike, ResolvedModuleWithFailedLookupLocations, SourceFile> {
|
||||
return {
|
||||
nameAndMode: moduleResolutionNameAndModeGetter,
|
||||
resolve: (moduleName, resoluionMode) => resolveModuleName(
|
||||
resolve: (moduleName, resolutionMode) => resolveModuleName(
|
||||
moduleName,
|
||||
containingFile,
|
||||
options,
|
||||
host,
|
||||
cache,
|
||||
redirectedReference,
|
||||
resoluionMode,
|
||||
resolutionMode,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -2957,14 +2960,21 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
|
||||
}
|
||||
else if (isClassDeclaration(parent)) {
|
||||
const exportIndex = findIndex(parent.modifiers, isExportModifier);
|
||||
const defaultIndex = findIndex(parent.modifiers, isDefaultModifier);
|
||||
if (exportIndex >= 0 && decoratorIndex < exportIndex) {
|
||||
// report illegal decorator before `export default`
|
||||
diagnostics.push(createDiagnosticForNode(parent.modifiers[decoratorIndex], Diagnostics.Decorators_must_come_after_export_or_export_default_in_JavaScript_files));
|
||||
}
|
||||
else if (defaultIndex >= 0 && decoratorIndex < defaultIndex) {
|
||||
// report illegal decorator before `export default`
|
||||
diagnostics.push(createDiagnosticForNode(parent.modifiers[decoratorIndex], Diagnostics.Decorators_are_not_valid_here));
|
||||
if (exportIndex >= 0) {
|
||||
const defaultIndex = findIndex(parent.modifiers, isDefaultModifier);
|
||||
if (decoratorIndex > exportIndex && defaultIndex >= 0 && decoratorIndex < defaultIndex) {
|
||||
// report illegal decorator between `export` and `default`
|
||||
diagnostics.push(createDiagnosticForNode(parent.modifiers[decoratorIndex], Diagnostics.Decorators_are_not_valid_here));
|
||||
}
|
||||
else if (exportIndex >= 0 && decoratorIndex < exportIndex) {
|
||||
const trailingDecoratorIndex = findIndex(parent.modifiers, isDecorator, exportIndex);
|
||||
if (trailingDecoratorIndex >= 0) {
|
||||
diagnostics.push(addRelatedInfo(
|
||||
createDiagnosticForNode(parent.modifiers[trailingDecoratorIndex], Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export),
|
||||
createDiagnosticForNode(parent.modifiers[decoratorIndex], Diagnostics.Decorator_used_before_export_here),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3178,7 +3188,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
|
||||
|
||||
// If we are importing helpers, we need to add a synthetic reference to resolve the
|
||||
// helpers library.
|
||||
if ((options.isolatedModules || isExternalModuleFile)
|
||||
if ((getIsolatedModules(options) || isExternalModuleFile)
|
||||
&& !file.isDeclarationFile) {
|
||||
if (options.importHelpers) {
|
||||
// synthesize 'import "tslib"' declaration
|
||||
@@ -3984,13 +3994,13 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "exactOptionalPropertyTypes", "strictNullChecks");
|
||||
}
|
||||
|
||||
if (options.isolatedModules) {
|
||||
if (options.isolatedModules || options.verbatimModuleSyntax) {
|
||||
if (options.out) {
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", options.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules");
|
||||
}
|
||||
|
||||
if (options.outFile) {
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", options.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4232,11 +4242,11 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
|
||||
}
|
||||
|
||||
if (options.preserveValueImports && getEmitModuleKind(options) < ModuleKind.ES2015) {
|
||||
createDiagnosticForOptionName(Diagnostics.Option_preserveValueImports_can_only_be_used_when_module_is_set_to_es2015_or_later, "preserveValueImports");
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_module_is_set_to_es2015_or_later, "preserveValueImports");
|
||||
}
|
||||
|
||||
const moduleKind = getEmitModuleKind(options);
|
||||
if (options.verbatimModuleSyntax) {
|
||||
const moduleKind = getEmitModuleKind(options);
|
||||
if (moduleKind === ModuleKind.AMD || moduleKind === ModuleKind.UMD || moduleKind === ModuleKind.System) {
|
||||
createDiagnosticForOptionName(Diagnostics.Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System, "verbatimModuleSyntax");
|
||||
}
|
||||
@@ -4257,13 +4267,17 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
|
||||
|
||||
const moduleResolution = getEmitModuleResolutionKind(options);
|
||||
if (options.resolvePackageJsonExports && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) {
|
||||
createOptionValueDiagnostic("resolvePackageJsonExports", Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonExports");
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonExports");
|
||||
}
|
||||
if (options.resolvePackageJsonImports && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) {
|
||||
createOptionValueDiagnostic("resolvePackageJsonImports", Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonImports");
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "resolvePackageJsonImports");
|
||||
}
|
||||
if (options.customConditions && !moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) {
|
||||
createOptionValueDiagnostic("customConditions", Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "customConditions");
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_can_only_be_used_when_moduleResolution_is_set_to_node16_nodenext_or_bundler, "customConditions");
|
||||
}
|
||||
|
||||
if (moduleResolution === ModuleResolutionKind.Bundler && !emitModuleKindIsNonNodeESM(moduleKind)) {
|
||||
createOptionValueDiagnostic("moduleResolution", Diagnostics.Option_0_can_only_be_used_when_module_is_set_to_es2015_or_later, "bundler");
|
||||
}
|
||||
|
||||
// If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
|
||||
@@ -4395,7 +4409,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
|
||||
createDiagnostic(Diagnostics.Flag_0_is_deprecated_Please_remove_it_from_your_configuration, value || name);
|
||||
}
|
||||
else {
|
||||
createDiagnostic(Diagnostics.Flag_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_ignoreDeprecations_Colon_2_to_silence_this_error, value || name, DeprecationVersion.v5_5, DeprecationVersion.v5_0);
|
||||
createDiagnostic(Diagnostics.Flag_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprecations_Colon_2_to_silence_this_error, value || name, DeprecationVersion.v5_5, DeprecationVersion.v5_0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+15
-11
@@ -961,31 +961,34 @@ export function createScanner(languageVersion: ScriptTarget,
|
||||
start?: number,
|
||||
length?: number): Scanner {
|
||||
|
||||
let text = textInitial!;
|
||||
// Why var? It avoids TDZ checks in the runtime which can be costly.
|
||||
// See: https://github.com/microsoft/TypeScript/issues/52924
|
||||
/* eslint-disable no-var */
|
||||
var text = textInitial!;
|
||||
|
||||
// Current position (end position of text of current token)
|
||||
let pos: number;
|
||||
var pos: number;
|
||||
|
||||
|
||||
// end of text
|
||||
let end: number;
|
||||
var end: number;
|
||||
|
||||
// Start position of whitespace before current token
|
||||
let startPos: number;
|
||||
var startPos: number;
|
||||
|
||||
// Start position of text of current token
|
||||
let tokenPos: number;
|
||||
var tokenPos: number;
|
||||
|
||||
let token: SyntaxKind;
|
||||
let tokenValue!: string;
|
||||
let tokenFlags: TokenFlags;
|
||||
var token: SyntaxKind;
|
||||
var tokenValue!: string;
|
||||
var tokenFlags: TokenFlags;
|
||||
|
||||
let commentDirectives: CommentDirective[] | undefined;
|
||||
let inJSDocType = 0;
|
||||
var commentDirectives: CommentDirective[] | undefined;
|
||||
var inJSDocType = 0;
|
||||
|
||||
setText(text, start, length);
|
||||
|
||||
const scanner: Scanner = {
|
||||
var scanner: Scanner = {
|
||||
getStartPos: () => startPos,
|
||||
getTextPos: () => pos,
|
||||
getToken: () => token,
|
||||
@@ -1030,6 +1033,7 @@ export function createScanner(languageVersion: ScriptTarget,
|
||||
lookAhead,
|
||||
scanRange,
|
||||
};
|
||||
/* eslint-enable no-var */
|
||||
|
||||
if (Debug.isDebugging) {
|
||||
Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
|
||||
|
||||
+29
-25
@@ -35,39 +35,43 @@ export interface SourceMapGeneratorOptions {
|
||||
|
||||
/** @internal */
|
||||
export function createSourceMapGenerator(host: EmitHost, file: string, sourceRoot: string, sourcesDirectoryPath: string, generatorOptions: SourceMapGeneratorOptions): SourceMapGenerator {
|
||||
const { enter, exit } = generatorOptions.extendedDiagnostics
|
||||
// Why var? It avoids TDZ checks in the runtime which can be costly.
|
||||
// See: https://github.com/microsoft/TypeScript/issues/52924
|
||||
/* eslint-disable no-var */
|
||||
var { enter, exit } = generatorOptions.extendedDiagnostics
|
||||
? performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
|
||||
: performance.nullTimer;
|
||||
|
||||
// Current source map file and its index in the sources list
|
||||
const rawSources: string[] = [];
|
||||
const sources: string[] = [];
|
||||
const sourceToSourceIndexMap = new Map<string, number>();
|
||||
let sourcesContent: (string | null)[] | undefined;
|
||||
var rawSources: string[] = [];
|
||||
var sources: string[] = [];
|
||||
var sourceToSourceIndexMap = new Map<string, number>();
|
||||
var sourcesContent: (string | null)[] | undefined;
|
||||
|
||||
const names: string[] = [];
|
||||
let nameToNameIndexMap: Map<string, number> | undefined;
|
||||
const mappingCharCodes: number[] = [];
|
||||
let mappings = "";
|
||||
var names: string[] = [];
|
||||
var nameToNameIndexMap: Map<string, number> | undefined;
|
||||
var mappingCharCodes: number[] = [];
|
||||
var mappings = "";
|
||||
|
||||
// Last recorded and encoded mappings
|
||||
let lastGeneratedLine = 0;
|
||||
let lastGeneratedCharacter = 0;
|
||||
let lastSourceIndex = 0;
|
||||
let lastSourceLine = 0;
|
||||
let lastSourceCharacter = 0;
|
||||
let lastNameIndex = 0;
|
||||
let hasLast = false;
|
||||
var lastGeneratedLine = 0;
|
||||
var lastGeneratedCharacter = 0;
|
||||
var lastSourceIndex = 0;
|
||||
var lastSourceLine = 0;
|
||||
var lastSourceCharacter = 0;
|
||||
var lastNameIndex = 0;
|
||||
var hasLast = false;
|
||||
|
||||
let pendingGeneratedLine = 0;
|
||||
let pendingGeneratedCharacter = 0;
|
||||
let pendingSourceIndex = 0;
|
||||
let pendingSourceLine = 0;
|
||||
let pendingSourceCharacter = 0;
|
||||
let pendingNameIndex = 0;
|
||||
let hasPending = false;
|
||||
let hasPendingSource = false;
|
||||
let hasPendingName = false;
|
||||
var pendingGeneratedLine = 0;
|
||||
var pendingGeneratedCharacter = 0;
|
||||
var pendingSourceIndex = 0;
|
||||
var pendingSourceLine = 0;
|
||||
var pendingSourceCharacter = 0;
|
||||
var pendingNameIndex = 0;
|
||||
var hasPending = false;
|
||||
var hasPendingSource = false;
|
||||
var hasPendingName = false;
|
||||
/* eslint-enable no-var */
|
||||
|
||||
return {
|
||||
getSources: () => rawSources,
|
||||
|
||||
@@ -55,6 +55,7 @@ import {
|
||||
transformECMAScriptModule,
|
||||
Transformer,
|
||||
TransformerFactory,
|
||||
transformES5,
|
||||
transformES2015,
|
||||
transformES2016,
|
||||
transformES2017,
|
||||
@@ -62,7 +63,6 @@ import {
|
||||
transformES2019,
|
||||
transformES2020,
|
||||
transformES2021,
|
||||
transformES5,
|
||||
transformESDecorators,
|
||||
transformESNext,
|
||||
transformGenerators,
|
||||
|
||||
@@ -1013,7 +1013,14 @@ export function transformClassFields(context: TransformationContext): (x: Source
|
||||
);
|
||||
}
|
||||
|
||||
return visitEachChild(node, visitor, context);
|
||||
return factory.updatePropertyDeclaration(
|
||||
node,
|
||||
visitNodes(node.modifiers, modifierVisitor, isModifier),
|
||||
visitNode(node.name, propertyNameVisitor, isPropertyName),
|
||||
/*questionOrExclamationToken*/ undefined,
|
||||
/*type*/ undefined,
|
||||
visitNode(node.initializer, visitor, isExpression)
|
||||
);
|
||||
}
|
||||
|
||||
function transformPublicFieldInitializer(node: PropertyDeclaration) {
|
||||
|
||||
@@ -113,6 +113,7 @@ import {
|
||||
isFunctionLike,
|
||||
isGlobalScopeAugmentation,
|
||||
isIdentifier,
|
||||
isIdentifierANonContextualKeyword,
|
||||
isImportDeclaration,
|
||||
isImportEqualsDeclaration,
|
||||
isIndexSignatureDeclaration,
|
||||
@@ -695,7 +696,7 @@ export function transformDeclarations(context: TransformationContext) {
|
||||
if (elem.kind === SyntaxKind.OmittedExpression) {
|
||||
return elem;
|
||||
}
|
||||
if (elem.propertyName && isIdentifier(elem.propertyName) && isIdentifier(elem.name) && !elem.symbol.isReferenced) {
|
||||
if (elem.propertyName && isIdentifier(elem.propertyName) && isIdentifier(elem.name) && !elem.symbol.isReferenced && !isIdentifierANonContextualKeyword(elem.propertyName)) {
|
||||
// Unnecessary property renaming is forbidden in types, so remove renaming
|
||||
return factory.updateBindingElement(
|
||||
elem,
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
concatenate,
|
||||
ConciseBody,
|
||||
ConstructorDeclaration,
|
||||
containsObjectRestOrSpread,
|
||||
createForOfBindingStatement,
|
||||
createSuperAccessVariableStatement,
|
||||
Debug,
|
||||
@@ -577,7 +578,7 @@ export function transformES2018(context: TransformationContext): (x: SourceFile
|
||||
* expression of an `ExpressionStatement`).
|
||||
*/
|
||||
function visitBinaryExpression(node: BinaryExpression, expressionResultIsUnused: boolean): Expression {
|
||||
if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
if (isDestructuringAssignment(node) && containsObjectRestOrSpread(node.left)) {
|
||||
return flattenDestructuringAssignment(
|
||||
node,
|
||||
visitor,
|
||||
@@ -703,7 +704,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile
|
||||
*/
|
||||
function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined): VisitResult<Statement> {
|
||||
const ancestorFacts = enterSubtree(HierarchyFacts.IterationStatementExcludes, HierarchyFacts.IterationStatementIncludes);
|
||||
if (node.initializer.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
if (node.initializer.transformFlags & TransformFlags.ContainsObjectRestOrSpread ||
|
||||
isAssignmentPattern(node.initializer) && containsObjectRestOrSpread(node.initializer)) {
|
||||
node = transformForOfStatementWithObjectRest(node);
|
||||
}
|
||||
const result = node.awaitModifier ?
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
getEmitModuleKind,
|
||||
getEmitScriptTarget,
|
||||
getExternalModuleNameLiteral,
|
||||
getIsolatedModules,
|
||||
hasSyntacticModifier,
|
||||
Identifier,
|
||||
idText,
|
||||
@@ -76,7 +77,7 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S
|
||||
return node;
|
||||
}
|
||||
|
||||
if (isExternalModule(node) || compilerOptions.isolatedModules) {
|
||||
if (isExternalModule(node) || getIsolatedModules(compilerOptions)) {
|
||||
currentSourceFile = node;
|
||||
importRequireStatements = undefined;
|
||||
let result = updateExternalModule(node);
|
||||
@@ -286,7 +287,7 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S
|
||||
*/
|
||||
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void {
|
||||
if (isSourceFile(node)) {
|
||||
if ((isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
|
||||
if ((isExternalModule(node) || getIsolatedModules(compilerOptions)) && compilerOptions.importHelpers) {
|
||||
helperNameSubstitutions = new Map<string, Identifier>();
|
||||
}
|
||||
previousOnEmitNode(hint, node, emitCallback);
|
||||
|
||||
@@ -850,6 +850,9 @@ export function transformModule(context: TransformationContext): (x: SourceFile
|
||||
}
|
||||
|
||||
function visitImportCallExpression(node: ImportCall): Expression {
|
||||
if (moduleKind === ModuleKind.None && languageVersion >= ScriptTarget.ES2020) {
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
const externalModuleName = getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions);
|
||||
const firstArgument = visitNode(firstOrUndefined(node.arguments), visitor, isExpression);
|
||||
// Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output.
|
||||
|
||||
@@ -54,6 +54,7 @@ import {
|
||||
getEmitScriptTarget,
|
||||
getFirstConstructorWithBody,
|
||||
getInitializedVariables,
|
||||
getIsolatedModules,
|
||||
getOriginalNode,
|
||||
getParseTreeNode,
|
||||
getProperties,
|
||||
@@ -2706,7 +2707,7 @@ export function transformTypeScript(context: TransformationContext) {
|
||||
}
|
||||
|
||||
function tryGetConstEnumValue(node: Node): string | number | undefined {
|
||||
if (compilerOptions.isolatedModules) {
|
||||
if (getIsolatedModules(compilerOptions)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
+10
-1
@@ -2,6 +2,7 @@ import {
|
||||
combinePaths,
|
||||
Extension,
|
||||
fileExtensionIs,
|
||||
Path,
|
||||
ResolvedConfigFileName,
|
||||
} from "./_namespaces/ts";
|
||||
|
||||
@@ -28,6 +29,7 @@ export enum UpToDateStatusType {
|
||||
OutOfDateWithUpstream,
|
||||
OutOfDateBuildInfo,
|
||||
OutOfDateOptions,
|
||||
OutOfDateRoots,
|
||||
UpstreamOutOfDate,
|
||||
UpstreamBlocked,
|
||||
ComputingUpstream,
|
||||
@@ -51,6 +53,7 @@ export type UpToDateStatus =
|
||||
| Status.OutOfDateWithSelf
|
||||
| Status.OutOfDateWithUpstream
|
||||
| Status.OutOfDateBuildInfo
|
||||
| Status.OutOfDateRoots
|
||||
| Status.UpstreamOutOfDate
|
||||
| Status.UpstreamBlocked
|
||||
| Status.ComputingUpstream
|
||||
@@ -127,10 +130,16 @@ export namespace Status {
|
||||
* Buildinfo indicates that build is out of date
|
||||
*/
|
||||
export interface OutOfDateBuildInfo {
|
||||
type: UpToDateStatusType.OutOfDateBuildInfo | UpToDateStatusType.OutOfDateOptions,
|
||||
type: UpToDateStatusType.OutOfDateBuildInfo | UpToDateStatusType.OutOfDateOptions;
|
||||
buildInfoFile: string;
|
||||
}
|
||||
|
||||
export interface OutOfDateRoots {
|
||||
type: UpToDateStatusType.OutOfDateRoots,
|
||||
buildInfoFile: string;
|
||||
inputFile: Path;
|
||||
}
|
||||
|
||||
/**
|
||||
* This project depends on an out-of-date project, so shouldn't be built yet
|
||||
*/
|
||||
|
||||
@@ -1729,7 +1729,7 @@ function getUpToDateStatusWorker<T extends BuilderProgram>(state: SolutionBuilde
|
||||
let oldestOutputFileTime = maximumDate;
|
||||
let buildInfoTime: Date | undefined;
|
||||
let buildInfoProgram: ProgramBuildInfo | undefined;
|
||||
let buildInfoVersionMap: Map<Path, string> | undefined;
|
||||
let buildInfoVersionMap: ReturnType<typeof getBuildInfoFileVersionMap> | undefined;
|
||||
if (buildInfoPath) {
|
||||
const buildInfoCacheEntry = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath);
|
||||
buildInfoTime = buildInfoCacheEntry?.modifiedTime || ts.getModifiedTime(host, buildInfoPath);
|
||||
@@ -1798,6 +1798,7 @@ function getUpToDateStatusWorker<T extends BuilderProgram>(state: SolutionBuilde
|
||||
let newestInputFileTime = minimumDate;
|
||||
/** True if input file has changed timestamp but text is not changed, we can then do only timestamp updates on output to make it look up-to-date later */
|
||||
let pseudoInputUpToDate = false;
|
||||
const seenRoots = new Set<Path>();
|
||||
// Get timestamps of input files
|
||||
for (const inputFile of project.fileNames) {
|
||||
const inputTime = getModifiedTime(state, inputFile);
|
||||
@@ -1815,7 +1816,7 @@ function getUpToDateStatusWorker<T extends BuilderProgram>(state: SolutionBuilde
|
||||
if (buildInfoProgram) {
|
||||
// Read files and see if they are same, read is anyways cached
|
||||
if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath!, host);
|
||||
version = buildInfoVersionMap.get(toPath(state, inputFile));
|
||||
version = buildInfoVersionMap.fileInfos.get(toPath(state, inputFile));
|
||||
const text = version ? state.readFileWithCache(inputFile) : undefined;
|
||||
currentVersion = text !== undefined ? getSourceFileVersionAsHashFromText(host, text) : undefined;
|
||||
if (version && version === currentVersion) pseudoInputUpToDate = true;
|
||||
@@ -1834,6 +1835,22 @@ function getUpToDateStatusWorker<T extends BuilderProgram>(state: SolutionBuilde
|
||||
newestInputFileName = inputFile;
|
||||
newestInputFileTime = inputTime;
|
||||
}
|
||||
|
||||
if (buildInfoProgram) seenRoots.add(toPath(state, inputFile));
|
||||
}
|
||||
|
||||
if (buildInfoProgram) {
|
||||
if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath!, host);
|
||||
for (const existingRoot of buildInfoVersionMap.roots) {
|
||||
if (!seenRoots.has(existingRoot)) {
|
||||
// File was root file when project was built but its not any more
|
||||
return {
|
||||
type: UpToDateStatusType.OutOfDateRoots,
|
||||
buildInfoFile: buildInfoPath!,
|
||||
inputFile: existingRoot,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Now see if all outputs are newer than the newest input
|
||||
@@ -2561,6 +2578,14 @@ function reportUpToDateStatus<T extends BuilderProgram>(state: SolutionBuilderSt
|
||||
relName(state, configFileName),
|
||||
relName(state, status.buildInfoFile)
|
||||
);
|
||||
case UpToDateStatusType.OutOfDateRoots:
|
||||
return reportStatus(
|
||||
state,
|
||||
Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_but_not_any_more,
|
||||
relName(state, configFileName),
|
||||
relName(state, status.buildInfoFile),
|
||||
relName(state, status.inputFile),
|
||||
);
|
||||
case UpToDateStatusType.UpToDate:
|
||||
if (status.newestInputFileTime !== undefined) {
|
||||
return reportStatus(
|
||||
|
||||
+48
-32
@@ -1362,7 +1362,6 @@ export type HasIllegalModifiers =
|
||||
| PropertyAssignment
|
||||
| ShorthandPropertyAssignment
|
||||
| MissingDeclaration
|
||||
| FunctionTypeNode
|
||||
| NamespaceExportDeclaration
|
||||
;
|
||||
|
||||
@@ -1801,7 +1800,7 @@ export interface TypeParameterDeclaration extends NamedDeclaration, JSDocContain
|
||||
readonly constraint?: TypeNode;
|
||||
readonly default?: TypeNode;
|
||||
|
||||
// For error recovery purposes.
|
||||
// For error recovery purposes (see `isGrammarError` in utilities.ts).
|
||||
expression?: Expression;
|
||||
}
|
||||
|
||||
@@ -1888,7 +1887,7 @@ export interface PropertySignature extends TypeElement, JSDocContainer {
|
||||
readonly questionToken?: QuestionToken; // Present on optional property
|
||||
readonly type?: TypeNode; // Optional type annotation
|
||||
|
||||
// The following properties are used only to report grammar errors
|
||||
// The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts)
|
||||
/** @internal */ readonly initializer?: Expression | undefined; // A property signature cannot have an initializer
|
||||
}
|
||||
|
||||
@@ -1897,7 +1896,7 @@ export interface PropertyDeclaration extends ClassElement, JSDocContainer {
|
||||
readonly parent: ClassLikeDeclaration;
|
||||
readonly modifiers?: NodeArray<ModifierLike>;
|
||||
readonly name: PropertyName;
|
||||
readonly questionToken?: QuestionToken; // Present for use with reporting a grammar error
|
||||
readonly questionToken?: QuestionToken; // Present for use with reporting a grammar error for auto-accessors (see `isGrammarError` in utilities.ts)
|
||||
readonly exclamationToken?: ExclamationToken;
|
||||
readonly type?: TypeNode;
|
||||
readonly initializer?: Expression; // Optional initializer
|
||||
@@ -1960,7 +1959,7 @@ export interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer
|
||||
readonly name: PropertyName;
|
||||
readonly initializer: Expression;
|
||||
|
||||
// The following properties are used only to report grammar errors
|
||||
// The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts)
|
||||
/** @internal */ readonly modifiers?: NodeArray<ModifierLike> | undefined; // property assignment cannot have decorators or modifiers
|
||||
/** @internal */ readonly questionToken?: QuestionToken | undefined; // property assignment cannot have a question token
|
||||
/** @internal */ readonly exclamationToken?: ExclamationToken | undefined; // property assignment cannot have an exclamation token
|
||||
@@ -1971,11 +1970,11 @@ export interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDoc
|
||||
readonly parent: ObjectLiteralExpression;
|
||||
readonly name: Identifier;
|
||||
// used when ObjectLiteralExpression is used in ObjectAssignmentPattern
|
||||
// it is a grammar error to appear in actual object initializer:
|
||||
// it is a grammar error to appear in actual object initializer (see `isGrammarError` in utilities.ts):
|
||||
readonly equalsToken?: EqualsToken;
|
||||
readonly objectAssignmentInitializer?: Expression;
|
||||
|
||||
// The following properties are used only to report grammar errors
|
||||
// The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts)
|
||||
/** @internal */ readonly modifiers?: NodeArray<ModifierLike> | undefined; // shorthand property assignment cannot have decorators or modifiers
|
||||
/** @internal */ readonly questionToken?: QuestionToken | undefined; // shorthand property assignment cannot have a question token
|
||||
/** @internal */ readonly exclamationToken?: ExclamationToken | undefined; // shorthand property assignment cannot have an exclamation token
|
||||
@@ -2076,7 +2075,7 @@ export interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassEle
|
||||
readonly name: PropertyName;
|
||||
readonly body?: FunctionBody | undefined;
|
||||
|
||||
// The following properties are used only to report grammar errors
|
||||
// The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts)
|
||||
/** @internal */ readonly exclamationToken?: ExclamationToken | undefined; // A method cannot have an exclamation token
|
||||
}
|
||||
|
||||
@@ -2086,7 +2085,7 @@ export interface ConstructorDeclaration extends FunctionLikeDeclarationBase, Cla
|
||||
readonly modifiers?: NodeArray<ModifierLike> | undefined;
|
||||
readonly body?: FunctionBody | undefined;
|
||||
|
||||
// The following properties are used only to report grammar errors
|
||||
// The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts)
|
||||
/** @internal */ readonly typeParameters?: NodeArray<TypeParameterDeclaration>; // A constructor cannot have type parameters
|
||||
/** @internal */ readonly type?: TypeNode; // A constructor cannot have a return type annotation
|
||||
}
|
||||
@@ -2106,7 +2105,7 @@ export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, Cla
|
||||
readonly name: PropertyName;
|
||||
readonly body?: FunctionBody;
|
||||
|
||||
// The following properties are used only to report grammar errors
|
||||
// The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts)
|
||||
/** @internal */ readonly typeParameters?: NodeArray<TypeParameterDeclaration> | undefined; // A get accessor cannot have type parameters
|
||||
}
|
||||
|
||||
@@ -2119,7 +2118,7 @@ export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, Cla
|
||||
readonly name: PropertyName;
|
||||
readonly body?: FunctionBody;
|
||||
|
||||
// The following properties are used only to report grammar errors
|
||||
// The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts)
|
||||
/** @internal */ readonly typeParameters?: NodeArray<TypeParameterDeclaration> | undefined; // A set accessor cannot have type parameters
|
||||
/** @internal */ readonly type?: TypeNode | undefined; // A set accessor cannot have a return type
|
||||
}
|
||||
@@ -2141,7 +2140,7 @@ export interface ClassStaticBlockDeclaration extends ClassElement, JSDocContaine
|
||||
/** @internal */ endFlowNode?: FlowNode;
|
||||
/** @internal */ returnFlowNode?: FlowNode;
|
||||
|
||||
// The following properties are used only to report grammar errors
|
||||
// The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts)
|
||||
/** @internal */ readonly modifiers?: NodeArray<ModifierLike> | undefined;
|
||||
}
|
||||
|
||||
@@ -2190,8 +2189,8 @@ export interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDe
|
||||
export interface FunctionTypeNode extends FunctionOrConstructorTypeNodeBase, LocalsContainer {
|
||||
readonly kind: SyntaxKind.FunctionType;
|
||||
|
||||
// The following properties are used only to report grammar errors
|
||||
/** @internal */ readonly modifiers?: NodeArray<Modifier> | undefined;
|
||||
// A function type cannot have modifiers
|
||||
/** @internal */ readonly modifiers?: undefined;
|
||||
}
|
||||
|
||||
export interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase, LocalsContainer {
|
||||
@@ -3723,7 +3722,7 @@ export interface NamespaceExportDeclaration extends DeclarationStatement, JSDocC
|
||||
readonly kind: SyntaxKind.NamespaceExportDeclaration;
|
||||
readonly name: Identifier;
|
||||
|
||||
// The following properties are used only to report grammar errors
|
||||
// The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts)
|
||||
/** @internal */ readonly modifiers?: NodeArray<ModifierLike> | undefined;
|
||||
}
|
||||
|
||||
@@ -4927,7 +4926,7 @@ export interface TypeCheckerHost extends ModuleSpecifierResolutionHost {
|
||||
|
||||
export interface TypeChecker {
|
||||
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
|
||||
/** @internal */ getTypeOfSymbol(symbol: Symbol): Type;
|
||||
getTypeOfSymbol(symbol: Symbol): Type;
|
||||
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
|
||||
getPropertiesOfType(type: Type): Symbol[];
|
||||
getPropertyOfType(type: Type, propertyName: string): Symbol | undefined;
|
||||
@@ -4946,6 +4945,8 @@ export interface TypeChecker {
|
||||
getPromisedTypeOfPromise(promise: Type, errorNode?: Node): Type | undefined;
|
||||
/** @internal */
|
||||
getAwaitedType(type: Type): Type | undefined;
|
||||
/** @internal */
|
||||
isEmptyAnonymousObjectType(type: Type): boolean;
|
||||
getReturnTypeOfSignature(signature: Signature): Type;
|
||||
/**
|
||||
* Gets the type of a parameter at a given position in a signature.
|
||||
@@ -5153,9 +5154,21 @@ export interface TypeChecker {
|
||||
/** @internal */ getRecursionIdentity(type: Type): object | undefined;
|
||||
/** @internal */ getUnmatchedProperties(source: Type, target: Type, requireOptionalProperties: boolean, matchDiscriminantProperties: boolean): IterableIterator<Symbol>;
|
||||
|
||||
/** @internal */ isArrayType(type: Type): boolean;
|
||||
/** @internal */ isTupleType(type: Type): boolean;
|
||||
/** @internal */ isArrayLikeType(type: Type): boolean;
|
||||
/**
|
||||
* True if this type is the `Array` or `ReadonlyArray` type from lib.d.ts.
|
||||
* This function will _not_ return true if passed a type which
|
||||
* extends `Array` (for example, the TypeScript AST's `NodeArray` type).
|
||||
*/
|
||||
isArrayType(type: Type): boolean;
|
||||
/**
|
||||
* True if this type is a tuple type. This function will _not_ return true if
|
||||
* passed a type which extends from a tuple.
|
||||
*/
|
||||
isTupleType(type: Type): boolean;
|
||||
/**
|
||||
* True if this type is assignable to `ReadonlyArray<any>`.
|
||||
*/
|
||||
isArrayLikeType(type: Type): boolean;
|
||||
|
||||
/**
|
||||
* True if `contextualType` should not be considered for completions because
|
||||
@@ -5225,8 +5238,9 @@ export interface TypeChecker {
|
||||
/** @internal */ isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean;
|
||||
/** @internal */ isPropertyAccessible(node: Node, isSuper: boolean, isWrite: boolean, containingType: Type, property: Symbol): boolean;
|
||||
/** @internal */ getTypeOnlyAliasDeclaration(symbol: Symbol): TypeOnlyAliasDeclaration | undefined;
|
||||
/** @internal */ getMemberOverrideModifierStatus(node: ClassLikeDeclaration, member: ClassElement): MemberOverrideStatus;
|
||||
/** @internal */ getMemberOverrideModifierStatus(node: ClassLikeDeclaration, member: ClassElement, memberSymbol: Symbol): MemberOverrideStatus;
|
||||
/** @internal */ isTypeParameterPossiblyReferenced(tp: TypeParameter, node: Node): boolean;
|
||||
/** @internal */ typeHasCallOrConstructSignatures(type: Type): boolean;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
@@ -5983,6 +5997,9 @@ export interface NodeLinks {
|
||||
declarationRequiresScopeChange?: boolean; // Set by `useOuterVariableScopeInParameter` in checker when downlevel emit would change the name resolution scope inside of a parameter.
|
||||
serializedTypes?: Map<string, SerializedTypeEntry>; // Collection of types serialized at this location
|
||||
decoratorSignature?: Signature; // Signature for decorator as if invoked by the runtime.
|
||||
firstSpreadIndex?: number; // Index of first spread element in array literal (-1 for none)
|
||||
parameterInitializerContainsUndefined?: boolean; // True if this is a parameter declaration whose type annotation contains "undefined".
|
||||
fakeScopeForSignatureDeclaration?: boolean; // True if this is a fake scope injected into an enclosing declaration chain.
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
@@ -6028,7 +6045,8 @@ export const enum TypeFlags {
|
||||
/** @internal */
|
||||
Nullable = Undefined | Null,
|
||||
Literal = StringLiteral | NumberLiteral | BigIntLiteral | BooleanLiteral,
|
||||
Unit = Literal | UniqueESSymbol | Nullable,
|
||||
Unit = Enum | Literal | UniqueESSymbol | Nullable,
|
||||
Freshable = Enum | Literal,
|
||||
StringOrNumberLiteral = StringLiteral | NumberLiteral,
|
||||
/** @internal */
|
||||
StringOrNumberLiteralOrUnique = StringLiteral | NumberLiteral | UniqueESSymbol,
|
||||
@@ -6038,7 +6056,7 @@ export const enum TypeFlags {
|
||||
/** @internal */
|
||||
Intrinsic = Any | Unknown | String | Number | BigInt | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never | NonPrimitive,
|
||||
/** @internal */
|
||||
Primitive = String | Number | BigInt | Boolean | Enum | EnumLiteral | ESSymbol | Void | Undefined | Null | Literal | UniqueESSymbol,
|
||||
Primitive = String | Number | BigInt | Boolean | Enum | EnumLiteral | ESSymbol | Void | Undefined | Null | Literal | UniqueESSymbol | TemplateLiteral,
|
||||
StringLike = String | StringLiteral | TemplateLiteral | StringMapping,
|
||||
NumberLike = Number | NumberLiteral | Enum,
|
||||
BigIntLike = BigInt | BigIntLiteral,
|
||||
@@ -6122,22 +6140,20 @@ export interface NullableType extends IntrinsicType {
|
||||
objectFlags: ObjectFlags;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export interface FreshableIntrinsicType extends IntrinsicType {
|
||||
freshType: IntrinsicType; // Fresh version of type
|
||||
regularType: IntrinsicType; // Regular version of type
|
||||
export interface FreshableType extends Type {
|
||||
freshType: FreshableType; // Fresh version of type
|
||||
regularType: FreshableType; // Regular version of type
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export type FreshableType = LiteralType | FreshableIntrinsicType;
|
||||
export interface FreshableIntrinsicType extends FreshableType, IntrinsicType {
|
||||
}
|
||||
|
||||
// String literal types (TypeFlags.StringLiteral)
|
||||
// Numeric literal types (TypeFlags.NumberLiteral)
|
||||
// BigInt literal types (TypeFlags.BigIntLiteral)
|
||||
export interface LiteralType extends Type {
|
||||
export interface LiteralType extends FreshableType {
|
||||
value: string | number | PseudoBigInt; // Value of literal
|
||||
freshType: LiteralType; // Fresh version of type
|
||||
regularType: LiteralType; // Regular version of type
|
||||
}
|
||||
|
||||
// Unique symbol types (TypeFlags.UniqueESSymbol)
|
||||
@@ -6159,7 +6175,7 @@ export interface BigIntLiteralType extends LiteralType {
|
||||
}
|
||||
|
||||
// Enum types (TypeFlags.Enum)
|
||||
export interface EnumType extends Type {
|
||||
export interface EnumType extends FreshableType {
|
||||
}
|
||||
|
||||
// Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags
|
||||
@@ -6409,7 +6425,7 @@ export interface AnonymousType extends ObjectType {
|
||||
|
||||
/** @internal */
|
||||
export interface InstantiationExpressionType extends AnonymousType {
|
||||
node: ExpressionWithTypeArguments | TypeQueryNode;
|
||||
node: NodeWithTypeArguments;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
|
||||
+445
-116
@@ -199,8 +199,8 @@ import {
|
||||
HasExpressionInitializer,
|
||||
hasExtension,
|
||||
HasFlowNode,
|
||||
hasInitializer,
|
||||
HasInitializer,
|
||||
hasInitializer,
|
||||
HasJSDoc,
|
||||
hasJSDocNodes,
|
||||
HasModifiers,
|
||||
@@ -234,6 +234,7 @@ import {
|
||||
isArray,
|
||||
isArrayLiteralExpression,
|
||||
isArrowFunction,
|
||||
isAutoAccessorPropertyDeclaration,
|
||||
isBigIntLiteral,
|
||||
isBinaryExpression,
|
||||
isBindingElement,
|
||||
@@ -300,6 +301,7 @@ import {
|
||||
isMetaProperty,
|
||||
isMethodDeclaration,
|
||||
isMethodOrAccessor,
|
||||
isModifierLike,
|
||||
isModuleDeclaration,
|
||||
isNamedDeclaration,
|
||||
isNamespaceExport,
|
||||
@@ -333,6 +335,7 @@ import {
|
||||
isTypeElement,
|
||||
isTypeLiteralNode,
|
||||
isTypeNode,
|
||||
isTypeParameterDeclaration,
|
||||
isTypeReferenceNode,
|
||||
isVariableDeclaration,
|
||||
isVariableStatement,
|
||||
@@ -461,7 +464,6 @@ import {
|
||||
Signature,
|
||||
SignatureDeclaration,
|
||||
SignatureFlags,
|
||||
SignatureKind,
|
||||
singleElementArray,
|
||||
singleOrUndefined,
|
||||
skipOuterExpressions,
|
||||
@@ -594,7 +596,11 @@ export function isTransientSymbol(symbol: Symbol): symbol is TransientSymbol {
|
||||
const stringWriter = createSingleLineStringWriter();
|
||||
|
||||
function createSingleLineStringWriter(): EmitTextWriter {
|
||||
let str = "";
|
||||
// Why var? It avoids TDZ checks in the runtime which can be costly.
|
||||
// See: https://github.com/microsoft/TypeScript/issues/52924
|
||||
/* eslint-disable no-var */
|
||||
var str = "";
|
||||
/* eslint-enable no-var */
|
||||
const writeText: (text: string) => void = text => str += text;
|
||||
return {
|
||||
getText: () => str,
|
||||
@@ -964,6 +970,30 @@ export function nodeIsPresent(node: Node | undefined): boolean {
|
||||
return !nodeIsMissing(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether `child` is a grammar error on `parent`.
|
||||
* @internal
|
||||
*/
|
||||
export function isGrammarError(parent: Node, child: Node | NodeArray<Node>) {
|
||||
if (isTypeParameterDeclaration(parent)) return child === parent.expression;
|
||||
if (isClassStaticBlockDeclaration(parent)) return child === parent.modifiers;
|
||||
if (isPropertySignature(parent)) return child === parent.initializer;
|
||||
if (isPropertyDeclaration(parent)) return child === parent.questionToken && isAutoAccessorPropertyDeclaration(parent);
|
||||
if (isPropertyAssignment(parent)) return child === parent.modifiers || child === parent.questionToken || child === parent.exclamationToken || isGrammarErrorElement(parent.modifiers, child, isModifierLike);
|
||||
if (isShorthandPropertyAssignment(parent)) return child === parent.equalsToken || child === parent.modifiers || child === parent.questionToken || child === parent.exclamationToken || isGrammarErrorElement(parent.modifiers, child, isModifierLike);
|
||||
if (isMethodDeclaration(parent)) return child === parent.exclamationToken;
|
||||
if (isConstructorDeclaration(parent)) return child === parent.typeParameters || child === parent.type || isGrammarErrorElement(parent.typeParameters, child, isTypeParameterDeclaration);
|
||||
if (isGetAccessorDeclaration(parent)) return child === parent.typeParameters || isGrammarErrorElement(parent.typeParameters, child, isTypeParameterDeclaration);
|
||||
if (isSetAccessorDeclaration(parent)) return child === parent.typeParameters || child === parent.type || isGrammarErrorElement(parent.typeParameters, child, isTypeParameterDeclaration);
|
||||
if (isNamespaceExportDeclaration(parent)) return child === parent.modifiers || isGrammarErrorElement(parent.modifiers, child, isModifierLike);
|
||||
return false;
|
||||
}
|
||||
|
||||
function isGrammarErrorElement<T extends Node>(nodeArray: NodeArray<T> | undefined, child: Node | NodeArray<Node>, isElement: (node: Node) => node is T) {
|
||||
if (!nodeArray || isArray(child) || !isElement(child)) return false;
|
||||
return contains(nodeArray, child);
|
||||
}
|
||||
|
||||
function insertStatementsAfterPrologue<T extends Statement>(to: T[], from: readonly T[] | undefined, isPrologueDirective: (node: Node) => boolean): T[] {
|
||||
if (from === undefined || from.length === 0) return to;
|
||||
let statementIndex = 0;
|
||||
@@ -1193,108 +1223,407 @@ export function getInternalEmitFlags(node: Node): InternalEmitFlags {
|
||||
return emitNode && emitNode.internalFlags || 0;
|
||||
}
|
||||
|
||||
// Map from a type name, to a map of targets to array of features introduced to the type at that target.
|
||||
/** @internal */
|
||||
export interface ScriptTargetFeatures {
|
||||
[key: string]: { [key: string]: string[] | undefined };
|
||||
}
|
||||
export type ScriptTargetFeatures = ReadonlyMap<string, ReadonlyMap<string, string[]>>;
|
||||
|
||||
|
||||
/** @internal */
|
||||
export function getScriptTargetFeatures(): ScriptTargetFeatures {
|
||||
return {
|
||||
es2015: {
|
||||
Array: ["find", "findIndex", "fill", "copyWithin", "entries", "keys", "values"],
|
||||
RegExp: ["flags", "sticky", "unicode"],
|
||||
Reflect: ["apply", "construct", "defineProperty", "deleteProperty", "get"," getOwnPropertyDescriptor", "getPrototypeOf", "has", "isExtensible", "ownKeys", "preventExtensions", "set", "setPrototypeOf"],
|
||||
ArrayConstructor: ["from", "of"],
|
||||
ObjectConstructor: ["assign", "getOwnPropertySymbols", "keys", "is", "setPrototypeOf"],
|
||||
NumberConstructor: ["isFinite", "isInteger", "isNaN", "isSafeInteger", "parseFloat", "parseInt"],
|
||||
Math: ["clz32", "imul", "sign", "log10", "log2", "log1p", "expm1", "cosh", "sinh", "tanh", "acosh", "asinh", "atanh", "hypot", "trunc", "fround", "cbrt"],
|
||||
Map: ["entries", "keys", "values"],
|
||||
Set: ["entries", "keys", "values"],
|
||||
Promise: emptyArray,
|
||||
PromiseConstructor: ["all", "race", "reject", "resolve"],
|
||||
Symbol: ["for", "keyFor"],
|
||||
WeakMap: ["entries", "keys", "values"],
|
||||
WeakSet: ["entries", "keys", "values"],
|
||||
Iterator: emptyArray,
|
||||
AsyncIterator: emptyArray,
|
||||
String: ["codePointAt", "includes", "endsWith", "normalize", "repeat", "startsWith", "anchor", "big", "blink", "bold", "fixed", "fontcolor", "fontsize", "italics", "link", "small", "strike", "sub", "sup"],
|
||||
StringConstructor: ["fromCodePoint", "raw"]
|
||||
},
|
||||
es2016: {
|
||||
Array: ["includes"]
|
||||
},
|
||||
es2017: {
|
||||
Atomics: emptyArray,
|
||||
SharedArrayBuffer: emptyArray,
|
||||
String: ["padStart", "padEnd"],
|
||||
ObjectConstructor: ["values", "entries", "getOwnPropertyDescriptors"],
|
||||
DateTimeFormat: ["formatToParts"]
|
||||
},
|
||||
es2018: {
|
||||
Promise: ["finally"],
|
||||
RegExpMatchArray: ["groups"],
|
||||
RegExpExecArray: ["groups"],
|
||||
RegExp: ["dotAll"],
|
||||
Intl: ["PluralRules"],
|
||||
AsyncIterable: emptyArray,
|
||||
AsyncIterableIterator: emptyArray,
|
||||
AsyncGenerator: emptyArray,
|
||||
AsyncGeneratorFunction: emptyArray,
|
||||
NumberFormat: ["formatToParts"]
|
||||
},
|
||||
es2019: {
|
||||
Array: ["flat", "flatMap"],
|
||||
ObjectConstructor: ["fromEntries"],
|
||||
String: ["trimStart", "trimEnd", "trimLeft", "trimRight"],
|
||||
Symbol: ["description"]
|
||||
},
|
||||
es2020: {
|
||||
BigInt: emptyArray,
|
||||
BigInt64Array: emptyArray,
|
||||
BigUint64Array: emptyArray,
|
||||
PromiseConstructor: ["allSettled"],
|
||||
SymbolConstructor: ["matchAll"],
|
||||
String: ["matchAll"],
|
||||
DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"],
|
||||
RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"]
|
||||
},
|
||||
es2021: {
|
||||
PromiseConstructor: ["any"],
|
||||
String: ["replaceAll"]
|
||||
},
|
||||
es2022: {
|
||||
Array: ["at"],
|
||||
String: ["at"],
|
||||
Int8Array: ["at"],
|
||||
Uint8Array: ["at"],
|
||||
Uint8ClampedArray: ["at"],
|
||||
Int16Array: ["at"],
|
||||
Uint16Array: ["at"],
|
||||
Int32Array: ["at"],
|
||||
Uint32Array: ["at"],
|
||||
Float32Array: ["at"],
|
||||
Float64Array: ["at"],
|
||||
BigInt64Array: ["at"],
|
||||
BigUint64Array: ["at"],
|
||||
ObjectConstructor: ["hasOwn"],
|
||||
Error: ["cause"]
|
||||
},
|
||||
es2023: {
|
||||
Array: ["findLastIndex", "findLast"],
|
||||
Int8Array: ["findLastIndex", "findLast"],
|
||||
Uint8Array: ["findLastIndex", "findLast"],
|
||||
Uint8ClampedArray: ["findLastIndex", "findLast"],
|
||||
Int16Array: ["findLastIndex", "findLast"],
|
||||
Uint16Array: ["findLastIndex", "findLast"],
|
||||
Int32Array: ["findLastIndex", "findLast"],
|
||||
Uint32Array: ["findLastIndex", "findLast"],
|
||||
Float32Array: ["findLastIndex", "findLast"],
|
||||
Float64Array: ["findLastIndex", "findLast"],
|
||||
BigInt64Array: ["findLastIndex", "findLast"],
|
||||
BigUint64Array: ["findLastIndex", "findLast"],
|
||||
}
|
||||
};
|
||||
return new Map(Object.entries({
|
||||
Array: new Map(Object.entries({
|
||||
es2015: [
|
||||
"find",
|
||||
"findIndex",
|
||||
"fill",
|
||||
"copyWithin",
|
||||
"entries",
|
||||
"keys",
|
||||
"values"
|
||||
],
|
||||
es2016: [
|
||||
"includes"
|
||||
],
|
||||
es2019: [
|
||||
"flat",
|
||||
"flatMap"
|
||||
],
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
Iterator: new Map(Object.entries({
|
||||
es2015: emptyArray,
|
||||
})),
|
||||
AsyncIterator: new Map(Object.entries({
|
||||
es2015: emptyArray,
|
||||
})),
|
||||
Atomics: new Map(Object.entries({
|
||||
es2017: emptyArray,
|
||||
})),
|
||||
SharedArrayBuffer: new Map(Object.entries({
|
||||
es2017: emptyArray,
|
||||
})),
|
||||
AsyncIterable: new Map(Object.entries({
|
||||
es2018: emptyArray,
|
||||
})),
|
||||
AsyncIterableIterator: new Map(Object.entries({
|
||||
es2018: emptyArray,
|
||||
})),
|
||||
AsyncGenerator: new Map(Object.entries({
|
||||
es2018: emptyArray,
|
||||
})),
|
||||
AsyncGeneratorFunction: new Map(Object.entries({
|
||||
es2018: emptyArray,
|
||||
})),
|
||||
RegExp: new Map(Object.entries({
|
||||
es2015: [
|
||||
"flags",
|
||||
"sticky",
|
||||
"unicode"
|
||||
],
|
||||
es2018: [
|
||||
"dotAll"
|
||||
]
|
||||
})),
|
||||
Reflect: new Map(Object.entries({
|
||||
es2015: [
|
||||
"apply",
|
||||
"construct",
|
||||
"defineProperty",
|
||||
"deleteProperty",
|
||||
"get",
|
||||
" getOwnPropertyDescriptor",
|
||||
"getPrototypeOf",
|
||||
"has",
|
||||
"isExtensible",
|
||||
"ownKeys",
|
||||
"preventExtensions",
|
||||
"set",
|
||||
"setPrototypeOf"
|
||||
]
|
||||
})),
|
||||
ArrayConstructor: new Map(Object.entries({
|
||||
es2015: [
|
||||
"from",
|
||||
"of"
|
||||
]
|
||||
})),
|
||||
ObjectConstructor: new Map(Object.entries({
|
||||
es2015: [
|
||||
"assign",
|
||||
"getOwnPropertySymbols",
|
||||
"keys",
|
||||
"is",
|
||||
"setPrototypeOf"
|
||||
],
|
||||
es2017: [
|
||||
"values",
|
||||
"entries",
|
||||
"getOwnPropertyDescriptors"
|
||||
],
|
||||
es2019: [
|
||||
"fromEntries"
|
||||
],
|
||||
es2022: [
|
||||
"hasOwn"
|
||||
]
|
||||
})),
|
||||
NumberConstructor: new Map(Object.entries({
|
||||
es2015: [
|
||||
"isFinite",
|
||||
"isInteger",
|
||||
"isNaN",
|
||||
"isSafeInteger",
|
||||
"parseFloat",
|
||||
"parseInt"
|
||||
]
|
||||
})),
|
||||
Math: new Map(Object.entries({
|
||||
es2015: [
|
||||
"clz32",
|
||||
"imul",
|
||||
"sign",
|
||||
"log10",
|
||||
"log2",
|
||||
"log1p",
|
||||
"expm1",
|
||||
"cosh",
|
||||
"sinh",
|
||||
"tanh",
|
||||
"acosh",
|
||||
"asinh",
|
||||
"atanh",
|
||||
"hypot",
|
||||
"trunc",
|
||||
"fround",
|
||||
"cbrt"
|
||||
]
|
||||
})),
|
||||
Map: new Map(Object.entries({
|
||||
es2015: [
|
||||
"entries",
|
||||
"keys",
|
||||
"values"
|
||||
]
|
||||
})),
|
||||
Set: new Map(Object.entries({
|
||||
es2015: [
|
||||
"entries",
|
||||
"keys",
|
||||
"values"
|
||||
]
|
||||
})),
|
||||
PromiseConstructor: new Map(Object.entries({
|
||||
es2015: [
|
||||
"all",
|
||||
"race",
|
||||
"reject",
|
||||
"resolve"
|
||||
],
|
||||
es2020: [
|
||||
"allSettled"
|
||||
],
|
||||
es2021: [
|
||||
"any"
|
||||
]
|
||||
})),
|
||||
Symbol: new Map(Object.entries({
|
||||
es2015: [
|
||||
"for",
|
||||
"keyFor"
|
||||
],
|
||||
es2019: [
|
||||
"description"
|
||||
]
|
||||
})),
|
||||
WeakMap: new Map(Object.entries({
|
||||
es2015: [
|
||||
"entries",
|
||||
"keys",
|
||||
"values"
|
||||
]
|
||||
})),
|
||||
WeakSet: new Map(Object.entries({
|
||||
es2015: [
|
||||
"entries",
|
||||
"keys",
|
||||
"values"
|
||||
]
|
||||
})),
|
||||
String: new Map(Object.entries({
|
||||
es2015: [
|
||||
"codePointAt",
|
||||
"includes",
|
||||
"endsWith",
|
||||
"normalize",
|
||||
"repeat",
|
||||
"startsWith",
|
||||
"anchor",
|
||||
"big",
|
||||
"blink",
|
||||
"bold",
|
||||
"fixed",
|
||||
"fontcolor",
|
||||
"fontsize",
|
||||
"italics",
|
||||
"link",
|
||||
"small",
|
||||
"strike",
|
||||
"sub",
|
||||
"sup"
|
||||
],
|
||||
es2017: [
|
||||
"padStart",
|
||||
"padEnd"
|
||||
],
|
||||
es2019: [
|
||||
"trimStart",
|
||||
"trimEnd",
|
||||
"trimLeft",
|
||||
"trimRight"
|
||||
],
|
||||
es2020: [
|
||||
"matchAll"
|
||||
],
|
||||
es2021: [
|
||||
"replaceAll"
|
||||
],
|
||||
es2022: [
|
||||
"at"
|
||||
]
|
||||
})),
|
||||
StringConstructor: new Map(Object.entries({
|
||||
es2015: [
|
||||
"fromCodePoint",
|
||||
"raw"
|
||||
]
|
||||
})),
|
||||
DateTimeFormat: new Map(Object.entries({
|
||||
es2017: [
|
||||
"formatToParts"
|
||||
]
|
||||
})),
|
||||
Promise: new Map(Object.entries({
|
||||
es2015: emptyArray,
|
||||
es2018: [
|
||||
"finally"
|
||||
]
|
||||
})),
|
||||
RegExpMatchArray: new Map(Object.entries({
|
||||
es2018: [
|
||||
"groups"
|
||||
]
|
||||
})),
|
||||
RegExpExecArray: new Map(Object.entries({
|
||||
es2018: [
|
||||
"groups"
|
||||
]
|
||||
})),
|
||||
Intl: new Map(Object.entries({
|
||||
es2018: [
|
||||
"PluralRules"
|
||||
]
|
||||
})),
|
||||
NumberFormat: new Map(Object.entries({
|
||||
es2018: [
|
||||
"formatToParts"
|
||||
]
|
||||
})),
|
||||
SymbolConstructor: new Map(Object.entries({
|
||||
es2020: [
|
||||
"matchAll"
|
||||
]
|
||||
})),
|
||||
DataView: new Map(Object.entries({
|
||||
es2020: [
|
||||
"setBigInt64",
|
||||
"setBigUint64",
|
||||
"getBigInt64",
|
||||
"getBigUint64"
|
||||
]
|
||||
})),
|
||||
BigInt: new Map(Object.entries({
|
||||
es2020: emptyArray
|
||||
})),
|
||||
RelativeTimeFormat: new Map(Object.entries({
|
||||
es2020: [
|
||||
"format",
|
||||
"formatToParts",
|
||||
"resolvedOptions"
|
||||
]
|
||||
})),
|
||||
Int8Array: new Map(Object.entries({
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
Uint8Array: new Map(Object.entries({
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
Uint8ClampedArray: new Map(Object.entries({
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
Int16Array: new Map(Object.entries({
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
Uint16Array: new Map(Object.entries({
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
Int32Array: new Map(Object.entries({
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
Uint32Array: new Map(Object.entries({
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
Float32Array: new Map(Object.entries({
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
Float64Array: new Map(Object.entries({
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
BigInt64Array: new Map(Object.entries({
|
||||
es2020: emptyArray,
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
BigUint64Array: new Map(Object.entries({
|
||||
es2020: emptyArray,
|
||||
es2022: [
|
||||
"at"
|
||||
],
|
||||
es2023: [
|
||||
"findLastIndex",
|
||||
"findLast"
|
||||
],
|
||||
})),
|
||||
Error: new Map(Object.entries({
|
||||
es2022: [
|
||||
"cause"
|
||||
]
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
@@ -1482,7 +1811,7 @@ function isCommonJSContainingModuleKind(kind: ModuleKind) {
|
||||
|
||||
/** @internal */
|
||||
export function isEffectiveExternalModule(node: SourceFile, compilerOptions: CompilerOptions) {
|
||||
return isExternalModule(node) || compilerOptions.isolatedModules || (isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator);
|
||||
return isExternalModule(node) || getIsolatedModules(compilerOptions) || (isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1513,7 +1842,7 @@ export function isEffectiveStrictModeSourceFile(node: SourceFile, compilerOption
|
||||
if (startsWithUseStrict(node.statements)) {
|
||||
return true;
|
||||
}
|
||||
if (isExternalModule(node) || compilerOptions.isolatedModules) {
|
||||
if (isExternalModule(node) || getIsolatedModules(compilerOptions)) {
|
||||
// ECMAScript Modules are always strict.
|
||||
if (getEmitModuleKind(compilerOptions) >= ModuleKind.ES2015) {
|
||||
return true;
|
||||
@@ -5485,12 +5814,16 @@ export function isNightly() {
|
||||
|
||||
/** @internal */
|
||||
export function createTextWriter(newLine: string): EmitTextWriter {
|
||||
let output: string;
|
||||
let indent: number;
|
||||
let lineStart: boolean;
|
||||
let lineCount: number;
|
||||
let linePos: number;
|
||||
let hasTrailingComment = false;
|
||||
// Why var? It avoids TDZ checks in the runtime which can be costly.
|
||||
// See: https://github.com/microsoft/TypeScript/issues/52924
|
||||
/* eslint-disable no-var */
|
||||
var output: string;
|
||||
var indent: number;
|
||||
var lineStart: boolean;
|
||||
var lineCount: number;
|
||||
var linePos: number;
|
||||
var hasTrailingComment = false;
|
||||
/* eslint-enable no-var */
|
||||
|
||||
function updateLineCountAndPosFor(s: string) {
|
||||
const lineStartsOfS = computeLineStarts(s);
|
||||
@@ -7319,11 +7652,6 @@ export function getObjectFlags(type: Type): ObjectFlags {
|
||||
return type.flags & TypeFlags.ObjectFlagsType ? (type as ObjectFlagsType).objectFlags : 0;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function typeHasCallOrConstructSignatures(type: Type, checker: TypeChecker) {
|
||||
return checker.getSignaturesOfType(type, SignatureKind.Call).length !== 0 || checker.getSignaturesOfType(type, SignatureKind.Construct).length !== 0;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function forSomeAncestorDirectory(directory: string, callback: (directory: string) => boolean): boolean {
|
||||
return !!forEachAncestorDirectory(directory, d => callback(d) ? true : undefined);
|
||||
@@ -7989,6 +8317,7 @@ export function getEmitModuleKind(compilerOptions: {module?: CompilerOptions["mo
|
||||
getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2015 ? ModuleKind.ES2015 : ModuleKind.CommonJS;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function emitModuleKindIsNonNodeESM(moduleKind: ModuleKind) {
|
||||
return moduleKind >= ModuleKind.ES2015 && moduleKind <= ModuleKind.ESNext;
|
||||
}
|
||||
@@ -8143,7 +8472,7 @@ export function getEmitDeclarations(compilerOptions: CompilerOptions): boolean {
|
||||
|
||||
/** @internal */
|
||||
export function shouldPreserveConstEnums(compilerOptions: CompilerOptions): boolean {
|
||||
return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules);
|
||||
return !!(compilerOptions.preserveConstEnums || getIsolatedModules(compilerOptions));
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
@@ -9079,7 +9408,7 @@ export function rangeOfNode(node: Node): TextRange {
|
||||
export function rangeOfTypeParameters(sourceFile: SourceFile, typeParameters: NodeArray<TypeParameterDeclaration>): TextRange {
|
||||
// Include the `<>`
|
||||
const pos = typeParameters.pos - 1;
|
||||
const end = skipTrivia(sourceFile.text, typeParameters.end) + 1;
|
||||
const end = Math.min(sourceFile.text.length, skipTrivia(sourceFile.text, typeParameters.end) + 1);
|
||||
return { pos, end };
|
||||
}
|
||||
|
||||
|
||||
@@ -1454,7 +1454,7 @@ const visitEachChildTable: VisitEachChildTable = {
|
||||
|
||||
[SyntaxKind.JsxExpression]: function visitEachChildOfJsxExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
|
||||
return context.factory.updateJsxExpression(node,
|
||||
Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)));
|
||||
nodeVisitor(node.expression, visitor, isExpression));
|
||||
},
|
||||
|
||||
// Clauses
|
||||
|
||||
@@ -3,8 +3,8 @@ import {
|
||||
DeprecationOptions,
|
||||
formatStringFromArgs,
|
||||
noop,
|
||||
version,
|
||||
Version,
|
||||
version,
|
||||
} from "./_namespaces/ts";
|
||||
|
||||
export let enableDeprecationWarnings = true;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as performance from "../compiler/_namespaces/ts.performance";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import {
|
||||
arrayFrom,
|
||||
@@ -19,8 +20,8 @@ import {
|
||||
createDiagnosticReporter,
|
||||
createGetCanonicalFileName,
|
||||
createIncrementalCompilerHost,
|
||||
createProgram,
|
||||
CreateProgram,
|
||||
createProgram,
|
||||
CreateProgramOptions,
|
||||
createSolutionBuilder,
|
||||
createSolutionBuilderHost,
|
||||
@@ -87,7 +88,6 @@ import {
|
||||
WatchCompilerHost,
|
||||
WatchOptions,
|
||||
} from "./_namespaces/ts";
|
||||
import * as performance from "../compiler/_namespaces/ts.performance";
|
||||
|
||||
interface Statistic {
|
||||
name: string;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as fakes from "./_namespaces/fakes";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
import * as documents from "./_namespaces/documents";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as collections from "./_namespaces/collections";
|
||||
import * as documents from "./_namespaces/documents";
|
||||
import * as fakes from "./_namespaces/fakes";
|
||||
import * as Harness from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
|
||||
/**
|
||||
* Test harness compiler functionality.
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as Harness from "./_namespaces/Harness";
|
||||
import * as fakes from "./_namespaces/fakes";
|
||||
import * as compiler from "./_namespaces/compiler";
|
||||
import * as fakes from "./_namespaces/fakes";
|
||||
import * as Harness from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
|
||||
declare let Symbol: SymbolConstructor;
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as Utils from "./_namespaces/Utils";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
import * as documents from "./_namespaces/documents";
|
||||
import * as collections from "./_namespaces/collections";
|
||||
import * as documents from "./_namespaces/documents";
|
||||
import * as Harness from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as Utils from "./_namespaces/Utils";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
|
||||
/**
|
||||
* Fake implementations of various compiler dependencies.
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import * as fakes from "./_namespaces/fakes";
|
||||
import * as FourSlashInterface from "./_namespaces/FourSlashInterface";
|
||||
import * as Harness from "./_namespaces/Harness";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as fakes from "./_namespaces/fakes";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
import * as Utils from "./_namespaces/Utils";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
|
||||
import ArrayOrSingle = FourSlashInterface.ArrayOrSingle;
|
||||
|
||||
@@ -882,18 +882,28 @@ export class TestState {
|
||||
|
||||
public verifyCompletions(options: FourSlashInterface.VerifyCompletionsOptions) {
|
||||
if (options.marker === undefined) {
|
||||
this.verifyCompletionsWorker(options);
|
||||
return this.verifyCompletionsWorker(options);
|
||||
}
|
||||
else {
|
||||
for (const marker of toArray(options.marker)) {
|
||||
this.goToMarker(marker);
|
||||
this.verifyCompletionsWorker({ ...options, marker });
|
||||
if (ts.isArray(options.marker)) {
|
||||
for (const marker of options.marker) {
|
||||
this.goToMarker(marker);
|
||||
this.verifyCompletionsWorker({ ...options, marker });
|
||||
}
|
||||
return {
|
||||
andApplyCodeAction: () => {
|
||||
this.raiseError(`Cannot apply code action when multiple markers are specified.`);
|
||||
}
|
||||
};
|
||||
}
|
||||
this.goToMarker(options.marker);
|
||||
return this.verifyCompletionsWorker({ ...options, marker: options.marker });
|
||||
}
|
||||
}
|
||||
|
||||
private verifyCompletionsWorker(options: FourSlashInterface.VerifyCompletionsOptions): void {
|
||||
const actualCompletions = this.getCompletionListAtCaret({ ...options.preferences, triggerCharacter: options.triggerCharacter })!;
|
||||
private verifyCompletionsWorker(options: FourSlashInterface.VerifyCompletionsOptions) {
|
||||
const preferences = options.preferences;
|
||||
const actualCompletions = this.getCompletionListAtCaret({ ...preferences, triggerCharacter: options.triggerCharacter })!;
|
||||
if (!actualCompletions) {
|
||||
if (ts.hasProperty(options, "exact") && (options.exact === undefined || ts.isArray(options.exact) && !options.exact.length)) {
|
||||
return;
|
||||
@@ -917,6 +927,7 @@ export class TestState {
|
||||
}
|
||||
|
||||
const nameToEntries = new Map<string, ts.CompletionEntry[]>();
|
||||
const nameAndSourceToData = new Map<string, ts.CompletionEntryData | false>();
|
||||
for (const entry of actualCompletions.entries) {
|
||||
const entries = nameToEntries.get(entry.name);
|
||||
if (!entries) {
|
||||
@@ -934,6 +945,15 @@ export class TestState {
|
||||
}
|
||||
entries.push(entry);
|
||||
}
|
||||
if (entry.data && entry.source) {
|
||||
const key = `${entry.name}|${entry.source}`;
|
||||
if (nameAndSourceToData.has(key)) {
|
||||
nameAndSourceToData.set(key, false);
|
||||
}
|
||||
else {
|
||||
nameAndSourceToData.set(key, entry.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (ts.hasProperty(options, "exact")) {
|
||||
@@ -977,6 +997,26 @@ export class TestState {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
andApplyCodeAction: (options: {
|
||||
name: string,
|
||||
source: string,
|
||||
description: string,
|
||||
newFileContent?: string,
|
||||
newRangeContent?: string,
|
||||
}) => {
|
||||
const { name, source, description, newFileContent, newRangeContent } = options;
|
||||
const data = nameAndSourceToData.get(`${options.name}|${options.source}`);
|
||||
if (data === false) {
|
||||
this.raiseError(`Multiple completion entries found for '${options.name}' from '${options.source}'. This API cannot be used. Use 'verify.applyCodeActionFromCompletion' instead.`);
|
||||
}
|
||||
if (data === undefined) {
|
||||
this.raiseError(`No completion entry found for '${options.name}' from '${options.source}'`);
|
||||
}
|
||||
this.applyCodeActionFromCompletion(/*markerName*/ undefined, { name, source, data, description, newFileContent, newRangeContent, preferences });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private verifyCompletionEntry(actual: ts.CompletionEntry, expected: FourSlashInterface.ExpectedCompletionEntry) {
|
||||
@@ -2046,7 +2086,27 @@ export class TestState {
|
||||
? entry.displayParts.map(p => p.text).join("").split("\n")
|
||||
: [`(${entry.kindModifiers}${entry.kind}) ${entry.name}`])
|
||||
);
|
||||
Harness.Baseline.runBaseline(baselineFile, annotations + "\n\n" + stringify(result));
|
||||
for (const r of result) {
|
||||
for (const entry of r.item.entries ?? ts.emptyArray) {
|
||||
for (const tag of entry.tags ?? ts.emptyArray) {
|
||||
for (const part of tag.text ?? ts.emptyArray) {
|
||||
if (part.kind === "linkName") {
|
||||
const link = part as ts.JSDocLinkDisplayPart;
|
||||
if (/lib(?:.*)\.d\.ts$/.test(link.target.fileName)) {
|
||||
// The object literal isn't a complete TextSpan, but we're only going to
|
||||
// use these results in the baseline for diffing, so just overwrite.
|
||||
(link.target.textSpan as any) = { start: "--", length: "--" };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Harness.Baseline.runBaseline(baselineFile, annotations + "\n\n" + stringify(result, (key, value) => {
|
||||
return key === "exportMapKey"
|
||||
? value.replace(/\|[0-9]+/g, "|*")
|
||||
: value;
|
||||
}));
|
||||
}
|
||||
|
||||
private annotateContentWithTooltips<T extends ts.QuickInfo | ts.SignatureHelpItems | {
|
||||
|
||||
@@ -252,9 +252,17 @@ export class Verify extends VerifyNegatable {
|
||||
}
|
||||
|
||||
public completions(...optionsArray: VerifyCompletionsOptions[]) {
|
||||
if (optionsArray.length === 1) {
|
||||
return this.state.verifyCompletions(optionsArray[0]);
|
||||
}
|
||||
for (const options of optionsArray) {
|
||||
this.state.verifyCompletions(options);
|
||||
}
|
||||
return {
|
||||
andApplyCodeAction: () => {
|
||||
throw new Error("Cannot call andApplyCodeAction on multiple completions requests");
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
public getInlayHints(expected: readonly VerifyInlayHintsOptions[], span: ts.TextSpan, preference?: ts.UserPreferences) {
|
||||
|
||||
+20
-11
@@ -1,7 +1,3 @@
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as Utils from "./_namespaces/Utils";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as compiler from "./_namespaces/compiler";
|
||||
import * as documents from "./_namespaces/documents";
|
||||
import * as fakes from "./_namespaces/fakes";
|
||||
@@ -10,6 +6,10 @@ import {
|
||||
TypeWriterResult,
|
||||
TypeWriterWalker,
|
||||
} from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as Utils from "./_namespaces/Utils";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
|
||||
export interface IO {
|
||||
newLine(): string;
|
||||
@@ -567,7 +567,7 @@ export namespace Compiler {
|
||||
diagnostics = ts.sort(diagnostics, ts.compareDiagnostics);
|
||||
let outputLines = "";
|
||||
// Count up all errors that were found in files other than lib.d.ts so we don't miss any
|
||||
let totalErrorsReportedInNonLibraryFiles = 0;
|
||||
let totalErrorsReportedInNonLibraryNonTsconfigFiles = 0;
|
||||
|
||||
let errorsReported = 0;
|
||||
|
||||
@@ -609,14 +609,19 @@ export namespace Compiler {
|
||||
// do not count errors from lib.d.ts here, they are computed separately as numLibraryDiagnostics
|
||||
// if lib.d.ts is explicitly included in input files and there are some errors in it (i.e. because of duplicate identifiers)
|
||||
// then they will be added twice thus triggering 'total errors' assertion with condition
|
||||
// 'totalErrorsReportedInNonLibraryFiles + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length
|
||||
// Similarly for tsconfig, which may be in the input files and contain errors.
|
||||
// 'totalErrorsReportedInNonLibraryNonTsconfigFiles + numLibraryDiagnostics + numTsconfigDiagnostics + numTest262HarnessDiagnostics, diagnostics.length
|
||||
|
||||
if (!error.file || !isDefaultLibraryFile(error.file.fileName)) {
|
||||
totalErrorsReportedInNonLibraryFiles++;
|
||||
if (!error.file || !isDefaultLibraryFile(error.file.fileName) && !vpath.isTsConfigFile(error.file.fileName)) {
|
||||
totalErrorsReportedInNonLibraryNonTsconfigFiles++;
|
||||
}
|
||||
}
|
||||
|
||||
yield [diagnosticSummaryMarker, Utils.removeTestPathPrefixes(minimalDiagnosticsToString(diagnostics, options && options.pretty)) + IO.newLine() + IO.newLine(), diagnostics.length];
|
||||
let topDiagnostics = minimalDiagnosticsToString(diagnostics, options && options.pretty);
|
||||
topDiagnostics = Utils.removeTestPathPrefixes(topDiagnostics);
|
||||
topDiagnostics = topDiagnostics.replace(/^(lib(?:.*)\.d\.ts)\(\d+,\d+\)/igm, "$1(--,--)");
|
||||
|
||||
yield [diagnosticSummaryMarker, topDiagnostics + IO.newLine() + IO.newLine(), diagnostics.length];
|
||||
|
||||
// Report global errors
|
||||
const globalErrors = diagnostics.filter(err => !err.file);
|
||||
@@ -700,7 +705,7 @@ export namespace Compiler {
|
||||
// Case-duplicated files on a case-insensitive build will have errors reported in both the dupe and the original
|
||||
// thanks to the canse-insensitive path comparison on the error file path - We only want to count those errors once
|
||||
// for the assert below, so we subtract them here.
|
||||
totalErrorsReportedInNonLibraryFiles -= errorsReported;
|
||||
totalErrorsReportedInNonLibraryNonTsconfigFiles -= errorsReported;
|
||||
}
|
||||
outputLines = "";
|
||||
errorsReported = 0;
|
||||
@@ -710,13 +715,17 @@ export namespace Compiler {
|
||||
return !!diagnostic.file && (isDefaultLibraryFile(diagnostic.file.fileName) || isBuiltFile(diagnostic.file.fileName));
|
||||
});
|
||||
|
||||
const numTsconfigDiagnostics = ts.countWhere(diagnostics, diagnostic => {
|
||||
return !!diagnostic.file && (vpath.isTsConfigFile(diagnostic.file.fileName));
|
||||
});
|
||||
|
||||
const numTest262HarnessDiagnostics = ts.countWhere(diagnostics, diagnostic => {
|
||||
// Count an error generated from tests262-harness folder.This should only apply for test262
|
||||
return !!diagnostic.file && diagnostic.file.fileName.indexOf("test262-harness") >= 0;
|
||||
});
|
||||
|
||||
// Verify we didn't miss any errors in total
|
||||
assert.equal(totalErrorsReportedInNonLibraryFiles + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length, "total number of errors");
|
||||
assert.equal(totalErrorsReportedInNonLibraryNonTsconfigFiles + numLibraryDiagnostics + numTsconfigDiagnostics + numTest262HarnessDiagnostics, diagnostics.length, "total number of errors");
|
||||
}
|
||||
|
||||
export function doErrorBaseline(baselinePath: string, inputFiles: readonly TestFile[], errors: readonly ts.Diagnostic[], pretty?: boolean) {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as fakes from "./_namespaces/fakes";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as collections from "./_namespaces/collections";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
import * as fakes from "./_namespaces/fakes";
|
||||
import {
|
||||
Compiler,
|
||||
mockHash,
|
||||
virtualFileSystemRoot,
|
||||
} from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import { getNewLineCharacter } from "./_namespaces/ts";
|
||||
import * as vfs from "./_namespaces/vfs";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
|
||||
export function makeDefaultProxy(info: ts.server.PluginCreateInfo): ts.LanguageService {
|
||||
const proxy = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as Harness from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
|
||||
export function encodeString(s: string): string {
|
||||
return ts.sys.bufferFrom!(s).toString("utf8");
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import {
|
||||
FileBasedTest,
|
||||
IO,
|
||||
userSpecifiedRoot,
|
||||
} from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
|
||||
export type TestRunnerKind = CompilerTestKind | FourslashTestKind | "project" | "rwc" | "test262" | "user" | "dt" | "docker";
|
||||
export type CompilerTestKind = "conformance" | "compiler";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as documents from "./_namespaces/documents";
|
||||
import * as Utils from "./_namespaces/Utils";
|
||||
import { Compiler } from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as Utils from "./_namespaces/Utils";
|
||||
|
||||
interface SourceMapSpanWithDecodeErrors {
|
||||
sourceMapSpan: ts.Mapping;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as collections from "./_namespaces/collections";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
import * as documents from "./_namespaces/documents";
|
||||
import * as Harness from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
|
||||
/**
|
||||
* Posix-style path to the TypeScript compiler build outputs (including tsc.js, lib.d.ts, etc.)
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
import {
|
||||
ActionInvalidate,
|
||||
ActionPackageInstalled,
|
||||
ActionSet,
|
||||
EventBeginInstallTypes,
|
||||
EventEndInstallTypes,
|
||||
EventInitializationFailed,
|
||||
EventTypesRegistry,
|
||||
} from "./_namespaces/ts.server";
|
||||
import {
|
||||
CompilerOptions,
|
||||
DirectoryWatcherCallback,
|
||||
@@ -19,6 +10,15 @@ import {
|
||||
TypeAcquisition,
|
||||
WatchOptions,
|
||||
} from "./_namespaces/ts";
|
||||
import {
|
||||
ActionInvalidate,
|
||||
ActionPackageInstalled,
|
||||
ActionSet,
|
||||
EventBeginInstallTypes,
|
||||
EventEndInstallTypes,
|
||||
EventInitializationFailed,
|
||||
EventTypesRegistry,
|
||||
} from "./_namespaces/ts.server";
|
||||
|
||||
export interface TypingInstallerResponse {
|
||||
readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed;
|
||||
|
||||
Vendored
+111
-94
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* The decorator context types provided to class member decorators.
|
||||
* The decorator context types provided to class element decorators.
|
||||
*/
|
||||
type ClassMemberDecoratorContext =
|
||||
| ClassMethodDecoratorContext
|
||||
@@ -60,34 +60,37 @@ interface ClassMethodDecoratorContext<
|
||||
This = unknown,
|
||||
Value extends (this: This, ...args: any) => any = (this: This, ...args: any) => any,
|
||||
> {
|
||||
/** The kind of class member that was decorated. */
|
||||
/** The kind of class element that was decorated. */
|
||||
readonly kind: "method";
|
||||
|
||||
/** The name of the decorated class member. */
|
||||
/** The name of the decorated class element. */
|
||||
readonly name: string | symbol;
|
||||
|
||||
/** A value indicating whether the class member is a static (`true`) or instance (`false`) member. */
|
||||
/** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */
|
||||
readonly static: boolean;
|
||||
|
||||
/** A value indicating whether the class member has a private name. */
|
||||
/** A value indicating whether the class element has a private name. */
|
||||
readonly private: boolean;
|
||||
|
||||
// NOTE: Disabled, pending the outcome of https://github.com/tc39/proposal-decorators/issues/494
|
||||
// /** An object that can be used to access the current value of the class member at runtime. */
|
||||
// readonly access: {
|
||||
// /**
|
||||
// * Gets the current value of the method from the provided receiver.
|
||||
// *
|
||||
// * @example
|
||||
// * let fn = context.access.get.call(instance);
|
||||
// */
|
||||
// get(this: This): Value;
|
||||
// };
|
||||
/** An object that can be used to access the current value of the class element at runtime. */
|
||||
readonly access: {
|
||||
/**
|
||||
* Determines whether an object has a property with the same name as the decorated element.
|
||||
*/
|
||||
has(object: This): boolean;
|
||||
/**
|
||||
* Gets the current value of the method from the provided object.
|
||||
*
|
||||
* @example
|
||||
* let fn = context.access.get(instance);
|
||||
*/
|
||||
get(object: This): Value;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a callback to be invoked either before static initializers are run (when
|
||||
* decorating a `static` member), or before instance initializers are run (when
|
||||
* decorating a non-`static` member).
|
||||
* decorating a `static` element), or before instance initializers are run (when
|
||||
* decorating a non-`static` element).
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
@@ -121,34 +124,37 @@ interface ClassGetterDecoratorContext<
|
||||
This = unknown,
|
||||
Value = unknown,
|
||||
> {
|
||||
/** The kind of class member that was decorated. */
|
||||
/** The kind of class element that was decorated. */
|
||||
readonly kind: "getter";
|
||||
|
||||
/** The name of the decorated class member. */
|
||||
/** The name of the decorated class element. */
|
||||
readonly name: string | symbol;
|
||||
|
||||
/** A value indicating whether the class member is a static (`true`) or instance (`false`) member. */
|
||||
/** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */
|
||||
readonly static: boolean;
|
||||
|
||||
/** A value indicating whether the class member has a private name. */
|
||||
/** A value indicating whether the class element has a private name. */
|
||||
readonly private: boolean;
|
||||
|
||||
// NOTE: Disabled, pending the outcome of https://github.com/tc39/proposal-decorators/issues/494
|
||||
// /** An object that can be used to access the current value of the class member at runtime. */
|
||||
// readonly access: {
|
||||
// /**
|
||||
// * Invokes the getter on the provided receiver.
|
||||
// *
|
||||
// * @example
|
||||
// * let value = context.access.get.call(instance);
|
||||
// */
|
||||
// get(this: This): Value;
|
||||
// };
|
||||
/** An object that can be used to access the current value of the class element at runtime. */
|
||||
readonly access: {
|
||||
/**
|
||||
* Determines whether an object has a property with the same name as the decorated element.
|
||||
*/
|
||||
has(object: This): boolean;
|
||||
/**
|
||||
* Invokes the getter on the provided object.
|
||||
*
|
||||
* @example
|
||||
* let value = context.access.get(instance);
|
||||
*/
|
||||
get(object: This): Value;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a callback to be invoked either before static initializers are run (when
|
||||
* decorating a `static` member), or before instance initializers are run (when
|
||||
* decorating a non-`static` member).
|
||||
* decorating a `static` element), or before instance initializers are run (when
|
||||
* decorating a non-`static` element).
|
||||
*/
|
||||
addInitializer(initializer: (this: This) => void): void;
|
||||
}
|
||||
@@ -163,34 +169,37 @@ interface ClassSetterDecoratorContext<
|
||||
This = unknown,
|
||||
Value = unknown,
|
||||
> {
|
||||
/** The kind of class member that was decorated. */
|
||||
/** The kind of class element that was decorated. */
|
||||
readonly kind: "setter";
|
||||
|
||||
/** The name of the decorated class member. */
|
||||
/** The name of the decorated class element. */
|
||||
readonly name: string | symbol;
|
||||
|
||||
/** A value indicating whether the class member is a static (`true`) or instance (`false`) member. */
|
||||
/** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */
|
||||
readonly static: boolean;
|
||||
|
||||
/** A value indicating whether the class member has a private name. */
|
||||
/** A value indicating whether the class element has a private name. */
|
||||
readonly private: boolean;
|
||||
|
||||
// NOTE: Disabled, pending the outcome of https://github.com/tc39/proposal-decorators/issues/494
|
||||
/** An object that can be used to access the current value of the class member at runtime. */
|
||||
// readonly access: {
|
||||
// /**
|
||||
// * Invokes the setter on the provided receiver.
|
||||
// *
|
||||
// * @example
|
||||
// * context.access.set.call(instance, value);
|
||||
// */
|
||||
// set(this: This, value: Value): void;
|
||||
// };
|
||||
/** An object that can be used to access the current value of the class element at runtime. */
|
||||
readonly access: {
|
||||
/**
|
||||
* Determines whether an object has a property with the same name as the decorated element.
|
||||
*/
|
||||
has(object: This): boolean;
|
||||
/**
|
||||
* Invokes the setter on the provided object.
|
||||
*
|
||||
* @example
|
||||
* context.access.set(instance, value);
|
||||
*/
|
||||
set(object: This, value: Value): void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a callback to be invoked either before static initializers are run (when
|
||||
* decorating a `static` member), or before instance initializers are run (when
|
||||
* decorating a non-`static` member).
|
||||
* decorating a `static` element), or before instance initializers are run (when
|
||||
* decorating a non-`static` element).
|
||||
*/
|
||||
addInitializer(initializer: (this: This) => void): void;
|
||||
}
|
||||
@@ -205,42 +214,46 @@ interface ClassAccessorDecoratorContext<
|
||||
This = unknown,
|
||||
Value = unknown,
|
||||
> {
|
||||
/** The kind of class member that was decorated. */
|
||||
/** The kind of class element that was decorated. */
|
||||
readonly kind: "accessor";
|
||||
|
||||
/** The name of the decorated class member. */
|
||||
/** The name of the decorated class element. */
|
||||
readonly name: string | symbol;
|
||||
|
||||
/** A value indicating whether the class member is a static (`true`) or instance (`false`) member. */
|
||||
/** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */
|
||||
readonly static: boolean;
|
||||
|
||||
/** A value indicating whether the class member has a private name. */
|
||||
/** A value indicating whether the class element has a private name. */
|
||||
readonly private: boolean;
|
||||
|
||||
// NOTE: Disabled, pending the outcome of https://github.com/tc39/proposal-decorators/issues/494
|
||||
// /** An object that can be used to access the current value of the class member at runtime. */
|
||||
// readonly access: {
|
||||
// /**
|
||||
// * Invokes the getter on the provided receiver.
|
||||
// *
|
||||
// * @example
|
||||
// * let value = context.access.get.call(instance);
|
||||
// */
|
||||
// get(this: This): Value;
|
||||
/** An object that can be used to access the current value of the class element at runtime. */
|
||||
readonly access: {
|
||||
/**
|
||||
* Determines whether an object has a property with the same name as the decorated element.
|
||||
*/
|
||||
has(object: This): boolean;
|
||||
|
||||
// /**
|
||||
// * Invokes the setter on the provided receiver.
|
||||
// *
|
||||
// * @example
|
||||
// * context.access.set.call(instance, value);
|
||||
// */
|
||||
// set(this: This, value: Value): void;
|
||||
// };
|
||||
/**
|
||||
* Invokes the getter on the provided object.
|
||||
*
|
||||
* @example
|
||||
* let value = context.access.get(instance);
|
||||
*/
|
||||
get(object: This): Value;
|
||||
|
||||
/**
|
||||
* Invokes the setter on the provided object.
|
||||
*
|
||||
* @example
|
||||
* context.access.set(instance, value);
|
||||
*/
|
||||
set(object: This, value: Value): void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a callback to be invoked either before static initializers are run (when
|
||||
* decorating a `static` member), or before instance initializers are run (when
|
||||
* decorating a non-`static` member).
|
||||
* decorating a `static` element), or before instance initializers are run (when
|
||||
* decorating a non-`static` element).
|
||||
*/
|
||||
addInitializer(initializer: (this: This) => void): void;
|
||||
}
|
||||
@@ -302,36 +315,40 @@ interface ClassFieldDecoratorContext<
|
||||
This = unknown,
|
||||
Value = unknown,
|
||||
> {
|
||||
/** The kind of class member that was decorated. */
|
||||
/** The kind of class element that was decorated. */
|
||||
readonly kind: "field";
|
||||
|
||||
/** The name of the decorated class member. */
|
||||
/** The name of the decorated class element. */
|
||||
readonly name: string | symbol;
|
||||
|
||||
/** A value indicating whether the class member is a static (`true`) or instance (`false`) member. */
|
||||
/** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */
|
||||
readonly static: boolean;
|
||||
|
||||
/** A value indicating whether the class member has a private name. */
|
||||
/** A value indicating whether the class element has a private name. */
|
||||
readonly private: boolean;
|
||||
|
||||
// NOTE: Disabled, pending the outcome of https://github.com/tc39/proposal-decorators/issues/494
|
||||
// /** An object that can be used to access the current value of the class member at runtime. */
|
||||
// readonly access: {
|
||||
// /**
|
||||
// * Gets the value of the field on the provided receiver.
|
||||
// */
|
||||
// get(this: This): Value;
|
||||
/** An object that can be used to access the current value of the class element at runtime. */
|
||||
readonly access: {
|
||||
/**
|
||||
* Determines whether an object has a property with the same name as the decorated element.
|
||||
*/
|
||||
has(object: This): boolean;
|
||||
|
||||
// /**
|
||||
// * Sets the value of the field on the provided receiver.
|
||||
// */
|
||||
// set(this: This, value: Value): void;
|
||||
// };
|
||||
/**
|
||||
* Gets the value of the field on the provided object.
|
||||
*/
|
||||
get(object: This): Value;
|
||||
|
||||
/**
|
||||
* Sets the value of the field on the provided object.
|
||||
*/
|
||||
set(object: This, value: Value): void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a callback to be invoked either before static initializers are run (when
|
||||
* decorating a `static` member), or before instance initializers are run (when
|
||||
* decorating a non-`static` member).
|
||||
* decorating a `static` element), or before instance initializers are run (when
|
||||
* decorating a non-`static` element).
|
||||
*/
|
||||
addInitializer(initializer: (this: This) => void): void;
|
||||
}
|
||||
Vendored
+14
-10
@@ -56,7 +56,7 @@ interface SymbolConstructor {
|
||||
readonly toStringTag: unique symbol;
|
||||
|
||||
/**
|
||||
* An Object whose own property names are property names that are excluded from the 'with'
|
||||
* An Object whose truthy properties are properties that are excluded from the 'with'
|
||||
* environment bindings of the associated objects.
|
||||
*/
|
||||
readonly unscopables: unique symbol;
|
||||
@@ -73,17 +73,21 @@ interface Symbol {
|
||||
|
||||
interface Array<T> {
|
||||
/**
|
||||
* Returns an object whose properties have the value 'true'
|
||||
* Is an object whose properties have the value 'true'
|
||||
* when they will be absent when used in a 'with' statement.
|
||||
*/
|
||||
[Symbol.unscopables](): {
|
||||
copyWithin: boolean;
|
||||
entries: boolean;
|
||||
fill: boolean;
|
||||
find: boolean;
|
||||
findIndex: boolean;
|
||||
keys: boolean;
|
||||
values: boolean;
|
||||
readonly [Symbol.unscopables]: {
|
||||
[K in keyof any[]]?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
interface ReadonlyArray<T> {
|
||||
/**
|
||||
* Is an object whose properties have the value 'true'
|
||||
* when they will be absent when used in a 'with' statement.
|
||||
*/
|
||||
readonly [Symbol.unscopables]: {
|
||||
[K in keyof readonly any[]]?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as Harness from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
|
||||
interface FileInformation {
|
||||
contents?: string;
|
||||
|
||||
@@ -1,50 +1,3 @@
|
||||
import {
|
||||
ActionInvalidate,
|
||||
ActionSet,
|
||||
asNormalizedPath,
|
||||
AutoImportProviderProject,
|
||||
BeginEnablePluginResult,
|
||||
BeginInstallTypes,
|
||||
ConfiguredProject,
|
||||
countEachFileTypes,
|
||||
createPackageJsonCache,
|
||||
emptyArray,
|
||||
EndInstallTypes,
|
||||
Errors,
|
||||
ExternalProject,
|
||||
getBaseConfigFileName,
|
||||
hasNoTypeScriptSource,
|
||||
InferredProject,
|
||||
InvalidateCachedTypings,
|
||||
isConfiguredProject,
|
||||
isDynamicFileName,
|
||||
isInferredProject,
|
||||
isInferredProjectName,
|
||||
ITypingsInstaller,
|
||||
Logger,
|
||||
LogLevel,
|
||||
makeAutoImportProviderProjectName,
|
||||
makeAuxiliaryProjectName,
|
||||
makeInferredProjectName,
|
||||
Msg,
|
||||
NormalizedPath,
|
||||
normalizedPathToPath,
|
||||
nullTypingsInstaller,
|
||||
PackageInstalledResponse,
|
||||
PackageJsonCache,
|
||||
Project,
|
||||
ProjectFilesWithTSDiagnostics,
|
||||
ProjectKind,
|
||||
ProjectOptions,
|
||||
ScriptInfo,
|
||||
ScriptInfoVersion,
|
||||
ServerHost,
|
||||
Session,
|
||||
SetTypings,
|
||||
ThrottledOperations,
|
||||
toNormalizedPath,
|
||||
TypingsCache,
|
||||
} from "./_namespaces/ts.server";
|
||||
import {
|
||||
addToSeen,
|
||||
arrayFrom,
|
||||
@@ -177,6 +130,53 @@ import {
|
||||
WatchType,
|
||||
WildcardDirectoryWatcher,
|
||||
} from "./_namespaces/ts";
|
||||
import {
|
||||
ActionInvalidate,
|
||||
ActionSet,
|
||||
asNormalizedPath,
|
||||
AutoImportProviderProject,
|
||||
BeginEnablePluginResult,
|
||||
BeginInstallTypes,
|
||||
ConfiguredProject,
|
||||
countEachFileTypes,
|
||||
createPackageJsonCache,
|
||||
emptyArray,
|
||||
EndInstallTypes,
|
||||
Errors,
|
||||
ExternalProject,
|
||||
getBaseConfigFileName,
|
||||
hasNoTypeScriptSource,
|
||||
InferredProject,
|
||||
InvalidateCachedTypings,
|
||||
isConfiguredProject,
|
||||
isDynamicFileName,
|
||||
isInferredProject,
|
||||
isInferredProjectName,
|
||||
ITypingsInstaller,
|
||||
Logger,
|
||||
LogLevel,
|
||||
makeAutoImportProviderProjectName,
|
||||
makeAuxiliaryProjectName,
|
||||
makeInferredProjectName,
|
||||
Msg,
|
||||
NormalizedPath,
|
||||
normalizedPathToPath,
|
||||
nullTypingsInstaller,
|
||||
PackageInstalledResponse,
|
||||
PackageJsonCache,
|
||||
Project,
|
||||
ProjectFilesWithTSDiagnostics,
|
||||
ProjectKind,
|
||||
ProjectOptions,
|
||||
ScriptInfo,
|
||||
ScriptInfoVersion,
|
||||
ServerHost,
|
||||
Session,
|
||||
SetTypings,
|
||||
ThrottledOperations,
|
||||
toNormalizedPath,
|
||||
TypingsCache,
|
||||
} from "./_namespaces/ts.server";
|
||||
import * as protocol from "./protocol";
|
||||
|
||||
export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
|
||||
|
||||
+22
-22
@@ -1,26 +1,4 @@
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import {
|
||||
asNormalizedPath,
|
||||
createModuleSpecifierCache,
|
||||
emptyArray,
|
||||
Errors,
|
||||
FileStats,
|
||||
forEachResolvedProjectReferenceProject,
|
||||
LogLevel,
|
||||
ModuleImportResult,
|
||||
Msg,
|
||||
NormalizedPath,
|
||||
projectContainsInfoDirectly,
|
||||
ProjectOptions,
|
||||
ProjectReferenceProjectLoadKind,
|
||||
ProjectService,
|
||||
ScriptInfo,
|
||||
ServerHost,
|
||||
Session,
|
||||
toNormalizedPath,
|
||||
TypingsCache,
|
||||
updateProjectIfDirty,
|
||||
} from "./_namespaces/ts.server";
|
||||
import {
|
||||
addRange,
|
||||
append,
|
||||
@@ -147,6 +125,28 @@ import {
|
||||
WatchOptions,
|
||||
WatchType,
|
||||
} from "./_namespaces/ts";
|
||||
import {
|
||||
asNormalizedPath,
|
||||
createModuleSpecifierCache,
|
||||
emptyArray,
|
||||
Errors,
|
||||
FileStats,
|
||||
forEachResolvedProjectReferenceProject,
|
||||
LogLevel,
|
||||
ModuleImportResult,
|
||||
Msg,
|
||||
NormalizedPath,
|
||||
projectContainsInfoDirectly,
|
||||
ProjectOptions,
|
||||
ProjectReferenceProjectLoadKind,
|
||||
ProjectService,
|
||||
ScriptInfo,
|
||||
ServerHost,
|
||||
Session,
|
||||
toNormalizedPath,
|
||||
TypingsCache,
|
||||
updateProjectIfDirty,
|
||||
} from "./_namespaces/ts.server";
|
||||
import * as protocol from "./protocol";
|
||||
|
||||
export enum ProjectKind {
|
||||
|
||||
+16
-16
@@ -1,19 +1,3 @@
|
||||
import {
|
||||
AbsolutePositionAndLineText,
|
||||
ConfiguredProject,
|
||||
Errors,
|
||||
ExternalProject,
|
||||
InferredProject,
|
||||
isConfiguredProject,
|
||||
isExternalProject,
|
||||
isInferredProject,
|
||||
maxFileSize,
|
||||
NormalizedPath,
|
||||
Project,
|
||||
ProjectKind,
|
||||
ScriptVersionCache,
|
||||
ServerHost,
|
||||
} from "./_namespaces/ts.server";
|
||||
import {
|
||||
assign,
|
||||
clear,
|
||||
@@ -51,6 +35,22 @@ import {
|
||||
TextSpan,
|
||||
unorderedRemoveItem,
|
||||
} from "./_namespaces/ts";
|
||||
import {
|
||||
AbsolutePositionAndLineText,
|
||||
ConfiguredProject,
|
||||
Errors,
|
||||
ExternalProject,
|
||||
InferredProject,
|
||||
isConfiguredProject,
|
||||
isExternalProject,
|
||||
isInferredProject,
|
||||
maxFileSize,
|
||||
NormalizedPath,
|
||||
Project,
|
||||
ProjectKind,
|
||||
ScriptVersionCache,
|
||||
ServerHost,
|
||||
} from "./_namespaces/ts.server";
|
||||
import * as protocol from "./protocol";
|
||||
|
||||
export interface ScriptInfoVersion {
|
||||
|
||||
@@ -730,6 +730,12 @@ function getPerProjectReferences<TResult>(
|
||||
if (resultsMap.has(project)) continue;
|
||||
if (isLocationProjectReferenceRedirect(project, location)) continue;
|
||||
|
||||
// The project could be dirty and could no longer contain the location's file after it's updated,
|
||||
// so we need to update the project and check if it still contains the file.
|
||||
updateProjectIfDirty(project);
|
||||
if (!project.containsFile(toNormalizedPath(location.fileName))) {
|
||||
continue;
|
||||
}
|
||||
const projectResults = searchPosition(project, location);
|
||||
resultsMap.set(project, projectResults ?? emptyArray);
|
||||
searchedProjectKeys.add(getProjectKey(project));
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import {
|
||||
createCodeFixActionWithoutFixAll,
|
||||
registerCodeFix,
|
||||
} from "../_namespaces/ts.codefix";
|
||||
import {
|
||||
Diagnostics,
|
||||
factory,
|
||||
textChanges,
|
||||
} from "../_namespaces/ts";
|
||||
import {
|
||||
createCodeFixActionWithoutFixAll,
|
||||
registerCodeFix,
|
||||
} from "../_namespaces/ts.codefix";
|
||||
|
||||
registerCodeFix({
|
||||
errorCodes: [
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
import {
|
||||
createCodeFixActionWithoutFixAll,
|
||||
moduleSpecifierToValidIdentifier,
|
||||
registerCodeFix,
|
||||
} from "../_namespaces/ts.codefix";
|
||||
import {
|
||||
__String,
|
||||
arrayFrom,
|
||||
@@ -81,6 +76,11 @@ import {
|
||||
TypeChecker,
|
||||
VariableStatement,
|
||||
} from "../_namespaces/ts";
|
||||
import {
|
||||
createCodeFixActionWithoutFixAll,
|
||||
moduleSpecifierToValidIdentifier,
|
||||
registerCodeFix,
|
||||
} from "../_namespaces/ts.codefix";
|
||||
|
||||
registerCodeFix({
|
||||
errorCodes: [Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code],
|
||||
|
||||
@@ -694,7 +694,7 @@ function tryGetValueFromType(context: CodeFixContextBase, checker: TypeChecker,
|
||||
}
|
||||
if (isObjectLiteralType(type)) {
|
||||
const props = map(checker.getPropertiesOfType(type), prop => {
|
||||
const initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration), enclosingDeclaration) : createUndefined();
|
||||
const initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop), enclosingDeclaration);
|
||||
return factory.createPropertyAssignment(prop.name, initializer);
|
||||
});
|
||||
return factory.createObjectLiteralExpression(props, /*multiLine*/ true);
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
findAncestor,
|
||||
findLast,
|
||||
firstOrUndefined,
|
||||
getIsolatedModules,
|
||||
getResolvedModule,
|
||||
getTokenAtPosition,
|
||||
Identifier,
|
||||
@@ -173,7 +174,7 @@ function tryGetExportDeclaration(sourceFile: SourceFile, isTypeOnly: boolean) {
|
||||
|
||||
function updateExport(changes: textChanges.ChangeTracker, program: Program, sourceFile: SourceFile, node: ExportDeclaration, names: ExportName[]) {
|
||||
const namedExports = node.exportClause && isNamedExports(node.exportClause) ? node.exportClause.elements : factory.createNodeArray([]);
|
||||
const allowTypeModifier = !node.isTypeOnly && !!(program.getCompilerOptions().isolatedModules || find(namedExports, e => e.isTypeOnly));
|
||||
const allowTypeModifier = !node.isTypeOnly && !!(getIsolatedModules(program.getCompilerOptions()) || find(namedExports, e => e.isTypeOnly));
|
||||
changes.replaceNode(sourceFile, node,
|
||||
factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly,
|
||||
factory.createNamedExports(
|
||||
@@ -183,7 +184,7 @@ function updateExport(changes: textChanges.ChangeTracker, program: Program, sour
|
||||
function createExport(changes: textChanges.ChangeTracker, program: Program, sourceFile: SourceFile, names: ExportName[]) {
|
||||
changes.insertNodeAtEndOfScope(sourceFile, sourceFile,
|
||||
factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false,
|
||||
factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ !!program.getCompilerOptions().isolatedModules)), /*moduleSpecifier*/ undefined, /*assertClause*/ undefined));
|
||||
factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ getIsolatedModules(program.getCompilerOptions()))), /*moduleSpecifier*/ undefined, /*assertClause*/ undefined));
|
||||
}
|
||||
|
||||
function createExportSpecifiers(names: ExportName[], allowTypeModifier: boolean) {
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
import {
|
||||
createCodeFixActionWithoutFixAll,
|
||||
registerCodeFix,
|
||||
setJsonCompilerOptionValue,
|
||||
setJsonCompilerOptionValues,
|
||||
} from "../_namespaces/ts.codefix";
|
||||
import {
|
||||
CodeFixAction,
|
||||
Diagnostics,
|
||||
@@ -16,6 +10,12 @@ import {
|
||||
ScriptTarget,
|
||||
textChanges,
|
||||
} from "../_namespaces/ts";
|
||||
import {
|
||||
createCodeFixActionWithoutFixAll,
|
||||
registerCodeFix,
|
||||
setJsonCompilerOptionValue,
|
||||
setJsonCompilerOptionValues,
|
||||
} from "../_namespaces/ts.codefix";
|
||||
|
||||
registerCodeFix({
|
||||
errorCodes: [
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
isWriteAccess,
|
||||
ModifierFlags,
|
||||
ModifierLike,
|
||||
Mutable,
|
||||
Node,
|
||||
nodeOverlapsWithStartEnd,
|
||||
ObjectLiteralExpression,
|
||||
@@ -258,7 +259,14 @@ function updatePropertyDeclaration(changeTracker: textChanges.ChangeTracker, fil
|
||||
}
|
||||
|
||||
function updatePropertyAssignmentDeclaration(changeTracker: textChanges.ChangeTracker, file: SourceFile, declaration: PropertyAssignment, fieldName: AcceptedNameType) {
|
||||
const assignment = factory.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
|
||||
let assignment = factory.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
|
||||
// Remove grammar errors from assignment
|
||||
if (assignment.modifiers || assignment.questionToken || assignment.exclamationToken) {
|
||||
if (assignment === declaration) assignment = factory.cloneNode(assignment);
|
||||
(assignment as Mutable<PropertyAssignment>).modifiers = undefined;
|
||||
(assignment as Mutable<PropertyAssignment>).questionToken = undefined;
|
||||
(assignment as Mutable<PropertyAssignment>).exclamationToken = undefined;
|
||||
}
|
||||
changeTracker.replacePropertyAssignment(file, declaration, assignment);
|
||||
}
|
||||
|
||||
|
||||
@@ -751,7 +751,7 @@ function createMethodImplementingSignatures(
|
||||
function getReturnTypeFromSignatures(signatures: readonly Signature[], checker: TypeChecker, context: TypeConstructionContext, enclosingDeclaration: ClassLikeDeclaration): TypeNode | undefined {
|
||||
if (length(signatures)) {
|
||||
const type = checker.getUnionType(map(signatures, checker.getReturnTypeOfSignature));
|
||||
return checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context));
|
||||
return checker.typeToTypeNode(type, enclosingDeclaration, NodeBuilderFlags.NoTruncation, getNoopSymbolTrackerWithResolver(context));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ import {
|
||||
ImportEqualsDeclaration,
|
||||
importFromModuleSpecifier,
|
||||
ImportKind,
|
||||
importNameElisionDisabled,
|
||||
ImportsNotUsedAsValues,
|
||||
insertImports,
|
||||
InternalSymbolName,
|
||||
@@ -230,9 +231,9 @@ function createImportAdderWorker(sourceFile: SourceFile, program: Program, useAu
|
||||
const symbolName = getNameForExportedSymbol(exportedSymbol, getEmitScriptTarget(compilerOptions));
|
||||
const checker = program.getTypeChecker();
|
||||
const symbol = checker.getMergedSymbol(skipAlias(exportedSymbol, checker));
|
||||
const exportInfo = getAllExportInfoForSymbol(sourceFile, symbol, symbolName, /*isJsxTagName*/ false, program, host, preferences, cancellationToken);
|
||||
const exportInfo = getAllExportInfoForSymbol(sourceFile, symbol, symbolName, moduleSymbol, /*isJsxTagName*/ false, program, host, preferences, cancellationToken);
|
||||
const useRequire = shouldUseRequire(sourceFile, program);
|
||||
const fix = getImportFixForSymbol(sourceFile, Debug.checkDefined(exportInfo), moduleSymbol, program, /*position*/ undefined, !!isValidTypeOnlyUseSite, useRequire, host, preferences);
|
||||
const fix = getImportFixForSymbol(sourceFile, Debug.checkDefined(exportInfo), program, /*position*/ undefined, !!isValidTypeOnlyUseSite, useRequire, host, preferences);
|
||||
if (fix) {
|
||||
addImport({ fix, symbolName, errorIdentifierText: undefined });
|
||||
}
|
||||
@@ -371,7 +372,8 @@ function createImportAdderWorker(sourceFile: SourceFile, program: Program, useAu
|
||||
quotePreference,
|
||||
defaultImport,
|
||||
namedImports && arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ addAsTypeOnly, name })),
|
||||
namespaceLikeImport);
|
||||
namespaceLikeImport,
|
||||
compilerOptions);
|
||||
newDeclarations = combine(newDeclarations, declarations);
|
||||
});
|
||||
if (newDeclarations) {
|
||||
@@ -490,6 +492,7 @@ interface FixAddToExistingImportInfo {
|
||||
export function getImportCompletionAction(
|
||||
targetSymbol: Symbol,
|
||||
moduleSymbol: Symbol,
|
||||
exportMapKey: string | undefined,
|
||||
sourceFile: SourceFile,
|
||||
symbolName: string,
|
||||
isJsxTagName: boolean,
|
||||
@@ -501,15 +504,25 @@ export function getImportCompletionAction(
|
||||
cancellationToken: CancellationToken,
|
||||
): { readonly moduleSpecifier: string, readonly codeAction: CodeAction } {
|
||||
const compilerOptions = program.getCompilerOptions();
|
||||
let exportInfos;
|
||||
|
||||
const exportInfos = pathIsBareSpecifier(stripQuotes(moduleSymbol.name))
|
||||
? [getSingleExportInfoForSymbol(targetSymbol, moduleSymbol, program, host)]
|
||||
: getAllExportInfoForSymbol(sourceFile, targetSymbol, symbolName, isJsxTagName, program, host, preferences, cancellationToken);
|
||||
if (exportMapKey) {
|
||||
// The new way: `exportMapKey` should be in the `data` of each auto-import completion entry and
|
||||
// sent back when asking for details.
|
||||
exportInfos = getExportInfoMap(sourceFile, host, program, preferences, cancellationToken).get(sourceFile.path, exportMapKey);
|
||||
Debug.assertIsDefined(exportInfos, "Some exportInfo should match the specified exportMapKey");
|
||||
}
|
||||
else {
|
||||
// The old way, kept alive for super old editors that don't give us `data` back.
|
||||
exportInfos = pathIsBareSpecifier(stripQuotes(moduleSymbol.name))
|
||||
? [getSingleExportInfoForSymbol(targetSymbol, symbolName, moduleSymbol, program, host)]
|
||||
: getAllExportInfoForSymbol(sourceFile, targetSymbol, symbolName, moduleSymbol, isJsxTagName, program, host, preferences, cancellationToken);
|
||||
Debug.assertIsDefined(exportInfos, "Some exportInfo should match the specified symbol / moduleSymbol");
|
||||
}
|
||||
|
||||
Debug.assertIsDefined(exportInfos);
|
||||
const useRequire = shouldUseRequire(sourceFile, program);
|
||||
const isValidTypeOnlyUseSite = isValidTypeOnlyAliasUseSite(getTokenAtPosition(sourceFile, position));
|
||||
const fix = Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences));
|
||||
const fix = Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences));
|
||||
return {
|
||||
moduleSpecifier: fix.moduleSpecifier,
|
||||
codeAction: codeFixActionToCodeAction(codeActionForFix(
|
||||
@@ -532,8 +545,7 @@ export function getPromoteTypeOnlyCompletionAction(sourceFile: SourceFile, symbo
|
||||
return fix && codeFixActionToCodeAction(codeActionForFix({ host, formatContext, preferences }, sourceFile, symbolName, fix, includeSymbolNameInDescription, compilerOptions, preferences));
|
||||
}
|
||||
|
||||
function getImportFixForSymbol(sourceFile: SourceFile, exportInfos: readonly SymbolExportInfo[], moduleSymbol: Symbol, program: Program, position: number | undefined, isValidTypeOnlyUseSite: boolean, useRequire: boolean, host: LanguageServiceHost, preferences: UserPreferences) {
|
||||
Debug.assert(exportInfos.some(info => info.moduleSymbol === moduleSymbol || info.symbol.parent === moduleSymbol), "Some exportInfo should match the specified moduleSymbol");
|
||||
function getImportFixForSymbol(sourceFile: SourceFile, exportInfos: readonly SymbolExportInfo[], program: Program, position: number | undefined, isValidTypeOnlyUseSite: boolean, useRequire: boolean, host: LanguageServiceHost, preferences: UserPreferences) {
|
||||
const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host);
|
||||
return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host);
|
||||
}
|
||||
@@ -542,17 +554,17 @@ function codeFixActionToCodeAction({ description, changes, commands }: CodeFixAc
|
||||
return { description, changes, commands };
|
||||
}
|
||||
|
||||
function getAllExportInfoForSymbol(importingFile: SourceFile, symbol: Symbol, symbolName: string, preferCapitalized: boolean, program: Program, host: LanguageServiceHost, preferences: UserPreferences, cancellationToken: CancellationToken | undefined): readonly SymbolExportInfo[] | undefined {
|
||||
function getAllExportInfoForSymbol(importingFile: SourceFile, symbol: Symbol, symbolName: string, moduleSymbol: Symbol, preferCapitalized: boolean, program: Program, host: LanguageServiceHost, preferences: UserPreferences, cancellationToken: CancellationToken | undefined): readonly SymbolExportInfo[] | undefined {
|
||||
const getChecker = createGetChecker(program, host);
|
||||
return getExportInfoMap(importingFile, host, program, preferences, cancellationToken)
|
||||
.search(importingFile.path, preferCapitalized, name => name === symbolName, info => {
|
||||
if (skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson)) === symbol) {
|
||||
if (skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson)) === symbol && info.some(i => i.moduleSymbol === moduleSymbol || i.symbol.parent === moduleSymbol)) {
|
||||
return info;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getSingleExportInfoForSymbol(symbol: Symbol, moduleSymbol: Symbol, program: Program, host: LanguageServiceHost): SymbolExportInfo {
|
||||
function getSingleExportInfoForSymbol(symbol: Symbol, symbolName: string, moduleSymbol: Symbol, program: Program, host: LanguageServiceHost): SymbolExportInfo {
|
||||
const compilerOptions = program.getCompilerOptions();
|
||||
const mainProgramInfo = getInfoWithChecker(program.getTypeChecker(), /*isFromPackageJson*/ false);
|
||||
if (mainProgramInfo) {
|
||||
@@ -566,7 +578,7 @@ function getSingleExportInfoForSymbol(symbol: Symbol, moduleSymbol: Symbol, prog
|
||||
if (defaultInfo && skipAlias(defaultInfo.symbol, checker) === symbol) {
|
||||
return { symbol: defaultInfo.symbol, moduleSymbol, moduleFileName: undefined, exportKind: defaultInfo.exportKind, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson };
|
||||
}
|
||||
const named = checker.tryGetMemberInModuleExportsAndProperties(symbol.name, moduleSymbol);
|
||||
const named = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol);
|
||||
if (named && skipAlias(named, checker) === symbol) {
|
||||
return { symbol: named, moduleSymbol, moduleFileName: undefined, exportKind: ExportKind.Named, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson };
|
||||
}
|
||||
@@ -666,7 +678,7 @@ function getAddAsTypeOnly(
|
||||
// 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 || compilerOptions.verbatimModuleSyntax) &&
|
||||
if (importNameElisionDisabled(compilerOptions) &&
|
||||
(!(targetFlags & SymbolFlags.Value) || !!checker.getTypeOnlyAliasDeclaration(symbol))
|
||||
) {
|
||||
// A type-only import is required for this symbol if under these settings if the symbol will
|
||||
@@ -1238,7 +1250,13 @@ function codeActionForFixWorker(changes: textChanges.ChangeTracker, sourceFile:
|
||||
const namespaceLikeImport = importKind === ImportKind.Namespace || importKind === ImportKind.CommonJS
|
||||
? { importKind, name: qualification?.namespacePrefix || symbolName, addAsTypeOnly }
|
||||
: undefined;
|
||||
insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport), /*blankLineBetween*/ true, preferences);
|
||||
insertImports(changes, sourceFile, getDeclarations(
|
||||
moduleSpecifier,
|
||||
quotePreference,
|
||||
defaultImport,
|
||||
namedImports,
|
||||
namespaceLikeImport,
|
||||
compilerOptions), /*blankLineBetween*/ true, preferences);
|
||||
if (qualification) {
|
||||
addNamespaceQualifier(changes, sourceFile, qualification);
|
||||
}
|
||||
@@ -1266,7 +1284,7 @@ function getModuleSpecifierText(promotedDeclaration: ImportClause | ImportEquals
|
||||
|
||||
function promoteFromTypeOnly(changes: textChanges.ChangeTracker, aliasDeclaration: TypeOnlyAliasDeclaration, compilerOptions: CompilerOptions, sourceFile: SourceFile, preferences: UserPreferences) {
|
||||
// See comment in `doAddExistingFix` on constant with the same name.
|
||||
const convertExistingToTypeOnly = compilerOptions.preserveValueImports && compilerOptions.isolatedModules || compilerOptions.verbatimModuleSyntax;
|
||||
const convertExistingToTypeOnly = importNameElisionDisabled(compilerOptions);
|
||||
switch (aliasDeclaration.kind) {
|
||||
case SyntaxKind.ImportSpecifier:
|
||||
if (aliasDeclaration.isTypeOnly) {
|
||||
@@ -1352,8 +1370,7 @@ function doAddExistingFix(
|
||||
// never used in an emitting position). These are allowed to be imported without being type-only,
|
||||
// but the user has clearly already signified that they don't need them to be present at runtime
|
||||
// by placing them in a type-only import. So, just mark each specifier as type-only.
|
||||
const convertExistingToTypeOnly = promoteFromTypeOnly
|
||||
&& (compilerOptions.preserveValueImports && compilerOptions.isolatedModules || compilerOptions.verbatimModuleSyntax);
|
||||
const convertExistingToTypeOnly = promoteFromTypeOnly && importNameElisionDisabled(compilerOptions);
|
||||
|
||||
if (defaultImport) {
|
||||
Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one");
|
||||
@@ -1479,12 +1496,18 @@ function getNewImports(
|
||||
quotePreference: QuotePreference,
|
||||
defaultImport: Import | undefined,
|
||||
namedImports: readonly Import[] | undefined,
|
||||
namespaceLikeImport: Import & { importKind: ImportKind.CommonJS | ImportKind.Namespace } | undefined
|
||||
namespaceLikeImport: Import & { importKind: ImportKind.CommonJS | ImportKind.Namespace } | undefined,
|
||||
compilerOptions: CompilerOptions,
|
||||
): AnyImportSyntax | readonly AnyImportSyntax[] {
|
||||
const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference);
|
||||
let statements: AnyImportSyntax | readonly AnyImportSyntax[] | undefined;
|
||||
if (defaultImport !== undefined || namedImports?.length) {
|
||||
const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly);
|
||||
// `verbatimModuleSyntax` should prefer top-level `import type` -
|
||||
// even though it's not an error, it would add unnecessary runtime emit.
|
||||
const topLevelTypeOnly = (!defaultImport || needsTypeOnly(defaultImport)) && every(namedImports, needsTypeOnly) ||
|
||||
compilerOptions.verbatimModuleSyntax &&
|
||||
defaultImport?.addAsTypeOnly !== AddAsTypeOnly.NotAllowed &&
|
||||
!some(namedImports, i => i.addAsTypeOnly === AddAsTypeOnly.NotAllowed);
|
||||
statements = combine(statements, makeImport(
|
||||
defaultImport && factory.createIdentifier(defaultImport.name),
|
||||
namedImports?.map(({ addAsTypeOnly, name }) => factory.createImportSpecifier(
|
||||
|
||||
@@ -64,8 +64,8 @@ import {
|
||||
mapEntries,
|
||||
NewExpression,
|
||||
Node,
|
||||
nodeSeenTracker,
|
||||
NodeSeenTracker,
|
||||
nodeSeenTracker,
|
||||
ObjectFlags,
|
||||
ParameterDeclaration,
|
||||
PrefixUnaryExpression,
|
||||
|
||||
+67
-108
@@ -7,7 +7,6 @@ import {
|
||||
CancellationToken,
|
||||
canUsePropertyAccess,
|
||||
CaseBlock,
|
||||
CaseClause,
|
||||
cast,
|
||||
CharacterCodes,
|
||||
ClassElement,
|
||||
@@ -37,19 +36,16 @@ import {
|
||||
createPackageJsonImportFilter,
|
||||
createPrinter,
|
||||
createSortedArray,
|
||||
createTextRangeFromSpan,
|
||||
createTextSpanFromBounds,
|
||||
createTextSpanFromNode,
|
||||
createTextSpanFromRange,
|
||||
Debug,
|
||||
Declaration,
|
||||
DefaultClause,
|
||||
Diagnostics,
|
||||
diagnosticToString,
|
||||
displayPart,
|
||||
EmitHint,
|
||||
EmitTextWriter,
|
||||
endsWith,
|
||||
EntityName,
|
||||
EnumMember,
|
||||
escapeSnippetText,
|
||||
@@ -66,6 +62,7 @@ import {
|
||||
first,
|
||||
firstDefined,
|
||||
flatMap,
|
||||
forEach,
|
||||
formatting,
|
||||
FunctionLikeDeclaration,
|
||||
getAllSuperTypeNodes,
|
||||
@@ -121,6 +118,7 @@ import {
|
||||
isAbstractConstructorSymbol,
|
||||
isArrowFunction,
|
||||
isAssertionExpression,
|
||||
isAwaitExpression,
|
||||
isBigIntLiteral,
|
||||
isBinaryExpression,
|
||||
isBindingElement,
|
||||
@@ -140,7 +138,6 @@ import {
|
||||
isConstructorDeclaration,
|
||||
isContextualKeyword,
|
||||
isDeclarationName,
|
||||
isDefaultClause,
|
||||
isDeprecatedDeclaration,
|
||||
isEntityName,
|
||||
isEnumMember,
|
||||
@@ -185,7 +182,6 @@ import {
|
||||
isKeyword,
|
||||
isKnownSymbol,
|
||||
isLabeledStatement,
|
||||
isLiteralExpression,
|
||||
isLiteralImportTypeNode,
|
||||
isMemberName,
|
||||
isMethodDeclaration,
|
||||
@@ -218,6 +214,7 @@ import {
|
||||
isStatement,
|
||||
isStatic,
|
||||
isString,
|
||||
isStringAndEmptyAnonymousObjectIntersection,
|
||||
isStringANonContextualKeyword,
|
||||
isStringLiteralLike,
|
||||
isStringLiteralOrTemplate,
|
||||
@@ -275,6 +272,7 @@ import {
|
||||
ModuleReference,
|
||||
moduleResolutionSupportsPackageJsonExportsAndImports,
|
||||
NamedImportBindings,
|
||||
newCaseClauseTracker,
|
||||
Node,
|
||||
NodeArray,
|
||||
NodeBuilderFlags,
|
||||
@@ -287,7 +285,6 @@ import {
|
||||
ObjectTypeDeclaration,
|
||||
or,
|
||||
ParenthesizedTypeNode,
|
||||
parseBigInt,
|
||||
positionBelongsToNode,
|
||||
positionIsASICandidate,
|
||||
positionsAreOnSameLine,
|
||||
@@ -350,7 +347,6 @@ import {
|
||||
TypeChecker,
|
||||
TypeElement,
|
||||
TypeFlags,
|
||||
typeHasCallOrConstructSignatures,
|
||||
TypeLiteralNode,
|
||||
TypeNode,
|
||||
TypeOnlyImportDeclaration,
|
||||
@@ -431,15 +427,16 @@ export enum CompletionSource {
|
||||
|
||||
/** @internal */
|
||||
export const enum SymbolOriginInfoKind {
|
||||
ThisType = 1 << 0,
|
||||
SymbolMember = 1 << 1,
|
||||
Export = 1 << 2,
|
||||
Promise = 1 << 3,
|
||||
Nullable = 1 << 4,
|
||||
ResolvedExport = 1 << 5,
|
||||
TypeOnlyAlias = 1 << 6,
|
||||
ObjectLiteralMethod = 1 << 7,
|
||||
Ignore = 1 << 8,
|
||||
ThisType = 1 << 0,
|
||||
SymbolMember = 1 << 1,
|
||||
Export = 1 << 2,
|
||||
Promise = 1 << 3,
|
||||
Nullable = 1 << 4,
|
||||
ResolvedExport = 1 << 5,
|
||||
TypeOnlyAlias = 1 << 6,
|
||||
ObjectLiteralMethod = 1 << 7,
|
||||
Ignore = 1 << 8,
|
||||
ComputedPropertyName = 1 << 9,
|
||||
|
||||
SymbolMemberNoExport = SymbolMember,
|
||||
SymbolMemberExport = SymbolMember | Export,
|
||||
@@ -465,6 +462,7 @@ interface SymbolOriginInfoResolvedExport extends SymbolOriginInfo {
|
||||
symbolName: string;
|
||||
moduleSymbol: Symbol;
|
||||
exportName: string;
|
||||
exportMapKey?: string;
|
||||
moduleSpecifier: string;
|
||||
}
|
||||
|
||||
@@ -478,6 +476,10 @@ interface SymbolOriginInfoObjectLiteralMethod extends SymbolOriginInfo {
|
||||
isSnippet?: true,
|
||||
}
|
||||
|
||||
interface SymbolOriginInfoComputedPropertyName extends SymbolOriginInfo {
|
||||
symbolName: string;
|
||||
}
|
||||
|
||||
function originIsThisType(origin: SymbolOriginInfo): boolean {
|
||||
return !!(origin.kind & SymbolOriginInfoKind.ThisType);
|
||||
}
|
||||
@@ -494,8 +496,8 @@ function originIsResolvedExport(origin: SymbolOriginInfo | undefined): origin is
|
||||
return !!(origin && origin.kind === SymbolOriginInfoKind.ResolvedExport);
|
||||
}
|
||||
|
||||
function originIncludesSymbolName(origin: SymbolOriginInfo | undefined): origin is SymbolOriginInfoExport | SymbolOriginInfoResolvedExport {
|
||||
return originIsExport(origin) || originIsResolvedExport(origin);
|
||||
function originIncludesSymbolName(origin: SymbolOriginInfo | undefined): origin is SymbolOriginInfoExport | SymbolOriginInfoResolvedExport | SymbolOriginInfoComputedPropertyName {
|
||||
return originIsExport(origin) || originIsResolvedExport(origin) || originIsComputedPropertyName(origin);
|
||||
}
|
||||
|
||||
function originIsPackageJsonImport(origin: SymbolOriginInfo | undefined): origin is SymbolOriginInfoExport {
|
||||
@@ -522,6 +524,10 @@ function originIsIgnore(origin: SymbolOriginInfo | undefined): boolean {
|
||||
return !!(origin && origin.kind & SymbolOriginInfoKind.Ignore);
|
||||
}
|
||||
|
||||
function originIsComputedPropertyName(origin: SymbolOriginInfo | undefined): origin is SymbolOriginInfoComputedPropertyName {
|
||||
return !!(origin && origin.kind & SymbolOriginInfoKind.ComputedPropertyName);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export interface UniqueNameSet {
|
||||
add(name: string): void;
|
||||
@@ -646,6 +652,7 @@ export function getCompletionsAtPosition(
|
||||
completionKind: CompletionTriggerKind | undefined,
|
||||
cancellationToken: CancellationToken,
|
||||
formatContext?: formatting.FormatContext,
|
||||
includeSymbol = false
|
||||
): CompletionInfo | undefined {
|
||||
const { previousToken } = getRelevantTokens(position, sourceFile);
|
||||
if (triggerCharacter && !isInString(sourceFile, position, previousToken) && !isValidTrigger(sourceFile, triggerCharacter, previousToken, position)) {
|
||||
@@ -675,7 +682,7 @@ export function getCompletionsAtPosition(
|
||||
incompleteCompletionsCache?.clear();
|
||||
}
|
||||
|
||||
const stringCompletions = StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences);
|
||||
const stringCompletions = StringCompletions.getStringLiteralCompletions(sourceFile, position, previousToken, compilerOptions, host, program, log, preferences, includeSymbol);
|
||||
if (stringCompletions) {
|
||||
return stringCompletions;
|
||||
}
|
||||
@@ -692,7 +699,7 @@ export function getCompletionsAtPosition(
|
||||
|
||||
switch (completionData.kind) {
|
||||
case CompletionDataKind.Data:
|
||||
const response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position);
|
||||
const response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position, includeSymbol);
|
||||
if (response?.isIncomplete) {
|
||||
incompleteCompletionsCache?.set(response);
|
||||
}
|
||||
@@ -866,7 +873,8 @@ function completionInfoFromData(
|
||||
completionData: CompletionData,
|
||||
preferences: UserPreferences,
|
||||
formatContext: formatting.FormatContext | undefined,
|
||||
position: number
|
||||
position: number,
|
||||
includeSymbol: boolean | undefined,
|
||||
): CompletionInfo | undefined {
|
||||
const {
|
||||
symbols,
|
||||
@@ -951,6 +959,7 @@ function completionInfoFromData(
|
||||
symbolToSortTextMap,
|
||||
isJsxIdentifierExpected,
|
||||
isRightOfOpenTag,
|
||||
includeSymbol
|
||||
);
|
||||
|
||||
if (keywordFilters !== KeywordCompletionFilters.None) {
|
||||
@@ -1104,75 +1113,6 @@ function getExhaustiveCaseSnippets(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
interface CaseClauseTracker {
|
||||
addValue(value: string | number): void;
|
||||
hasValue(value: string | number | PseudoBigInt): boolean;
|
||||
}
|
||||
|
||||
function newCaseClauseTracker(checker: TypeChecker, clauses: readonly (CaseClause | DefaultClause)[]): CaseClauseTracker {
|
||||
const existingStrings = new Set<string>();
|
||||
const existingNumbers = new Set<number>();
|
||||
const existingBigInts = new Set<string>();
|
||||
|
||||
for (const clause of clauses) {
|
||||
if (!isDefaultClause(clause)) {
|
||||
if (isLiteralExpression(clause.expression)) {
|
||||
const expression = clause.expression;
|
||||
switch (expression.kind) {
|
||||
case SyntaxKind.NoSubstitutionTemplateLiteral:
|
||||
case SyntaxKind.StringLiteral:
|
||||
existingStrings.add(expression.text);
|
||||
break;
|
||||
case SyntaxKind.NumericLiteral:
|
||||
existingNumbers.add(parseInt(expression.text));
|
||||
break;
|
||||
case SyntaxKind.BigIntLiteral:
|
||||
const parsedBigInt = parseBigInt(endsWith(expression.text, "n") ? expression.text.slice(0, -1) : expression.text);
|
||||
if (parsedBigInt) {
|
||||
existingBigInts.add(pseudoBigIntToString(parsedBigInt));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
else {
|
||||
const symbol = checker.getSymbolAtLocation(clause.expression);
|
||||
if (symbol && symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) {
|
||||
const enumValue = checker.getConstantValue(symbol.valueDeclaration);
|
||||
if (enumValue !== undefined) {
|
||||
addValue(enumValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
addValue,
|
||||
hasValue,
|
||||
};
|
||||
|
||||
function addValue(value: string | number) {
|
||||
switch (typeof value) {
|
||||
case "string":
|
||||
existingStrings.add(value);
|
||||
break;
|
||||
case "number":
|
||||
existingNumbers.add(value);
|
||||
}
|
||||
}
|
||||
|
||||
function hasValue(value: string | number | PseudoBigInt): boolean {
|
||||
switch (typeof value) {
|
||||
case "string":
|
||||
return existingStrings.has(value);
|
||||
case "number":
|
||||
return existingNumbers.has(value);
|
||||
case "object":
|
||||
return existingBigInts.has(pseudoBigIntToString(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function typeNodeToExpression(typeNode: TypeNode, languageVersion: ScriptTarget, quotePreference: QuotePreference): Expression | undefined {
|
||||
switch (typeNode.kind) {
|
||||
case SyntaxKind.TypeReference:
|
||||
@@ -1339,6 +1279,7 @@ function createCompletionEntry(
|
||||
formatContext: formatting.FormatContext | undefined,
|
||||
isJsxIdentifierExpected: boolean | undefined,
|
||||
isRightOfOpenTag: boolean | undefined,
|
||||
includeSymbol: boolean
|
||||
): CompletionEntry | undefined {
|
||||
let insertText: string | undefined;
|
||||
let replacementSpan = getReplacementSpanForContextToken(replacementToken);
|
||||
@@ -1392,7 +1333,9 @@ function createCompletionEntry(
|
||||
|
||||
awaitText += `(await ${propertyAccessToConvert.expression.getText()})`;
|
||||
insertText = needsConvertPropertyAccess ? `${awaitText}${insertText}` : `${awaitText}${insertQuestionDot ? "?." : "."}${insertText}`;
|
||||
replacementSpan = createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end);
|
||||
const isInAwaitExpression = tryCast(propertyAccessToConvert.parent, isAwaitExpression);
|
||||
const wrapNode = isInAwaitExpression ? propertyAccessToConvert.parent : propertyAccessToConvert.expression;
|
||||
replacementSpan = createTextSpanFromBounds(wrapNode.getStart(sourceFile), propertyAccessToConvert.end);
|
||||
}
|
||||
|
||||
if (originIsResolvedExport(origin)) {
|
||||
@@ -1442,7 +1385,7 @@ function createCompletionEntry(
|
||||
&& !(type.flags & TypeFlags.BooleanLike)
|
||||
&& !(type.flags & TypeFlags.Union && find((type as UnionType).types, type => !!(type.flags & TypeFlags.BooleanLike)))
|
||||
) {
|
||||
if (type.flags & TypeFlags.StringLike || (type.flags & TypeFlags.Union && every((type as UnionType).types, type => !!(type.flags & (TypeFlags.StringLike | TypeFlags.Undefined))))) {
|
||||
if (type.flags & TypeFlags.StringLike || (type.flags & TypeFlags.Union && every((type as UnionType).types, type => !!(type.flags & (TypeFlags.StringLike | TypeFlags.Undefined) || isStringAndEmptyAnonymousObjectIntersection(type))))) {
|
||||
// If is string like or undefined use quotes
|
||||
insertText = `${escapeSnippetText(name)}=${quote(sourceFile, preferences, "$1")}`;
|
||||
isSnippet = true;
|
||||
@@ -1492,6 +1435,7 @@ function createCompletionEntry(
|
||||
isPackageJsonImport: originIsPackageJsonImport(origin) || undefined,
|
||||
isImportStatementCompletion: !!importStatementCompletion || undefined,
|
||||
data,
|
||||
...includeSymbol ? { symbol } : undefined
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1617,10 +1561,9 @@ function getEntryForMemberCompletion(
|
||||
requiredModifiers |= ModifierFlags.Abstract;
|
||||
}
|
||||
if (isClassElement(node)
|
||||
&& checker.getMemberOverrideModifierStatus(classLikeDeclaration, node) === MemberOverrideStatus.NeedsOverride) {
|
||||
&& checker.getMemberOverrideModifierStatus(classLikeDeclaration, node, symbol) === MemberOverrideStatus.NeedsOverride) {
|
||||
requiredModifiers |= ModifierFlags.Override;
|
||||
}
|
||||
|
||||
if (!completionNodes.length) {
|
||||
// Keep track of added missing required modifiers and modifiers already present.
|
||||
// This is needed when we have overloaded signatures,
|
||||
@@ -1997,6 +1940,7 @@ function originToCompletionEntryData(origin: SymbolOriginInfoExport | SymbolOrig
|
||||
if (originIsResolvedExport(origin)) {
|
||||
const resolvedData: CompletionEntryDataResolved = {
|
||||
exportName: origin.exportName,
|
||||
exportMapKey: origin.exportMapKey,
|
||||
moduleSpecifier: origin.moduleSpecifier,
|
||||
ambientModuleName,
|
||||
fileName: origin.fileName,
|
||||
@@ -2021,6 +1965,7 @@ function completionEntryDataToSymbolOriginInfo(data: CompletionEntryData, comple
|
||||
const resolvedOrigin: SymbolOriginInfoResolvedExport = {
|
||||
kind: SymbolOriginInfoKind.ResolvedExport,
|
||||
exportName: data.exportName,
|
||||
exportMapKey: data.exportMapKey,
|
||||
moduleSpecifier: data.moduleSpecifier,
|
||||
symbolName: completionName,
|
||||
fileName: data.fileName,
|
||||
@@ -2045,7 +1990,7 @@ function completionEntryDataToSymbolOriginInfo(data: CompletionEntryData, comple
|
||||
|
||||
function getInsertTextAndReplacementSpanForImportCompletion(name: string, importStatementCompletion: ImportStatementCompletionInfo, origin: SymbolOriginInfoResolvedExport, useSemicolons: boolean, sourceFile: SourceFile, options: CompilerOptions, preferences: UserPreferences) {
|
||||
const replacementSpan = importStatementCompletion.replacementSpan;
|
||||
const quotedModuleSpecifier = quote(sourceFile, preferences, origin.moduleSpecifier);
|
||||
const quotedModuleSpecifier = quote(sourceFile, preferences, escapeSnippetText(origin.moduleSpecifier));
|
||||
const exportKind =
|
||||
origin.isDefaultExport ? ExportKind.Default :
|
||||
origin.exportName === InternalSymbolName.ExportEquals ? ExportKind.ExportEquals :
|
||||
@@ -2119,6 +2064,7 @@ export function getCompletionEntriesFromSymbols(
|
||||
symbolToSortTextMap?: SymbolSortTextMap,
|
||||
isJsxIdentifierExpected?: boolean,
|
||||
isRightOfOpenTag?: boolean,
|
||||
includeSymbol = false
|
||||
): UniqueNameSet {
|
||||
const start = timestamp();
|
||||
const variableDeclaration = getVariableDeclaration(location);
|
||||
@@ -2164,6 +2110,7 @@ export function getCompletionEntriesFromSymbols(
|
||||
formatContext,
|
||||
isJsxIdentifierExpected,
|
||||
isRightOfOpenTag,
|
||||
includeSymbol
|
||||
);
|
||||
if (!entry) {
|
||||
continue;
|
||||
@@ -2383,7 +2330,8 @@ export function getCompletionEntryDetails(
|
||||
case "symbol": {
|
||||
const { symbol, location, contextToken, origin, previousToken } = symbolCompletion;
|
||||
const { codeActions, sourceDisplay } = getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source, cancellationToken);
|
||||
return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217
|
||||
const symbolName = originIsComputedPropertyName(origin) ? origin.symbolName : symbol.name;
|
||||
return createCompletionDetailsForSymbol(symbol, symbolName, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217
|
||||
}
|
||||
case "literal": {
|
||||
const { literal } = symbolCompletion;
|
||||
@@ -2435,12 +2383,12 @@ function createSimpleDetails(name: string, kind: ScriptElementKind, kind2: Symbo
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function createCompletionDetailsForSymbol(symbol: Symbol, checker: TypeChecker, sourceFile: SourceFile, location: Node, cancellationToken: CancellationToken, codeActions?: CodeAction[], sourceDisplay?: SymbolDisplayPart[]): CompletionEntryDetails {
|
||||
export function createCompletionDetailsForSymbol(symbol: Symbol, name: string, checker: TypeChecker, sourceFile: SourceFile, location: Node, cancellationToken: CancellationToken, codeActions?: CodeAction[], sourceDisplay?: SymbolDisplayPart[]): CompletionEntryDetails {
|
||||
const { displayParts, documentation, symbolKind, tags } =
|
||||
checker.runWithCancellationToken(cancellationToken, checker =>
|
||||
SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, SemanticMeaning.All)
|
||||
);
|
||||
return createCompletionDetails(symbol.name, SymbolDisplay.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay);
|
||||
return createCompletionDetails(name, SymbolDisplay.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
@@ -2527,6 +2475,7 @@ function getCompletionEntryCodeActionsAndSourceDisplay(
|
||||
const { moduleSpecifier, codeAction } = codefix.getImportCompletionAction(
|
||||
targetSymbol,
|
||||
moduleSymbol,
|
||||
data?.exportMapKey,
|
||||
sourceFile,
|
||||
name,
|
||||
isJsxOpeningTagName,
|
||||
@@ -2898,7 +2847,8 @@ function getCompletionData(
|
||||
// First case is for `<div foo={true} [||] />` or `<div foo={true} [||] ></div>`,
|
||||
// `parent` will be `{true}` and `previousToken` will be `}`
|
||||
// Second case is for `<div foo={true} t[||] ></div>`
|
||||
if (previousToken.kind === SyntaxKind.CloseBraceToken || (previousToken.kind === SyntaxKind.Identifier || previousToken.parent.kind === SyntaxKind.JsxAttribute)) {
|
||||
// Second case must not match for `<div foo={undefine[||]}></div>`
|
||||
if (previousToken.kind === SyntaxKind.CloseBraceToken || (previousToken.kind === SyntaxKind.Identifier && previousToken.parent.kind === SyntaxKind.JsxAttribute)) {
|
||||
isJsxIdentifierExpected = true;
|
||||
}
|
||||
break;
|
||||
@@ -3511,8 +3461,8 @@ function getCompletionData(
|
||||
// module resolution modes, getting past this point guarantees that we'll be
|
||||
// able to generate a suitable module specifier, so we can safely show a completion,
|
||||
// even if we defer computing the module specifier.
|
||||
const firstImportableExportInfo = find(info, isImportableExportInfo);
|
||||
if (!firstImportableExportInfo) {
|
||||
info = filter(info, isImportableExportInfo);
|
||||
if (!info.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3529,9 +3479,9 @@ function getCompletionData(
|
||||
// it should be identical regardless of which one is used. During the subsequent
|
||||
// `CompletionEntryDetails` request, we'll get all the ExportInfos again and pick
|
||||
// the best one based on the module specifier it produces.
|
||||
let exportInfo = firstImportableExportInfo, moduleSpecifier;
|
||||
let exportInfo = info[0], moduleSpecifier;
|
||||
if (result !== "skipped") {
|
||||
({ exportInfo = firstImportableExportInfo, moduleSpecifier } = result);
|
||||
({ exportInfo = info[0], moduleSpecifier } = result);
|
||||
}
|
||||
|
||||
const isDefaultExport = exportInfo.exportKind === ExportKind.Default;
|
||||
@@ -3769,7 +3719,7 @@ function getCompletionData(
|
||||
// 2. at the end position of an unterminated token.
|
||||
// 3. at the end of a regular expression (due to trailing flags like '/foo/g').
|
||||
return (isRegularExpressionLiteral(contextToken) || isStringTextContainingNode(contextToken)) && (
|
||||
rangeContainsPositionExclusive(createTextRangeFromSpan(createTextSpanFromNode(contextToken)), position) ||
|
||||
rangeContainsPositionExclusive(contextToken, position) ||
|
||||
position === contextToken.end && (!!contextToken.isUnterminated || isRegularExpressionLiteral(contextToken)));
|
||||
}
|
||||
|
||||
@@ -4022,8 +3972,17 @@ function getCompletionData(
|
||||
type && typeChecker.getPropertiesOfType(type);
|
||||
});
|
||||
symbols = concatenate(symbols, filterClassMembersList(baseSymbols, decl.members, classElementModifierFlags));
|
||||
forEach(symbols, (symbol, index) => {
|
||||
const declaration = symbol?.valueDeclaration;
|
||||
if (declaration && isClassElement(declaration) && declaration.name && isComputedPropertyName(declaration.name)) {
|
||||
const origin: SymbolOriginInfoComputedPropertyName = {
|
||||
kind: SymbolOriginInfoKind.ComputedPropertyName,
|
||||
symbolName: typeChecker.symbolToString(symbol),
|
||||
};
|
||||
symbolToOriginInfoMap[index] = origin;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return GlobalsSearch.Success;
|
||||
}
|
||||
|
||||
@@ -4604,7 +4563,7 @@ function getCompletionEntryDisplayNameForSymbol(
|
||||
}
|
||||
switch (kind) {
|
||||
case CompletionKind.MemberLike:
|
||||
return undefined;
|
||||
return originIsComputedPropertyName(origin) ? { name: origin.symbolName, needsConvertPropertyAccess: false } : undefined;
|
||||
case CompletionKind.ObjectPropertyDeclaration:
|
||||
// TODO: GH#18169
|
||||
return { name: JSON.stringify(name), needsConvertPropertyAccess: false };
|
||||
@@ -4814,7 +4773,7 @@ function getApparentProperties(type: Type, node: ObjectLiteralExpression | JsxAt
|
||||
!(memberType.flags & TypeFlags.Primitive
|
||||
|| checker.isArrayLikeType(memberType)
|
||||
|| checker.isTypeInvalidDueToUnionDiscriminant(memberType, node)
|
||||
|| typeHasCallOrConstructSignatures(memberType, checker)
|
||||
|| checker.typeHasCallOrConstructSignatures(memberType)
|
||||
|| memberType.isClass() && containsNonPublicProperties(memberType.getApparentProperties()))));
|
||||
}
|
||||
|
||||
|
||||
@@ -422,7 +422,16 @@ export function forEachExternalModuleToImportFrom(
|
||||
const autoImportProvider = useAutoImportProvider && host.getPackageJsonAutoImportProvider?.();
|
||||
if (autoImportProvider) {
|
||||
const start = timestamp();
|
||||
forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, (module, file) => cb(module, file, autoImportProvider, /*isFromPackageJson*/ true));
|
||||
const checker = program.getTypeChecker();
|
||||
forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, (module, file) => {
|
||||
if (file && !program.getSourceFile(file.fileName) || !file && !checker.resolveName(module.name, /*location*/ undefined, SymbolFlags.Module, /*excludeGlobals*/ false)) {
|
||||
// The AutoImportProvider filters files already in the main program out of its *root* files,
|
||||
// but non-root files can still be present in both programs, and already in the export info map
|
||||
// at this point. This doesn't create any incorrect behavior, but is a waste of time and memory,
|
||||
// so we filter them out here.
|
||||
cb(module, file, autoImportProvider, /*isFromPackageJson*/ true);
|
||||
}
|
||||
});
|
||||
host.log?.(`forEachExternalModuleToImportFrom autoImportProvider: ${timestamp() - start}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
InterfaceDeclaration,
|
||||
isComment,
|
||||
isDecorator,
|
||||
isGrammarError,
|
||||
isJSDoc,
|
||||
isLineBreak,
|
||||
isModifier,
|
||||
@@ -803,7 +804,7 @@ function formatSpanWorker(
|
||||
isFirstListItem?: boolean): number {
|
||||
Debug.assert(!nodeIsSynthesized(child));
|
||||
|
||||
if (nodeIsMissing(child)) {
|
||||
if (nodeIsMissing(child) || isGrammarError(parent, child)) {
|
||||
return inheritedIndentation;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { TextRangeWithKind } from "../_namespaces/ts.formatting";
|
||||
import {
|
||||
Debug,
|
||||
findChildOfKind,
|
||||
@@ -7,6 +6,7 @@ import {
|
||||
SourceFileLike,
|
||||
SyntaxKind,
|
||||
} from "../_namespaces/ts";
|
||||
import { TextRangeWithKind } from "../_namespaces/ts.formatting";
|
||||
|
||||
/** @internal */
|
||||
export const enum FormattingRequestKind {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { FormattingContext } from "../_namespaces/ts.formatting";
|
||||
import {
|
||||
emptyArray,
|
||||
SyntaxKind,
|
||||
} from "../_namespaces/ts";
|
||||
import { FormattingContext } from "../_namespaces/ts.formatting";
|
||||
|
||||
/** @internal */
|
||||
export interface Rule {
|
||||
|
||||
@@ -1,14 +1,3 @@
|
||||
import {
|
||||
anyContext,
|
||||
ContextPredicate,
|
||||
FormattingContext,
|
||||
FormattingRequestKind,
|
||||
Rule,
|
||||
RuleAction,
|
||||
RuleFlags,
|
||||
TextRangeWithKind,
|
||||
TokenRange,
|
||||
} from "../_namespaces/ts.formatting";
|
||||
import {
|
||||
BinaryExpression,
|
||||
contains,
|
||||
@@ -32,6 +21,17 @@ import {
|
||||
typeKeywords,
|
||||
YieldExpression,
|
||||
} from "../_namespaces/ts";
|
||||
import {
|
||||
anyContext,
|
||||
ContextPredicate,
|
||||
FormattingContext,
|
||||
FormattingRequestKind,
|
||||
Rule,
|
||||
RuleAction,
|
||||
RuleFlags,
|
||||
TextRangeWithKind,
|
||||
TokenRange,
|
||||
} from "../_namespaces/ts.formatting";
|
||||
|
||||
/** @internal */
|
||||
export interface RuleSpec {
|
||||
|
||||
@@ -145,6 +145,7 @@ const jsDocTagNames = [
|
||||
"module",
|
||||
"name",
|
||||
"namespace",
|
||||
"overload",
|
||||
"override",
|
||||
"package",
|
||||
"param",
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
RefactorContext,
|
||||
RefactorEditInfo,
|
||||
ReturnStatement,
|
||||
setTextRange,
|
||||
SourceFile,
|
||||
Statement,
|
||||
suppressLeadingAndTrailingTrivia,
|
||||
@@ -237,6 +238,7 @@ function convertToBlock(body: ConciseBody): Block {
|
||||
if (isExpression(body)) {
|
||||
const returnStatement = factory.createReturnStatement(body);
|
||||
const file = body.getSourceFile();
|
||||
setTextRange(returnStatement, body);
|
||||
suppressLeadingAndTrailingTrivia(returnStatement);
|
||||
copyTrailingAsLeadingComments(body, returnStatement, file, /* commentKind */ undefined, /* hasTrailingNewLine */ true);
|
||||
return factory.createBlock([returnStatement], /* multiLine */ true);
|
||||
|
||||
@@ -762,7 +762,7 @@ function filterImport(i: SupportedImport, moduleSpecifier: StringLiteralLike, ke
|
||||
const defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
|
||||
const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
|
||||
return defaultImport || namedBindings
|
||||
? factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(/*isTypeOnly*/ false, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined)
|
||||
? factory.createImportDeclaration(/*modifiers*/ undefined, factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), moduleSpecifier, /*assertClause*/ undefined)
|
||||
: undefined;
|
||||
}
|
||||
case SyntaxKind.ImportEqualsDeclaration:
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as NavigateTo from "./_namespaces/ts.NavigateTo";
|
||||
import * as NavigationBar from "./_namespaces/ts.NavigationBar";
|
||||
import {
|
||||
__String,
|
||||
ApplicableRefactorInfo,
|
||||
@@ -182,8 +180,8 @@ import {
|
||||
isTextWhiteSpaceLike,
|
||||
isThisTypeParameter,
|
||||
isTransientSymbol,
|
||||
JsDoc,
|
||||
JSDoc,
|
||||
JsDoc,
|
||||
JSDocContainer,
|
||||
JSDocTagInfo,
|
||||
JsonSourceFile,
|
||||
@@ -318,6 +316,8 @@ import {
|
||||
UserPreferences,
|
||||
VariableDeclaration,
|
||||
} from "./_namespaces/ts";
|
||||
import * as NavigateTo from "./_namespaces/ts.NavigateTo";
|
||||
import * as NavigationBar from "./_namespaces/ts.NavigationBar";
|
||||
|
||||
/** The version of the language service API */
|
||||
export const servicesVersion = "0.8";
|
||||
@@ -1990,7 +1990,8 @@ export function createLanguageService(
|
||||
options.triggerCharacter,
|
||||
options.triggerKind,
|
||||
cancellationToken,
|
||||
formattingSettings && formatting.getFormatContext(formattingSettings, host));
|
||||
formattingSettings && formatting.getFormatContext(formattingSettings, host),
|
||||
options.includeSymbol);
|
||||
}
|
||||
|
||||
function getCompletionEntryDetails(fileName: string, position: number, name: string, formattingOptions: FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences = emptyOptions, data?: CompletionEntryData): CompletionEntryDetails | undefined {
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
arrayFrom,
|
||||
CallLikeExpression,
|
||||
CancellationToken,
|
||||
CaseClause,
|
||||
changeExtension,
|
||||
CharacterCodes,
|
||||
combinePaths,
|
||||
@@ -94,6 +95,7 @@ import {
|
||||
moduleResolutionUsesNodeModules,
|
||||
ModuleSpecifierEnding,
|
||||
moduleSpecifiers,
|
||||
newCaseClauseTracker,
|
||||
Node,
|
||||
normalizePath,
|
||||
normalizeSlashes,
|
||||
@@ -190,7 +192,8 @@ export function getStringLiteralCompletions(
|
||||
host: LanguageServiceHost,
|
||||
program: Program,
|
||||
log: Log,
|
||||
preferences: UserPreferences): CompletionInfo | undefined {
|
||||
preferences: UserPreferences,
|
||||
includeSymbol: boolean): CompletionInfo | undefined {
|
||||
if (isInReferenceComment(sourceFile, position)) {
|
||||
const entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host);
|
||||
return entries && convertPathCompletions(entries);
|
||||
@@ -198,7 +201,7 @@ export function getStringLiteralCompletions(
|
||||
if (isInString(sourceFile, position, contextToken)) {
|
||||
if (!contextToken || !isStringLiteralLike(contextToken)) return undefined;
|
||||
const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program.getTypeChecker(), options, host, preferences);
|
||||
return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences, position);
|
||||
return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,6 +215,7 @@ function convertStringLiteralCompletions(
|
||||
options: CompilerOptions,
|
||||
preferences: UserPreferences,
|
||||
position: number,
|
||||
includeSymbol: boolean,
|
||||
): CompletionInfo | undefined {
|
||||
if (completion === undefined) {
|
||||
return undefined;
|
||||
@@ -239,6 +243,17 @@ function convertStringLiteralCompletions(
|
||||
preferences,
|
||||
options,
|
||||
/*formatContext*/ undefined,
|
||||
/*isTypeOnlyLocation */ undefined,
|
||||
/*propertyAccessToConvert*/ undefined,
|
||||
/*jsxIdentifierExpected*/ undefined,
|
||||
/*isJsxInitializer*/ undefined,
|
||||
/*importStatementCompletion*/ undefined,
|
||||
/*recommendedCompletion*/ undefined,
|
||||
/*symbolToOriginInfoMap*/ undefined,
|
||||
/*symbolToSortTextMap*/ undefined,
|
||||
/*isJsxIdentifierExpected*/ undefined,
|
||||
/*isRightOfOpenTag*/ undefined,
|
||||
includeSymbol
|
||||
); // Target will not be used, so arbitrary
|
||||
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan, entries };
|
||||
}
|
||||
@@ -272,10 +287,10 @@ function stringLiteralCompletionDetails(name: string, location: Node, completion
|
||||
}
|
||||
case StringLiteralCompletionKind.Properties: {
|
||||
const match = find(completion.symbols, s => s.name === name);
|
||||
return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken);
|
||||
return match && createCompletionDetailsForSymbol(match, match.name, checker, sourceFile, location, cancellationToken);
|
||||
}
|
||||
case StringLiteralCompletionKind.Types:
|
||||
return find(completion.types, t => t.value === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.typeElement, [textPart(name)]) : undefined;
|
||||
return find(completion.types, t => t.value === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.string, [textPart(name)]) : undefined;
|
||||
default:
|
||||
return Debug.assertNever(completion);
|
||||
}
|
||||
@@ -377,7 +392,7 @@ function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringL
|
||||
// });
|
||||
return stringLiteralCompletionsForObjectLiteral(typeChecker, parent.parent);
|
||||
}
|
||||
return fromContextualType();
|
||||
return fromContextualType() || fromContextualType(ContextFlags.None);
|
||||
|
||||
case SyntaxKind.ElementAccessExpression: {
|
||||
const { expression, argumentExpression } = parent as ElementAccessExpression;
|
||||
@@ -415,15 +430,26 @@ function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringL
|
||||
// var y = require("/*completion position*/");
|
||||
// export * from "/*completion position*/";
|
||||
return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker, preferences) };
|
||||
|
||||
case SyntaxKind.CaseClause:
|
||||
const tracker = newCaseClauseTracker(typeChecker, (parent as CaseClause).parent.clauses);
|
||||
const contextualTypes = fromContextualType();
|
||||
if (!contextualTypes) {
|
||||
return;
|
||||
}
|
||||
const literals = contextualTypes.types.filter(literal => !tracker.hasValue(literal.value));
|
||||
return { kind: StringLiteralCompletionKind.Types, types: literals, isNewIdentifier: false };
|
||||
default:
|
||||
return fromContextualType();
|
||||
}
|
||||
|
||||
function fromContextualType(): StringLiteralCompletion {
|
||||
function fromContextualType(contextFlags: ContextFlags = ContextFlags.Completions): StringLiteralCompletionsFromTypes | undefined {
|
||||
// Get completion for string literal from string literal type
|
||||
// i.e. var x: "hi" | "hello" = "/*completion position*/"
|
||||
return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker, ContextFlags.Completions)), isNewIdentifier: false };
|
||||
const types = getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker, contextFlags));
|
||||
if (!types.length) {
|
||||
return;
|
||||
}
|
||||
return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier: false };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -531,7 +557,7 @@ function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile: SourceFile
|
||||
|
||||
const scriptPath = sourceFile.path;
|
||||
const scriptDirectory = getDirectoryPath(scriptPath);
|
||||
const extensionOptions = getExtensionOptions(compilerOptions, ReferenceKind.ModuleSpecifier, sourceFile, preferences, mode);
|
||||
const extensionOptions = getExtensionOptions(compilerOptions, ReferenceKind.ModuleSpecifier, sourceFile, typeChecker, preferences, mode);
|
||||
|
||||
return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (isRootedDiskPath(literalValue) || isUrl(literalValue))
|
||||
? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, extensionOptions)
|
||||
@@ -539,16 +565,16 @@ function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile: SourceFile
|
||||
}
|
||||
|
||||
interface ExtensionOptions {
|
||||
readonly extensionsToSearch: readonly Extension[];
|
||||
readonly extensionsToSearch: readonly string[];
|
||||
readonly referenceKind: ReferenceKind;
|
||||
readonly importingSourceFile: SourceFile;
|
||||
readonly endingPreference?: UserPreferences["importModuleSpecifierEnding"];
|
||||
readonly resolutionMode?: ResolutionMode;
|
||||
}
|
||||
|
||||
function getExtensionOptions(compilerOptions: CompilerOptions, referenceKind: ReferenceKind, importingSourceFile: SourceFile, preferences?: UserPreferences, resolutionMode?: ResolutionMode): ExtensionOptions {
|
||||
function getExtensionOptions(compilerOptions: CompilerOptions, referenceKind: ReferenceKind, importingSourceFile: SourceFile, typeChecker?: TypeChecker, preferences?: UserPreferences, resolutionMode?: ResolutionMode): ExtensionOptions {
|
||||
return {
|
||||
extensionsToSearch: flatten(getSupportedExtensionsForModuleResolution(compilerOptions)),
|
||||
extensionsToSearch: flatten(getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker)),
|
||||
referenceKind,
|
||||
importingSourceFile,
|
||||
endingPreference: preferences?.importModuleSpecifierEnding,
|
||||
@@ -565,8 +591,17 @@ function getCompletionEntriesForRelativeModules(literalValue: string, scriptDire
|
||||
}
|
||||
}
|
||||
|
||||
function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions): readonly Extension[][] {
|
||||
const extensions = getSupportedExtensions(compilerOptions);
|
||||
function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions, typeChecker?: TypeChecker): readonly string[][] {
|
||||
/** file extensions from ambient modules declarations e.g. *.css */
|
||||
const ambientModulesExtensions = !typeChecker ? [] : mapDefined(typeChecker.getAmbientModules(),
|
||||
module => {
|
||||
const name = module.name.slice(1, -1);
|
||||
if (!name.startsWith("*.") || name.includes("/")) return;
|
||||
return name.slice(1);
|
||||
}
|
||||
);
|
||||
|
||||
const extensions = [...getSupportedExtensions(compilerOptions), ambientModulesExtensions];
|
||||
const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
|
||||
return moduleResolutionUsesNodeModules(moduleResolution) ?
|
||||
getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, extensions) :
|
||||
|
||||
+14
-1
@@ -700,6 +700,13 @@ export interface GetCompletionsAtPositionOptions extends UserPreferences {
|
||||
*/
|
||||
triggerCharacter?: CompletionsTriggerCharacter;
|
||||
triggerKind?: CompletionTriggerKind;
|
||||
/**
|
||||
* Include a `symbol` property on each completion entry object.
|
||||
* Symbols reference cyclic data structures and sometimes an entire TypeChecker instance,
|
||||
* so use caution when serializing or retaining completion entries retrieved with this option.
|
||||
* @default false
|
||||
*/
|
||||
includeSymbol?: boolean
|
||||
/** @deprecated Use includeCompletionsForModuleExports */
|
||||
includeExternalModuleExports?: boolean;
|
||||
/** @deprecated Use includeCompletionsWithInsertText */
|
||||
@@ -1337,6 +1344,7 @@ export interface CompletionEntryDataAutoImport {
|
||||
* in the case of InternalSymbolName.ExportEquals and InternalSymbolName.Default.
|
||||
*/
|
||||
exportName: string;
|
||||
exportMapKey?: string;
|
||||
moduleSpecifier?: string;
|
||||
/** The file name declaring the export's module symbol, if it was an external module */
|
||||
fileName?: string;
|
||||
@@ -1347,7 +1355,6 @@ export interface CompletionEntryDataAutoImport {
|
||||
}
|
||||
|
||||
export interface CompletionEntryDataUnresolved extends CompletionEntryDataAutoImport {
|
||||
/** The key in the `ExportMapCache` where the completion entry's `SymbolExportInfo[]` is found */
|
||||
exportMapKey: string;
|
||||
}
|
||||
|
||||
@@ -1379,6 +1386,12 @@ export interface CompletionEntry {
|
||||
isFromUncheckedFile?: true;
|
||||
isPackageJsonImport?: true;
|
||||
isImportStatementCompletion?: true;
|
||||
/**
|
||||
* For API purposes.
|
||||
* Included for non-string completions only when `includeSymbol: true` option is passed to `getCompletionsAtPosition`.
|
||||
* @example Get declaration of completion: `symbol.valueDeclaration`
|
||||
*/
|
||||
symbol?: Symbol
|
||||
/**
|
||||
* A property to be sent back to TS Server in the CompletionDetailsRequest, along with `name`,
|
||||
* that allows TS Server to look up the symbol represented by the completion item, disambiguating
|
||||
|
||||
+146
-13
@@ -38,6 +38,7 @@ import {
|
||||
Debug,
|
||||
Declaration,
|
||||
Decorator,
|
||||
DefaultClause,
|
||||
defaultMaximumTruncationLength,
|
||||
DeleteExpression,
|
||||
Diagnostic,
|
||||
@@ -53,6 +54,7 @@ import {
|
||||
EmitHint,
|
||||
emptyArray,
|
||||
EndOfFileToken,
|
||||
endsWith,
|
||||
ensureScriptKind,
|
||||
EqualityOperator,
|
||||
escapeString,
|
||||
@@ -138,10 +140,12 @@ import {
|
||||
isDeclaration,
|
||||
isDeclarationName,
|
||||
isDecorator,
|
||||
isDefaultClause,
|
||||
isDeleteExpression,
|
||||
isElementAccessExpression,
|
||||
isEntityName,
|
||||
isEnumDeclaration,
|
||||
isEnumMember,
|
||||
isExportAssignment,
|
||||
isExportDeclaration,
|
||||
isExportSpecifier,
|
||||
@@ -188,6 +192,7 @@ import {
|
||||
isKeyword,
|
||||
isLabeledStatement,
|
||||
isLet,
|
||||
isLiteralExpression,
|
||||
isLiteralTypeNode,
|
||||
isMappedTypeNode,
|
||||
isModifier,
|
||||
@@ -281,6 +286,7 @@ import {
|
||||
or,
|
||||
OrganizeImports,
|
||||
PackageJsonDependencyGroup,
|
||||
parseBigInt,
|
||||
pathIsRelative,
|
||||
PrefixUnaryExpression,
|
||||
Program,
|
||||
@@ -288,6 +294,8 @@ import {
|
||||
PropertyAccessExpression,
|
||||
PropertyAssignment,
|
||||
PropertyName,
|
||||
PseudoBigInt,
|
||||
pseudoBigIntToString,
|
||||
QualifiedName,
|
||||
RefactorContext,
|
||||
Scanner,
|
||||
@@ -304,6 +312,7 @@ import {
|
||||
singleOrUndefined,
|
||||
skipAlias,
|
||||
skipOuterExpressions,
|
||||
skipParentheses,
|
||||
some,
|
||||
SortKind,
|
||||
SourceFile,
|
||||
@@ -342,6 +351,7 @@ import {
|
||||
tryCast,
|
||||
Type,
|
||||
TypeChecker,
|
||||
TypeFlags,
|
||||
TypeFormatFlags,
|
||||
TypeNode,
|
||||
TypeOfExpression,
|
||||
@@ -351,6 +361,7 @@ import {
|
||||
VariableDeclaration,
|
||||
visitEachChild,
|
||||
VoidExpression,
|
||||
walkUpParenthesizedExpressions,
|
||||
YieldExpression,
|
||||
} from "./_namespaces/ts";
|
||||
|
||||
@@ -2154,6 +2165,17 @@ export function isStringOrRegularExpressionOrTemplateLiteral(kind: SyntaxKind):
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function isStringAndEmptyAnonymousObjectIntersection(type: Type) {
|
||||
if (!type.isIntersection()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { types, checker } = type;
|
||||
return types.length === 2
|
||||
&& (types[0].flags & TypeFlags.String) && checker.isEmptyAnonymousObjectType(types[1]);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function isPunctuation(kind: SyntaxKind): boolean {
|
||||
return SyntaxKind.FirstPunctuation <= kind && kind <= SyntaxKind.LastPunctuation;
|
||||
@@ -2413,7 +2435,9 @@ export function getModuleSpecifierResolverHost(program: Program, host: LanguageS
|
||||
|
||||
/** @internal */
|
||||
export function moduleResolutionUsesNodeModules(moduleResolution: ModuleResolutionKind): boolean {
|
||||
return moduleResolution === ModuleResolutionKind.Node10 || moduleResolution >= ModuleResolutionKind.Node16 && moduleResolution <= ModuleResolutionKind.NodeNext;
|
||||
return moduleResolution === ModuleResolutionKind.Node10
|
||||
|| moduleResolution >= ModuleResolutionKind.Node16 && moduleResolution <= ModuleResolutionKind.NodeNext
|
||||
|| moduleResolution === ModuleResolutionKind.Bundler;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
@@ -3276,7 +3300,7 @@ export function needsParentheses(expression: Expression): boolean {
|
||||
|
||||
/** @internal */
|
||||
export function getContextualTypeFromParent(node: Expression, checker: TypeChecker, contextFlags?: ContextFlags): Type | undefined {
|
||||
const { parent } = node;
|
||||
const parent = walkUpParenthesizedExpressions(node.parent);
|
||||
switch (parent.kind) {
|
||||
case SyntaxKind.NewExpression:
|
||||
return checker.getContextualType(parent as NewExpression, contextFlags);
|
||||
@@ -3287,7 +3311,7 @@ export function getContextualTypeFromParent(node: Expression, checker: TypeCheck
|
||||
: checker.getContextualType(node, contextFlags);
|
||||
}
|
||||
case SyntaxKind.CaseClause:
|
||||
return (parent as CaseClause).expression === node ? getSwitchedType(parent as CaseClause, checker) : undefined;
|
||||
return getSwitchedType(parent as CaseClause, checker);
|
||||
default:
|
||||
return checker.getContextualType(node, contextFlags);
|
||||
}
|
||||
@@ -3663,7 +3687,13 @@ export function createPackageJsonImportFilter(fromFile: SourceFile, preferences:
|
||||
).filter(p => p.parseable);
|
||||
|
||||
let usesNodeCoreModules: boolean | undefined;
|
||||
return { allowsImportingAmbientModule, allowsImportingSourceFile, allowsImportingSpecifier };
|
||||
let ambientModuleCache: Map<Symbol, boolean> | undefined;
|
||||
let sourceFileCache: Map<SourceFile, boolean> | undefined;
|
||||
return {
|
||||
allowsImportingAmbientModule,
|
||||
allowsImportingSourceFile,
|
||||
allowsImportingSpecifier,
|
||||
};
|
||||
|
||||
function moduleSpecifierIsCoveredByPackageJson(specifier: string) {
|
||||
const packageName = getNodeModuleRootSpecifier(specifier);
|
||||
@@ -3680,19 +3710,34 @@ export function createPackageJsonImportFilter(fromFile: SourceFile, preferences:
|
||||
return true;
|
||||
}
|
||||
|
||||
const declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile();
|
||||
const declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, moduleSpecifierResolutionHost);
|
||||
if (typeof declaringNodeModuleName === "undefined") {
|
||||
return true;
|
||||
if (!ambientModuleCache) {
|
||||
ambientModuleCache = new Map();
|
||||
}
|
||||
else {
|
||||
const cached = ambientModuleCache.get(moduleSymbol);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
const declaredModuleSpecifier = stripQuotes(moduleSymbol.getName());
|
||||
if (isAllowedCoreNodeModulesImport(declaredModuleSpecifier)) {
|
||||
ambientModuleCache.set(moduleSymbol, true);
|
||||
return true;
|
||||
}
|
||||
|
||||
return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName)
|
||||
|| moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier);
|
||||
const declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile();
|
||||
const declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, moduleSpecifierResolutionHost);
|
||||
if (typeof declaringNodeModuleName === "undefined") {
|
||||
ambientModuleCache.set(moduleSymbol, true);
|
||||
return true;
|
||||
}
|
||||
|
||||
const result =
|
||||
moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) ||
|
||||
moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier);
|
||||
ambientModuleCache.set(moduleSymbol, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function allowsImportingSourceFile(sourceFile: SourceFile, moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost): boolean {
|
||||
@@ -3700,12 +3745,25 @@ export function createPackageJsonImportFilter(fromFile: SourceFile, preferences:
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!sourceFileCache) {
|
||||
sourceFileCache = new Map();
|
||||
}
|
||||
else {
|
||||
const cached = sourceFileCache.get(sourceFile);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
const moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName, moduleSpecifierResolutionHost);
|
||||
if (!moduleSpecifier) {
|
||||
sourceFileCache.set(sourceFile, true);
|
||||
return true;
|
||||
}
|
||||
|
||||
return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
|
||||
const result = moduleSpecifierIsCoveredByPackageJson(moduleSpecifier);
|
||||
sourceFileCache.set(sourceFile, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function allowsImportingSpecifier(moduleSpecifier: string) {
|
||||
@@ -3903,8 +3961,12 @@ function needsNameFromDeclaration(symbol: Symbol) {
|
||||
return !(symbol.flags & SymbolFlags.Transient) && (symbol.escapedName === InternalSymbolName.ExportEquals || symbol.escapedName === InternalSymbolName.Default);
|
||||
}
|
||||
|
||||
function getDefaultLikeExportNameFromDeclaration(symbol: Symbol) {
|
||||
return firstDefined(symbol.declarations, d => isExportAssignment(d) ? tryCast(skipOuterExpressions(d.expression), isIdentifier)?.text : undefined);
|
||||
function getDefaultLikeExportNameFromDeclaration(symbol: Symbol): string | undefined {
|
||||
return firstDefined(symbol.declarations, d =>
|
||||
isExportAssignment(d)
|
||||
? tryCast(skipOuterExpressions(d.expression), isIdentifier)?.text
|
||||
: tryCast(getNameOfDeclaration(d), isIdentifier)?.text
|
||||
);
|
||||
}
|
||||
|
||||
function getSymbolParentOrFail(symbol: Symbol) {
|
||||
@@ -4023,3 +4085,74 @@ export function jsxModeNeedsExplicitImport(jsx: JsxEmit | undefined) {
|
||||
export function isSourceFileFromLibrary(program: Program, node: SourceFile) {
|
||||
return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export interface CaseClauseTracker {
|
||||
addValue(value: string | number): void;
|
||||
hasValue(value: string | number | PseudoBigInt): boolean;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function newCaseClauseTracker(checker: TypeChecker, clauses: readonly (CaseClause | DefaultClause)[]): CaseClauseTracker {
|
||||
const existingStrings = new Set<string>();
|
||||
const existingNumbers = new Set<number>();
|
||||
const existingBigInts = new Set<string>();
|
||||
|
||||
for (const clause of clauses) {
|
||||
if (!isDefaultClause(clause)) {
|
||||
const expression = skipParentheses(clause.expression);
|
||||
if (isLiteralExpression(expression)) {
|
||||
switch (expression.kind) {
|
||||
case SyntaxKind.NoSubstitutionTemplateLiteral:
|
||||
case SyntaxKind.StringLiteral:
|
||||
existingStrings.add(expression.text);
|
||||
break;
|
||||
case SyntaxKind.NumericLiteral:
|
||||
existingNumbers.add(parseInt(expression.text));
|
||||
break;
|
||||
case SyntaxKind.BigIntLiteral:
|
||||
const parsedBigInt = parseBigInt(endsWith(expression.text, "n") ? expression.text.slice(0, -1) : expression.text);
|
||||
if (parsedBigInt) {
|
||||
existingBigInts.add(pseudoBigIntToString(parsedBigInt));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
else {
|
||||
const symbol = checker.getSymbolAtLocation(clause.expression);
|
||||
if (symbol && symbol.valueDeclaration && isEnumMember(symbol.valueDeclaration)) {
|
||||
const enumValue = checker.getConstantValue(symbol.valueDeclaration);
|
||||
if (enumValue !== undefined) {
|
||||
addValue(enumValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
addValue,
|
||||
hasValue,
|
||||
};
|
||||
|
||||
function addValue(value: string | number) {
|
||||
switch (typeof value) {
|
||||
case "string":
|
||||
existingStrings.add(value);
|
||||
break;
|
||||
case "number":
|
||||
existingNumbers.add(value);
|
||||
}
|
||||
}
|
||||
|
||||
function hasValue(value: string | number | PseudoBigInt): boolean {
|
||||
switch (typeof value) {
|
||||
case "string":
|
||||
return existingStrings.has(value);
|
||||
case "number":
|
||||
return existingNumbers.has(value);
|
||||
case "object":
|
||||
return existingBigInts.has(pseudoBigIntToString(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as compiler from "./_namespaces/compiler";
|
||||
import * as Utils from "./_namespaces/Utils";
|
||||
import {
|
||||
Baseline,
|
||||
Compiler,
|
||||
@@ -14,6 +11,9 @@ import {
|
||||
TestCaseParser,
|
||||
TestRunnerKind,
|
||||
} from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import * as Utils from "./_namespaces/Utils";
|
||||
import * as vpath from "./_namespaces/vpath";
|
||||
|
||||
export const enum CompilerTestType {
|
||||
Conformance,
|
||||
|
||||
@@ -2,7 +2,6 @@ import * as del from "del";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import {
|
||||
Baseline,
|
||||
IO,
|
||||
@@ -10,6 +9,7 @@ import {
|
||||
RunnerBase,
|
||||
TestRunnerKind,
|
||||
} from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
|
||||
interface ExecResult {
|
||||
stdout: Buffer;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import * as FourSlash from "./_namespaces/FourSlash";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
import {
|
||||
IO,
|
||||
RunnerBase,
|
||||
TestRunnerKind,
|
||||
} from "./_namespaces/Harness";
|
||||
import * as ts from "./_namespaces/ts";
|
||||
|
||||
export class FourSlashRunner extends RunnerBase {
|
||||
protected basePath: string;
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import * as Utils from "../_namespaces/Utils";
|
||||
import * as ts from "../_namespaces/ts";
|
||||
import {
|
||||
configOption,
|
||||
globalTimeout,
|
||||
@@ -24,6 +22,8 @@ import {
|
||||
TaskTimeout,
|
||||
TestInfo,
|
||||
} from "../_namespaces/Harness.Parallel";
|
||||
import * as ts from "../_namespaces/ts";
|
||||
import * as Utils from "../_namespaces/Utils";
|
||||
|
||||
export function start() {
|
||||
const Mocha = require("mocha") as typeof import("mocha");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as ts from "../_namespaces/ts";
|
||||
import { TestRunnerKind } from "../_namespaces/Harness";
|
||||
import * as ts from "../_namespaces/ts";
|
||||
|
||||
export interface RunnerTask {
|
||||
runner: TestRunnerKind;
|
||||
|
||||
Loaded 100 of 1859 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user