Respond to PR comments

This commit is contained in:
Andy Hanson 2016-10-27 13:14:56 -07:00
parent 867093707b
commit bcc0807198
48 changed files with 203 additions and 190 deletions

View File

@ -69,7 +69,7 @@ function checkForUniqueCodes(messages: string[], diagnosticTable: InputDiagnosti
}
function buildUniqueNameMap(names: string[]): ts.Map<string, string> {
var nameMap = new ts.StringMap<string>();
var nameMap = ts.createMap<string, string>();
var uniqueNames = NameGenerator.ensureUniqueness(names, /* isCaseSensitive */ false, /* isFixed */ undefined);

View File

@ -147,7 +147,7 @@ namespace ts {
options = opts;
languageVersion = getEmitScriptTarget(options);
inStrictMode = bindInStrictMode(file, opts);
classifiableNames = new StringSet();
classifiableNames = createSet();
symbolCount = 0;
skipTransformFlagAggregation = isDeclarationFile(file);
@ -207,11 +207,11 @@ namespace ts {
symbol.declarations.push(node);
if (symbolFlags & SymbolFlags.HasExports && !symbol.exports) {
symbol.exports = new StringMap<Symbol>();
symbol.exports = createMap<string, Symbol>();
}
if (symbolFlags & SymbolFlags.HasMembers && !symbol.members) {
symbol.members = new StringMap<Symbol>();
symbol.members = createMap<string, Symbol>();
}
if (symbolFlags & SymbolFlags.Value) {
@ -484,7 +484,7 @@ namespace ts {
if (containerFlags & ContainerFlags.IsContainer) {
container = blockScopeContainer = node;
if (containerFlags & ContainerFlags.HasLocals) {
container.locals = new StringMap<Symbol>();
container.locals = createMap<string, Symbol>();
}
addToContainerChain(container);
}
@ -1525,7 +1525,7 @@ namespace ts {
const typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type");
addDeclarationToSymbol(typeLiteralSymbol, node, SymbolFlags.TypeLiteral);
typeLiteralSymbol.members = new StringMap([[symbol.name, symbol]]);
typeLiteralSymbol.members = createMap([[symbol.name, symbol]]);
}
function bindObjectLiteralExpression(node: ObjectLiteralExpression) {
@ -1535,7 +1535,7 @@ namespace ts {
}
if (inStrictMode) {
const seen = new StringMap<ElementKind>();
const seen = createMap<string, ElementKind>();
for (const prop of node.properties) {
if (prop.name.kind !== SyntaxKind.Identifier) {
@ -1591,7 +1591,7 @@ namespace ts {
// fall through.
default:
if (!blockScopeContainer.locals) {
blockScopeContainer.locals = new StringMap<Symbol>();
blockScopeContainer.locals = createMap<string, Symbol>();
addToContainerChain(blockScopeContainer);
}
declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
@ -2071,7 +2071,7 @@ namespace ts {
}
}
file.symbol.globalExports = file.symbol.globalExports || new StringMap<Symbol>();
file.symbol.globalExports = file.symbol.globalExports || createMap<string, Symbol>();
declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
}
@ -2118,7 +2118,7 @@ namespace ts {
Debug.assert(isInJavaScriptFile(node));
// Declare a 'member' if the container is an ES5 class or ES6 constructor
if (container.kind === SyntaxKind.FunctionDeclaration || container.kind === SyntaxKind.FunctionExpression) {
container.symbol.members = container.symbol.members || new StringMap<Symbol>();
container.symbol.members = container.symbol.members || createMap<string, Symbol>();
// It's acceptable for multiple 'this' assignments of the same identifier to occur
declareSymbol(container.symbol.members, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes & ~SymbolFlags.Property);
}
@ -2157,7 +2157,7 @@ namespace ts {
// Set up the members collection if it doesn't exist already
if (!funcSymbol.members) {
funcSymbol.members = new StringMap<Symbol>();
funcSymbol.members = createMap<string, Symbol>();
}
// Declare the method/property

View File

@ -47,7 +47,7 @@ namespace ts {
let symbolCount = 0;
const emptyArray: any[] = [];
const emptySymbols = new StringMap<Symbol>();
const emptySymbols = createMap<string, Symbol>();
const compilerOptions = host.getCompilerOptions();
const languageVersion = compilerOptions.target || ScriptTarget.ES3;
@ -111,10 +111,10 @@ namespace ts {
};
const tupleTypes: GenericType[] = [];
const unionTypes = new StringMap<UnionType>();
const intersectionTypes = new StringMap<IntersectionType>();
const stringLiteralTypes = new StringMap<LiteralType>();
const numericLiteralTypes = new StringMap<LiteralType>();
const unionTypes = createMap<string, UnionType>();
const intersectionTypes = createMap<string, IntersectionType>();
const stringLiteralTypes = createMap<string, LiteralType>();
const numericLiteralTypes = createMap<string, LiteralType>();
const evolvingArrayTypes: EvolvingArrayType[] = [];
const unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown");
@ -139,7 +139,7 @@ namespace ts {
const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
const emptyGenericType = <GenericType><ObjectType>createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
emptyGenericType.instantiations = new StringMap<TypeReference>();
emptyGenericType.instantiations = createMap<string, TypeReference>();
const anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
// The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
@ -155,7 +155,7 @@ namespace ts {
const enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
const globals = new StringMap<Symbol>();
const globals = createMap<string, Symbol>();
/**
* List of every ambient module with a "*" wildcard.
* Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
@ -325,7 +325,7 @@ namespace ts {
let jsxElementType: Type;
/** Things we lazy load from the JSX namespace */
const jsxTypes = new StringMap<Type>();
const jsxTypes = createMap<string, Type>();
const JsxNames = {
JSX: "JSX",
IntrinsicElements: "IntrinsicElements",
@ -336,11 +336,11 @@ namespace ts {
IntrinsicClassAttributes: "IntrinsicClassAttributes"
};
const subtypeRelation = new StringMap<RelationComparisonResult>();
const assignableRelation = new StringMap<RelationComparisonResult>();
const comparableRelation = new StringMap<RelationComparisonResult>();
const identityRelation = new StringMap<RelationComparisonResult>();
const enumRelation = new StringMap<boolean>();
const subtypeRelation = createMap<string, RelationComparisonResult>();
const assignableRelation = createMap<string, RelationComparisonResult>();
const comparableRelation = createMap<string, RelationComparisonResult>();
const identityRelation = createMap<string, RelationComparisonResult>();
const enumRelation = createMap<string, boolean>();
// This is for caching the result of getSymbolDisplayBuilder. Do not access directly.
let _displayBuilder: SymbolDisplayBuilder;
@ -354,7 +354,7 @@ namespace ts {
ResolvedReturnType
}
const builtinGlobals = new StringMap([[undefinedSymbol.name, undefinedSymbol]]);
const builtinGlobals = createMap([[undefinedSymbol.name, undefinedSymbol]]);
initializeTypeChecker();
@ -437,11 +437,11 @@ namespace ts {
target.declarations.push(node);
});
if (source.members) {
if (!target.members) target.members = new StringMap<Symbol>();
if (!target.members) target.members = createMap<string, Symbol>();
mergeSymbolTable(target.members, source.members);
}
if (source.exports) {
if (!target.exports) target.exports = new StringMap<Symbol>();
if (!target.exports) target.exports = createMap<string, Symbol>();
mergeSymbolTable(target.exports, source.exports);
}
recordMergedSymbol(target, source);
@ -1418,7 +1418,7 @@ namespace ts {
// This provides a name to the module. See the test tests/cases/fourslash/untypedModuleImport.ts
const newSymbol = createSymbol(SymbolFlags.ValueModule, quotedName);
// Module symbols are expected to have 'exports', although since this is an untyped module it can be empty.
newSymbol.exports = new StringMap<Symbol>();
newSymbol.exports = createMap<string, Symbol>();
// Cache it so subsequent accesses will return the same module.
globals.set(quotedName, newSymbol);
return newSymbol;
@ -1531,8 +1531,8 @@ namespace ts {
// All export * declarations are collected in an __export symbol by the binder
const exportStars = symbol.exports.get("__export");
if (exportStars) {
const nestedSymbols = new StringMap<Symbol>();
const lookupTable = new StringMap<ExportCollisionTracker>();
const nestedSymbols = createMap<string, Symbol>();
const lookupTable = createMap<string, ExportCollisionTracker>();
for (const node of exportStars.declarations) {
const resolvedModule = resolveExternalModuleName(node, (node as ExportDeclaration).moduleSpecifier);
const exportedSymbols = visit(resolvedModule);
@ -3237,7 +3237,7 @@ namespace ts {
// Return the type implied by an object binding pattern
function getTypeFromObjectBindingPattern(pattern: ObjectBindingPattern, includePatternInType: boolean, reportErrors: boolean): Type {
const members = new StringMap<Symbol>();
const members = createMap<string, Symbol>();
let hasComputedProperties = false;
forEach(pattern.elements, e => {
const name = e.propertyName || <Identifier>e.name;
@ -3842,7 +3842,7 @@ namespace ts {
type.typeParameters = concatenate(outerTypeParameters, localTypeParameters);
type.outerTypeParameters = outerTypeParameters;
type.localTypeParameters = localTypeParameters;
(<GenericType>type).instantiations = new StringMap([[getTypeListId(type.typeParameters), <GenericType>type]]);
(<GenericType>type).instantiations = createMap([[getTypeListId(type.typeParameters), <GenericType>type]]);
(<GenericType>type).target = <GenericType>type;
(<GenericType>type).typeArguments = type.typeParameters;
type.thisType = <TypeParameter>createType(TypeFlags.TypeParameter);
@ -3884,7 +3884,7 @@ namespace ts {
if (typeParameters) {
// Initialize the instantiation cache for generic type aliases. The declared type corresponds to
// an instantiation of the type alias with the type parameters supplied as type arguments.
links.instantiations = new StringMap([[getTypeListId(links.typeParameters), type]]);
links.instantiations = createMap([[getTypeListId(links.typeParameters), type]]);
}
}
else {
@ -4572,7 +4572,7 @@ namespace ts {
// these partial properties when identifying discriminant properties, but otherwise they are filtered out
// and do not appear to be present in the union type.
function getUnionOrIntersectionProperty(type: UnionOrIntersectionType, name: string): Symbol {
const properties = type.resolvedProperties || (type.resolvedProperties = new StringMap<Symbol>());
const properties = type.resolvedProperties || (type.resolvedProperties = createMap<string, Symbol>());
let property = properties.get(name);
if (!property) {
property = createUnionOrIntersectionProperty(type, name);
@ -5393,7 +5393,7 @@ namespace ts {
type.typeParameters = typeParameters;
type.outerTypeParameters = undefined;
type.localTypeParameters = typeParameters;
type.instantiations = new StringMap([[getTypeListId(type.typeParameters), <GenericType>type]]);
type.instantiations = createMap([[getTypeListId(type.typeParameters), <GenericType>type]]);
type.target = <GenericType>type;
type.typeArguments = type.typeParameters;
type.thisType = <TypeParameter>createType(TypeFlags.TypeParameter);
@ -6906,7 +6906,7 @@ namespace ts {
}
sourceStack[depth] = source;
targetStack[depth] = target;
maybeStack[depth] = new StringMap([[id, RelationComparisonResult.Succeeded]]);
maybeStack[depth] = createMap([[id, RelationComparisonResult.Succeeded]]);
depth++;
const saveExpandingFlags = expandingFlags;
if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1;
@ -7591,7 +7591,7 @@ namespace ts {
}
function transformTypeOfMembers(type: Type, f: (propertyType: Type) => Type) {
const members = new StringMap<Symbol>();
const members = createMap<string, Symbol>();
for (const property of getPropertiesOfObjectType(type)) {
const original = getTypeOfSymbol(property);
const updated = f(original);
@ -7814,7 +7814,7 @@ namespace ts {
let targetStack: Type[];
let depth = 0;
let inferiority = 0;
const visited = new StringSet();
const visited = createSet();
inferFromTypes(originalSource, originalTarget);
function isInProcess(source: Type, target: Type) {
@ -8894,7 +8894,7 @@ namespace ts {
// If we have previously computed the control flow type for the reference at
// this flow loop junction, return the cached type.
const id = getFlowNodeId(flow);
const cache = flowLoopCaches[id] || (flowLoopCaches[id] = new StringMap<Type>());
const cache = flowLoopCaches[id] || (flowLoopCaches[id] = createMap<string, Type>());
if (!key) {
key = getFlowCacheKey(reference);
}
@ -10594,7 +10594,7 @@ namespace ts {
// Grammar checking
checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
const propertiesTable = new StringMap<Symbol>();
const propertiesTable = createMap<string, Symbol>();
const propertiesArray: Symbol[] = [];
const contextualType = getApparentTypeOfContextualType(node);
const contextualTypeHasPattern = contextualType && contextualType.pattern &&
@ -11145,7 +11145,7 @@ namespace ts {
const targetAttributesType = getJsxElementAttributesType(node);
const nameTable = new StringSet();
const nameTable = createSet();
// Process this array in right-to-left order so we know which
// attributes (mostly from spreads) are being overwritten and
// thus should have their types ignored
@ -14622,8 +14622,8 @@ namespace ts {
Property = Getter | Setter
}
const instanceNames = new StringMap<Accessor>();
const staticNames = new StringMap<Accessor>();
const instanceNames = createMap<string, Accessor>();
const staticNames = createMap<string, Accessor>();
for (const member of node.members) {
if (member.kind === SyntaxKind.Constructor) {
for (const param of (member as ConstructorDeclaration).parameters) {
@ -14672,7 +14672,7 @@ namespace ts {
}
function checkObjectTypeForDuplicateDeclarations(node: TypeLiteralNode | InterfaceDeclaration) {
const names = new StringSet();
const names = createSet();
for (const member of node.members) {
if (member.kind == SyntaxKind.PropertySignature) {
let memberName: string;
@ -18490,7 +18490,7 @@ namespace ts {
}
function getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[] {
const symbols = new StringMap<Symbol>();
const symbols = createMap<string, Symbol>();
let memberFlags: ModifierFlags = ModifierFlags.None;
if (isInsideWithStatementBody(location)) {
@ -20315,7 +20315,7 @@ namespace ts {
}
function checkGrammarObjectLiteralExpression(node: ObjectLiteralExpression, inDestructuring: boolean) {
const seen = new StringMap<SymbolFlags>();
const seen = createMap<string, SymbolFlags>();
const Property = 1;
const GetAccessor = 2;
const SetAccessor = 4;
@ -20402,7 +20402,7 @@ namespace ts {
}
function checkGrammarJsxElement(node: JsxOpeningLikeElement) {
const seen = new StringSet();
const seen = createSet();
for (const attr of node.attributes) {
if (attr.kind === SyntaxKind.JsxSpreadAttribute) {
continue;

View File

@ -2,10 +2,11 @@
/* @internal */
namespace ts {
// The global Map object. This may not be available, so we must test for it.
declare const Map: { new<K, V>(pairs?: [K, V][]): Map<K, V> } | undefined;
// Non-ES6 native maps don't support constructor arguments, so `createMap` must provide that functionality.
declare const Map: { new<K, V>(): Map<K, V> } | undefined;
const usingNativeMaps = typeof Map !== "undefined";
// tslint:disable-next-line:no-in-operator
const fullyFeaturedMaps = usingNativeMaps && "keys" in Map.prototype && "values" in Map.prototype && "entries" in Map.prototype;
const usingES6NativeMaps = usingNativeMaps && "keys" in Map.prototype && "values" in Map.prototype && "entries" in Map.prototype;
/** Extra Map methods that may not be available, so we must provide fallbacks. */
interface ES6Map<K, V> extends Map<K, V> {
@ -32,20 +33,18 @@ namespace ts {
However, `forEach` will iterate over strings because values are stringified before being put in the map.
*/
constructor(pairs?: [K, V][]) {
if (pairs) {
for (const [key, value] of pairs) {
this.data[key as string] = value;
}
}
}
constructor() {}
clear(): void {
this.data = createDictionaryModeObject<V>();
}
delete(key: K): void {
delete this.data[key as string];
delete(key: K): boolean {
const had = this.has(key);
if (had) {
delete this.data[key as string];
}
return had;
}
get(key: K): V {
@ -68,14 +67,22 @@ namespace ts {
}
}
const MapCtr = usingNativeMaps ? Map : ShimMap;
/**
* In runtimes without Maps, this is implemented using an object.
* `pairs` is an optional list of entries to add to the new map.
*/
export const StringMap: { new<T>(pairs?: [string, T][]): Map<string, T>; } = usingNativeMaps ? Map : ShimMap;
export function createMap<K extends string | number, V>(pairs?: [K, V][]): Map<K, V> {
const map = new MapCtr<K, V>();
/** This is generic over the key type because it is usually an enum. */
export const NumberMap: { new<K extends number, V>(pairs?: [K, V][]): Map<K, V> } = usingNativeMaps ? Map : ShimMap;
if (pairs) {
for (const [key, value] of pairs) {
map.set(key, value);
}
}
return map;
}
const createObject = Object.create;
function createDictionaryModeObject<T>(): MapLike<T> {
@ -94,7 +101,7 @@ namespace ts {
* Iterates over entries in the map, returning the first output of `getResult` that is not `undefined`.
* Only works for strings because shims iterate with `for-in`.
*/
export const findInMap: <V, U>(map: Map<string, V>, getResult: (value: V, key: string) => U | undefined) => U | undefined = fullyFeaturedMaps
export const findInMap: <V, U>(map: Map<string, V>, getResult: (value: V, key: string) => U | undefined) => U | undefined = usingES6NativeMaps
? <V, U>(map: ES6Map<string, V>, f: (value: V, key: string) => U | undefined) => {
const iter = map.entries();
while (true) {
@ -122,7 +129,7 @@ namespace ts {
* Whether `predicate` is true for at least one entry in the map.
* Only works for strings because shims iterate with `for-in`.
*/
export const someInMap: <V>(map: Map<string, V>, predicate: (value: V, key: string) => boolean) => boolean = fullyFeaturedMaps
export const someInMap: <V>(map: Map<string, V>, predicate: (value: V, key: string) => boolean) => boolean = usingES6NativeMaps
? <V>(map: ES6Map<string, V>, predicate: (value: V, key: string) => boolean) =>
someInIterator(map.entries(), ([key, value]) => predicate(value, key))
: <V>(map: Map<string, V>, predicate: (value: V, key: string) => boolean) => {
@ -137,13 +144,13 @@ namespace ts {
* Whether `predicate` is true for at least one key in the map.
* Only works for strings because shims iterate with `for-in`.
*/
export const someKeyInMap: (map: Map<string, any>, predicate: (key: string) => boolean) => boolean = fullyFeaturedMaps
export const someKeyInMap: (map: Map<string, any>, predicate: (key: string) => boolean) => boolean = usingES6NativeMaps
? (map: ES6Map<string, any>, predicate: (key: string) => boolean) => someInIterator(map.keys(), predicate)
: (map: Map<string, any>, predicate: (key: string) => boolean) =>
someInMap(map, (_value, key) => predicate(key));
/** Whether `predicate` is true for at least one value in the map. */
export const someValueInMap: <T>(map: Map<any, T>, predicate: (value: T) => boolean) => boolean = fullyFeaturedMaps
export const someValueInMap: <T>(map: Map<any, T>, predicate: (value: T) => boolean) => boolean = usingES6NativeMaps
? <T>(map: ES6Map<any, T>, predicate: (value: T) => boolean) =>
someInIterator(map.values(), predicate)
: someInMap;
@ -165,7 +172,7 @@ namespace ts {
* `for (const key of map.keys()) action(key);`
* Only works for strings because shims iterate with `for-in`.
*/
export const forEachKeyInMap: (map: Map<string, any>, action: (key: string) => void) => void = fullyFeaturedMaps
export const forEachKeyInMap: (map: Map<string, any>, action: (key: string) => void) => void = usingES6NativeMaps
? (map: ES6Map<string, any>, action: (key: string) => void) => {
const iter: Iterator<string> = map.keys();
while (true) {
@ -200,7 +207,7 @@ namespace ts {
/** Create a map from a MapLike. This is useful for writing large maps as object literals. */
export function mapOfMapLike<T>(object: MapLike<T>): Map<string, T> {
const map = new StringMap<T>();
const map = createMap<string, T>();
// Copies keys/values from template. Note that for..in will not throw if
// template is undefined, and instead will just exit the loop.
for (const key in object) if (hasProperty(object, key)) {
@ -222,8 +229,12 @@ namespace ts {
this.data = createDictionaryModeObject<true>();
}
delete(value: string) {
delete this.data[value];
delete(value: string): boolean {
const had = this.has(value);
if (had) {
delete this.data[value];
}
return had;
}
forEach(action: (value: string) => void) {
@ -250,8 +261,10 @@ namespace ts {
declare const Set: { new(): Set<string> } | undefined;
const usingNativeSets = typeof Set !== "undefined";
/** In runtimes without Sets, this is implemented using an object. */
export const StringSet: { new(): Set<string> } = usingNativeSets ? Set : ShimStringSet;
const SetCtr = usingNativeSets ? Set : ShimStringSet;
export function createSet(): Set<string> {
return new SetCtr();
}
/** False if there are any values in the set. */
export const setIsEmpty: (set: Set<string>) => boolean = usingNativeSets
@ -273,7 +286,7 @@ namespace ts {
/** Create a new copy of a Map. */
export function cloneMap<T>(map: Map<string, T>) {
const clone = new StringMap<T>();
const clone = createMap<string, T>();
copyMapEntriesFromTo(map, clone);
return clone;
}
@ -309,7 +322,7 @@ namespace ts {
/** Return a new map with each key transformed by `getNewKey`. */
export function transformKeys<T>(map: Map<string, T>, getNewKey: (key: string) => string): Map<string, T> {
const newMap = new StringMap<T>();
const newMap = createMap<string, T>();
map.forEach((value, key) => {
newMap.set(getNewKey(key), value);
});
@ -382,7 +395,7 @@ namespace ts {
export function arrayToMap<T>(array: T[], makeKey: (value: T) => string): Map<string, T>;
export function arrayToMap<T, U>(array: T[], makeKey: (value: T) => string, makeValue: (value: T) => U): Map<string, U>;
export function arrayToMap<T, U>(array: T[], makeKey: (value: T) => string, makeValue?: (value: T) => U): Map<string, T | U> {
const result = new StringMap<T | U>();
const result = createMap<string, T | U>();
for (const value of array) {
result.set(makeKey(value), makeValue ? makeValue(value) : value);
}
@ -437,7 +450,7 @@ namespace ts {
* Creates a sorted array of keys.
* Sorts keys according to the iteration order they would have if they were in an object, instead of from a Map.
* This is so that tests run consistently whether or not we have a Map shim in place.
* The difference between Map iteration order and V8 object insertion order is that V8 moves natrual-number-like keys to the front.
* The difference between Map iteration order and V8 object insertion order is that V8 moves natural-number-like keys to the front.
*/
export function sortInV8ObjectInsertionOrder<T>(values: T[], toKey: (t: T) => string): T[] {
const naturalNumberKeys: T[] = [];
@ -458,7 +471,7 @@ namespace ts {
/** Union of the `getSet` of each element in the array. */
export function setAggregate<T>(array: T[], getSet: (t: T) => Set<string>): Set<string> {
const result = new StringSet();
const result = createSet();
for (const value of array) {
copySetValuesFromTo(getSet(value), result);
}

View File

@ -500,8 +500,8 @@ namespace ts {
return optionNameMapCache;
}
const optionNameMap = new StringMap<CommandLineOption>();
const shortOptionNames = new StringMap<string>();
const optionNameMap = createMap<string, CommandLineOption>();
const shortOptionNames = createMap<string, string>();
forEach(optionDeclarations, option => {
optionNameMap.set(option.name.toLowerCase(), option);
if (option.shortName) {
@ -741,7 +741,7 @@ namespace ts {
}
function serializeCompilerOptions(options: CompilerOptions): MapLike<CompilerOptionsValue> {
const result = new StringMap<CompilerOptionsValue>();
const result = createMap<string, CompilerOptionsValue>();
const optionsNameMap = getOptionNameMap().optionNameMap;
for (const name in options) {
@ -1172,12 +1172,12 @@ namespace ts {
// Literal file names (provided via the "files" array in tsconfig.json) are stored in a
// file map with a possibly case insensitive key. We use this map later when when including
// wildcard paths.
const literalFileMap = new StringMap<string>();
const literalFileMap = createMap<string, string>();
// Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
// file map with a possibly case insensitive key. We use this map to store paths matched
// via wildcard, and to handle extension priority.
const wildcardFileMap = new StringMap<string>();
const wildcardFileMap = createMap<string, string>();
if (include) {
include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false);
@ -1276,7 +1276,7 @@ namespace ts {
// /a/b/a?z - Watch /a/b directly to catch any new file matching a?z
const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude");
const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
const wildcardDirectories = new StringMap<WatchDirectoryFlags>();
const wildcardDirectories = createMap<string, WatchDirectoryFlags>();
if (include !== undefined) {
const recursiveKeys: string[] = [];
for (const file of include) {

View File

@ -23,7 +23,7 @@ namespace ts {
export const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined;
export function createFileMap<T>(keyMapper?: (key: string) => string): FileMap<T> {
const files = new StringMap<T>();
const files = createMap<string, T>();
return {
get,
set,

View File

@ -267,7 +267,7 @@ namespace ts {
}
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = new StringSet();
usedTypeDirectiveReferences = createSet();
}
for (const directive of typeReferenceDirectives) {
if (!usedTypeDirectiveReferences.has(directive)) {

View File

@ -292,7 +292,7 @@ const _super = (function (geti, seti) {
sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit);
nodeIdToGeneratedName = [];
autoGeneratedIdToGeneratedName = [];
generatedNameSet = new StringSet();
generatedNameSet = createSet();
isOwnFileEmit = !isBundledEmit;
// Emit helpers from all the files

View File

@ -1622,7 +1622,7 @@ namespace ts {
// flag and setting a parent node.
const react = createIdentifier(reactNamespace || "React");
react.flags &= ~NodeFlags.Synthesized;
// Set the parent that is in parse tree
// Set the parent that is in parse tree
// this makes sure that parent chain is intact for checker to traverse complete scope tree
react.parent = getParseTreeNode(parent);
return react;
@ -2806,7 +2806,7 @@ namespace ts {
}
function mergeTokenSourceMapRanges(sourceRanges: Map<SyntaxKind, TextRange>, destRanges: Map<SyntaxKind, TextRange>): Map<SyntaxKind, TextRange> {
if (!destRanges) destRanges = new NumberMap<SyntaxKind, TextRange>();
if (!destRanges) destRanges = createMap<SyntaxKind, TextRange>();
copyMapEntriesFromTo(sourceRanges, destRanges);
return destRanges;
}
@ -2899,7 +2899,7 @@ namespace ts {
*/
export function setTokenSourceMapRange<T extends Node>(node: T, token: SyntaxKind, range: TextRange) {
const emitNode = getOrCreateEmitNode(node);
const tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = new NumberMap<SyntaxKind, TextRange>());
const tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = createMap<SyntaxKind, TextRange>());
tokenSourceMapRanges.set(token, range);
return node;
}

View File

@ -601,7 +601,7 @@ namespace ts {
parseDiagnostics = [];
parsingContext = 0;
identifiers = new StringMap<string>();
identifiers = createMap<string, string>();
identifierCount = 0;
nodeCount = 0;

View File

@ -79,9 +79,9 @@ namespace ts.performance {
/** Enables (and resets) performance measurements for the compiler. */
export function enable() {
counts = new StringMap<number>();
marks = new StringMap<number>();
measures = new StringMap<number>();
counts = createMap<string, number>();
marks = createMap<string, number>();
measures = createMap<string, number>();
enabled = true;
profilerStart = timestamp();
}

View File

@ -82,7 +82,7 @@ namespace ts {
}
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
const existingDirectories = new StringSet();
const existingDirectories = createSet();
function getCanonicalFileName(fileName: string): string {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
@ -136,7 +136,7 @@ namespace ts {
function writeFileIfUpdated(fileName: string, data: string, writeByteOrderMark: boolean): void {
if (!outputFingerprints) {
outputFingerprints = new StringMap<OutputFingerprint>();
outputFingerprints = createMap<string, OutputFingerprint>();
}
const hash = sys.createHash(data);
@ -279,7 +279,7 @@ namespace ts {
return [];
}
const resolutions: T[] = [];
const cache = new StringMap<T>();
const cache = createMap<string, T>();
for (const name of names) {
const result = cache.has(name)
? cache.get(name)
@ -297,7 +297,7 @@ namespace ts {
let noDiagnosticsTypeChecker: TypeChecker;
let classifiableNames: Set<string>;
let resolvedTypeReferenceDirectives = new StringMap<ResolvedTypeReferenceDirective>();
let resolvedTypeReferenceDirectives = createMap<string, ResolvedTypeReferenceDirective>();
let fileProcessingDiagnostics = createDiagnosticCollection();
// The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
@ -312,10 +312,10 @@ namespace ts {
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
const modulesWithElidedImports = new StringMap<boolean>();
const modulesWithElidedImports = createMap<string, boolean>();
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
const sourceFilesFoundSearchingNodeModules = new StringMap<boolean>();
const sourceFilesFoundSearchingNodeModules = createMap<string, boolean>();
performance.mark("beforeProgram");
@ -1290,7 +1290,7 @@ namespace ts {
function processImportedModules(file: SourceFile) {
collectExternalModuleReferences(file);
if (file.imports.length || file.moduleAugmentations.length) {
file.resolvedModules = new StringMap<ResolvedModuleFull>();
file.resolvedModules = createMap<string, ResolvedModuleFull>();
const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral);
const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory));
Debug.assert(resolutions.length === moduleNames.length);

View File

@ -237,9 +237,9 @@ namespace ts {
const useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"];
function createWatchedFileSet() {
const dirWatchers = new StringMap<DirectoryWatcher>();
const dirWatchers = createMap<string, DirectoryWatcher>();
// One file can have multiple watchers
const fileWatcherCallbacks = new StringMap<FileWatcherCallback[]>();
const fileWatcherCallbacks = createMap<string, FileWatcherCallback[]>();
return { addFile, removeFile };
function reduceDirWatcherRefCountForFile(fileName: string) {

View File

@ -12,7 +12,7 @@
/* @internal */
namespace ts {
const moduleTransformerMap = new NumberMap<ModuleKind, Transformer>([
const moduleTransformerMap = createMap<ModuleKind, Transformer>([
[ModuleKind.ES2015, transformES2015Module],
[ModuleKind.System, transformSystemModule],
[ModuleKind.AMD, transformModule],

View File

@ -279,7 +279,7 @@ namespace ts {
else if (node.transformFlags & TransformFlags.ContainsES2015 || (isInConstructorWithCapturedSuper && !isExpression(node))) {
// we want to dive in this branch either if node has children with ES2015 specific syntax
// or we are inside constructor that captures result of the super call so all returns without expression should be
// rewritten. Note: we skip expressions since returns should never appear there
// rewritten. Note: we skip expressions since returns should never appear there
return visitEachChild(node, visitor, context);
}
else {
@ -1880,7 +1880,7 @@ namespace ts {
function visitLabeledStatement(node: LabeledStatement): VisitResult<Statement> {
if (convertedLoopState) {
if (!convertedLoopState.labels) {
convertedLoopState.labels = new StringMap<string>();
convertedLoopState.labels = createMap<string, string>();
}
convertedLoopState.labels.set(node.label.text, node.label.text);
}
@ -2497,13 +2497,13 @@ namespace ts {
function setLabeledJump(state: ConvertedLoopState, isBreak: boolean, labelText: string, labelMarker: string): void {
if (isBreak) {
if (!state.labeledNonLocalBreaks) {
state.labeledNonLocalBreaks = new StringMap<string>();
state.labeledNonLocalBreaks = createMap<string, string>();
}
state.labeledNonLocalBreaks.set(labelText, labelMarker);
}
else {
if (!state.labeledNonLocalContinues) {
state.labeledNonLocalContinues = new StringMap<string>();
state.labeledNonLocalContinues = createMap<string, string>();
}
state.labeledNonLocalContinues.set(labelText, labelMarker);
}

View File

@ -217,7 +217,7 @@ namespace ts {
Endfinally = 7,
}
const instructionNames = new NumberMap<Instruction, string>([
const instructionNames = createMap<Instruction, string>([
[Instruction.Return, "return"],
[Instruction.Break, "break"],
[Instruction.Yield, "yield"],
@ -2078,8 +2078,8 @@ namespace ts {
const name = declareLocal(text);
if (!renamedCatchVariables) {
renamedCatchVariables = new StringSet();
renamedCatchVariableDeclarations = new NumberMap<number, Identifier>();
renamedCatchVariables = createSet();
renamedCatchVariableDeclarations = createMap<number, Identifier>();
context.enableSubstitution(SyntaxKind.Identifier);
}

View File

@ -10,7 +10,7 @@ namespace ts {
importAliasNames: ParameterDeclaration[];
}
const transformModuleDelegates = new NumberMap<ModuleKind, (node: SourceFile) => SourceFile>([
const transformModuleDelegates = createMap<ModuleKind, (node: SourceFile) => SourceFile>([
[ModuleKind.None, transformCommonJSModule],
[ModuleKind.CommonJS, transformCommonJSModule],
[ModuleKind.AMD, transformAMDModule],
@ -40,8 +40,8 @@ namespace ts {
context.enableSubstitution(SyntaxKind.ShorthandPropertyAssignment); // Substitutes shorthand property assignments for imported/exported symbols.
context.enableEmitNotification(SyntaxKind.SourceFile); // Restore state when substituting nodes in a file.
const moduleInfoMap = new NumberMap<number, ExternalModuleInfo>(); // The ExternalModuleInfo for each file.
const deferredExports = new NumberMap<number, Statement[]>(); // Exports to defer until an EndOfDeclarationMarker is found.
const moduleInfoMap = createMap<number, ExternalModuleInfo>(); // The ExternalModuleInfo for each file.
const deferredExports = createMap<number, Statement[]>(); // Exports to defer until an EndOfDeclarationMarker is found.
let currentSourceFile: SourceFile; // The current file.
let currentModuleInfo: ExternalModuleInfo; // The ExternalModuleInfo for the current file.
@ -1101,7 +1101,7 @@ namespace ts {
if (node.kind === SyntaxKind.SourceFile) {
currentSourceFile = <SourceFile>node;
currentModuleInfo = moduleInfoMap.get(getOriginalNodeId(currentSourceFile));
noSubstitution = new NumberMap<number, boolean>();
noSubstitution = createMap<number, boolean>();
previousOnEmitNode(emitContext, node, emitCallback);

View File

@ -28,10 +28,10 @@ namespace ts {
context.enableSubstitution(SyntaxKind.PostfixUnaryExpression); // Substitutes updates to exported symbols.
context.enableEmitNotification(SyntaxKind.SourceFile); // Restore state when substituting nodes in a file.
const moduleInfoMap = new NumberMap<number, ExternalModuleInfo>(); // The ExternalModuleInfo for each file.
const deferredExports = new NumberMap<number, Statement[]>(); // Exports to defer until an EndOfDeclarationMarker is found.
const exportFunctionsMap = new NumberMap<number, Identifier>(); // The export function associated with a source file.
const noSubstitutionMap = new NumberMap<number, Map<number, boolean>>(); // Set of nodes for which substitution rules should be ignored for each file.
const moduleInfoMap = createMap<number, ExternalModuleInfo>(); // The ExternalModuleInfo for each file.
const deferredExports = createMap<number, Statement[]>(); // Exports to defer until an EndOfDeclarationMarker is found.
const exportFunctionsMap = createMap<number, Identifier>(); // The export function associated with a source file.
const noSubstitutionMap = createMap<number, Map<number, boolean>>(); // Set of nodes for which substitution rules should be ignored for each file.
let currentSourceFile: SourceFile; // The current file.
let moduleInfo: ExternalModuleInfo; // ExternalModuleInfo for the current file.
@ -138,7 +138,7 @@ namespace ts {
* @param externalImports The imports for the file.
*/
function collectDependencyGroups(externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]) {
const groupIndices = new StringMap<number>();
const groupIndices = createMap<string, number>();
const dependencyGroups: DependencyGroup[] = [];
for (let i = 0; i < externalImports.length; i++) {
const externalImport = externalImports[i];
@ -1739,7 +1739,7 @@ namespace ts {
* @param node The node which should not be substituted.
*/
function preventSubstitution<T extends Node>(node: T): T {
if (noSubstitution === undefined) noSubstitution = new NumberMap<number, boolean>();
if (noSubstitution === undefined) noSubstitution = createMap<number, boolean>();
noSubstitution.set(getNodeId(node), true);
return node;
}

View File

@ -2245,7 +2245,7 @@ namespace ts {
const savedCurrentScope = currentScope;
const savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
currentScope = body;
currentScopeFirstDeclarationsOfName = new StringMap<Node>();
currentScopeFirstDeclarationsOfName = createMap<string, Node>();
startLexicalEnvironment();
const statements = visitNodes(body.statements, visitor, isStatement, start);
@ -2630,7 +2630,7 @@ namespace ts {
const name = node.symbol && node.symbol.name;
if (name) {
if (!currentScopeFirstDeclarationsOfName) {
currentScopeFirstDeclarationsOfName = new StringMap<Node>();
currentScopeFirstDeclarationsOfName = createMap<string, Node>();
}
setIfNotSet(currentScopeFirstDeclarationsOfName, name, node);
@ -3218,7 +3218,7 @@ namespace ts {
context.enableSubstitution(SyntaxKind.Identifier);
// Keep track of class aliases.
classAliases = new NumberMap<number, Identifier>();
classAliases = createMap<number, Identifier>();
}
}

View File

@ -127,7 +127,7 @@ namespace ts {
const gutterSeparator = " ";
const resetEscapeSequence = "\u001b[0m";
const ellipsis = "...";
const categoryFormatMap = new NumberMap<DiagnosticCategory, string>([
const categoryFormatMap = createMap<DiagnosticCategory, string>([
[DiagnosticCategory.Warning, yellowForegroundEscapeSequence],
[DiagnosticCategory.Error, redForegroundEscapeSequence],
[DiagnosticCategory.Message, blueForegroundEscapeSequence],
@ -425,7 +425,7 @@ namespace ts {
}
// reset the cache of existing files
cachedExistingFiles = new StringMap<boolean>();
cachedExistingFiles = createMap<string, boolean>();
const compileResult = compile(rootFileNames, compilerOptions, compilerHost);
@ -706,7 +706,7 @@ namespace ts {
const usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
const descriptionColumn: string[] = [];
const optionsDescriptionMap = new StringMap<string[]>(); // Map between option.description and list of option.type if it is a kind
const optionsDescriptionMap = createMap<string, string[]>(); // Map between option.description and list of option.type if it is a kind
for (let i = 0; i < optsList.length; i++) {
const option = optsList[i];

View File

@ -17,7 +17,7 @@ namespace ts {
*/
export interface Map<K, V> {
clear(): void;
delete(key: K): void;
delete(key: K): boolean;
/**
* Call `action` for each entry in the map.
* Since we use a `for-in` loop for our shims, `key` may be a string.
@ -38,7 +38,7 @@ namespace ts {
export interface Set<T> {
add(value: T): void;
clear(): void;
delete(value: T): void;
delete(value: T): boolean;
forEach(action: (value: T) => void): void;
has(value: T): boolean;
}

View File

@ -93,7 +93,7 @@ namespace ts {
export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModuleFull): void {
if (!sourceFile.resolvedModules) {
sourceFile.resolvedModules = new StringMap<ResolvedModuleFull>();
sourceFile.resolvedModules = createMap<string, ResolvedModuleFull>();
}
sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
@ -101,7 +101,7 @@ namespace ts {
export function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective): void {
if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
sourceFile.resolvedTypeReferenceDirectiveNames = new StringMap<ResolvedTypeReferenceDirective>();
sourceFile.resolvedTypeReferenceDirectiveNames = createMap<string, ResolvedTypeReferenceDirective>();
}
sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
@ -2201,7 +2201,7 @@ namespace ts {
export function createDiagnosticCollection(): DiagnosticCollection {
let nonFileDiagnostics: Diagnostic[] = [];
const fileDiagnostics = new StringMap<Diagnostic[]>();
const fileDiagnostics = createMap<string, Diagnostic[]>();
let diagnosticsModified = false;
let modificationCount = 0;
@ -3349,7 +3349,7 @@ namespace ts {
return false;
}
const syntaxKindCache = new NumberMap<SyntaxKind, string>();
const syntaxKindCache = createMap<SyntaxKind, string>();
export function formatSyntaxKind(kind: SyntaxKind): string {
const syntaxKindEnum = (<any>ts).SyntaxKind;
@ -3507,9 +3507,9 @@ namespace ts {
export function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver): ExternalModuleInfo {
const externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[] = [];
const exportSpecifiers = new StringMap<ExportSpecifier[]>();
const exportedBindings = new NumberMap<number, Identifier[]>();
const uniqueExports = new StringMap<Identifier>();
const exportSpecifiers = createMap<string, ExportSpecifier[]>();
const exportedBindings = createMap<number, Identifier[]>();
const uniqueExports = createMap<string, Identifier>();
let hasExportDefault = false;
let exportEquals: ExportAssignment = undefined;
let hasExportStarsToExportValues = false;

View File

@ -46,7 +46,7 @@ namespace ts {
* supplant the existing `forEachChild` implementation if performance is not
* significantly impacted.
*/
const nodeEdgeTraversalMap = new NumberMap<SyntaxKind, NodeTraversalPath>([
const nodeEdgeTraversalMap = createMap<SyntaxKind, NodeTraversalPath>([
[SyntaxKind.QualifiedName, [
{ name: "left", test: isEntityName },
{ name: "right", test: isIdentifier }

View File

@ -189,7 +189,7 @@ namespace FourSlash {
public formatCodeSettings: ts.FormatCodeSettings;
private inputFiles = new ts.StringMap<string>(); // Map between inputFile's fileName and its content for easily looking up when resolving references
private inputFiles = ts.createMap<string, string>(); // Map between inputFile's fileName and its content for easily looking up when resolving references
private static getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[]) {
let result = "";
@ -674,7 +674,7 @@ namespace FourSlash {
public noItemsWithSameNameButDifferentKind(): void {
const completions = this.getCompletionListAtCaret();
const uniqueItems = new ts.StringMap<string>();
const uniqueItems = ts.createMap<string, string>();
for (const item of completions.entries) {
if (!ts.setIfNotSet(uniqueItems, item.name, item.kind)) {
const uniqueItem = uniqueItems.get(item.name);
@ -1777,7 +1777,7 @@ namespace FourSlash {
}
private rangesByTextMap(): ts.Map<string, Range[]> {
const result = new ts.StringMap<Range[]>();
const result = ts.createMap<string, Range[]>();
for (const range of this.getRanges()) {
const text = this.rangeText(range);
ts.multiMapAdd(result, text, range);

View File

@ -922,7 +922,7 @@ namespace Harness {
export const defaultLibFileName = "lib.d.ts";
export const es2015DefaultLibFileName = "lib.es2015.d.ts";
const libFileNameSourceFileMap = new ts.StringMap<ts.SourceFile>([[
const libFileNameSourceFileMap = ts.createMap<string, ts.SourceFile>([[
defaultLibFileName,
createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.es5.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest)
]]);
@ -1089,7 +1089,7 @@ namespace Harness {
let optionsIndex: ts.Map<string, ts.CommandLineOption>;
function getCommandLineOption(name: string): ts.CommandLineOption {
if (!optionsIndex) {
optionsIndex = new ts.StringMap<ts.CommandLineOption>();
optionsIndex = ts.createMap<string, ts.CommandLineOption>();
const optionDeclarations = harnessOptionDeclarations.concat(ts.optionDeclarations);
for (const option of optionDeclarations) {
optionsIndex.set(option.name.toLowerCase(), option);
@ -1452,7 +1452,7 @@ namespace Harness {
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
const fullResults = new ts.StringMap<TypeWriterResult[]>();
const fullResults = ts.createMap<string, TypeWriterResult[]>();
for (const sourceFile of allFiles) {
fullResults.set(sourceFile.unitName, fullWalker.getTypeAndSymbols(sourceFile.unitName));

View File

@ -91,7 +91,7 @@ namespace Playback {
}
function memoize<T>(func: (s: string) => T): Memoized<T> {
const lookup = new ts.StringMap<T>();
const lookup = ts.createMap<string, T>();
const run: Memoized<T> = <Memoized<T>>((s: string) =>
ts.getOrUpdateAndAllowUndefined(lookup, s, func));
run.reset = () => {

View File

@ -7,7 +7,7 @@ namespace ts {
}
function createDefaultServerHost(fileMap: Map<string, File>): server.ServerHost {
const existingDirectories = new StringSet();
const existingDirectories = createSet();
forEachKeyInMap(fileMap, name => {
let dir = getDirectoryPath(name);
let previous: string;

View File

@ -32,7 +32,7 @@ namespace ts {
const map = arrayToMap(files, f => f.name);
if (hasDirectoryExists) {
const directories = new StringSet();
const directories = createSet();
for (const f of files) {
let name = getDirectoryPath(f.name);
while (true) {

View File

@ -411,8 +411,8 @@ namespace ts.server {
class InProcClient {
private server: InProcSession;
private seq = 0;
private callbacks = new NumberMap<number, (resp: protocol.Response) => void>();
private eventHandlers = new StringMap<(args: any) => void>();
private callbacks = createMap<number, (resp: protocol.Response) => void>();
private eventHandlers = createMap<string, (args: any) => void>();
handle(msg: protocol.Message): void {
if (msg.type === "response") {

View File

@ -298,7 +298,7 @@ namespace ts.projectSystem {
}
export class Callbacks {
private map = new NumberMap<number, TimeOutCallback>();
private map = createMap<number, TimeOutCallback>();
private nextId = 1;
register(cb: (...args: any[]) => void, args: any[]) {
@ -335,8 +335,8 @@ namespace ts.projectSystem {
private timeoutCallbacks = new Callbacks();
private immediateCallbacks = new Callbacks();
readonly watchedDirectories = new StringMap<{ cb: DirectoryWatcherCallback, recursive: boolean }[]>();
readonly watchedFiles = new StringMap<FileWatcherCallback[]>();
readonly watchedDirectories = createMap<string, { cb: DirectoryWatcherCallback, recursive: boolean }[]>();
readonly watchedFiles = createMap<string, FileWatcherCallback[]>();
private filesOrFolders: FileOrFolder[];

View File

@ -955,7 +955,7 @@ namespace ts.projectSystem {
content: ""
};
const host = createServerHost([f]);
const cache = new StringMap<string>();
const cache = createMap<string, string>();
for (const name of JsTyping.nodeCoreModuleList) {
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enableAutoDiscovery: true }, [name, "somename"]);
assert.deepEqual(result.newTypingNames.sort(), ["node", "somename"]);

View File

@ -346,7 +346,7 @@ namespace ts.server {
// Use slice to clone the array to avoid manipulating in place
const queue = fileInfo.referencedBy.slice(0);
const fileNameSet = new StringMap<ScriptInfo>();
const fileNameSet = createMap<string, ScriptInfo>();
fileNameSet.set(scriptInfo.fileName, scriptInfo);
while (queue.length > 0) {
const processingFileInfo = queue.pop();

View File

@ -15,7 +15,7 @@ namespace ts.server {
export class SessionClient implements LanguageService {
private sequence: number = 0;
private lineMaps = new ts.StringMap<number[]>();
private lineMaps = ts.createMap<string, number[]>();
private messages: string[] = [];
private lastRenameEntry: RenameEntry;

View File

@ -18,7 +18,7 @@ namespace ts.server {
}
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions: CommandLineOption[]): Map<string, Map<string, number>> {
const map = new StringMap<Map<string, number>>();
const map = createMap<string, Map<string, number>>();
for (const option of commandLineOptions) {
if (typeof option.type === "object") {
const optionMap = <Map<string, number>>option.type;
@ -159,12 +159,12 @@ namespace ts.server {
/**
* a path to directory watcher map that detects added tsconfig files
**/
private readonly directoryWatchersForTsconfig = new StringMap<FileWatcher>();
private readonly directoryWatchersForTsconfig = createMap<string, FileWatcher>();
/**
* count of how many projects are using the directory watcher.
* If the number becomes 0 for a watcher, then we should close it.
**/
private readonly directoryWatchersRefCount = new StringMap<number>();
private readonly directoryWatchersRefCount = createMap<string, number>();
constructor(private readonly projectService: ProjectService) {
}
@ -212,7 +212,7 @@ namespace ts.server {
/**
* maps external project file name to list of config files that were the part of this project
*/
private readonly externalProjectToConfiguredProjectMap = new StringMap<NormalizedPath[]>();
private readonly externalProjectToConfiguredProjectMap = createMap<string, NormalizedPath[]>();
/**
* external projects (configuration and list of root files is not controlled by tsserver)
@ -902,7 +902,7 @@ namespace ts.server {
private updateNonInferredProject<T>(project: ExternalProject | ConfiguredProject, newUncheckedFiles: T[], propertyReader: FilePropertyReader<T>, newOptions: CompilerOptions, newTypingOptions: TypingOptions, compileOnSave: boolean, configFileErrors: Diagnostic[]) {
const oldRootScriptInfos = project.getRootScriptInfos();
const newRootScriptInfos: ScriptInfo[] = [];
const newRootScriptInfoMap: Map<NormalizedPath, ScriptInfo> = new StringMap<ScriptInfo>();
const newRootScriptInfoMap: Map<NormalizedPath, ScriptInfo> = createMap<string, ScriptInfo>();
let projectErrors: Diagnostic[];
let rootFilesChanged = false;

View File

@ -63,7 +63,7 @@ namespace ts.server {
const path = toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
const currentResolutionsInFile = cache.get(path);
const newResolutions = new StringMap<T>();
const newResolutions = createMap<string, T>();
const resolvedModules: R[] = [];
const compilerOptions = this.getCompilationSettings();
const lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName;

View File

@ -603,7 +603,7 @@ namespace ts.server {
// We need to use a set here since the code can contain the same import twice,
// but that will only be one dependency.
// To avoid invernal conversion, the key of the referencedFiles map must be of type Path
const referencedFiles = new StringSet();
const referencedFiles = createSet();
if (sourceFile.imports && sourceFile.imports.length > 0) {
const checker: TypeChecker = this.program.getTypeChecker();
for (const importName of sourceFile.imports) {
@ -778,7 +778,7 @@ namespace ts.server {
}
const configDirectoryPath = getDirectoryPath(this.configFileName);
this.directoriesWatchedForWildcards = new StringMap<FileWatcher>();
this.directoriesWatchedForWildcards = createMap<string, FileWatcher>();
this.wildcardDirectories.forEach((flag, directory) => {
if (comparePaths(configDirectoryPath, directory, ".", !this.projectService.host.useCaseSensitiveFileNames) !== Comparison.EqualTo) {
const recursive = (flag & WatchDirectoryFlags.Recursive) !== 0;

View File

@ -31,7 +31,7 @@ namespace ts.server {
if ((arr1 || emptyArray).length === 0 && (arr2 || emptyArray).length === 0) {
return true;
}
const set = new StringMap<boolean>();
const set = createMap<string, boolean>();
let unique = 0;
for (const v of arr1) {
@ -72,7 +72,7 @@ namespace ts.server {
}
export class TypingsCache {
private readonly perProjectCache = new StringMap<TypingsCacheEntry>();
private readonly perProjectCache = createMap<string, TypingsCacheEntry>();
constructor(private readonly installer: ITypingsInstaller) {
}

View File

@ -78,10 +78,10 @@ namespace ts.server.typingsInstaller {
};
export abstract class TypingsInstaller {
private readonly packageNameToTypingLocation = new StringMap<string>();
private readonly missingTypingsSet = new StringSet();
private readonly knownCachesSet = new StringSet();
private readonly projectWatchers = new StringMap<FileWatcher[]>();
private readonly packageNameToTypingLocation = createMap<string, string>();
private readonly missingTypingsSet = createSet();
private readonly knownCachesSet = createSet();
private readonly projectWatchers = createMap<string, FileWatcher[]>();
readonly pendingRunRequests: PendingRequest[] = [];
private installRunCount = 1;
@ -296,7 +296,7 @@ namespace ts.server.typingsInstaller {
if (this.log.isEnabled()) {
this.log.writeLine(`Requested to install typings ${JSON.stringify(typingsToInstall)}, installed typings ${JSON.stringify(installedTypings)}`);
}
const installedPackages = new StringSet();
const installedPackages = createSet();
const installedTypingFiles: string[] = [];
for (const t of installedTypings) {
const packageName = getBaseFileName(t);

View File

@ -225,7 +225,7 @@ namespace ts.server {
}
export class ThrottledOperations {
private pendingTimeouts = new StringMap<any>();
private pendingTimeouts = createMap<string, any>();
constructor(private readonly host: ServerHost) {
}

View File

@ -14,7 +14,7 @@ namespace ts {
}
export namespace codefix {
const codeFixes = new NumberMap<number, CodeFix[]>();
const codeFixes = createMap<number, CodeFix[]>();
export function registerCodeFix(action: CodeFix) {
forEach(action.errorCodes, error => {

View File

@ -115,7 +115,7 @@ namespace ts.Completions {
function getCompletionEntriesFromSymbols(symbols: Symbol[], entries: CompletionEntry[], location: Node, performCharacterChecks: boolean): Set<string> {
const start = timestamp();
const uniqueNames = new StringSet();
const uniqueNames = createSet();
if (symbols) {
for (const symbol of symbols) {
const entry = createCompletionEntry(symbol, location, performCharacterChecks);
@ -363,7 +363,7 @@ namespace ts.Completions {
*
* both foo.ts and foo.tsx become foo
*/
const foundFiles = new StringSet();
const foundFiles = createSet();
for (let filePath of files) {
filePath = normalizePath(filePath);
if (exclude && comparePaths(filePath, exclude, scriptPath, ignoreCase) === Comparison.EqualTo) {
@ -1553,7 +1553,7 @@ namespace ts.Completions {
* do not occur at the current position and have not otherwise been typed.
*/
function filterNamedImportOrExportCompletionItems(exportsOfModule: Symbol[], namedImportsOrExports: ImportOrExportSpecifier[]): Symbol[] {
const existingImportsOrExports = new StringSet();
const existingImportsOrExports = createSet();
for (const element of namedImportsOrExports) {
// If this is the current item we are editing right now, do not filter it out
@ -1583,7 +1583,7 @@ namespace ts.Completions {
return contextualMemberSymbols;
}
const existingMemberNames = new StringSet();
const existingMemberNames = createSet();
for (const m of existingMembers) {
// Ignore omitted expressions for missing members
if (m.kind !== SyntaxKind.PropertyAssignment &&
@ -1628,7 +1628,7 @@ namespace ts.Completions {
* do not occur at the current position and have not otherwise been typed.
*/
function filterJsxAttributes(symbols: Symbol[], attributes: NodeArray<JsxAttribute | JsxSpreadAttribute>): Symbol[] {
const seenNames = new StringSet();
const seenNames = createSet();
for (const attr of attributes) {
// If this is the current item we are editing right now, do not filter it out
if (attr.getStart() <= position && position <= attr.getEnd()) {

View File

@ -39,7 +39,7 @@ namespace ts.DocumentHighlights {
return undefined;
}
const fileNameToDocumentHighlights = new StringMap<DocumentHighlights>();
const fileNameToDocumentHighlights = createMap<string, DocumentHighlights>();
const result: DocumentHighlights[] = [];
for (const referencedSymbol of referencedSymbols) {
for (const referenceEntry of referencedSymbol.references) {

View File

@ -105,7 +105,7 @@ namespace ts {
export function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory = ""): DocumentRegistry {
// Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have
// for those settings.
const buckets = new StringMap<FileMap<DocumentRegistryEntry>>();
const buckets = createMap<string, FileMap<DocumentRegistryEntry>>();
const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames);
function getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey {

View File

@ -378,7 +378,7 @@ namespace ts.FindAllReferences {
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, start, container.getEnd());
const parents = getParentSymbolsOfPropertyAccess();
const inheritsFromCache = new StringMap<boolean>();
const inheritsFromCache = createMap<string, boolean>();
if (possiblePositions.length) {
// Build the set of symbols to search for, initially it has only the current symbol
@ -1047,7 +1047,7 @@ namespace ts.FindAllReferences {
// Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions
if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ new StringMap<Symbol>());
getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ createMap<string, Symbol>());
}
});
@ -1177,7 +1177,7 @@ namespace ts.FindAllReferences {
}
const result: Symbol[] = [];
getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ new StringMap<Symbol>());
getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ createMap<string, Symbol>());
return forEach(result, s => searchSymbols.indexOf(s) >= 0 ? s : undefined);
}

View File

@ -29,7 +29,7 @@ namespace ts.JsTyping {
// that we are confident require typings
let safeList: Map<string, string>;
const EmptySafeList = new StringMap<string>();
const EmptySafeList = createMap<string, string>();
/* @internal */
export const nodeCoreModuleList: ReadonlyArray<string> = [
@ -62,7 +62,7 @@ namespace ts.JsTyping {
{ cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } {
// A typing name to typing file path mapping
const inferredTypings = new StringMap<string | undefined>();
const inferredTypings = createMap<string, string | undefined>();
if (!typingOptions || !typingOptions.enableAutoDiscovery) {
return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };

View File

@ -239,7 +239,7 @@ namespace ts.NavigationBar {
/** Merge declarations of the same kind. */
function mergeChildren(children: NavigationBarNode[]): void {
const nameToItems = new StringMap<NavigationBarNode | NavigationBarNode[]>();
const nameToItems = createMap<string, NavigationBarNode | NavigationBarNode[]>();
filterMutate(children, child => {
const decl = <Declaration>child.node;
const name = decl.name && nodeText(decl.name);
@ -626,15 +626,15 @@ namespace ts.NavigationBar {
/**
* Matches all whitespace characters in a string. Eg:
*
*
* "app.
*
*
* onactivated"
*
*
* matches because of the newline, whereas
*
*
* "app.onactivated"
*
*
* does not match.
*/
const whiteSpaceRegex = /\s+/g;

View File

@ -113,7 +113,7 @@ namespace ts {
// we see the name of a module that is used everywhere, or the name of an overload). As
// such, we cache the information we compute about the candidate for the life of this
// pattern matcher so we don't have to compute it multiple times.
const stringToWordSpans = new StringMap<TextSpan[]>();
const stringToWordSpans = createMap<string, TextSpan[]>();
pattern = pattern.trim();

View File

@ -502,7 +502,7 @@ namespace ts {
}
private computeNamedDeclarations(): Map<string, Declaration[]> {
const result = new StringMap<Declaration[]>();
const result = createMap<string, Declaration[]>();
forEachChild(this, visit);
@ -1931,7 +1931,7 @@ namespace ts {
}
function initializeNameTable(sourceFile: SourceFile): void {
const nameTable = new StringMap<number>();
const nameTable = createMap<string, number>();
walk(sourceFile);
sourceFile.nameTable = nameTable;