mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-12-12 03:20:56 -06:00
Apply 'variable-name' tslint rule (#19743)
This commit is contained in:
parent
8d5b0529b2
commit
0a7b7e07ee
@ -99,12 +99,12 @@ const lclDirectory = "src/loc/lcl";
|
||||
|
||||
const builtDirectory = "built/";
|
||||
const builtLocalDirectory = "built/local/";
|
||||
const LKGDirectory = "lib/";
|
||||
const lkgDirectory = "lib/";
|
||||
|
||||
const copyright = "CopyrightNotice.txt";
|
||||
|
||||
const compilerFilename = "tsc.js";
|
||||
const LKGCompiler = path.join(LKGDirectory, compilerFilename);
|
||||
const lkgCompiler = path.join(lkgDirectory, compilerFilename);
|
||||
const builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
|
||||
|
||||
const nodeModulesPathPrefix = path.resolve("./node_modules/.bin/");
|
||||
@ -589,7 +589,7 @@ gulp.task("VerifyLKG", /*help*/ false, [], () => {
|
||||
". The following files are missing:\n" + missingFiles.join("\n"));
|
||||
}
|
||||
// Copy all the targets into the LKG directory
|
||||
return gulp.src([...expectedFiles, path.join(builtLocalDirectory, "**"), `!${path.join(builtLocalDirectory, "tslint")}`, `!${path.join(builtLocalDirectory, "*.*")}`]).pipe(gulp.dest(LKGDirectory));
|
||||
return gulp.src([...expectedFiles, path.join(builtLocalDirectory, "**"), `!${path.join(builtLocalDirectory, "tslint")}`, `!${path.join(builtLocalDirectory, "*.*")}`]).pipe(gulp.dest(lkgDirectory));
|
||||
});
|
||||
|
||||
gulp.task("LKGInternal", /*help*/ false, ["lib", "local"]);
|
||||
@ -992,7 +992,7 @@ gulp.task(loggedIOJsPath, /*help*/ false, [], (done) => {
|
||||
const temp = path.join(builtLocalDirectory, "temp");
|
||||
mkdirP(temp, (err) => {
|
||||
if (err) { console.error(err); done(err); process.exit(1); }
|
||||
exec(host, [LKGCompiler, "--types", "--target es5", "--lib es5", "--outdir", temp, loggedIOpath], () => {
|
||||
exec(host, [lkgCompiler, "--types", "--target es5", "--lib es5", "--outdir", temp, loggedIOpath], () => {
|
||||
fs.renameSync(path.join(temp, "/harness/loggedIO.js"), loggedIOJsPath);
|
||||
del(temp).then(() => done(), done);
|
||||
}, done);
|
||||
|
||||
@ -87,9 +87,9 @@ function main(): void {
|
||||
const out: any = {};
|
||||
for (const item of o.LCX.Item[0].Item[0].Item) {
|
||||
let ItemId = item.$.ItemId;
|
||||
let Val = item.Str[0].Tgt ? item.Str[0].Tgt[0].Val[0] : item.Str[0].Val[0];
|
||||
let val = item.Str[0].Tgt ? item.Str[0].Tgt[0].Val[0] : item.Str[0].Val[0];
|
||||
|
||||
if (typeof ItemId !== "string" || typeof Val !== "string") {
|
||||
if (typeof ItemId !== "string" || typeof val !== "string") {
|
||||
console.error("Unexpected XML file structure");
|
||||
process.exit(1);
|
||||
}
|
||||
@ -98,8 +98,8 @@ function main(): void {
|
||||
ItemId = ItemId.slice(1); // remove leading semicolon
|
||||
}
|
||||
|
||||
Val = Val.replace(/]5D;/, "]"); // unescape `]`
|
||||
out[ItemId] = Val;
|
||||
val = val.replace(/]5D;/, "]"); // unescape `]`
|
||||
out[ItemId] = val;
|
||||
}
|
||||
return JSON.stringify(out, undefined, 2);
|
||||
}
|
||||
|
||||
@ -63,7 +63,8 @@ function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable): string
|
||||
" function diag(code: number, category: DiagnosticCategory, key: string, message: string): DiagnosticMessage {\r\n" +
|
||||
" return { code, category, key, message };\r\n" +
|
||||
" }\r\n" +
|
||||
' export const Diagnostics = {\r\n';
|
||||
" // tslint:disable-next-line variable-name\r\n" +
|
||||
" export const Diagnostics = {\r\n";
|
||||
messageTable.forEach(({ code, category }, name) => {
|
||||
const propName = convertPropertyName(name);
|
||||
result += ` ${propName}: diag(${code}, DiagnosticCategory.${category}, "${createKey(propName, code)}", ${JSON.stringify(name)}),\r\n`;
|
||||
|
||||
@ -133,7 +133,7 @@ namespace ts {
|
||||
|
||||
let symbolCount = 0;
|
||||
|
||||
let Symbol: { new (flags: SymbolFlags, name: __String): Symbol };
|
||||
let Symbol: { new (flags: SymbolFlags, name: __String): Symbol }; // tslint:disable-line variable-name
|
||||
let classifiableNames: UnderscoreEscapedMap<true>;
|
||||
|
||||
const unreachableFlow: FlowNode = { flags: FlowFlags.Unreachable };
|
||||
|
||||
@ -48,9 +48,11 @@ namespace ts {
|
||||
let requestedExternalEmitHelpers: ExternalEmitHelpers;
|
||||
let externalHelpersModule: Symbol;
|
||||
|
||||
// tslint:disable variable-name
|
||||
const Symbol = objectAllocator.getSymbolConstructor();
|
||||
const Type = objectAllocator.getTypeConstructor();
|
||||
const Signature = objectAllocator.getSignatureConstructor();
|
||||
// tslint:enable variable-name
|
||||
|
||||
let typeCount = 0;
|
||||
let symbolCount = 0;
|
||||
@ -488,17 +490,6 @@ namespace ts {
|
||||
/** Things we lazy load from the JSX namespace */
|
||||
const jsxTypes = createUnderscoreEscapedMap<Type>();
|
||||
|
||||
const JsxNames = {
|
||||
JSX: "JSX" as __String,
|
||||
IntrinsicElements: "IntrinsicElements" as __String,
|
||||
ElementClass: "ElementClass" as __String,
|
||||
ElementAttributesPropertyNameContainer: "ElementAttributesProperty" as __String,
|
||||
ElementChildrenAttributeNameContainer: "ElementChildrenAttribute" as __String,
|
||||
Element: "Element" as __String,
|
||||
IntrinsicAttributes: "IntrinsicAttributes" as __String,
|
||||
IntrinsicClassAttributes: "IntrinsicClassAttributes" as __String
|
||||
};
|
||||
|
||||
const subtypeRelation = createMap<RelationComparisonResult>();
|
||||
const assignableRelation = createMap<RelationComparisonResult>();
|
||||
const comparableRelation = createMap<RelationComparisonResult>();
|
||||
@ -25103,11 +25094,13 @@ namespace ts {
|
||||
}
|
||||
|
||||
function checkGrammarObjectLiteralExpression(node: ObjectLiteralExpression, inDestructuring: boolean) {
|
||||
const seen = createUnderscoreEscapedMap<SymbolFlags>();
|
||||
const Property = 1;
|
||||
const GetAccessor = 2;
|
||||
const SetAccessor = 4;
|
||||
const GetOrSetAccessor = GetAccessor | SetAccessor;
|
||||
const enum Flags {
|
||||
Property = 1,
|
||||
GetAccessor = 2,
|
||||
SetAccessor = 4,
|
||||
GetOrSetAccessor = GetAccessor | SetAccessor,
|
||||
}
|
||||
const seen = createUnderscoreEscapedMap<Flags>();
|
||||
|
||||
for (const prop of node.properties) {
|
||||
if (prop.kind === SyntaxKind.SpreadAssignment) {
|
||||
@ -25142,26 +25135,27 @@ namespace ts {
|
||||
// c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
|
||||
// d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
|
||||
// and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
|
||||
let currentKind: number;
|
||||
if (prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment) {
|
||||
// Grammar checking for computedPropertyName and shorthandPropertyAssignment
|
||||
checkGrammarForInvalidQuestionMark((<PropertyAssignment>prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional);
|
||||
if (name.kind === SyntaxKind.NumericLiteral) {
|
||||
checkGrammarNumericLiteral(<NumericLiteral>name);
|
||||
}
|
||||
currentKind = Property;
|
||||
}
|
||||
else if (prop.kind === SyntaxKind.MethodDeclaration) {
|
||||
currentKind = Property;
|
||||
}
|
||||
else if (prop.kind === SyntaxKind.GetAccessor) {
|
||||
currentKind = GetAccessor;
|
||||
}
|
||||
else if (prop.kind === SyntaxKind.SetAccessor) {
|
||||
currentKind = SetAccessor;
|
||||
}
|
||||
else {
|
||||
Debug.assertNever(prop, "Unexpected syntax kind:" + (<Node>prop).kind);
|
||||
let currentKind: Flags;
|
||||
switch (prop.kind) {
|
||||
case SyntaxKind.PropertyAssignment:
|
||||
case SyntaxKind.ShorthandPropertyAssignment:
|
||||
// Grammar checking for computedPropertyName and shorthandPropertyAssignment
|
||||
checkGrammarForInvalidQuestionMark((<PropertyAssignment>prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional);
|
||||
if (name.kind === SyntaxKind.NumericLiteral) {
|
||||
checkGrammarNumericLiteral(<NumericLiteral>name);
|
||||
}
|
||||
// falls through
|
||||
case SyntaxKind.MethodDeclaration:
|
||||
currentKind = Flags.Property;
|
||||
break;
|
||||
case SyntaxKind.GetAccessor:
|
||||
currentKind = Flags.GetAccessor;
|
||||
break;
|
||||
case SyntaxKind.SetAccessor:
|
||||
currentKind = Flags.SetAccessor;
|
||||
break;
|
||||
default:
|
||||
Debug.assertNever(prop, "Unexpected syntax kind:" + (<Node>prop).kind);
|
||||
}
|
||||
|
||||
const effectiveName = getPropertyNameForPropertyNameNode(name);
|
||||
@ -25174,11 +25168,11 @@ namespace ts {
|
||||
seen.set(effectiveName, currentKind);
|
||||
}
|
||||
else {
|
||||
if (currentKind === Property && existingKind === Property) {
|
||||
if (currentKind === Flags.Property && existingKind === Flags.Property) {
|
||||
grammarErrorOnNode(name, Diagnostics.Duplicate_identifier_0, getTextOfNode(name));
|
||||
}
|
||||
else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) {
|
||||
if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) {
|
||||
else if ((currentKind & Flags.GetOrSetAccessor) && (existingKind & Flags.GetOrSetAccessor)) {
|
||||
if (existingKind !== Flags.GetOrSetAccessor && currentKind !== existingKind) {
|
||||
seen.set(effectiveName, currentKind | existingKind);
|
||||
}
|
||||
else {
|
||||
@ -25806,4 +25800,17 @@ namespace ts {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
namespace JsxNames {
|
||||
// tslint:disable variable-name
|
||||
export const JSX = "JSX" as __String;
|
||||
export const IntrinsicElements = "IntrinsicElements" as __String;
|
||||
export const ElementClass = "ElementClass" as __String;
|
||||
export const ElementAttributesPropertyNameContainer = "ElementAttributesProperty" as __String;
|
||||
export const ElementChildrenAttributeNameContainer = "ElementChildrenAttribute" as __String;
|
||||
export const Element = "Element" as __String;
|
||||
export const IntrinsicAttributes = "IntrinsicAttributes" as __String;
|
||||
export const IntrinsicClassAttributes = "IntrinsicClassAttributes" as __String;
|
||||
// tslint:enable variable-name
|
||||
}
|
||||
}
|
||||
|
||||
@ -76,7 +76,7 @@ namespace ts {
|
||||
// The global Map object. This may not be available, so we must test for it.
|
||||
declare const Map: { new<T>(): Map<T> } | undefined;
|
||||
// Internet Explorer's Map doesn't support iteration, so don't use it.
|
||||
// tslint:disable-next-line:no-in-operator
|
||||
// tslint:disable-next-line no-in-operator variable-name
|
||||
const MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap();
|
||||
|
||||
// Keep the class inside a function so it doesn't get compiled if it's not used.
|
||||
|
||||
@ -2654,6 +2654,7 @@ namespace ts {
|
||||
return node;
|
||||
}
|
||||
|
||||
// tslint:disable-next-line variable-name
|
||||
let SourceMapSource: new (fileName: string, text: string, skipTrivia?: (pos: number) => number) => SourceMapSource;
|
||||
|
||||
/**
|
||||
|
||||
@ -12,10 +12,12 @@ namespace ts {
|
||||
JSDoc = 1 << 5,
|
||||
}
|
||||
|
||||
// tslint:disable variable-name
|
||||
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, pos: number, end: number) => Node;
|
||||
let SourceFileConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
|
||||
// tslint:enable variable-name
|
||||
|
||||
export function createNode(kind: SyntaxKind, pos?: number, end?: number): Node {
|
||||
if (kind === SyntaxKind.SourceFile) {
|
||||
@ -524,10 +526,12 @@ namespace ts {
|
||||
const disallowInAndDecoratorContext = NodeFlags.DisallowInContext | NodeFlags.DecoratorContext;
|
||||
|
||||
// capture constructors in 'initializeState' to avoid null checks
|
||||
// tslint:disable variable-name
|
||||
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, pos: number, end: number) => Node;
|
||||
let SourceFileConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
|
||||
// tslint:enable variable-name
|
||||
|
||||
let sourceFile: SourceFile;
|
||||
let parseDiagnostics: Diagnostic[];
|
||||
|
||||
@ -1404,8 +1404,8 @@ namespace ts {
|
||||
return charCode === CharacterCodes.singleQuote || charCode === CharacterCodes.doubleQuote;
|
||||
}
|
||||
|
||||
export function isStringDoubleQuoted(string: StringLiteral, sourceFile: SourceFile): boolean {
|
||||
return getSourceTextOfNodeFromSourceFile(sourceFile, string).charCodeAt(0) === CharacterCodes.doubleQuote;
|
||||
export function isStringDoubleQuoted(str: StringLiteral, sourceFile: SourceFile): boolean {
|
||||
return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === CharacterCodes.doubleQuote;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -126,8 +126,8 @@ namespace FourSlash {
|
||||
// 0 - cancelled
|
||||
// >0 - not cancelled
|
||||
// <0 - not cancelled and value denotes number of isCancellationRequested after which token become cancelled
|
||||
private static readonly NotCanceled: number = -1;
|
||||
private numberOfCallsBeforeCancellation: number = TestCancellationToken.NotCanceled;
|
||||
private static readonly notCanceled = -1;
|
||||
private numberOfCallsBeforeCancellation = TestCancellationToken.notCanceled;
|
||||
|
||||
public isCancellationRequested(): boolean {
|
||||
if (this.numberOfCallsBeforeCancellation < 0) {
|
||||
@ -148,7 +148,7 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
public resetCancelled(): void {
|
||||
this.numberOfCallsBeforeCancellation = TestCancellationToken.NotCanceled;
|
||||
this.numberOfCallsBeforeCancellation = TestCancellationToken.notCanceled;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1113,11 +1113,11 @@ namespace Harness {
|
||||
case "string":
|
||||
return value;
|
||||
case "number": {
|
||||
const number = parseInt(value, 10);
|
||||
if (isNaN(number)) {
|
||||
const numverValue = parseInt(value, 10);
|
||||
if (isNaN(numverValue)) {
|
||||
throw new Error(`Value must be a number, got: ${JSON.stringify(value)}`);
|
||||
}
|
||||
return number;
|
||||
return numverValue;
|
||||
}
|
||||
// If not a primitive, the possible types are specified in what is effectively a map of options.
|
||||
case "list":
|
||||
@ -1964,7 +1964,7 @@ namespace Harness {
|
||||
|
||||
/** Support class for baseline files */
|
||||
export namespace Baseline {
|
||||
const NoContent = "<no content>";
|
||||
const noContent = "<no content>";
|
||||
|
||||
export interface BaselineOptions {
|
||||
Subfolder?: string;
|
||||
@ -2023,7 +2023,7 @@ namespace Harness {
|
||||
/* tslint:disable:no-null-keyword */
|
||||
if (actual === null) {
|
||||
/* tslint:enable:no-null-keyword */
|
||||
actual = NoContent;
|
||||
actual = noContent;
|
||||
}
|
||||
|
||||
let expected = "<no content>";
|
||||
@ -2060,13 +2060,13 @@ namespace Harness {
|
||||
IO.deleteFile(actualFileName);
|
||||
}
|
||||
|
||||
const encoded_actual = Utils.encodeString(actual);
|
||||
if (expected !== encoded_actual) {
|
||||
if (actual === NoContent) {
|
||||
const encodedActual = Utils.encodeString(actual);
|
||||
if (expected !== encodedActual) {
|
||||
if (actual === noContent) {
|
||||
IO.writeFile(actualFileName + ".delete", "");
|
||||
}
|
||||
else {
|
||||
IO.writeFile(actualFileName, encoded_actual);
|
||||
IO.writeFile(actualFileName, encodedActual);
|
||||
}
|
||||
throw new Error(`The baseline file ${relativeFileName} has changed.`);
|
||||
}
|
||||
|
||||
@ -108,7 +108,7 @@ namespace Harness.LanguageService {
|
||||
}
|
||||
|
||||
class DefaultHostCancellationToken implements ts.HostCancellationToken {
|
||||
public static readonly Instance = new DefaultHostCancellationToken();
|
||||
public static readonly instance = new DefaultHostCancellationToken();
|
||||
|
||||
public isCancellationRequested() {
|
||||
return false;
|
||||
@ -126,7 +126,7 @@ namespace Harness.LanguageService {
|
||||
public typesRegistry: ts.Map<void> | undefined;
|
||||
protected virtualFileSystem: Utils.VirtualFileSystem = new Utils.VirtualFileSystem(virtualFileSystemRoot, /*useCaseSensitiveFilenames*/false);
|
||||
|
||||
constructor(protected cancellationToken = DefaultHostCancellationToken.Instance,
|
||||
constructor(protected cancellationToken = DefaultHostCancellationToken.instance,
|
||||
protected settings = ts.getDefaultCompilerOptions()) {
|
||||
}
|
||||
|
||||
|
||||
@ -251,7 +251,7 @@ namespace Playback {
|
||||
let i = 0;
|
||||
const getBase = () => recordLogFileNameBase + i;
|
||||
while (underlying.fileExists(ts.combinePaths(getBase(), "test.json"))) i++;
|
||||
const newLog = oldStyleLogIntoNewStyleLog(recordLog, (path, string) => underlying.writeFile(path, string), getBase());
|
||||
const newLog = oldStyleLogIntoNewStyleLog(recordLog, (path, str) => underlying.writeFile(path, str), getBase());
|
||||
underlying.writeFile(ts.combinePaths(getBase(), "test.json"), JSON.stringify(newLog, null, 4)); // tslint:disable-line:no-null-keyword
|
||||
const syntheticTsconfig = generateTsconfig(newLog);
|
||||
if (syntheticTsconfig) {
|
||||
|
||||
@ -274,15 +274,15 @@ namespace Harness.Parallel.Host {
|
||||
function completeBar() {
|
||||
const isPartitionFail = failingFiles !== 0;
|
||||
const summaryColor = isPartitionFail ? "fail" : "green";
|
||||
const summarySymbol = isPartitionFail ? Base.symbols.err : Base.symbols.ok;
|
||||
const summarySymbol = isPartitionFail ? base.symbols.err : base.symbols.ok;
|
||||
|
||||
const summaryTests = (isPartitionFail ? totalPassing + "/" + (errorResults.length + totalPassing) : totalPassing) + " passing";
|
||||
const summaryDuration = "(" + ms(duration) + ")";
|
||||
const savedUseColors = Base.useColors;
|
||||
Base.useColors = !noColors;
|
||||
const savedUseColors = base.useColors;
|
||||
base.useColors = !noColors;
|
||||
|
||||
const summary = color(summaryColor, summarySymbol + " " + summaryTests) + " " + color("light", summaryDuration);
|
||||
Base.useColors = savedUseColors;
|
||||
base.useColors = savedUseColors;
|
||||
|
||||
updateProgress(1, summary);
|
||||
}
|
||||
@ -307,7 +307,7 @@ namespace Harness.Parallel.Host {
|
||||
completeBar();
|
||||
progressBars.disable();
|
||||
|
||||
const reporter = new Base();
|
||||
const reporter = new base();
|
||||
const stats = reporter.stats;
|
||||
const failures = reporter.failures;
|
||||
stats.passes = totalPassing;
|
||||
@ -318,10 +318,10 @@ namespace Harness.Parallel.Host {
|
||||
failures.push(makeMochaTest(failure));
|
||||
}
|
||||
if (noColors) {
|
||||
const savedUseColors = Base.useColors;
|
||||
Base.useColors = false;
|
||||
const savedUseColors = base.useColors;
|
||||
base.useColors = false;
|
||||
reporter.epilogue();
|
||||
Base.useColors = savedUseColors;
|
||||
base.useColors = savedUseColors;
|
||||
}
|
||||
else {
|
||||
reporter.epilogue();
|
||||
@ -352,8 +352,8 @@ namespace Harness.Parallel.Host {
|
||||
return;
|
||||
}
|
||||
|
||||
let Mocha: any;
|
||||
let Base: any;
|
||||
let mocha: any;
|
||||
let base: any;
|
||||
let color: any;
|
||||
let cursor: any;
|
||||
let readline: any;
|
||||
@ -394,10 +394,10 @@ namespace Harness.Parallel.Host {
|
||||
}
|
||||
|
||||
function initializeProgressBarsDependencies() {
|
||||
Mocha = require("mocha");
|
||||
Base = Mocha.reporters.Base;
|
||||
color = Base.color;
|
||||
cursor = Base.cursor;
|
||||
mocha = require("mocha");
|
||||
base = mocha.reporters.Base;
|
||||
color = base.color;
|
||||
cursor = base.cursor;
|
||||
readline = require("readline");
|
||||
os = require("os");
|
||||
tty = require("tty");
|
||||
@ -414,8 +414,8 @@ namespace Harness.Parallel.Host {
|
||||
const open = options.open || "[";
|
||||
const close = options.close || "]";
|
||||
const complete = options.complete || "▬";
|
||||
const incomplete = options.incomplete || Base.symbols.dot;
|
||||
const maxWidth = Base.window.width - open.length - close.length - 34;
|
||||
const incomplete = options.incomplete || base.symbols.dot;
|
||||
const maxWidth = base.window.width - open.length - close.length - 34;
|
||||
const width = minMax(options.width || maxWidth, 10, maxWidth);
|
||||
this._options = {
|
||||
open,
|
||||
|
||||
@ -627,8 +627,8 @@ namespace ts.projectSystem {
|
||||
const mapFileContent = host.readFile(expectedMapFileName);
|
||||
verifyContentHasString(mapFileContent, `"sources":["${inputFileName}"]`);
|
||||
|
||||
function verifyContentHasString(content: string, string: string) {
|
||||
assert.isTrue(content.indexOf(string) !== -1, `Expected "${content}" to have "${string}"`);
|
||||
function verifyContentHasString(content: string, str: string) {
|
||||
assert.isTrue(stringContains(content, str), `Expected "${content}" to have "${str}"`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@ -191,7 +191,7 @@ function f() {
|
||||
}
|
||||
`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRangeContainingConditionalReturnStatement.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed2",
|
||||
@ -210,7 +210,7 @@ function f() {
|
||||
}
|
||||
`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed3",
|
||||
@ -229,7 +229,7 @@ function f() {
|
||||
}
|
||||
`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed4",
|
||||
@ -248,7 +248,7 @@ function f() {
|
||||
}
|
||||
`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed5",
|
||||
@ -269,7 +269,7 @@ function f2() {
|
||||
}
|
||||
`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRangeContainingConditionalReturnStatement.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed6",
|
||||
@ -290,7 +290,7 @@ function f2() {
|
||||
}
|
||||
`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRangeContainingConditionalReturnStatement.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed7",
|
||||
@ -303,7 +303,7 @@ while (x) {
|
||||
}
|
||||
`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed8",
|
||||
@ -316,13 +316,13 @@ switch (x) {
|
||||
}
|
||||
`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed9",
|
||||
`var x = ([#||]1 + 2);`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractEmpty.message
|
||||
refactor.extractSymbol.Messages.cannotExtractEmpty.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed10",
|
||||
@ -333,7 +333,7 @@ switch (x) {
|
||||
}
|
||||
`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRange.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRange.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed11",
|
||||
@ -350,21 +350,21 @@ switch (x) {
|
||||
}
|
||||
`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed12",
|
||||
`let [#|x|];`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.StatementOrExpressionExpected.message
|
||||
refactor.extractSymbol.Messages.statementOrExpressionExpected.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extractRangeFailed13",
|
||||
`[#|return;|]`,
|
||||
[
|
||||
refactor.extractSymbol.Messages.CannotExtractRange.message
|
||||
refactor.extractSymbol.Messages.cannotExtractRange.message
|
||||
]);
|
||||
|
||||
testExtractRangeFailed("extract-method-not-for-token-expression-statement", `[#|a|]`, [refactor.extractSymbol.Messages.CannotExtractIdentifier.message]);
|
||||
testExtractRangeFailed("extract-method-not-for-token-expression-statement", `[#|a|]`, [refactor.extractSymbol.Messages.cannotExtractIdentifier.message]);
|
||||
});
|
||||
}
|
||||
@ -803,7 +803,7 @@ import b = require("./moduleB");
|
||||
|
||||
function test(hasDirectoryExists: boolean) {
|
||||
const file1: File = { name: "/root/folder1/file1.ts" };
|
||||
const file1_1: File = { name: "/root/folder1/file1_1/index.d.ts" };
|
||||
const file1_1: File = { name: "/root/folder1/file1_1/index.d.ts" }; // tslint:disable-line variable-name
|
||||
const file2: File = { name: "/root/generated/folder1/file2.ts" };
|
||||
const file3: File = { name: "/root/generated/folder2/file3.ts" };
|
||||
const host = createModuleResolutionHost(hasDirectoryExists, file1, file1_1, file2, file3);
|
||||
|
||||
@ -243,111 +243,111 @@ namespace ts {
|
||||
];
|
||||
|
||||
it("successful if change does not affect imports", () => {
|
||||
const program_1 = newProgram(files, ["a.ts"], { target });
|
||||
const program_2 = updateProgram(program_1, ["a.ts"], { target }, files => {
|
||||
const program1 = newProgram(files, ["a.ts"], { target });
|
||||
const program2 = updateProgram(program1, ["a.ts"], { target }, files => {
|
||||
files[0].text = files[0].text.updateProgram("var x = 100");
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Completely);
|
||||
const program1Diagnostics = program_1.getSemanticDiagnostics(program_1.getSourceFile("a.ts"));
|
||||
const program2Diagnostics = program_2.getSemanticDiagnostics(program_1.getSourceFile("a.ts"));
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Completely);
|
||||
const program1Diagnostics = program1.getSemanticDiagnostics(program1.getSourceFile("a.ts"));
|
||||
const program2Diagnostics = program2.getSemanticDiagnostics(program1.getSourceFile("a.ts"));
|
||||
assert.equal(program1Diagnostics.length, program2Diagnostics.length);
|
||||
});
|
||||
|
||||
it("successful if change does not affect type reference directives", () => {
|
||||
const program_1 = newProgram(files, ["a.ts"], { target });
|
||||
const program_2 = updateProgram(program_1, ["a.ts"], { target }, files => {
|
||||
const program1 = newProgram(files, ["a.ts"], { target });
|
||||
const program2 = updateProgram(program1, ["a.ts"], { target }, files => {
|
||||
files[0].text = files[0].text.updateProgram("var x = 100");
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Completely);
|
||||
const program1Diagnostics = program_1.getSemanticDiagnostics(program_1.getSourceFile("a.ts"));
|
||||
const program2Diagnostics = program_2.getSemanticDiagnostics(program_1.getSourceFile("a.ts"));
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Completely);
|
||||
const program1Diagnostics = program1.getSemanticDiagnostics(program1.getSourceFile("a.ts"));
|
||||
const program2Diagnostics = program2.getSemanticDiagnostics(program1.getSourceFile("a.ts"));
|
||||
assert.equal(program1Diagnostics.length, program2Diagnostics.length);
|
||||
});
|
||||
|
||||
it("fails if change affects tripleslash references", () => {
|
||||
const program_1 = newProgram(files, ["a.ts"], { target });
|
||||
updateProgram(program_1, ["a.ts"], { target }, files => {
|
||||
const program1 = newProgram(files, ["a.ts"], { target });
|
||||
updateProgram(program1, ["a.ts"], { target }, files => {
|
||||
const newReferences = `/// <reference path='b.ts'/>
|
||||
/// <reference path='c.ts'/>
|
||||
`;
|
||||
files[0].text = files[0].text.updateReferences(newReferences);
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.SafeModules);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.SafeModules);
|
||||
});
|
||||
|
||||
it("fails if change affects type references", () => {
|
||||
const program_1 = newProgram(files, ["a.ts"], { types: ["a"] });
|
||||
updateProgram(program_1, ["a.ts"], { types: ["b"] }, noop);
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Not);
|
||||
const program1 = newProgram(files, ["a.ts"], { types: ["a"] });
|
||||
updateProgram(program1, ["a.ts"], { types: ["b"] }, noop);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Not);
|
||||
});
|
||||
|
||||
it("succeeds if change doesn't affect type references", () => {
|
||||
const program_1 = newProgram(files, ["a.ts"], { types: ["a"] });
|
||||
updateProgram(program_1, ["a.ts"], { types: ["a"] }, noop);
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Completely);
|
||||
const program1 = newProgram(files, ["a.ts"], { types: ["a"] });
|
||||
updateProgram(program1, ["a.ts"], { types: ["a"] }, noop);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Completely);
|
||||
});
|
||||
|
||||
it("fails if change affects imports", () => {
|
||||
const program_1 = newProgram(files, ["a.ts"], { target });
|
||||
updateProgram(program_1, ["a.ts"], { target }, files => {
|
||||
const program1 = newProgram(files, ["a.ts"], { target });
|
||||
updateProgram(program1, ["a.ts"], { target }, files => {
|
||||
files[2].text = files[2].text.updateImportsAndExports("import x from 'b'");
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.SafeModules);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.SafeModules);
|
||||
});
|
||||
|
||||
it("fails if change affects type directives", () => {
|
||||
const program_1 = newProgram(files, ["a.ts"], { target });
|
||||
updateProgram(program_1, ["a.ts"], { target }, files => {
|
||||
const program1 = newProgram(files, ["a.ts"], { target });
|
||||
updateProgram(program1, ["a.ts"], { target }, files => {
|
||||
const newReferences = `
|
||||
/// <reference path='b.ts'/>
|
||||
/// <reference path='non-existing-file.ts'/>
|
||||
/// <reference types="typerefs1" />`;
|
||||
files[0].text = files[0].text.updateReferences(newReferences);
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.SafeModules);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.SafeModules);
|
||||
});
|
||||
|
||||
it("fails if module kind changes", () => {
|
||||
const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS });
|
||||
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.AMD }, noop);
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Not);
|
||||
const program1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS });
|
||||
updateProgram(program1, ["a.ts"], { target, module: ModuleKind.AMD }, noop);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Not);
|
||||
});
|
||||
|
||||
it("fails if rootdir changes", () => {
|
||||
const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/b" });
|
||||
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, noop);
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Not);
|
||||
const program1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/b" });
|
||||
updateProgram(program1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, noop);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Not);
|
||||
});
|
||||
|
||||
it("fails if config path changes", () => {
|
||||
const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/b/tsconfig.json" });
|
||||
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/c/tsconfig.json" }, noop);
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Not);
|
||||
const program1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/b/tsconfig.json" });
|
||||
updateProgram(program1, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/c/tsconfig.json" }, noop);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Not);
|
||||
});
|
||||
|
||||
it("succeeds if missing files remain missing", () => {
|
||||
const options: CompilerOptions = { target, noLib: true };
|
||||
|
||||
const program_1 = newProgram(files, ["a.ts"], options);
|
||||
assert.notDeepEqual(emptyArray, program_1.getMissingFilePaths());
|
||||
const program1 = newProgram(files, ["a.ts"], options);
|
||||
assert.notDeepEqual(emptyArray, program1.getMissingFilePaths());
|
||||
|
||||
const program_2 = updateProgram(program_1, ["a.ts"], options, noop);
|
||||
assert.deepEqual(program_1.getMissingFilePaths(), program_2.getMissingFilePaths());
|
||||
const program2 = updateProgram(program1, ["a.ts"], options, noop);
|
||||
assert.deepEqual(program1.getMissingFilePaths(), program2.getMissingFilePaths());
|
||||
|
||||
assert.equal(StructureIsReused.Completely, program_1.structureIsReused);
|
||||
assert.equal(StructureIsReused.Completely, program1.structureIsReused);
|
||||
});
|
||||
|
||||
it("fails if missing file is created", () => {
|
||||
const options: CompilerOptions = { target, noLib: true };
|
||||
|
||||
const program_1 = newProgram(files, ["a.ts"], options);
|
||||
assert.notDeepEqual(emptyArray, program_1.getMissingFilePaths());
|
||||
const program1 = newProgram(files, ["a.ts"], options);
|
||||
assert.notDeepEqual(emptyArray, program1.getMissingFilePaths());
|
||||
|
||||
const newTexts: NamedSourceText[] = files.concat([{ name: "non-existing-file.ts", text: SourceText.New("", "", `var x = 1`) }]);
|
||||
const program_2 = updateProgram(program_1, ["a.ts"], options, noop, newTexts);
|
||||
assert.deepEqual(emptyArray, program_2.getMissingFilePaths());
|
||||
const program2 = updateProgram(program1, ["a.ts"], options, noop, newTexts);
|
||||
assert.deepEqual(emptyArray, program2.getMissingFilePaths());
|
||||
|
||||
assert.equal(StructureIsReused.Not, program_1.structureIsReused);
|
||||
assert.equal(StructureIsReused.Not, program1.structureIsReused);
|
||||
});
|
||||
|
||||
it("resolution cache follows imports", () => {
|
||||
@ -359,34 +359,34 @@ namespace ts {
|
||||
];
|
||||
const options: CompilerOptions = { target };
|
||||
|
||||
const program_1 = newProgram(files, ["a.ts"], options);
|
||||
checkResolvedModulesCache(program_1, "a.ts", createMapFromTemplate({ "b": createResolvedModule("b.ts") }));
|
||||
checkResolvedModulesCache(program_1, "b.ts", /*expectedContent*/ undefined);
|
||||
const program1 = newProgram(files, ["a.ts"], options);
|
||||
checkResolvedModulesCache(program1, "a.ts", createMapFromTemplate({ "b": createResolvedModule("b.ts") }));
|
||||
checkResolvedModulesCache(program1, "b.ts", /*expectedContent*/ undefined);
|
||||
|
||||
const program_2 = updateProgram(program_1, ["a.ts"], options, files => {
|
||||
const program2 = updateProgram(program1, ["a.ts"], options, files => {
|
||||
files[0].text = files[0].text.updateProgram("var x = 2");
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Completely);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Completely);
|
||||
|
||||
// content of resolution cache should not change
|
||||
checkResolvedModulesCache(program_1, "a.ts", createMapFromTemplate({ "b": createResolvedModule("b.ts") }));
|
||||
checkResolvedModulesCache(program_1, "b.ts", /*expectedContent*/ undefined);
|
||||
checkResolvedModulesCache(program1, "a.ts", createMapFromTemplate({ "b": createResolvedModule("b.ts") }));
|
||||
checkResolvedModulesCache(program1, "b.ts", /*expectedContent*/ undefined);
|
||||
|
||||
// imports has changed - program is not reused
|
||||
const program_3 = updateProgram(program_2, ["a.ts"], options, files => {
|
||||
const program3 = updateProgram(program2, ["a.ts"], options, files => {
|
||||
files[0].text = files[0].text.updateImportsAndExports("");
|
||||
});
|
||||
assert.equal(program_2.structureIsReused, StructureIsReused.SafeModules);
|
||||
checkResolvedModulesCache(program_3, "a.ts", /*expectedContent*/ undefined);
|
||||
assert.equal(program2.structureIsReused, StructureIsReused.SafeModules);
|
||||
checkResolvedModulesCache(program3, "a.ts", /*expectedContent*/ undefined);
|
||||
|
||||
const program_4 = updateProgram(program_3, ["a.ts"], options, files => {
|
||||
const program4 = updateProgram(program3, ["a.ts"], options, files => {
|
||||
const newImports = `import x from 'b'
|
||||
import y from 'c'
|
||||
`;
|
||||
files[0].text = files[0].text.updateImportsAndExports(newImports);
|
||||
});
|
||||
assert.equal(program_3.structureIsReused, StructureIsReused.SafeModules);
|
||||
checkResolvedModulesCache(program_4, "a.ts", createMapFromTemplate({ "b": createResolvedModule("b.ts"), "c": undefined }));
|
||||
assert.equal(program3.structureIsReused, StructureIsReused.SafeModules);
|
||||
checkResolvedModulesCache(program4, "a.ts", createMapFromTemplate({ "b": createResolvedModule("b.ts"), "c": undefined }));
|
||||
});
|
||||
|
||||
it("resolved type directives cache follows type directives", () => {
|
||||
@ -396,35 +396,35 @@ namespace ts {
|
||||
];
|
||||
const options: CompilerOptions = { target, typeRoots: ["/types"] };
|
||||
|
||||
const program_1 = newProgram(files, ["/a.ts"], options);
|
||||
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMapFromTemplate({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
|
||||
checkResolvedTypeDirectivesCache(program_1, "/types/typedefs/index.d.ts", /*expectedContent*/ undefined);
|
||||
const program1 = newProgram(files, ["/a.ts"], options);
|
||||
checkResolvedTypeDirectivesCache(program1, "/a.ts", createMapFromTemplate({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
|
||||
checkResolvedTypeDirectivesCache(program1, "/types/typedefs/index.d.ts", /*expectedContent*/ undefined);
|
||||
|
||||
const program_2 = updateProgram(program_1, ["/a.ts"], options, files => {
|
||||
const program2 = updateProgram(program1, ["/a.ts"], options, files => {
|
||||
files[0].text = files[0].text.updateProgram("var x = 2");
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Completely);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Completely);
|
||||
|
||||
// content of resolution cache should not change
|
||||
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMapFromTemplate({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
|
||||
checkResolvedTypeDirectivesCache(program_1, "/types/typedefs/index.d.ts", /*expectedContent*/ undefined);
|
||||
checkResolvedTypeDirectivesCache(program1, "/a.ts", createMapFromTemplate({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
|
||||
checkResolvedTypeDirectivesCache(program1, "/types/typedefs/index.d.ts", /*expectedContent*/ undefined);
|
||||
|
||||
// type reference directives has changed - program is not reused
|
||||
const program_3 = updateProgram(program_2, ["/a.ts"], options, files => {
|
||||
const program3 = updateProgram(program2, ["/a.ts"], options, files => {
|
||||
files[0].text = files[0].text.updateReferences("");
|
||||
});
|
||||
|
||||
assert.equal(program_2.structureIsReused, StructureIsReused.SafeModules);
|
||||
checkResolvedTypeDirectivesCache(program_3, "/a.ts", /*expectedContent*/ undefined);
|
||||
assert.equal(program2.structureIsReused, StructureIsReused.SafeModules);
|
||||
checkResolvedTypeDirectivesCache(program3, "/a.ts", /*expectedContent*/ undefined);
|
||||
|
||||
updateProgram(program_3, ["/a.ts"], options, files => {
|
||||
updateProgram(program3, ["/a.ts"], options, files => {
|
||||
const newReferences = `/// <reference types="typedefs"/>
|
||||
/// <reference types="typedefs2"/>
|
||||
`;
|
||||
files[0].text = files[0].text.updateReferences(newReferences);
|
||||
});
|
||||
assert.equal(program_3.structureIsReused, StructureIsReused.SafeModules);
|
||||
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMapFromTemplate({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
|
||||
assert.equal(program3.structureIsReused, StructureIsReused.SafeModules);
|
||||
checkResolvedTypeDirectivesCache(program1, "/a.ts", createMapFromTemplate({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
|
||||
});
|
||||
|
||||
it("fetches imports after npm install", () => {
|
||||
@ -529,18 +529,18 @@ namespace ts {
|
||||
"======== Module name 'fs' was not resolved. ========",
|
||||
], "should look for 'fs'");
|
||||
|
||||
const program_2 = updateProgram(program, program.getRootFileNames(), options, f => {
|
||||
const program2 = updateProgram(program, program.getRootFileNames(), options, f => {
|
||||
f[0].text = f[0].text.updateProgram("var x = 1;");
|
||||
});
|
||||
assert.deepEqual(program_2.host.getTrace(), [
|
||||
assert.deepEqual(program2.host.getTrace(), [
|
||||
"Module 'fs' was resolved as ambient module declared in '/a/b/node.d.ts' since this file was not modified."
|
||||
], "should reuse 'fs' since node.d.ts was not changed");
|
||||
|
||||
const program_3 = updateProgram(program_2, program_2.getRootFileNames(), options, f => {
|
||||
const program3 = updateProgram(program2, program2.getRootFileNames(), options, f => {
|
||||
f[0].text = f[0].text.updateProgram("var y = 1;");
|
||||
f[1].text = f[1].text.updateProgram("declare var process: any");
|
||||
});
|
||||
assert.deepEqual(program_3.host.getTrace(),
|
||||
assert.deepEqual(program3.host.getTrace(),
|
||||
[
|
||||
"======== Resolving module 'fs' from '/a/b/app.ts'. ========",
|
||||
"Module resolution kind is not specified, using 'Classic'.",
|
||||
@ -598,10 +598,10 @@ namespace ts {
|
||||
];
|
||||
|
||||
const options: CompilerOptions = { target: ScriptTarget.ES2015, traceResolution: true, moduleResolution: ModuleResolutionKind.Classic };
|
||||
const program_1 = newProgram(files, files.map(f => f.name), options);
|
||||
const program1 = newProgram(files, files.map(f => f.name), options);
|
||||
let expectedErrors = 0;
|
||||
{
|
||||
assert.deepEqual(program_1.host.getTrace(),
|
||||
assert.deepEqual(program1.host.getTrace(),
|
||||
[
|
||||
"======== Resolving type reference directive 'typerefs1', containing file 'f1.ts', root directory 'node_modules/@types'. ========",
|
||||
"Resolving with primary search path 'node_modules/@types'.",
|
||||
@ -626,22 +626,22 @@ namespace ts {
|
||||
"File 'f1.ts' exist - use it as a name resolution result.",
|
||||
"======== Module name './f1' was successfully resolved to 'f1.ts'. ========"
|
||||
],
|
||||
"program_1: execute module resolution normally.");
|
||||
"program1: execute module resolution normally.");
|
||||
|
||||
const program_1Diagnostics = program_1.getSemanticDiagnostics(program_1.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program_1Diagnostics, expectedErrors, `initial program should be well-formed`);
|
||||
const program1Diagnostics = program1.getSemanticDiagnostics(program1.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program1Diagnostics, expectedErrors, `initial program should be well-formed`);
|
||||
}
|
||||
const indexOfF1 = 6;
|
||||
const program_2 = updateProgram(program_1, program_1.getRootFileNames(), options, f => {
|
||||
const program2 = updateProgram(program1, program1.getRootFileNames(), options, f => {
|
||||
const newSourceText = f[indexOfF1].text.updateReferences(`/// <reference path="a1.ts"/>${newLine}/// <reference types="typerefs1"/>`);
|
||||
f[indexOfF1] = { name: "f1.ts", text: newSourceText };
|
||||
});
|
||||
|
||||
{
|
||||
const program_2Diagnostics = program_2.getSemanticDiagnostics(program_2.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program_2Diagnostics, expectedErrors, `removing no-default-lib shouldn't affect any types used.`);
|
||||
const program2Diagnostics = program2.getSemanticDiagnostics(program2.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program2Diagnostics, expectedErrors, `removing no-default-lib shouldn't affect any types used.`);
|
||||
|
||||
assert.deepEqual(program_2.host.getTrace(), [
|
||||
assert.deepEqual(program2.host.getTrace(), [
|
||||
"======== Resolving type reference directive 'typerefs1', containing file 'f1.ts', root directory 'node_modules/@types'. ========",
|
||||
"Resolving with primary search path 'node_modules/@types'.",
|
||||
"File 'node_modules/@types/typerefs1/package.json' does not exist.",
|
||||
@ -658,19 +658,19 @@ namespace ts {
|
||||
"======== Type reference directive 'typerefs2' was successfully resolved to 'node_modules/@types/typerefs2/index.d.ts', primary: true. ========",
|
||||
"Reusing resolution of module './b2' to file 'f2.ts' from old program.",
|
||||
"Reusing resolution of module './f1' to file 'f2.ts' from old program."
|
||||
], "program_2: reuse module resolutions in f2 since it is unchanged");
|
||||
], "program2: reuse module resolutions in f2 since it is unchanged");
|
||||
}
|
||||
|
||||
const program_3 = updateProgram(program_2, program_2.getRootFileNames(), options, f => {
|
||||
const program3 = updateProgram(program2, program2.getRootFileNames(), options, f => {
|
||||
const newSourceText = f[indexOfF1].text.updateReferences(`/// <reference path="a1.ts"/>`);
|
||||
f[indexOfF1] = { name: "f1.ts", text: newSourceText };
|
||||
});
|
||||
|
||||
{
|
||||
const program_3Diagnostics = program_3.getSemanticDiagnostics(program_3.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program_3Diagnostics, expectedErrors, `typerefs2 was unused, so diagnostics should be unaffected.`);
|
||||
const program3Diagnostics = program3.getSemanticDiagnostics(program3.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program3Diagnostics, expectedErrors, `typerefs2 was unused, so diagnostics should be unaffected.`);
|
||||
|
||||
assert.deepEqual(program_3.host.getTrace(), [
|
||||
assert.deepEqual(program3.host.getTrace(), [
|
||||
"======== Resolving module './b1' from 'f1.ts'. ========",
|
||||
"Explicitly specified module resolution kind: 'Classic'.",
|
||||
"File 'b1.ts' exist - use it as a name resolution result.",
|
||||
@ -682,20 +682,20 @@ namespace ts {
|
||||
"======== Type reference directive 'typerefs2' was successfully resolved to 'node_modules/@types/typerefs2/index.d.ts', primary: true. ========",
|
||||
"Reusing resolution of module './b2' to file 'f2.ts' from old program.",
|
||||
"Reusing resolution of module './f1' to file 'f2.ts' from old program."
|
||||
], "program_3: reuse module resolutions in f2 since it is unchanged");
|
||||
], "program3: reuse module resolutions in f2 since it is unchanged");
|
||||
}
|
||||
|
||||
|
||||
const program_4 = updateProgram(program_3, program_3.getRootFileNames(), options, f => {
|
||||
const program4 = updateProgram(program3, program3.getRootFileNames(), options, f => {
|
||||
const newSourceText = f[indexOfF1].text.updateReferences("");
|
||||
f[indexOfF1] = { name: "f1.ts", text: newSourceText };
|
||||
});
|
||||
|
||||
{
|
||||
const program_4Diagnostics = program_4.getSemanticDiagnostics(program_4.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program_4Diagnostics, expectedErrors, `a1.ts was unused, so diagnostics should be unaffected.`);
|
||||
const program4Diagnostics = program4.getSemanticDiagnostics(program4.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program4Diagnostics, expectedErrors, `a1.ts was unused, so diagnostics should be unaffected.`);
|
||||
|
||||
assert.deepEqual(program_4.host.getTrace(), [
|
||||
assert.deepEqual(program4.host.getTrace(), [
|
||||
"======== Resolving module './b1' from 'f1.ts'. ========",
|
||||
"Explicitly specified module resolution kind: 'Classic'.",
|
||||
"File 'b1.ts' exist - use it as a name resolution result.",
|
||||
@ -710,16 +710,16 @@ namespace ts {
|
||||
], "program_4: reuse module resolutions in f2 since it is unchanged");
|
||||
}
|
||||
|
||||
const program_5 = updateProgram(program_4, program_4.getRootFileNames(), options, f => {
|
||||
const program5 = updateProgram(program4, program4.getRootFileNames(), options, f => {
|
||||
const newSourceText = f[indexOfF1].text.updateImportsAndExports(`import { B } from './b1';`);
|
||||
f[indexOfF1] = { name: "f1.ts", text: newSourceText };
|
||||
});
|
||||
|
||||
{
|
||||
const program_5Diagnostics = program_5.getSemanticDiagnostics(program_5.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program_5Diagnostics, ++expectedErrors, `import of BB in f1 fails. BB is of type any. Add one error`);
|
||||
const program5Diagnostics = program5.getSemanticDiagnostics(program5.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program5Diagnostics, ++expectedErrors, `import of BB in f1 fails. BB is of type any. Add one error`);
|
||||
|
||||
assert.deepEqual(program_5.host.getTrace(), [
|
||||
assert.deepEqual(program5.host.getTrace(), [
|
||||
"======== Resolving module './b1' from 'f1.ts'. ========",
|
||||
"Explicitly specified module resolution kind: 'Classic'.",
|
||||
"File 'b1.ts' exist - use it as a name resolution result.",
|
||||
@ -727,16 +727,16 @@ namespace ts {
|
||||
], "program_5: exports do not affect program structure, so f2's resolutions are silently reused.");
|
||||
}
|
||||
|
||||
const program_6 = updateProgram(program_5, program_5.getRootFileNames(), options, f => {
|
||||
const program6 = updateProgram(program5, program5.getRootFileNames(), options, f => {
|
||||
const newSourceText = f[indexOfF1].text.updateProgram("");
|
||||
f[indexOfF1] = { name: "f1.ts", text: newSourceText };
|
||||
});
|
||||
|
||||
{
|
||||
const program_6Diagnostics = program_6.getSemanticDiagnostics(program_6.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program_6Diagnostics, expectedErrors, `import of BB in f1 fails.`);
|
||||
const program6Diagnostics = program6.getSemanticDiagnostics(program6.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program6Diagnostics, expectedErrors, `import of BB in f1 fails.`);
|
||||
|
||||
assert.deepEqual(program_6.host.getTrace(), [
|
||||
assert.deepEqual(program6.host.getTrace(), [
|
||||
"======== Resolving module './b1' from 'f1.ts'. ========",
|
||||
"Explicitly specified module resolution kind: 'Classic'.",
|
||||
"File 'b1.ts' exist - use it as a name resolution result.",
|
||||
@ -751,16 +751,16 @@ namespace ts {
|
||||
], "program_6: reuse module resolutions in f2 since it is unchanged");
|
||||
}
|
||||
|
||||
const program_7 = updateProgram(program_6, program_6.getRootFileNames(), options, f => {
|
||||
const program7 = updateProgram(program6, program6.getRootFileNames(), options, f => {
|
||||
const newSourceText = f[indexOfF1].text.updateImportsAndExports("");
|
||||
f[indexOfF1] = { name: "f1.ts", text: newSourceText };
|
||||
});
|
||||
|
||||
{
|
||||
const program_7Diagnostics = program_7.getSemanticDiagnostics(program_7.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program_7Diagnostics, expectedErrors, `removing import is noop with respect to program, so no change in diagnostics.`);
|
||||
const program7Diagnostics = program7.getSemanticDiagnostics(program7.getSourceFile("f2.ts"));
|
||||
assert.lengthOf(program7Diagnostics, expectedErrors, `removing import is noop with respect to program, so no change in diagnostics.`);
|
||||
|
||||
assert.deepEqual(program_7.host.getTrace(), [
|
||||
assert.deepEqual(program7.host.getTrace(), [
|
||||
"======== Resolving type reference directive 'typerefs2', containing file 'f2.ts', root directory 'node_modules/@types'. ========",
|
||||
"Resolving with primary search path 'node_modules/@types'.",
|
||||
"File 'node_modules/@types/typerefs2/package.json' does not exist.",
|
||||
@ -820,47 +820,47 @@ namespace ts {
|
||||
}
|
||||
|
||||
it("No changes -> redirect not broken", () => {
|
||||
const program_1 = createRedirectProgram();
|
||||
const program1 = createRedirectProgram();
|
||||
|
||||
const program_2 = updateRedirectProgram(program_1, files => {
|
||||
const program2 = updateRedirectProgram(program1, files => {
|
||||
updateProgramText(files, root, "const x = 1;");
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Completely);
|
||||
assert.deepEqual(program_2.getSemanticDiagnostics(), emptyArray);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Completely);
|
||||
assert.deepEqual(program2.getSemanticDiagnostics(), emptyArray);
|
||||
});
|
||||
|
||||
it("Target changes -> redirect broken", () => {
|
||||
const program_1 = createRedirectProgram();
|
||||
assert.deepEqual(program_1.getSemanticDiagnostics(), emptyArray);
|
||||
const program1 = createRedirectProgram();
|
||||
assert.deepEqual(program1.getSemanticDiagnostics(), emptyArray);
|
||||
|
||||
const program_2 = updateRedirectProgram(program_1, files => {
|
||||
const program2 = updateRedirectProgram(program1, files => {
|
||||
updateProgramText(files, axIndex, "export default class X { private x: number; private y: number; }");
|
||||
updateProgramText(files, axPackage, JSON.stringify('{ name: "x", version: "1.2.4" }'));
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Not);
|
||||
assert.lengthOf(program_2.getSemanticDiagnostics(), 1);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Not);
|
||||
assert.lengthOf(program2.getSemanticDiagnostics(), 1);
|
||||
});
|
||||
|
||||
it("Underlying changes -> redirect broken", () => {
|
||||
const program_1 = createRedirectProgram();
|
||||
const program1 = createRedirectProgram();
|
||||
|
||||
const program_2 = updateRedirectProgram(program_1, files => {
|
||||
const program2 = updateRedirectProgram(program1, files => {
|
||||
updateProgramText(files, bxIndex, "export default class X { private x: number; private y: number; }");
|
||||
updateProgramText(files, bxPackage, JSON.stringify({ name: "x", version: "1.2.4" }));
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Not);
|
||||
assert.lengthOf(program_2.getSemanticDiagnostics(), 1);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Not);
|
||||
assert.lengthOf(program2.getSemanticDiagnostics(), 1);
|
||||
});
|
||||
|
||||
it("Previously duplicate packages -> program structure not reused", () => {
|
||||
const program_1 = createRedirectProgram({ bVersion: "1.2.4", bText: "export = class X { private x: number; }" });
|
||||
const program1 = createRedirectProgram({ bVersion: "1.2.4", bText: "export = class X { private x: number; }" });
|
||||
|
||||
const program_2 = updateRedirectProgram(program_1, files => {
|
||||
const program2 = updateRedirectProgram(program1, files => {
|
||||
updateProgramText(files, bxIndex, "export default class X { private x: number; }");
|
||||
updateProgramText(files, bxPackage, JSON.stringify({ name: "x", version: "1.2.3" }));
|
||||
});
|
||||
assert.equal(program_1.structureIsReused, StructureIsReused.Not);
|
||||
assert.deepEqual(program_2.getSemanticDiagnostics(), []);
|
||||
assert.equal(program1.structureIsReused, StructureIsReused.Not);
|
||||
assert.deepEqual(program2.getSemanticDiagnostics(), []);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -9,10 +9,12 @@
|
||||
namespace ts.server {
|
||||
export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
|
||||
|
||||
// tslint:disable variable-name
|
||||
export const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
|
||||
export const ConfigFileDiagEvent = "configFileDiag";
|
||||
export const ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
|
||||
export const ProjectInfoTelemetryEvent = "projectInfo";
|
||||
// tslint:enable variable-name
|
||||
|
||||
export interface ProjectsUpdatedInBackgroundEvent {
|
||||
eventName: typeof ProjectsUpdatedInBackgroundEvent;
|
||||
@ -1061,7 +1063,7 @@ namespace ts.server {
|
||||
* Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project
|
||||
*/
|
||||
private configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo: ConfigFileExistenceInfo) {
|
||||
return forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, (isRootOfInferredProject, __key) => isRootOfInferredProject);
|
||||
return forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, (isRootOfInferredProject) => isRootOfInferredProject);
|
||||
}
|
||||
|
||||
private setConfigFileExistenceInfoByClosedConfiguredProject(closedProject: ConfiguredProject) {
|
||||
|
||||
@ -124,7 +124,7 @@ namespace ts.server {
|
||||
// we want to ensure the value is maintained in the out since the file is
|
||||
// built using --preseveConstEnum.
|
||||
export type CommandNames = protocol.CommandTypes;
|
||||
export const CommandNames = (<any>protocol).CommandTypes;
|
||||
export const CommandNames = (<any>protocol).CommandTypes; // tslint:disable-line variable-name
|
||||
|
||||
export function formatMessage<T extends protocol.Message>(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string {
|
||||
const verboseLogging = logger.hasLevel(LogLevel.verbose);
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
/// <reference path="types.ts" />
|
||||
|
||||
namespace ts.server {
|
||||
// tslint:disable variable-name
|
||||
export const ActionSet: ActionSet = "action::set";
|
||||
export const ActionInvalidate: ActionInvalidate = "action::invalidate";
|
||||
export const EventTypesRegistry: EventTypesRegistry = "event::typesRegistry";
|
||||
|
||||
@ -63,9 +63,9 @@ namespace ts.server.typingsInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
const TypesRegistryPackageName = "types-registry";
|
||||
const typesRegistryPackageName = "types-registry";
|
||||
function getTypesRegistryFileLocation(globalTypingsCacheLocation: string): string {
|
||||
return combinePaths(normalizeSlashes(globalTypingsCacheLocation), `node_modules/${TypesRegistryPackageName}/index.json`);
|
||||
return combinePaths(normalizeSlashes(globalTypingsCacheLocation), `node_modules/${typesRegistryPackageName}/index.json`);
|
||||
}
|
||||
|
||||
interface ExecSyncOptions {
|
||||
@ -105,16 +105,16 @@ namespace ts.server.typingsInstaller {
|
||||
|
||||
try {
|
||||
if (this.log.isEnabled()) {
|
||||
this.log.writeLine(`Updating ${TypesRegistryPackageName} npm package...`);
|
||||
this.log.writeLine(`Updating ${typesRegistryPackageName} npm package...`);
|
||||
}
|
||||
this.execSyncAndLog(`${this.npmPath} install --ignore-scripts ${TypesRegistryPackageName}`, { cwd: globalTypingsCacheLocation });
|
||||
this.execSyncAndLog(`${this.npmPath} install --ignore-scripts ${typesRegistryPackageName}`, { cwd: globalTypingsCacheLocation });
|
||||
if (this.log.isEnabled()) {
|
||||
this.log.writeLine(`Updated ${TypesRegistryPackageName} npm package`);
|
||||
this.log.writeLine(`Updated ${typesRegistryPackageName} npm package`);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
if (this.log.isEnabled()) {
|
||||
this.log.writeLine(`Error updating ${TypesRegistryPackageName} package: ${(<Error>e).message}`);
|
||||
this.log.writeLine(`Error updating ${typesRegistryPackageName} package: ${(<Error>e).message}`);
|
||||
}
|
||||
// store error info to report it later when it is known that server is already listening to events from typings installer
|
||||
this.delayedInitializationError = {
|
||||
@ -243,7 +243,7 @@ namespace ts.server.typingsInstaller {
|
||||
const installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, /*throttleLimit*/5, log);
|
||||
installer.listen();
|
||||
|
||||
function indent(newline: string, string: string): string {
|
||||
return `${newline} ` + string.replace(/\r?\n/, `${newline} `);
|
||||
function indent(newline: string, str: string): string {
|
||||
return `${newline} ` + str.replace(/\r?\n/, `${newline} `);
|
||||
}
|
||||
}
|
||||
|
||||
@ -24,6 +24,7 @@ namespace ts.server {
|
||||
}
|
||||
|
||||
export namespace Msg {
|
||||
// tslint:disable variable-name
|
||||
export type Err = "Err";
|
||||
export const Err: Err = "Err";
|
||||
export type Info = "Info";
|
||||
@ -31,6 +32,7 @@ namespace ts.server {
|
||||
export type Perf = "Perf";
|
||||
export const Perf: Perf = "Perf";
|
||||
export type Types = Err | Info | Perf;
|
||||
// tslint:enable variable-name
|
||||
}
|
||||
|
||||
function getProjectRootPath(project: Project): Path {
|
||||
@ -320,8 +322,8 @@ namespace ts.server {
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function indent(string: string): string {
|
||||
return "\n " + string;
|
||||
export function indent(str: string): string {
|
||||
return "\n " + str;
|
||||
}
|
||||
|
||||
/** Put stringified JSON on the next line, indented. */
|
||||
|
||||
@ -924,7 +924,7 @@ namespace ts.formatting {
|
||||
if (rule) {
|
||||
applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine);
|
||||
|
||||
if (rule.Operation.Action & (RuleAction.Space | RuleAction.Delete) && currentStartLine !== previousStartLine) {
|
||||
if (rule.operation.action & (RuleAction.Space | RuleAction.Delete) && currentStartLine !== previousStartLine) {
|
||||
lineAdded = false;
|
||||
// Handle the case where the next line is moved to be the end of this line.
|
||||
// In this case we don't indent the next line in the next pass.
|
||||
@ -932,7 +932,7 @@ namespace ts.formatting {
|
||||
dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false);
|
||||
}
|
||||
}
|
||||
else if (rule.Operation.Action & RuleAction.NewLine && currentStartLine === previousStartLine) {
|
||||
else if (rule.operation.action & RuleAction.NewLine && currentStartLine === previousStartLine) {
|
||||
lineAdded = true;
|
||||
// Handle the case where token2 is moved to the new line.
|
||||
// In this case we indent token2 in the next pass but we set
|
||||
@ -943,7 +943,7 @@ namespace ts.formatting {
|
||||
}
|
||||
|
||||
// We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line
|
||||
trimTrailingWhitespaces = !(rule.Operation.Action & RuleAction.Delete) && rule.Flag !== RuleFlags.CanDeleteNewLines;
|
||||
trimTrailingWhitespaces = !(rule.operation.action & RuleAction.Delete) && rule.flag !== RuleFlags.CanDeleteNewLines;
|
||||
}
|
||||
else {
|
||||
trimTrailingWhitespaces = true;
|
||||
@ -1118,7 +1118,7 @@ namespace ts.formatting {
|
||||
currentRange: TextRangeWithKind,
|
||||
currentStartLine: number): void {
|
||||
|
||||
switch (rule.Operation.Action) {
|
||||
switch (rule.operation.action) {
|
||||
case RuleAction.Ignore:
|
||||
// no action required
|
||||
return;
|
||||
@ -1132,7 +1132,7 @@ namespace ts.formatting {
|
||||
// exit early if we on different lines and rule cannot change number of newlines
|
||||
// if line1 and line2 are on subsequent lines then no edits are required - ok to exit
|
||||
// if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines
|
||||
if (rule.Flag !== RuleFlags.CanDeleteNewLines && previousStartLine !== currentStartLine) {
|
||||
if (rule.flag !== RuleFlags.CanDeleteNewLines && previousStartLine !== currentStartLine) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -1144,7 +1144,7 @@ namespace ts.formatting {
|
||||
break;
|
||||
case RuleAction.Space:
|
||||
// exit early if we on different lines and rule cannot change number of newlines
|
||||
if (rule.Flag !== RuleFlags.CanDeleteNewLines && previousStartLine !== currentStartLine) {
|
||||
if (rule.flag !== RuleFlags.CanDeleteNewLines && previousStartLine !== currentStartLine) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@ -6,9 +6,9 @@ namespace ts.formatting {
|
||||
// Used for debugging to identify each rule based on the property name it's assigned to.
|
||||
public debugName?: string;
|
||||
constructor(
|
||||
readonly Descriptor: RuleDescriptor,
|
||||
readonly Operation: RuleOperation,
|
||||
readonly Flag: RuleFlags = RuleFlags.None) {
|
||||
readonly descriptor: RuleDescriptor,
|
||||
readonly operation: RuleOperation,
|
||||
readonly flag: RuleFlags = RuleFlags.None) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -3,12 +3,12 @@
|
||||
/* @internal */
|
||||
namespace ts.formatting {
|
||||
export class RuleDescriptor {
|
||||
constructor(public LeftTokenRange: Shared.TokenRange, public RightTokenRange: Shared.TokenRange) {
|
||||
constructor(public leftTokenRange: Shared.TokenRange, public rightTokenRange: Shared.TokenRange) {
|
||||
}
|
||||
|
||||
public toString(): string {
|
||||
return "[leftRange=" + this.LeftTokenRange + "," +
|
||||
"rightRange=" + this.RightTokenRange + "]";
|
||||
return "[leftRange=" + this.leftTokenRange + "," +
|
||||
"rightRange=" + this.rightTokenRange + "]";
|
||||
}
|
||||
|
||||
static create1(left: SyntaxKind, right: SyntaxKind): RuleDescriptor {
|
||||
|
||||
@ -3,15 +3,15 @@
|
||||
/* @internal */
|
||||
namespace ts.formatting {
|
||||
export class RuleOperation {
|
||||
constructor(public Context: RuleOperationContext, public Action: RuleAction) {}
|
||||
constructor(readonly context: RuleOperationContext, readonly action: RuleAction) {}
|
||||
|
||||
public toString(): string {
|
||||
return "[context=" + this.Context + "," +
|
||||
"action=" + this.Action + "]";
|
||||
return "[context=" + this.context + "," +
|
||||
"action=" + this.action + "]";
|
||||
}
|
||||
|
||||
static create1(action: RuleAction) {
|
||||
return RuleOperation.create2(RuleOperationContext.Any, action);
|
||||
return RuleOperation.create2(RuleOperationContext.any, action);
|
||||
}
|
||||
|
||||
static create2(context: RuleOperationContext, action: RuleAction) {
|
||||
|
||||
@ -10,10 +10,10 @@ namespace ts.formatting {
|
||||
this.customContextChecks = funcs;
|
||||
}
|
||||
|
||||
static readonly Any: RuleOperationContext = new RuleOperationContext();
|
||||
static readonly any: RuleOperationContext = new RuleOperationContext();
|
||||
|
||||
public IsAny(): boolean {
|
||||
return this === RuleOperationContext.Any;
|
||||
return this === RuleOperationContext.any;
|
||||
}
|
||||
|
||||
public InContext(context: FormattingContext): boolean {
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
/* @internal */
|
||||
namespace ts.formatting {
|
||||
// tslint:disable variable-name (TODO)
|
||||
export class Rules {
|
||||
public IgnoreBeforeComment: Rule;
|
||||
public IgnoreAfterLineComment: Rule;
|
||||
|
||||
@ -23,10 +23,10 @@ namespace ts.formatting {
|
||||
}
|
||||
|
||||
private FillRule(rule: Rule, rulesBucketConstructionStateList: RulesBucketConstructionState[]): void {
|
||||
const specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific();
|
||||
const specificRule = rule.descriptor.leftTokenRange.isSpecific() && rule.descriptor.rightTokenRange.isSpecific();
|
||||
|
||||
rule.Descriptor.LeftTokenRange.GetTokens().forEach((left) => {
|
||||
rule.Descriptor.RightTokenRange.GetTokens().forEach((right) => {
|
||||
rule.descriptor.leftTokenRange.GetTokens().forEach((left) => {
|
||||
rule.descriptor.rightTokenRange.GetTokens().forEach((right) => {
|
||||
const rulesBucketIndex = this.GetRuleBucketIndex(left, right);
|
||||
|
||||
let rulesBucket = this.map[rulesBucketIndex];
|
||||
@ -44,7 +44,7 @@ namespace ts.formatting {
|
||||
const bucket = this.map[bucketIndex];
|
||||
if (bucket) {
|
||||
for (const rule of bucket.Rules()) {
|
||||
if (rule.Operation.Context.InContext(context)) {
|
||||
if (rule.operation.context.InContext(context)) {
|
||||
return rule;
|
||||
}
|
||||
}
|
||||
@ -53,16 +53,16 @@ namespace ts.formatting {
|
||||
}
|
||||
}
|
||||
|
||||
const MaskBitSize = 5;
|
||||
const Mask = 0x1f;
|
||||
const maskBitSize = 5;
|
||||
const mask = 0x1f;
|
||||
|
||||
enum RulesPosition {
|
||||
IgnoreRulesSpecific = 0,
|
||||
IgnoreRulesAny = MaskBitSize * 1,
|
||||
ContextRulesSpecific = MaskBitSize * 2,
|
||||
ContextRulesAny = MaskBitSize * 3,
|
||||
NoContextRulesSpecific = MaskBitSize * 4,
|
||||
NoContextRulesAny = MaskBitSize * 5
|
||||
IgnoreRulesAny = maskBitSize * 1,
|
||||
ContextRulesSpecific = maskBitSize * 2,
|
||||
ContextRulesAny = maskBitSize * 3,
|
||||
NoContextRulesSpecific = maskBitSize * 4,
|
||||
NoContextRulesAny = maskBitSize * 5
|
||||
}
|
||||
|
||||
export class RulesBucketConstructionState {
|
||||
@ -94,20 +94,20 @@ namespace ts.formatting {
|
||||
let indexBitmap = this.rulesInsertionIndexBitmap;
|
||||
|
||||
while (pos <= maskPosition) {
|
||||
index += (indexBitmap & Mask);
|
||||
indexBitmap >>= MaskBitSize;
|
||||
pos += MaskBitSize;
|
||||
index += (indexBitmap & mask);
|
||||
indexBitmap >>= maskBitSize;
|
||||
pos += maskBitSize;
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
public IncreaseInsertionIndex(maskPosition: RulesPosition): void {
|
||||
let value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask;
|
||||
let value = (this.rulesInsertionIndexBitmap >> maskPosition) & mask;
|
||||
value++;
|
||||
Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
|
||||
Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
|
||||
|
||||
let temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition);
|
||||
let temp = this.rulesInsertionIndexBitmap & ~(mask << maskPosition);
|
||||
temp |= value << maskPosition;
|
||||
|
||||
this.rulesInsertionIndexBitmap = temp;
|
||||
@ -128,12 +128,12 @@ namespace ts.formatting {
|
||||
public AddRule(rule: Rule, specificTokens: boolean, constructionState: RulesBucketConstructionState[], rulesBucketIndex: number): void {
|
||||
let position: RulesPosition;
|
||||
|
||||
if (rule.Operation.Action === RuleAction.Ignore) {
|
||||
if (rule.operation.action === RuleAction.Ignore) {
|
||||
position = specificTokens ?
|
||||
RulesPosition.IgnoreRulesSpecific :
|
||||
RulesPosition.IgnoreRulesAny;
|
||||
}
|
||||
else if (!rule.Operation.Context.IsAny()) {
|
||||
else if (!rule.operation.context.IsAny()) {
|
||||
position = specificTokens ?
|
||||
RulesPosition.ContextRulesSpecific :
|
||||
RulesPosition.ContextRulesAny;
|
||||
|
||||
@ -95,6 +95,7 @@ namespace ts.formatting {
|
||||
return new TokenAllExceptAccess(token);
|
||||
}
|
||||
|
||||
// tslint:disable variable-name (TODO)
|
||||
export const Any: TokenRange = new TokenAllAccess();
|
||||
export const AnyIncludingMultilineComments = TokenRange.FromTokens([...allTokens, SyntaxKind.MultiLineCommentTrivia]);
|
||||
export const Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword);
|
||||
|
||||
@ -257,7 +257,7 @@ namespace ts.JsTyping {
|
||||
NameContainsNonURISafeCharacters
|
||||
}
|
||||
|
||||
const MaxPackageNameLength = 214;
|
||||
const maxPackageNameLength = 214;
|
||||
|
||||
/**
|
||||
* Validates package name using rules defined at https://docs.npmjs.com/files/package.json
|
||||
@ -266,7 +266,7 @@ namespace ts.JsTyping {
|
||||
if (!packageName) {
|
||||
return PackageNameValidationResult.EmptyName;
|
||||
}
|
||||
if (packageName.length > MaxPackageNameLength) {
|
||||
if (packageName.length > maxPackageNameLength) {
|
||||
return PackageNameValidationResult.NameTooLong;
|
||||
}
|
||||
if (packageName.charCodeAt(0) === CharacterCodes.dot) {
|
||||
@ -292,7 +292,7 @@ namespace ts.JsTyping {
|
||||
case PackageNameValidationResult.EmptyName:
|
||||
return `Package name '${typing}' cannot be empty`;
|
||||
case PackageNameValidationResult.NameTooLong:
|
||||
return `Package name '${typing}' should be less than ${MaxPackageNameLength} characters`;
|
||||
return `Package name '${typing}' should be less than ${maxPackageNameLength} characters`;
|
||||
case PackageNameValidationResult.NameStartsWithDot:
|
||||
return `Package name '${typing}' cannot start with '.'`;
|
||||
case PackageNameValidationResult.NameStartsWithUnderscore:
|
||||
|
||||
@ -515,10 +515,10 @@ namespace ts {
|
||||
}
|
||||
|
||||
// Assumes 'value' is already lowercase.
|
||||
function indexOfIgnoringCase(string: string, value: string): number {
|
||||
const n = string.length - value.length;
|
||||
function indexOfIgnoringCase(str: string, value: string): number {
|
||||
const n = str.length - value.length;
|
||||
for (let i = 0; i <= n; i++) {
|
||||
if (startsWithIgnoringCase(string, value, i)) {
|
||||
if (startsWithIgnoringCase(str, value, i)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
@ -527,9 +527,9 @@ namespace ts {
|
||||
}
|
||||
|
||||
// Assumes 'value' is already lowercase.
|
||||
function startsWithIgnoringCase(string: string, value: string, start: number): boolean {
|
||||
function startsWithIgnoringCase(str: string, value: string, start: number): boolean {
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
const ch1 = toLowerCase(string.charCodeAt(i + start));
|
||||
const ch1 = toLowerCase(str.charCodeAt(i + start));
|
||||
const ch2 = value.charCodeAt(i);
|
||||
|
||||
if (ch1 !== ch2) {
|
||||
|
||||
@ -122,28 +122,28 @@ namespace ts.refactor.extractSymbol {
|
||||
return { message, code: 0, category: DiagnosticCategory.Message, key: message };
|
||||
}
|
||||
|
||||
export const CannotExtractRange: DiagnosticMessage = createMessage("Cannot extract range.");
|
||||
export const CannotExtractImport: DiagnosticMessage = createMessage("Cannot extract import statement.");
|
||||
export const CannotExtractSuper: DiagnosticMessage = createMessage("Cannot extract super call.");
|
||||
export const CannotExtractEmpty: DiagnosticMessage = createMessage("Cannot extract empty range.");
|
||||
export const ExpressionExpected: DiagnosticMessage = createMessage("expression expected.");
|
||||
export const UselessConstantType: DiagnosticMessage = createMessage("No reason to extract constant of type.");
|
||||
export const StatementOrExpressionExpected: DiagnosticMessage = createMessage("Statement or expression expected.");
|
||||
export const CannotExtractRangeContainingConditionalBreakOrContinueStatements: DiagnosticMessage = createMessage("Cannot extract range containing conditional break or continue statements.");
|
||||
export const CannotExtractRangeContainingConditionalReturnStatement: DiagnosticMessage = createMessage("Cannot extract range containing conditional return statement.");
|
||||
export const CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange: DiagnosticMessage = createMessage("Cannot extract range containing labeled break or continue with target outside of the range.");
|
||||
export const CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators: DiagnosticMessage = createMessage("Cannot extract range containing writes to references located outside of the target range in generators.");
|
||||
export const TypeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope.");
|
||||
export const FunctionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope.");
|
||||
export const CannotExtractIdentifier = createMessage("Select more than a single identifier.");
|
||||
export const CannotExtractExportedEntity = createMessage("Cannot extract exported declaration");
|
||||
export const CannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression");
|
||||
export const CannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor");
|
||||
export const CannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts");
|
||||
export const CannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
|
||||
export const CannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function");
|
||||
export const CannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS");
|
||||
export const CannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block");
|
||||
export const cannotExtractRange: DiagnosticMessage = createMessage("Cannot extract range.");
|
||||
export const cannotExtractImport: DiagnosticMessage = createMessage("Cannot extract import statement.");
|
||||
export const cannotExtractSuper: DiagnosticMessage = createMessage("Cannot extract super call.");
|
||||
export const cannotExtractEmpty: DiagnosticMessage = createMessage("Cannot extract empty range.");
|
||||
export const expressionExpected: DiagnosticMessage = createMessage("expression expected.");
|
||||
export const uselessConstantType: DiagnosticMessage = createMessage("No reason to extract constant of type.");
|
||||
export const statementOrExpressionExpected: DiagnosticMessage = createMessage("Statement or expression expected.");
|
||||
export const cannotExtractRangeContainingConditionalBreakOrContinueStatements: DiagnosticMessage = createMessage("Cannot extract range containing conditional break or continue statements.");
|
||||
export const cannotExtractRangeContainingConditionalReturnStatement: DiagnosticMessage = createMessage("Cannot extract range containing conditional return statement.");
|
||||
export const cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange: DiagnosticMessage = createMessage("Cannot extract range containing labeled break or continue with target outside of the range.");
|
||||
export const cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators: DiagnosticMessage = createMessage("Cannot extract range containing writes to references located outside of the target range in generators.");
|
||||
export const typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope.");
|
||||
export const functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope.");
|
||||
export const cannotExtractIdentifier = createMessage("Select more than a single identifier.");
|
||||
export const cannotExtractExportedEntity = createMessage("Cannot extract exported declaration");
|
||||
export const cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression");
|
||||
export const cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor");
|
||||
export const cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts");
|
||||
export const cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes");
|
||||
export const cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function");
|
||||
export const cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS");
|
||||
export const cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block");
|
||||
}
|
||||
|
||||
enum RangeFacts {
|
||||
@ -198,7 +198,7 @@ namespace ts.refactor.extractSymbol {
|
||||
const { length } = span;
|
||||
|
||||
if (length === 0) {
|
||||
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractEmpty)] };
|
||||
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractEmpty)] };
|
||||
}
|
||||
|
||||
// Walk up starting from the the start position until we find a non-SourceFile node that subsumes the selected span.
|
||||
@ -215,18 +215,18 @@ namespace ts.refactor.extractSymbol {
|
||||
|
||||
if (!start || !end) {
|
||||
// cannot find either start or end node
|
||||
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractRange)] };
|
||||
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
|
||||
}
|
||||
|
||||
if (start.parent !== end.parent) {
|
||||
// start and end nodes belong to different subtrees
|
||||
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractRange)] };
|
||||
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
|
||||
}
|
||||
|
||||
if (start !== end) {
|
||||
// start and end should be statements and parent should be either block or a source file
|
||||
if (!isBlockLike(start.parent)) {
|
||||
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractRange)] };
|
||||
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
|
||||
}
|
||||
const statements: Statement[] = [];
|
||||
for (const statement of (<BlockLike>start.parent).statements) {
|
||||
@ -246,7 +246,7 @@ namespace ts.refactor.extractSymbol {
|
||||
|
||||
if (isReturnStatement(start) && !start.expression) {
|
||||
// Makes no sense to extract an expression-less return statement.
|
||||
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.CannotExtractRange)] };
|
||||
return { errors: [createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] };
|
||||
}
|
||||
|
||||
// We have a single node (start)
|
||||
@ -293,7 +293,7 @@ namespace ts.refactor.extractSymbol {
|
||||
|
||||
function checkRootNode(node: Node): Diagnostic[] | undefined {
|
||||
if (isIdentifier(isExpressionStatement(node) ? node.expression : node)) {
|
||||
return [createDiagnosticForNode(node, Messages.CannotExtractIdentifier)];
|
||||
return [createDiagnosticForNode(node, Messages.cannotExtractIdentifier)];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@ -332,11 +332,11 @@ namespace ts.refactor.extractSymbol {
|
||||
Return = 1 << 2
|
||||
}
|
||||
if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) {
|
||||
return [createDiagnosticForNode(nodeToCheck, Messages.StatementOrExpressionExpected)];
|
||||
return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)];
|
||||
}
|
||||
|
||||
if (nodeToCheck.flags & NodeFlags.Ambient) {
|
||||
return [createDiagnosticForNode(nodeToCheck, Messages.CannotExtractAmbientBlock)];
|
||||
return [createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)];
|
||||
}
|
||||
|
||||
// If we're in a class, see whether we're in a static region (static property initializer, static method, class constructor parameter default)
|
||||
@ -362,7 +362,7 @@ namespace ts.refactor.extractSymbol {
|
||||
if (isDeclaration(node)) {
|
||||
const declaringNode = (node.kind === SyntaxKind.VariableDeclaration) ? node.parent.parent : node;
|
||||
if (hasModifier(declaringNode, ModifierFlags.Export)) {
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.CannotExtractExportedEntity));
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.cannotExtractExportedEntity));
|
||||
return true;
|
||||
}
|
||||
declarations.push(node.symbol);
|
||||
@ -371,7 +371,7 @@ namespace ts.refactor.extractSymbol {
|
||||
// Some things can't be extracted in certain situations
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.ImportDeclaration:
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.CannotExtractImport));
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.cannotExtractImport));
|
||||
return true;
|
||||
case SyntaxKind.SuperKeyword:
|
||||
// For a super *constructor call*, we have to be extracting the entire class,
|
||||
@ -380,7 +380,7 @@ namespace ts.refactor.extractSymbol {
|
||||
// Super constructor call
|
||||
const containingClass = getContainingClass(node);
|
||||
if (containingClass.pos < span.start || containingClass.end >= (span.start + span.length)) {
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.CannotExtractSuper));
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.cannotExtractSuper));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -396,7 +396,7 @@ namespace ts.refactor.extractSymbol {
|
||||
case SyntaxKind.ClassDeclaration:
|
||||
if (node.parent.kind === SyntaxKind.SourceFile && (node.parent as ts.SourceFile).externalModuleIndicator === undefined) {
|
||||
// You cannot extract global declarations
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.FunctionWillNotBeVisibleInTheNewScope));
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope));
|
||||
}
|
||||
break;
|
||||
}
|
||||
@ -452,13 +452,13 @@ namespace ts.refactor.extractSymbol {
|
||||
if (label) {
|
||||
if (!contains(seenLabels, label.escapedText)) {
|
||||
// attempts to jump to label that is not in range to be extracted
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.CannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange));
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange));
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (!(permittedJumps & (node.kind === SyntaxKind.BreakStatement ? PermittedJumps.Break : PermittedJumps.Continue))) {
|
||||
// attempt to break or continue in a forbidden context
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalBreakOrContinueStatements));
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements));
|
||||
}
|
||||
}
|
||||
break;
|
||||
@ -474,7 +474,7 @@ namespace ts.refactor.extractSymbol {
|
||||
rangeFacts |= RangeFacts.HasReturn;
|
||||
}
|
||||
else {
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.CannotExtractRangeContainingConditionalReturnStatement));
|
||||
(errors || (errors = [])).push(createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalReturnStatement));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
@ -1455,10 +1455,10 @@ namespace ts.refactor.extractSymbol {
|
||||
const statements = targetRange.range as ReadonlyArray<Statement>;
|
||||
const start = first(statements).getStart();
|
||||
const end = last(statements).end;
|
||||
expressionDiagnostic = createFileDiagnostic(sourceFile, start, end - start, Messages.ExpressionExpected);
|
||||
expressionDiagnostic = createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected);
|
||||
}
|
||||
else if (checker.getTypeAtLocation(expression).flags & (TypeFlags.Void | TypeFlags.Never)) {
|
||||
expressionDiagnostic = createDiagnosticForNode(expression, Messages.UselessConstantType);
|
||||
expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType);
|
||||
}
|
||||
|
||||
// initialize results
|
||||
@ -1468,7 +1468,7 @@ namespace ts.refactor.extractSymbol {
|
||||
|
||||
functionErrorsPerScope.push(
|
||||
isFunctionLikeDeclaration(scope) && scope.kind !== SyntaxKind.FunctionDeclaration
|
||||
? [createDiagnosticForNode(scope, Messages.CannotExtractToOtherFunctionLike)]
|
||||
? [createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)]
|
||||
: []);
|
||||
|
||||
const constantErrors = [];
|
||||
@ -1476,11 +1476,11 @@ namespace ts.refactor.extractSymbol {
|
||||
constantErrors.push(expressionDiagnostic);
|
||||
}
|
||||
if (isClassLike(scope) && isInJavaScriptFile(scope)) {
|
||||
constantErrors.push(createDiagnosticForNode(scope, Messages.CannotExtractToJSClass));
|
||||
constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass));
|
||||
}
|
||||
if (isArrowFunction(scope) && !isBlock(scope.body)) {
|
||||
// TODO (https://github.com/Microsoft/TypeScript/issues/18924): allow this
|
||||
constantErrors.push(createDiagnosticForNode(scope, Messages.CannotExtractToExpressionArrowFunction));
|
||||
constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction));
|
||||
}
|
||||
constantErrorsPerScope.push(constantErrors);
|
||||
}
|
||||
@ -1548,7 +1548,7 @@ namespace ts.refactor.extractSymbol {
|
||||
// local will actually be declared at the same level as the extracted expression).
|
||||
if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) {
|
||||
const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range;
|
||||
constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.CannotAccessVariablesFromNestedScopes));
|
||||
constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes));
|
||||
}
|
||||
|
||||
let hasWrite = false;
|
||||
@ -1568,17 +1568,17 @@ namespace ts.refactor.extractSymbol {
|
||||
Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0);
|
||||
|
||||
if (hasWrite && !isReadonlyArray(targetRange.range)) {
|
||||
const diag = createDiagnosticForNode(targetRange.range, Messages.CannotWriteInExpression);
|
||||
const diag = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression);
|
||||
functionErrorsPerScope[i].push(diag);
|
||||
constantErrorsPerScope[i].push(diag);
|
||||
}
|
||||
else if (readonlyClassPropertyWrite && i > 0) {
|
||||
const diag = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.CannotExtractReadonlyPropertyInitializerOutsideConstructor);
|
||||
const diag = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor);
|
||||
functionErrorsPerScope[i].push(diag);
|
||||
constantErrorsPerScope[i].push(diag);
|
||||
}
|
||||
else if (firstExposedNonVariableDeclaration) {
|
||||
const diag = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.CannotExtractExportedEntity);
|
||||
const diag = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity);
|
||||
functionErrorsPerScope[i].push(diag);
|
||||
constantErrorsPerScope[i].push(diag);
|
||||
}
|
||||
@ -1710,7 +1710,7 @@ namespace ts.refactor.extractSymbol {
|
||||
if (targetRange.facts & RangeFacts.IsGenerator && usage === Usage.Write) {
|
||||
// this is write to a reference located outside of the target scope and range is extracted into generator
|
||||
// currently this is unsupported scenario
|
||||
const diag = createDiagnosticForNode(identifier, Messages.CannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators);
|
||||
const diag = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators);
|
||||
for (const errors of functionErrorsPerScope) {
|
||||
errors.push(diag);
|
||||
}
|
||||
@ -1733,7 +1733,7 @@ namespace ts.refactor.extractSymbol {
|
||||
// If the symbol is a type parameter that won't be in scope, we'll pass it as a type argument
|
||||
// so there's no problem.
|
||||
if (!(symbol.flags & SymbolFlags.TypeParameter)) {
|
||||
const diag = createDiagnosticForNode(identifier, Messages.TypeWillNotBeVisibleInTheNewScope);
|
||||
const diag = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope);
|
||||
functionErrorsPerScope[i].push(diag);
|
||||
constantErrorsPerScope[i].push(diag);
|
||||
}
|
||||
|
||||
@ -1997,9 +1997,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function isNodeModulesFile(path: string): boolean {
|
||||
const node_modulesFolderName = "/node_modules/";
|
||||
|
||||
return stringContains(path, node_modulesFolderName);
|
||||
return stringContains(path, "/node_modules/");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -74,6 +74,7 @@
|
||||
|
||||
// Config different from tslint:latest
|
||||
"no-implicit-dependencies": [true, "dev"],
|
||||
"variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore"],
|
||||
|
||||
// TODO
|
||||
"arrow-parens": false, // [true, "ban-single-arg-parens"]
|
||||
@ -102,7 +103,6 @@
|
||||
"space-before-function-paren": false,
|
||||
"trailing-comma": false,
|
||||
"unified-signatures": false,
|
||||
"variable-name": false,
|
||||
|
||||
// These should be done automatically by a formatter. https://github.com/Microsoft/TypeScript/issues/18340
|
||||
"align": false,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user