Merge branch 'master' into conditionalTypes

# Conflicts:
#	src/compiler/checker.ts
This commit is contained in:
Anders Hejlsberg
2018-02-03 07:26:38 -08:00
220 changed files with 3008 additions and 705 deletions
+128 -81
View File
@@ -581,6 +581,21 @@ namespace ts {
Both = Source | Target,
}
const enum TypeIncludes {
Any = 1 << 0,
Undefined = 1 << 1,
Null = 1 << 2,
Never = 1 << 3,
NonWideningType = 1 << 4,
String = 1 << 5,
Number = 1 << 6,
ESSymbol = 1 << 7,
LiteralOrUniqueESSymbol = 1 << 8,
ObjectType = 1 << 9,
EmptyObject = 1 << 10,
Union = 1 << 11,
}
const enum MembersOrExportsResolutionKind {
resolvedExports = "resolvedExports",
resolvedMembers = "resolvedMembers"
@@ -750,12 +765,10 @@ namespace ts {
return _jsxNamespace;
}
function getEmitResolver(sourceFile: SourceFile, cancellationToken: CancellationToken, ignoreDiagnostics?: boolean) {
function getEmitResolver(sourceFile: SourceFile, cancellationToken: CancellationToken) {
// Ensure we have all the type information in place for this file so that all the
// emitter questions of this resolver will return the right information.
if (!ignoreDiagnostics) {
getDiagnostics(sourceFile, cancellationToken);
}
getDiagnostics(sourceFile, cancellationToken);
return emitResolver;
}
@@ -2696,6 +2709,9 @@ namespace ts {
if (flags & SymbolFormatFlags.WriteTypeParametersOrArguments) {
nodeFlags |= NodeBuilderFlags.WriteTypeParametersInQualifiedName;
}
if (flags & SymbolFormatFlags.UseAliasDefinedOutsideCurrentScope) {
nodeFlags |= NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope;
}
const builder = flags & SymbolFormatFlags.AllowAnyNodeKind ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker);
@@ -3467,7 +3483,14 @@ namespace ts {
function createEntityNameFromSymbolChain(chain: Symbol[], index: number): EntityName {
const typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
const symbol = chain[index];
if (index === 0) {
context.flags |= NodeBuilderFlags.InInitialEntityName;
}
const symbolName = getNameOfSymbolAsWritten(symbol, context);
if (index === 0) {
context.flags ^= NodeBuilderFlags.InInitialEntityName;
}
const identifier = setEmitFlags(createIdentifier(symbolName, typeParameterNodes), EmitFlags.NoAsciiEscaping);
identifier.symbol = symbol;
@@ -3484,7 +3507,13 @@ namespace ts {
const typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
const symbol = chain[index];
if (index === 0) {
context.flags |= NodeBuilderFlags.InInitialEntityName;
}
let symbolName = getNameOfSymbolAsWritten(symbol, context);
if (index === 0) {
context.flags ^= NodeBuilderFlags.InInitialEntityName;
}
let firstChar = symbolName.charCodeAt(0);
const canUsePropertyAccess = isIdentifierStart(firstChar, languageVersion);
if (index === 0 || canUsePropertyAccess) {
@@ -3597,6 +3626,10 @@ namespace ts {
symbolStack: Symbol[] | undefined;
}
function isDefaultBindingContext(location: Node) {
return location.kind === SyntaxKind.SourceFile || isAmbientModule(location);
}
/**
* Gets a human-readable name for a symbol.
* Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
@@ -3605,7 +3638,13 @@ namespace ts {
* It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
*/
function getNameOfSymbolAsWritten(symbol: Symbol, context?: NodeBuilderContext): string {
if (context && context.flags & NodeBuilderFlags.WriteDefaultSymbolWithoutName && symbol.escapedName === InternalSymbolName.Default) {
if (context && symbol.escapedName === InternalSymbolName.Default && !(context.flags & NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope) &&
// If it's not the first part of an entity name, it must print as `default`
(!(context.flags & NodeBuilderFlags.InInitialEntityName) ||
// if the symbol is synthesized, it will only be referenced externally it must print as `default`
!symbol.declarations ||
// if not in the same binding context (source file, module declaration), it must print as `default`
(context.enclosingDeclaration && findAncestor(symbol.declarations[0], isDefaultBindingContext) !== findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
return "default";
}
if (symbol.declarations && symbol.declarations.length) {
@@ -5527,6 +5566,8 @@ namespace ts {
sig.minArgumentCount = minArgumentCount;
sig.hasRestParameter = hasRestParameter;
sig.hasLiteralTypes = hasLiteralTypes;
sig.target = undefined;
sig.mapper = undefined;
return sig;
}
@@ -7482,21 +7523,6 @@ namespace ts {
return links.resolvedType;
}
interface TypeSet extends Array<Type> {
containsAny?: boolean;
containsUndefined?: boolean;
containsNull?: boolean;
containsNever?: boolean;
containsNonWideningType?: boolean;
containsString?: boolean;
containsNumber?: boolean;
containsESSymbol?: boolean;
containsLiteralOrUniqueESSymbol?: boolean;
containsObjectType?: boolean;
containsEmptyObject?: boolean;
unionIndex?: number;
}
function getTypeId(type: Type) {
return type.id;
}
@@ -7521,28 +7547,28 @@ namespace ts {
return false;
}
function addTypeToUnion(typeSet: TypeSet, type: Type) {
function addTypeToUnion(typeSet: Type[], includes: TypeIncludes, type: Type) {
const flags = type.flags;
if (flags & TypeFlags.Union) {
addTypesToUnion(typeSet, (<UnionType>type).types);
includes = addTypesToUnion(typeSet, includes, (<UnionType>type).types);
}
else if (flags & TypeFlags.Any) {
typeSet.containsAny = true;
includes |= TypeIncludes.Any;
}
else if (!strictNullChecks && flags & TypeFlags.Nullable) {
if (flags & TypeFlags.Undefined) typeSet.containsUndefined = true;
if (flags & TypeFlags.Null) typeSet.containsNull = true;
if (!(flags & TypeFlags.ContainsWideningType)) typeSet.containsNonWideningType = true;
if (flags & TypeFlags.Undefined) includes |= TypeIncludes.Undefined;
if (flags & TypeFlags.Null) includes |= TypeIncludes.Null;
if (!(flags & TypeFlags.ContainsWideningType)) includes |= TypeIncludes.NonWideningType;
}
else if (!(flags & TypeFlags.Never || flags & TypeFlags.Intersection && isEmptyIntersectionType(<IntersectionType>type))) {
// We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are
// another form of 'never' (in that they have an empty value domain). We could in theory turn
// intersections of unit types into 'never' upon construction, but deferring the reduction makes it
// easier to reason about their origin.
if (flags & TypeFlags.String) typeSet.containsString = true;
if (flags & TypeFlags.Number) typeSet.containsNumber = true;
if (flags & TypeFlags.ESSymbol) typeSet.containsESSymbol = true;
if (flags & TypeFlags.StringOrNumberLiteralOrUnique) typeSet.containsLiteralOrUniqueESSymbol = true;
if (flags & TypeFlags.String) includes |= TypeIncludes.String;
if (flags & TypeFlags.Number) includes |= TypeIncludes.Number;
if (flags & TypeFlags.ESSymbol) includes |= TypeIncludes.ESSymbol;
if (flags & TypeFlags.StringOrNumberLiteralOrUnique) includes |= TypeIncludes.LiteralOrUniqueESSymbol;
const len = typeSet.length;
const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues);
if (index < 0) {
@@ -7552,14 +7578,16 @@ namespace ts {
}
}
}
return includes;
}
// Add the given types to the given type set. Order is preserved, duplicates are removed,
// and nested types of the given kind are flattened into the set.
function addTypesToUnion(typeSet: TypeSet, types: Type[]) {
function addTypesToUnion(typeSet: Type[], includes: TypeIncludes, types: Type[]): TypeIncludes {
for (const type of types) {
addTypeToUnion(typeSet, type);
includes = addTypeToUnion(typeSet, includes, type);
}
return includes;
}
function containsIdenticalType(types: Type[], type: Type) {
@@ -7583,7 +7611,7 @@ namespace ts {
return false;
}
function isSetOfLiteralsFromSameEnum(types: TypeSet): boolean {
function isSetOfLiteralsFromSameEnum(types: Type[]): boolean {
const first = types[0];
if (first.flags & TypeFlags.EnumLiteral) {
const firstEnum = getParentOfSymbol(first.symbol);
@@ -7599,7 +7627,7 @@ namespace ts {
return false;
}
function removeSubtypes(types: TypeSet) {
function removeSubtypes(types: Type[]) {
if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) {
return;
}
@@ -7612,15 +7640,15 @@ namespace ts {
}
}
function removeRedundantLiteralTypes(types: TypeSet) {
function removeRedundantLiteralTypes(types: Type[], includes: TypeIncludes) {
let i = types.length;
while (i > 0) {
i--;
const t = types[i];
const remove =
t.flags & TypeFlags.StringLiteral && types.containsString ||
t.flags & TypeFlags.NumberLiteral && types.containsNumber ||
t.flags & TypeFlags.UniqueESSymbol && types.containsESSymbol ||
t.flags & TypeFlags.StringLiteral && includes & TypeIncludes.String ||
t.flags & TypeFlags.NumberLiteral && includes & TypeIncludes.Number ||
t.flags & TypeFlags.UniqueESSymbol && includes & TypeIncludes.ESSymbol ||
t.flags & TypeFlags.StringOrNumberLiteral && t.flags & TypeFlags.FreshLiteral && containsType(types, (<LiteralType>t).regularType);
if (remove) {
orderedRemoveItemAt(types, i);
@@ -7642,15 +7670,15 @@ namespace ts {
if (types.length === 1) {
return types[0];
}
const typeSet = [] as TypeSet;
addTypesToUnion(typeSet, types);
if (typeSet.containsAny) {
const typeSet: Type[] = [];
const includes = addTypesToUnion(typeSet, 0, types);
if (includes & TypeIncludes.Any) {
return anyType;
}
switch (unionReduction) {
case UnionReduction.Literal:
if (typeSet.containsLiteralOrUniqueESSymbol) {
removeRedundantLiteralTypes(typeSet);
if (includes & TypeIncludes.LiteralOrUniqueESSymbol) {
removeRedundantLiteralTypes(typeSet, includes);
}
break;
case UnionReduction.Subtype:
@@ -7658,8 +7686,8 @@ namespace ts {
break;
}
if (typeSet.length === 0) {
return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType :
typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType :
return includes & TypeIncludes.Null ? includes & TypeIncludes.NonWideningType ? nullType : nullWideningType :
includes & TypeIncludes.Undefined ? includes & TypeIncludes.NonWideningType ? undefinedType : undefinedWideningType :
neverType;
}
return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments);
@@ -7737,39 +7765,42 @@ namespace ts {
return links.resolvedType;
}
function addTypeToIntersection(typeSet: TypeSet, type: Type) {
if (type.flags & TypeFlags.Intersection) {
addTypesToIntersection(typeSet, (<IntersectionType>type).types);
function addTypeToIntersection(typeSet: Type[], includes: TypeIncludes, type: Type) {
const flags = type.flags;
if (flags & TypeFlags.Intersection) {
includes = addTypesToIntersection(typeSet, includes, (<IntersectionType>type).types);
}
else if (type.flags & TypeFlags.Any) {
typeSet.containsAny = true;
else if (flags & TypeFlags.Any) {
includes |= TypeIncludes.Any;
}
else if (type.flags & TypeFlags.Never) {
typeSet.containsNever = true;
else if (flags & TypeFlags.Never) {
includes |= TypeIncludes.Never;
}
else if (getObjectFlags(type) & ObjectFlags.Anonymous && isEmptyObjectType(type)) {
typeSet.containsEmptyObject = true;
includes |= TypeIncludes.EmptyObject;
}
else if ((strictNullChecks || !(type.flags & TypeFlags.Nullable)) && !contains(typeSet, type)) {
if (type.flags & TypeFlags.Object) {
typeSet.containsObjectType = true;
else if ((strictNullChecks || !(flags & TypeFlags.Nullable)) && !contains(typeSet, type)) {
if (flags & TypeFlags.Object) {
includes |= TypeIncludes.ObjectType;
}
if (type.flags & TypeFlags.Union && typeSet.unionIndex === undefined) {
typeSet.unionIndex = typeSet.length;
if (flags & TypeFlags.Union) {
includes |= TypeIncludes.Union;
}
if (!(type.flags & TypeFlags.Object && (<ObjectType>type).objectFlags & ObjectFlags.Anonymous &&
if (!(flags & TypeFlags.Object && (<ObjectType>type).objectFlags & ObjectFlags.Anonymous &&
type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && containsIdenticalType(typeSet, type))) {
typeSet.push(type);
}
}
return includes;
}
// Add the given types to the given type set. Order is preserved, freshness is removed from literal
// types, duplicates are removed, and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet: TypeSet, types: Type[]) {
function addTypesToIntersection(typeSet: Type[], includes: TypeIncludes, types: Type[]) {
for (const type of types) {
addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type));
includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
}
return includes;
}
// We normalize combinations of intersection and union types based on the distributive property of the '&'
@@ -7786,27 +7817,27 @@ namespace ts {
if (types.length === 0) {
return emptyObjectType;
}
const typeSet = [] as TypeSet;
addTypesToIntersection(typeSet, types);
if (typeSet.containsNever) {
const typeSet: Type[] = [];
const includes = addTypesToIntersection(typeSet, 0, types);
if (includes & TypeIncludes.Never) {
return neverType;
}
if (typeSet.containsAny) {
if (includes & TypeIncludes.Any) {
return anyType;
}
if (typeSet.containsEmptyObject && !typeSet.containsObjectType) {
if (includes & TypeIncludes.EmptyObject && !(includes & TypeIncludes.ObjectType)) {
typeSet.push(emptyObjectType);
}
if (typeSet.length === 1) {
return typeSet[0];
}
const unionIndex = typeSet.unionIndex;
if (unionIndex !== undefined) {
if (includes & TypeIncludes.Union) {
// We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
// the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
const unionIndex = findIndex(typeSet, t => (t.flags & TypeFlags.Union) !== 0);
const unionType = <UnionType>typeSet[unionIndex];
return getUnionType(map(unionType.types, t => getIntersectionType(replaceElement(typeSet, unionIndex, t))),
UnionReduction.Literal, aliasSymbol, aliasTypeArguments);
UnionReduction.Literal, aliasSymbol, aliasTypeArguments);
}
const id = getTypeListId(typeSet);
let type = intersectionTypes.get(id);
@@ -13505,13 +13536,13 @@ namespace ts {
.expression; // x
const classSymbol = checkExpression(className).symbol;
if (classSymbol && classSymbol.members && (classSymbol.flags & SymbolFlags.Function)) {
return getInferredClassType(classSymbol);
return getFlowTypeOfReference(node, getInferredClassType(classSymbol));
}
}
const thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container);
if (thisType) {
return thisType;
return getFlowTypeOfReference(node, thisType);
}
}
@@ -13524,7 +13555,7 @@ namespace ts {
if (isInJavaScriptFile(node)) {
const type = getTypeForThisExpressionFromJSDoc(container);
if (type && type !== unknownType) {
return type;
return getFlowTypeOfReference(node, type);
}
}
}
@@ -17768,7 +17799,7 @@ namespace ts {
const anonymousSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type);
const defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
anonymousSymbol.type = defaultContainingObject;
synthType.syntheticType = (type.flags & TypeFlags.StructuredType && type.symbol.flags & (SymbolFlags.Module | SymbolFlags.Variable)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject;
synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject;
}
else {
synthType.syntheticType = type;
@@ -19169,13 +19200,9 @@ namespace ts {
function isLiteralOfContextualType(candidateType: Type, contextualType: Type): boolean {
if (contextualType) {
if (contextualType.flags & TypeFlags.UnionOrIntersection && !(contextualType.flags & TypeFlags.Boolean)) {
// If the contextual type is a union containing both of the 'true' and 'false' types we
// don't consider it a literal context for boolean literals.
if (contextualType.flags & TypeFlags.UnionOrIntersection) {
const types = (<UnionType>contextualType).types;
return some(types, t =>
!(t.flags & TypeFlags.BooleanLiteral && containsType(types, trueType) && containsType(types, falseType)) &&
isLiteralOfContextualType(candidateType, t));
return some(types, t => isLiteralOfContextualType(candidateType, t));
}
if (contextualType.flags & TypeFlags.InstantiableNonPrimitive) {
// If the contextual type is a type variable constrained to a primitive type, consider
@@ -20466,6 +20493,8 @@ namespace ts {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
return DeclarationSpaces.ExportType | DeclarationSpaces.ExportValue;
case SyntaxKind.SourceFile:
return DeclarationSpaces.ExportType | DeclarationSpaces.ExportValue | DeclarationSpaces.ExportNamespace;
// The below options all declare an Alias, which is allowed to merge with other values within the importing module
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.NamespaceImport:
@@ -25394,11 +25423,18 @@ namespace ts {
}
}
// We do global augmentations seperately from module augmentations (and before creating global types) because they
// 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
// 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
// checking for an export or property on the module (if export=) which, in turn, can fall back to the
// apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
// did module augmentations prior to finalizing the global types.
if (augmentations) {
// merge module augmentations.
// merge _global_ module augmentations.
// this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
for (const list of augmentations) {
for (const augmentation of list) {
if (!isGlobalScopeAugmentation(augmentation.parent as ModuleDeclaration)) continue;
mergeModuleAugmentation(augmentation);
}
}
@@ -25430,6 +25466,17 @@ namespace ts {
globalReadonlyArrayType = <GenericType>getGlobalTypeOrUndefined("ReadonlyArray" as __String, /*arity*/ 1);
anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
globalThisType = <GenericType>getGlobalTypeOrUndefined("ThisType" as __String, /*arity*/ 1);
if (augmentations) {
// merge _nonglobal_ module augmentations.
// this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
for (const list of augmentations) {
for (const augmentation of list) {
if (isGlobalScopeAugmentation(augmentation.parent as ModuleDeclaration)) continue;
mergeModuleAugmentation(augmentation);
}
}
}
}
function checkExternalEmitHelpers(location: Node, helpers: ExternalEmitHelpers) {
@@ -26794,7 +26841,7 @@ namespace ts {
switch (name.parent.kind) {
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
return true;
return isIdentifier(name);
default:
return isDeclarationName(name);
}
+22 -27
View File
@@ -1425,9 +1425,9 @@ namespace ts {
}
function directoryOfCombinedPath(fileName: string, basePath: string) {
// Use the `identity` function to avoid canonicalizing the path, as it must remain noncanonical
// Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
// until consistient casing errors are reported
return getDirectoryPath(toPath(fileName, basePath, identity));
return getDirectoryPath(getNormalizedAbsolutePath(fileName, basePath));
}
/**
@@ -1452,8 +1452,7 @@ namespace ts {
Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
const errors: Diagnostic[] = [];
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, getCanonicalFileName, resolutionStack, errors);
const parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors);
const { raw } = parsedConfig;
const options = extend(existingOptions, parsedConfig.options || {});
options.configFilePath = configFileName;
@@ -1547,7 +1546,10 @@ namespace ts {
raw: any;
options?: CompilerOptions;
typeAcquisition?: TypeAcquisition;
extendedConfigPath?: Path;
/**
* Note that the case of the config path has not yet been normalized, as no files have been imported into the project yet
*/
extendedConfigPath?: string;
}
function isSuccessfulParsedTsconfig(value: ParsedTsconfig) {
@@ -1564,12 +1566,11 @@ namespace ts {
host: ParseConfigHost,
basePath: string,
configFileName: string,
getCanonicalFileName: GetCanonicalFileName,
resolutionStack: Path[],
resolutionStack: string[],
errors: Push<Diagnostic>,
): ParsedTsconfig {
basePath = normalizeSlashes(basePath);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath);
if (resolutionStack.indexOf(resolvedPath) >= 0) {
errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> ")));
@@ -1577,14 +1578,13 @@ namespace ts {
}
const ownConfig = json ?
parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) :
parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors);
parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
if (ownConfig.extendedConfigPath) {
// copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
resolutionStack = resolutionStack.concat([resolvedPath]);
const extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName,
resolutionStack, errors);
const extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors);
if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
const baseRaw = extendedConfig.raw;
const raw = ownConfig.raw;
@@ -1612,7 +1612,6 @@ namespace ts {
json: any,
host: ParseConfigHost,
basePath: string,
getCanonicalFileName: GetCanonicalFileName,
configFileName: string | undefined,
errors: Push<Diagnostic>
): ParsedTsconfig {
@@ -1625,7 +1624,7 @@ namespace ts {
// It should be removed in future releases - use typeAcquisition instead.
const typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
let extendedConfigPath: Path;
let extendedConfigPath: string;
if (json.extends) {
if (!isString(json.extends)) {
@@ -1633,7 +1632,7 @@ namespace ts {
}
else {
const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, getCanonicalFileName, errors, createCompilerDiagnostic);
extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, createCompilerDiagnostic);
}
}
return { raw: json, options, typeAcquisition, extendedConfigPath };
@@ -1643,13 +1642,12 @@ namespace ts {
sourceFile: JsonSourceFile,
host: ParseConfigHost,
basePath: string,
getCanonicalFileName: GetCanonicalFileName,
configFileName: string | undefined,
errors: Push<Diagnostic>
): ParsedTsconfig {
const options = getDefaultCompilerOptions(configFileName);
let typeAcquisition: TypeAcquisition, typingOptionstypeAcquisition: TypeAcquisition;
let extendedConfigPath: Path;
let extendedConfigPath: string;
const optionsIterator: JsonConversionNotifier = {
onSetValidOptionKeyValueInParent(parentOption: string, option: CommandLineOption, value: CompilerOptionsValue) {
@@ -1670,7 +1668,6 @@ namespace ts {
<string>value,
host,
newBase,
getCanonicalFileName,
errors,
(message, arg0) =>
createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0)
@@ -1712,7 +1709,6 @@ namespace ts {
extendedConfig: string,
host: ParseConfigHost,
basePath: string,
getCanonicalFileName: GetCanonicalFileName,
errors: Push<Diagnostic>,
createDiagnostic: (message: DiagnosticMessage, arg1?: string) => Diagnostic) {
extendedConfig = normalizeSlashes(extendedConfig);
@@ -1721,9 +1717,9 @@ namespace ts {
errors.push(createDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig));
return undefined;
}
let extendedConfigPath = toPath(extendedConfig, basePath, getCanonicalFileName);
let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath);
if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, Extension.Json)) {
extendedConfigPath = `${extendedConfigPath}.json` as Path;
extendedConfigPath = `${extendedConfigPath}.json`;
if (!host.fileExists(extendedConfigPath)) {
errors.push(createDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig));
return undefined;
@@ -1734,11 +1730,10 @@ namespace ts {
function getExtendedConfig(
sourceFile: JsonSourceFile,
extendedConfigPath: Path,
extendedConfigPath: string,
host: ts.ParseConfigHost,
basePath: string,
getCanonicalFileName: GetCanonicalFileName,
resolutionStack: Path[],
resolutionStack: string[],
errors: Push<Diagnostic>,
): ParsedTsconfig | undefined {
const extendedResult = readJsonConfigFile(extendedConfigPath, path => host.readFile(path));
@@ -1752,14 +1747,14 @@ namespace ts {
const extendedDirname = getDirectoryPath(extendedConfigPath);
const extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname,
getBaseFileName(extendedConfigPath), getCanonicalFileName, resolutionStack, errors);
getBaseFileName(extendedConfigPath), resolutionStack, errors);
if (sourceFile) {
sourceFile.extendedSourceFiles.push(...extendedResult.extendedSourceFiles);
}
if (isSuccessfulParsedTsconfig(extendedConfig)) {
// Update the paths to reflect base path
const relativeDifference = convertToRelativePath(extendedDirname, basePath, getCanonicalFileName);
const relativeDifference = convertToRelativePath(extendedDirname, basePath, identity);
const updatePath = (path: string) => isRootedDiskPath(path) ? path : combinePaths(relativeDifference, path);
const mapPropertiesInRawIfNotUndefined = (propertyName: string) => {
if (raw[propertyName]) {
@@ -1801,7 +1796,7 @@ namespace ts {
function getDefaultCompilerOptions(configFileName?: string) {
const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json"
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true }
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
: {};
return options;
}
+16 -1
View File
@@ -1452,7 +1452,13 @@ namespace ts {
export function cast<TOut extends TIn, TIn = any>(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut {
if (value !== undefined && test(value)) return value;
Debug.fail(`Invalid cast. The supplied value did not pass the test '${Debug.getFunctionName(test)}'.`);
if (value && typeof (value as any).kind === "number") {
Debug.fail(`Invalid cast. The supplied ${(ts as any).SyntaxKind[(value as any).kind]} did not pass the test '${Debug.getFunctionName(test)}'.`);
}
else {
Debug.fail(`Invalid cast. The supplied value did not pass the test '${Debug.getFunctionName(test)}'.`);
}
}
/** Does nothing. */
@@ -2770,6 +2776,10 @@ namespace ts {
this.flags = flags;
this.escapedName = name;
this.declarations = undefined;
this.valueDeclaration = undefined;
this.id = undefined;
this.mergeId = undefined;
this.parent = undefined;
}
function Type(this: Type, checker: TypeChecker, flags: TypeFlags) {
@@ -2874,6 +2884,11 @@ namespace ts {
throw e;
}
export function assertDefined<T>(value: T | null | undefined, message?: string): T {
assert(value !== undefined && value !== null, message);
return value;
}
export function assertNever(member: never, message?: string, stackCrawlMark?: AnyFunction): never {
return fail(message || `Illegal value: ${member}`, stackCrawlMark || assertNever);
}
+3 -3
View File
@@ -358,7 +358,7 @@ namespace ts {
}
else {
errorNameNode = declaration.name;
const format = TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseStructuralFallback | TypeFormatFlags.WriteDefaultSymbolWithoutName |
const format = TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseStructuralFallback |
TypeFormatFlags.WriteClassExpressionAsTypeLiteral |
(shouldUseResolverType ? TypeFormatFlags.AddUndefined : 0);
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer);
@@ -378,7 +378,7 @@ namespace ts {
resolver.writeReturnTypeOfSignatureDeclaration(
signature,
enclosingDeclaration,
TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseStructuralFallback | TypeFormatFlags.WriteClassExpressionAsTypeLiteral | TypeFormatFlags.WriteDefaultSymbolWithoutName,
TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseStructuralFallback | TypeFormatFlags.WriteClassExpressionAsTypeLiteral,
writer);
errorNameNode = undefined;
}
@@ -655,7 +655,7 @@ namespace ts {
resolver.writeTypeOfExpression(
expr,
enclosingDeclaration,
TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseStructuralFallback | TypeFormatFlags.WriteClassExpressionAsTypeLiteral | TypeFormatFlags.WriteDefaultSymbolWithoutName,
TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseStructuralFallback | TypeFormatFlags.WriteClassExpressionAsTypeLiteral,
writer);
write(";");
writeLine();
+9 -7
View File
@@ -349,14 +349,15 @@ namespace ts {
decorators: ReadonlyArray<Decorator> | undefined,
modifiers: ReadonlyArray<Modifier> | undefined,
name: string | PropertyName,
questionToken: QuestionToken | undefined,
questionOrExclamationToken: QuestionToken | ExclamationToken | undefined,
type: TypeNode | undefined,
initializer: Expression | undefined) {
const node = <PropertyDeclaration>createSynthesizedNode(SyntaxKind.PropertyDeclaration);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.name = asName(name);
node.questionToken = questionToken;
node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === SyntaxKind.QuestionToken ? questionOrExclamationToken : undefined;
node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === SyntaxKind.ExclamationToken ? questionOrExclamationToken : undefined;
node.type = type;
node.initializer = initializer;
return node;
@@ -367,16 +368,17 @@ namespace ts {
decorators: ReadonlyArray<Decorator> | undefined,
modifiers: ReadonlyArray<Modifier> | undefined,
name: string | PropertyName,
questionToken: QuestionToken | undefined,
questionOrExclamationToken: QuestionToken | ExclamationToken | undefined,
type: TypeNode | undefined,
initializer: Expression | undefined) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.questionToken !== questionToken
|| node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === SyntaxKind.QuestionToken ? questionOrExclamationToken : undefined)
|| node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === SyntaxKind.ExclamationToken ? questionOrExclamationToken : undefined)
|| node.type !== type
|| node.initializer !== initializer
? updateNode(createProperty(decorators, modifiers, name, questionToken, type, initializer), node)
? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
: node;
}
@@ -4315,7 +4317,7 @@ namespace ts {
return emitNode && emitNode.externalHelpersModuleName;
}
export function getOrCreateExternalHelpersModuleNameIfNeeded(node: SourceFile, compilerOptions: CompilerOptions, hasExportStarsToExportValues?: boolean) {
export function getOrCreateExternalHelpersModuleNameIfNeeded(node: SourceFile, compilerOptions: CompilerOptions, hasExportStarsToExportValues?: boolean, hasImportStarOrImportDefault?: boolean) {
if (compilerOptions.importHelpers && isEffectiveExternalModule(node, compilerOptions)) {
const externalHelpersModuleName = getExternalHelpersModuleName(node);
if (externalHelpersModuleName) {
@@ -4323,7 +4325,7 @@ namespace ts {
}
const moduleKind = getEmitModuleKind(compilerOptions);
let create = hasExportStarsToExportValues
let create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
&& moduleKind !== ModuleKind.System
&& moduleKind !== ModuleKind.ES2015
&& moduleKind !== ModuleKind.ESNext;
+39 -11
View File
@@ -801,7 +801,7 @@ namespace ts {
}
const resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state);
if (resolvedFromFile) {
const nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined;
const nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
const packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId;
return withPackageId(packageId, resolvedFromFile);
}
@@ -826,12 +826,13 @@ namespace ts {
*
* packageDirectory is the directory of the package itself.
* subModuleName is the path within the package.
* For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "" }. (Part before "/node_modules/" is ignored.)
* For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar" }.
* For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar" }.
* For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "index.d.ts" }. (Part before "/node_modules/" is ignored.)
* For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }.
* For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar/index.d.ts" }.
* For `/node_modules/foo/bar/index.d.ts` this is { packageDirectory: "foo", subModuleName": "bar/index.d.ts" }.
*/
function parseNodeModuleFromPath(path: string): { packageDirectory: string, subModuleName: string } | undefined {
path = normalizePath(path);
function parseNodeModuleFromPath(resolved: PathAndExtension): { packageDirectory: string, subModuleName: string } | undefined {
const path = normalizePath(resolved.path);
const idx = path.lastIndexOf(nodeModulesPathPart);
if (idx === -1) {
return undefined;
@@ -843,7 +844,7 @@ namespace ts {
indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
}
const packageDirectory = path.slice(0, indexAfterPackageName);
const subModuleName = removeExtensionAndIndex(path.slice(indexAfterPackageName + 1));
const subModuleName = removeExtension(path.slice(indexAfterPackageName + 1), resolved.ext) + Extension.Dts;
return { packageDirectory, subModuleName };
}
@@ -852,9 +853,17 @@ namespace ts {
return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
}
function removeExtensionAndIndex(path: string): string {
const noExtension = removeFileExtension(path);
return noExtension === "index" ? "" : removeSuffix(noExtension, "/index");
function addExtensionAndIndex(path: string): string {
if (path === "") {
return "index.d.ts";
}
if (endsWith(path, ".d.ts")) {
return path;
}
if (endsWith(path, "/index")) {
return path + ".d.ts";
}
return path + "/index.d.ts";
}
/* @internal */
@@ -955,12 +964,31 @@ namespace ts {
subModuleName: string,
failedLookupLocations: Push<string>,
onlyRecordFailures: boolean,
{ host, traceEnabled }: ModuleResolutionState,
state: ModuleResolutionState,
): { found: boolean, packageJsonContent: PackageJsonPathFields | undefined, packageId: PackageId | undefined } {
const { host, traceEnabled } = state;
const directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host);
const packageJsonPath = pathToPackageJson(nodeModuleDirectory);
if (directoryExists && host.fileExists(packageJsonPath)) {
const packageJsonContent = readJson(packageJsonPath, host);
if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName
const path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state);
if (typeof path === "string") {
subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1));
}
else {
const jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state);
if (typeof jsPath === "string") {
subModuleName = removeExtension(removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), Extension.Js), Extension.Jsx) + Extension.Dts;
}
else {
subModuleName = "index.d.ts";
}
}
}
if (!endsWith(subModuleName, Extension.Dts)) {
subModuleName = addExtensionAndIndex(subModuleName);
}
const packageId: PackageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string"
? { name: packageJsonContent.name, subModuleName, version: packageJsonContent.version }
: undefined;
+4 -4
View File
@@ -416,7 +416,7 @@ namespace ts {
hasInvalidatedResolution: HasInvalidatedResolution,
hasChangedAutomaticTypeDirectiveNames: boolean,
): boolean {
// If we haven't create a program yet or has changed automatic type directives, then it is not up-to-date
// If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
if (!program || hasChangedAutomaticTypeDirectiveNames) {
return false;
}
@@ -457,10 +457,10 @@ namespace ts {
}
/**
* Determined if source file needs to be re-created even if its text hasnt changed
* Determined if source file needs to be re-created even if its text hasn't changed
*/
function shouldProgramCreateNewSourceFiles(program: Program, newOptions: CompilerOptions) {
// If any of these options change, we cant reuse old source file even if version match
// If any of these options change, we can't reuse old source file even if version match
// The change in options like these could result in change in syntax tree change
const oldOptions = program && program.getCompilerOptions();
return oldOptions && (
@@ -1179,7 +1179,7 @@ namespace ts {
// This is because in the -out scenario all files need to be emitted, and therefore all
// files need to be type checked. And the way to specify that all files need to be type
// checked is to not pass the file to getEmitResolver.
const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles);
const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
performance.mark("beforeEmit");
+60 -53
View File
@@ -3439,64 +3439,71 @@ namespace ts {
function visitCallExpressionWithPotentialCapturedThisAssignment(node: CallExpression, assignToCapturedThis: boolean): CallExpression | BinaryExpression {
// We are here either because SuperKeyword was used somewhere in the expression, or
// because we contain a SpreadElementExpression.
if (node.transformFlags & TransformFlags.ContainsSpread ||
node.expression.kind === SyntaxKind.SuperKeyword ||
isSuperProperty(skipOuterExpressions(node.expression))) {
const { target, thisArg } = createCallBinding(node.expression, hoistVariableDeclaration);
if (node.expression.kind === SyntaxKind.SuperKeyword) {
setEmitFlags(thisArg, EmitFlags.NoSubstitution);
}
let resultingCall: CallExpression | BinaryExpression;
if (node.transformFlags & TransformFlags.ContainsSpread) {
// [source]
// f(...a, b)
// x.m(...a, b)
// super(...a, b)
// super.m(...a, b) // in static
// super.m(...a, b) // in instance
//
// [output]
// f.apply(void 0, a.concat([b]))
// (_a = x).m.apply(_a, a.concat([b]))
// _super.apply(this, a.concat([b]))
// _super.m.apply(this, a.concat([b]))
// _super.prototype.m.apply(this, a.concat([b]))
const { target, thisArg } = createCallBinding(node.expression, hoistVariableDeclaration);
if (node.expression.kind === SyntaxKind.SuperKeyword) {
setEmitFlags(thisArg, EmitFlags.NoSubstitution);
}
resultingCall = createFunctionApply(
visitNode(target, callExpressionVisitor, isExpression),
visitNode(thisArg, visitor, isExpression),
transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)
);
}
else {
// [source]
// super(a)
// super.m(a) // in static
// super.m(a) // in instance
//
// [output]
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
resultingCall = createFunctionCall(
visitNode(target, callExpressionVisitor, isExpression),
visitNode(thisArg, visitor, isExpression),
visitNodes(node.arguments, visitor, isExpression),
/*location*/ node
);
}
let resultingCall: CallExpression | BinaryExpression;
if (node.transformFlags & TransformFlags.ContainsSpread) {
// [source]
// f(...a, b)
// x.m(...a, b)
// super(...a, b)
// super.m(...a, b) // in static
// super.m(...a, b) // in instance
//
// [output]
// f.apply(void 0, a.concat([b]))
// (_a = x).m.apply(_a, a.concat([b]))
// _super.apply(this, a.concat([b]))
// _super.m.apply(this, a.concat([b]))
// _super.prototype.m.apply(this, a.concat([b]))
if (node.expression.kind === SyntaxKind.SuperKeyword) {
const actualThis = createThis();
setEmitFlags(actualThis, EmitFlags.NoSubstitution);
const initializer =
createLogicalOr(
resultingCall,
actualThis
resultingCall = createFunctionApply(
visitNode(target, callExpressionVisitor, isExpression),
visitNode(thisArg, visitor, isExpression),
transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)
);
resultingCall = assignToCapturedThis
? createAssignment(createIdentifier("_this"), initializer)
: initializer;
}
else {
// [source]
// super(a)
// super.m(a) // in static
// super.m(a) // in instance
//
// [output]
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
resultingCall = createFunctionCall(
visitNode(target, callExpressionVisitor, isExpression),
visitNode(thisArg, visitor, isExpression),
visitNodes(node.arguments, visitor, isExpression),
/*location*/ node
);
}
if (node.expression.kind === SyntaxKind.SuperKeyword) {
const actualThis = createThis();
setEmitFlags(actualThis, EmitFlags.NoSubstitution);
const initializer =
createLogicalOr(
resultingCall,
actualThis
);
resultingCall = assignToCapturedThis
? createAssignment(createIdentifier("_this"), initializer)
: initializer;
}
return setOriginalNode(resultingCall, node);
}
return setOriginalNode(resultingCall, node);
return visitEachChild(node, visitor, context);
}
/**
+2 -3
View File
@@ -690,16 +690,15 @@ namespace ts {
return createCall(createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
}
function getHelperExpressionForImport(node: ImportDeclaration, innerExpr: Expression) {
if (!compilerOptions.esModuleInterop || getEmitFlags(node) & EmitFlags.NeverApplyImportHelper) {
return innerExpr;
}
if (getNamespaceDeclarationNode(node)) {
if (getImportNeedsImportStarHelper(node)) {
context.requestEmitHelper(importStarHelper);
return createCall(getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (isDefaultImport(node)) {
if (getImportNeedsImportDefaultHelper(node)) {
context.requestEmitHelper(importDefaultHelper);
return createCall(getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
+29 -1
View File
@@ -15,6 +15,32 @@ namespace ts {
hasExportStarsToExportValues: boolean; // whether this module contains export*
}
function getNamedImportCount(node: ImportDeclaration) {
if (!(node.importClause && node.importClause.namedBindings)) return 0;
const names = node.importClause.namedBindings;
if (!names) return 0;
if (!isNamedImports(names)) return 0;
return names.elements.length;
}
function containsDefaultReference(node: NamedImportBindings) {
if (!node) return false;
if (!isNamedImports(node)) return false;
return some(node.elements, isNamedDefaultReference);
}
function isNamedDefaultReference(e: ImportSpecifier) {
return e.propertyName && e.propertyName.escapedText === InternalSymbolName.Default;
}
export function getImportNeedsImportStarHelper(node: ImportDeclaration) {
return !!getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings));
}
export function getImportNeedsImportDefaultHelper(node: ImportDeclaration) {
return isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings));
}
export function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver, compilerOptions: CompilerOptions): ExternalModuleInfo {
const externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[] = [];
const exportSpecifiers = createMultiMap<ExportSpecifier>();
@@ -24,6 +50,7 @@ namespace ts {
let hasExportDefault = false;
let exportEquals: ExportAssignment = undefined;
let hasExportStarsToExportValues = false;
let hasImportStarOrImportDefault = false;
for (const node of sourceFile.statements) {
switch (node.kind) {
@@ -33,6 +60,7 @@ namespace ts {
// import * as x from "mod"
// import { x, y } from "mod"
externalImports.push(<ImportDeclaration>node);
hasImportStarOrImportDefault = getImportNeedsImportStarHelper(<ImportDeclaration>node) || getImportNeedsImportDefaultHelper(<ImportDeclaration>node);
break;
case SyntaxKind.ImportEqualsDeclaration:
@@ -135,7 +163,7 @@ namespace ts {
}
}
const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues);
const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault);
const externalHelpersImportDeclaration = externalHelpersModuleName && createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
+8 -4
View File
@@ -2901,7 +2901,7 @@ namespace ts {
// Should not be called directly. Should only be accessed through the Program instance.
/* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
/* @internal */ getGlobalDiagnostics(): Diagnostic[];
/* @internal */ getEmitResolver(sourceFile?: SourceFile, cancellationToken?: CancellationToken, ignoreDiagnostics?: boolean): EmitResolver;
/* @internal */ getEmitResolver(sourceFile?: SourceFile, cancellationToken?: CancellationToken): EmitResolver;
/* @internal */ getNodeCount(): number;
/* @internal */ getIdentifierCount(): number;
@@ -2946,7 +2946,7 @@ namespace ts {
// Options
NoTruncation = 1 << 0, // Don't truncate result
WriteArrayAsGenericType = 1 << 1, // Write Array<T> instead T[]
WriteDefaultSymbolWithoutName = 1 << 2, // Write `default`-named symbols as `default` instead of how they were written
// empty space
UseStructuralFallback = 1 << 3, // When an alias cannot be named by its symbol, rather than report an error, fallback to a structural printout if possible
// empty space
WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature
@@ -2974,6 +2974,7 @@ namespace ts {
// State
InObjectTypeLiteral = 1 << 22,
InTypeAlias = 1 << 23, // Writing type in type alias declaration
InInitialEntityName = 1 << 24, // Set when writing the LHS of an entity name or entity name expression
}
// Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
@@ -2981,7 +2982,7 @@ namespace ts {
None = 0,
NoTruncation = 1 << 0, // Don't truncate typeToString result
WriteArrayAsGenericType = 1 << 1, // Write Array<T> instead T[]
WriteDefaultSymbolWithoutName = 1 << 2, // Write all `defaut`-named symbols as `default` instead of their written name
// hole because there's a hole in node builder flags
UseStructuralFallback = 1 << 3, // When an alias cannot be named by its symbol, rather than report an error, fallback to a structural printout if possible
// hole because there's a hole in node builder flags
WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature
@@ -3012,7 +3013,7 @@ namespace ts {
/** @deprecated */ WriteOwnNameForAnyLike = 0, // Does nothing
NodeBuilderFlagsMask =
NoTruncation | WriteArrayAsGenericType | WriteDefaultSymbolWithoutName | UseStructuralFallback | WriteTypeArgumentsOfSignature |
NoTruncation | WriteArrayAsGenericType | UseStructuralFallback | WriteTypeArgumentsOfSignature |
UseFullyQualifiedType | SuppressAnyReturnType | MultilineObjectLiterals | WriteClassExpressionAsTypeLiteral |
UseTypeOfFunction | OmitParameterModifiers | UseAliasDefinedOutsideCurrentScope | AllowUniqueESSymbolType | InTypeAlias,
}
@@ -3033,6 +3034,9 @@ namespace ts {
// Build symbol name using any nodes needed, instead of just components of an entity name
AllowAnyNodeKind = 0x00000004,
// Prefer aliases which are not directly visible
UseAliasDefinedOutsideCurrentScope = 0x00000008,
}
/* @internal */
+12 -1
View File
@@ -681,10 +681,21 @@ namespace ts {
return getSpanOfTokenAtPosition(sourceFile, node.pos);
}
const pos = nodeIsMissing(errorNode)
const isMissing = nodeIsMissing(errorNode);
const pos = isMissing
? errorNode.pos
: skipTrivia(sourceFile.text, errorNode.pos);
// These asserts should all be satisfied for a properly constructed `errorNode`.
if (isMissing) {
Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
}
else {
Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
}
return createTextSpanFromBounds(pos, errorNode.end);
}
+25 -17
View File
@@ -31,8 +31,11 @@ namespace ts {
};
}
function clearScreenIfNotWatchingForFileChanges(system: System, diagnostic: Diagnostic) {
if (system.clearScreen && diagnostic.code !== Diagnostics.Compilation_complete_Watching_for_file_changes.code) {
function clearScreenIfNotWatchingForFileChanges(system: System, diagnostic: Diagnostic, options: CompilerOptions) {
if (system.clearScreen &&
diagnostic.code !== Diagnostics.Compilation_complete_Watching_for_file_changes.code &&
!options.extendedDiagnostics &&
!options.diagnostics) {
system.clearScreen();
}
}
@@ -42,18 +45,18 @@ namespace ts {
*/
export function createWatchStatusReporter(system: System, pretty?: boolean): WatchStatusReporter {
return pretty ?
(diagnostic: Diagnostic, newLine: string) => {
clearScreenIfNotWatchingForFileChanges(system, diagnostic);
let output = `[${ formatColorAndReset(new Date().toLocaleTimeString(), ForegroundColorEscapeSequences.Grey) }] `;
output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${newLine + newLine + newLine}`;
system.write(output);
} :
(diagnostic: Diagnostic, newLine: string) => {
clearScreenIfNotWatchingForFileChanges(system, diagnostic);
let output = new Date().toLocaleTimeString() + " - ";
output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${newLine + newLine + newLine}`;
system.write(output);
};
(diagnostic, newLine, options) => {
clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
let output = `[${formatColorAndReset(new Date().toLocaleTimeString(), ForegroundColorEscapeSequences.Grey)}] `;
output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${newLine + newLine + newLine}`;
system.write(output);
} :
(diagnostic, newLine, options) => {
clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
let output = new Date().toLocaleTimeString() + " - ";
output += `${flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)}${newLine + newLine + newLine}`;
system.write(output);
};
}
/**
@@ -254,7 +257,7 @@ namespace ts {
namespace ts {
export type DiagnosticReporter = (diagnostic: Diagnostic) => void;
export type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string) => void;
export type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void;
export type CreateProgram<T extends BuilderProgram> = (rootNames: ReadonlyArray<string>, options: CompilerOptions, host?: CompilerHost, oldProgram?: T) => T;
export interface WatchCompilerHost<T extends BuilderProgram> {
/**
@@ -264,7 +267,7 @@ namespace ts {
/** If provided, callback to invoke after every new program creation */
afterProgramCreate?(program: T): void;
/** If provided, called with Diagnostic message that informs about change in watch status */
onWatchStatusChange?(diagnostic: Diagnostic, newLine: string): void;
onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void;
// Only for testing
/*@internal*/
@@ -477,6 +480,7 @@ namespace ts {
const watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher;
const watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher;
writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`);
if (configFileName) {
watchFile(host, configFileName, scheduleProgramReload, writeLog);
}
@@ -570,6 +574,10 @@ namespace ts {
}
// Compile the program
if (loggingEnabled) {
writeLog(`CreatingProgramWith::\n roots: ${JSON.stringify(rootFileNames)}\n options: ${JSON.stringify(compilerOptions)}`);
}
const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program;
hasChangedCompilerOptions = false;
resolutionCache.startCachingPerDirectoryResolution();
@@ -725,7 +733,7 @@ namespace ts {
function reportWatchDiagnostic(message: DiagnosticMessage) {
if (host.onWatchStatusChange) {
host.onWatchStatusChange(createCompilerDiagnostic(message), newLine);
host.onWatchStatusChange(createCompilerDiagnostic(message), newLine, compilerOptions);
}
}
+13
View File
@@ -2859,6 +2859,15 @@ Actual: ${stringify(fullActual)}`);
}
}
public verifyNoDocumentHighlights(startRange: Range) {
this.goToRangeStart(startRange);
const documentHighlights = this.getDocumentHighlightsAtCurrentPosition([this.activeFile.fileName]);
const numHighlights = ts.length(documentHighlights);
if (numHighlights > 0) {
this.raiseError(`verifyNoDocumentHighlights failed - unexpectedly got ${numHighlights} highlights`);
}
}
private verifyDocumentHighlights(expectedRanges: Range[], fileNames: string[] = [this.activeFile.fileName]) {
const documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNames) || [];
@@ -4267,6 +4276,10 @@ namespace FourSlashInterface {
this.state.verifyDocumentHighlightsOf(startRange, ranges);
}
public noDocumentHighlights(startRange: FourSlash.Range) {
this.state.verifyNoDocumentHighlights(startRange);
}
public completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]) {
this.state.verifyCompletionEntryDetails(entryName, text, documentation, kind, tags);
}
-7
View File
@@ -70,13 +70,6 @@ namespace ts {
// Change e.ts and verify previously b.js as well as a.js get emitted again since previous change was consumed completely but not d.ts
program = updateProgramFile(program, "/e.ts", "export function bar3() { }");
assertChanges(["/b.js", "/a.js", "/e.js"]);
// Cancel in the middle of affected files list after b.js emit
program = updateProgramFile(program, "/b.ts", "export class b { foo2() { c + 1; } }");
assertChanges(["/b.js", "/a.js"], 1);
// Change e.ts and verify previously b.js as well as a.js get emitted again since previous change was consumed completely but not d.ts
program = updateProgramFile(program, "/e.ts", "export function bar5() { }");
assertChanges(["/b.js", "/a.js", "/e.js"]);
});
});
@@ -457,6 +457,7 @@ namespace ts {
maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true,
skipLibCheck: true,
noEmit: true,
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
noImplicitAny: false,
@@ -486,6 +487,7 @@ namespace ts {
maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true,
skipLibCheck: true,
noEmit: true,
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
noImplicitAny: false,
@@ -510,7 +512,8 @@ namespace ts {
allowJs: true,
maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true,
skipLibCheck: true
skipLibCheck: true,
noEmit: true
},
errors: [{
file: undefined,
@@ -532,7 +535,8 @@ namespace ts {
allowJs: true,
maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true,
skipLibCheck: true
skipLibCheck: true,
noEmit: true
},
errors: []
}
+1
View File
@@ -185,6 +185,7 @@ namespace ts.projectSystem {
allowSyntheticDefaultImports: true,
maxNodeModuleJsDepth: 2,
skipLibCheck: true,
noEmit: true
};
it("sends telemetry for typeAcquisition settings", () => {
+58 -21
View File
@@ -1086,6 +1086,33 @@ namespace ts.tscWatch {
// This should be 0
host.checkTimeoutQueueLengthAndRun(0);
});
it("shouldnt report error about unused function incorrectly when file changes from global to module", () => {
const getFileContent = (asModule: boolean) => `
function one() {}
${asModule ? "export " : ""}function two() {
return function three() {
one();
}
}`;
const file: FileOrFolder = {
path: "/a/b/file.ts",
content: getFileContent(/*asModule*/ false)
};
const files = [file, libFile];
const host = createWatchedSystem(files);
const watch = createWatchOfFilesAndCompilerOptions([file.path], host, {
noUnusedLocals: true
});
checkProgramActualFiles(watch(), files.map(file => file.path));
checkOutputErrors(host, [], ExpectedOutputErrorsPosition.AfterCompilationStarting);
file.content = getFileContent(/*asModule*/ true);
host.reloadFS(files);
host.runQueuedTimeoutCallbacks();
checkProgramActualFiles(watch(), files.map(file => file.path));
checkOutputErrors(host, [], ExpectedOutputErrorsPosition.AfterFileChangeDetected);
});
});
describe("tsc-watch emit with outFile or out setting", () => {
@@ -2075,35 +2102,45 @@ declare module "fs" {
});
describe("tsc-watch console clearing", () => {
it("clears the console when it starts", () => {
function checkConsoleClearing(diagnostics: boolean, extendedDiagnostics: boolean) {
const file = {
path: "f.ts",
content: ""
};
const host = createWatchedSystem([file]);
const files = [file];
const host = createWatchedSystem(files);
let clearCount: number | undefined;
checkConsoleClears();
createWatchOfFilesAndCompilerOptions([file.path], host);
createWatchOfFilesAndCompilerOptions([file.path], host, { diagnostics, extendedDiagnostics });
checkConsoleClears();
file.content = "//";
host.reloadFS(files);
host.runQueuedTimeoutCallbacks();
host.checkScreenClears(1);
checkConsoleClears();
function checkConsoleClears() {
if (clearCount === undefined) {
clearCount = 0;
}
else if (!diagnostics && !extendedDiagnostics) {
clearCount++;
}
host.checkScreenClears(clearCount);
return clearCount;
}
}
it("without --diagnostics or --extendedDiagnostics", () => {
checkConsoleClearing(/*diagnostics*/ false, /*extendedDiagnostics*/ false);
});
it("clears the console on recompile", () => {
const file = {
path: "f.ts",
content: ""
};
const host = createWatchedSystem([file]);
createWatchOfFilesAndCompilerOptions([file.path], host);
const modifiedFile = {
...file,
content: "//"
};
host.reloadFS([modifiedFile]);
host.runQueuedTimeoutCallbacks();
host.checkScreenClears(2);
it("with --diagnostics", () => {
checkConsoleClearing(/*diagnostics*/ true, /*extendedDiagnostics*/ false);
});
it("with --extendedDiagnostics", () => {
checkConsoleClearing(/*diagnostics*/ false, /*extendedDiagnostics*/ true);
});
});
}
@@ -6795,4 +6795,48 @@ namespace ts.projectSystem {
}
});
});
describe("tsserverProjectSystem forceConsistentCasingInFileNames", () => {
it("works when extends is specified with a case insensitive file system", () => {
const rootPath = "/Users/username/dev/project";
const file1: FileOrFolder = {
path: `${rootPath}/index.ts`,
content: 'import {x} from "file2";',
};
const file2: FileOrFolder = {
path: `${rootPath}/file2.js`,
content: "",
};
const file2Dts: FileOrFolder = {
path: `${rootPath}/types/file2/index.d.ts`,
content: "export declare const x: string;",
};
const tsconfigAll: FileOrFolder = {
path: `${rootPath}/tsconfig.all.json`,
content: JSON.stringify({
compilerOptions: {
baseUrl: ".",
paths: { file2: ["./file2.js"] },
typeRoots: ["./types"],
forceConsistentCasingInFileNames: true,
},
}),
};
const tsconfig: FileOrFolder = {
path: `${rootPath}/tsconfig.json`,
content: JSON.stringify({ extends: "./tsconfig.all.json" }),
};
const host = createServerHost([file1, file2, file2Dts, libFile, tsconfig, tsconfigAll], { useCaseSensitiveFileNames: false });
const session = createSession(host);
openFilesForSession([file1], session);
const projectService = session.getProjectService();
checkNumberOfProjects(projectService, { configuredProjects: 1 });
const diagnostics = configuredProjectAt(projectService, 0).getLanguageService().getCompilerOptionsDiagnostics();
assert.deepEqual(diagnostics, []);
});
});
}
+11 -4
View File
@@ -992,12 +992,12 @@ interface ReadonlyArray<T> {
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: (T[] | ReadonlyArray<T>)[]): T[];
concat(...items: ConcatArray<T>[]): T[];
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: (T | T[] | ReadonlyArray<T>)[]): T[];
concat(...items: (T | ConcatArray<T>)[]): T[];
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
@@ -1087,6 +1087,13 @@ interface ReadonlyArray<T> {
readonly [n: number]: T;
}
interface ConcatArray<T> {
readonly length: number;
readonly [n: number]: T;
join(separator?: string): string;
slice(start?: number, end?: number): T[];
}
interface Array<T> {
/**
* Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
@@ -1113,12 +1120,12 @@ interface Array<T> {
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: (T[] | ReadonlyArray<T>)[]): T[];
concat(...items: ConcatArray<T>[]): T[];
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: (T | T[] | ReadonlyArray<T>)[]): T[];
concat(...items: (T | ConcatArray<T>)[]): T[];
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
@@ -14,7 +14,7 @@
<Cmt Name="LcxAdmin" />
<Cmt Name="Loc" />
<Cmt Name="Note" />
<Cmt Name="RCCX" />
<Cmt Name="Rccx" />
</OwnedComments>
<Settings Name="@vsLocTools@\current\default.lss" Type="LSS" />
<Item ItemId=";String Table" ItemType="0" PsrId="306" Leaf="false">
@@ -5103,6 +5103,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_emit_d_ts_declaration_files_6014" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only emit '.d.ts' declaration files.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[只發出 '.d.ts' 宣告檔案。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.]]></Val>
@@ -8647,7 +8656,7 @@
<Str Cat="Text">
<Val><![CDATA['enum declarations' can only be used in a .ts file.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['enum declarations' 只可用於 .ts 檔案中。]]></Val>
<Val><![CDATA[「列舉宣告」只可用於 .ts 檔案中。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -19,7 +19,7 @@
<Cmt Name="ManifestData" />
<Cmt Name="Mnemonic" />
<Cmt Name="Note" />
<Cmt Name="RCCX" />
<Cmt Name="Rccx" />
<Cmt Name="UIType" />
<Cmt Name="UTSData" />
<Cmt Name="UTSUI" />
@@ -5112,6 +5112,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_emit_d_ts_declaration_files_6014" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only emit '.d.ts' declaration files.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Bude vydávat jen soubory deklarací .d.ts.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.]]></Val>
@@ -8656,7 +8665,7 @@
<Str Cat="Text">
<Val><![CDATA['enum declarations' can only be used in a .ts file.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Deklarace výčtu se dají použít jenom v souboru .ts.]]></Val>
<Val><![CDATA[Deklarace enum se dají použít jen v souboru .ts.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -14,7 +14,7 @@
<Cmt Name="LcxAdmin" />
<Cmt Name="Loc" />
<Cmt Name="Note" />
<Cmt Name="RCCX" />
<Cmt Name="Rccx" />
</OwnedComments>
<Settings Name="@vsLocTools@\current\default.lss" Type="LSS" />
<Item ItemId=";String Table" ItemType="0" PsrId="306" Leaf="false">
@@ -5100,6 +5100,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_emit_d_ts_declaration_files_6014" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only emit '.d.ts' declaration files.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Geben Sie nur .d.ts-Deklarationsdateien aus.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.]]></Val>
@@ -8638,7 +8647,7 @@
<Str Cat="Text">
<Val><![CDATA['enum declarations' can only be used in a .ts file.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA["enum declarations" kann nur in einer TS-Datei verwendet werden.]]></Val>
<Val><![CDATA[enum-Deklarationen können nur in einer TS-Datei verwendet werden.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -19,7 +19,7 @@
<Cmt Name="ManifestData" />
<Cmt Name="Mnemonic" />
<Cmt Name="Note" />
<Cmt Name="RCCX" />
<Cmt Name="Rccx" />
<Cmt Name="UIType" />
<Cmt Name="UTSData" />
<Cmt Name="UTSUI" />
@@ -5112,6 +5112,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_emit_d_ts_declaration_files_6014" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only emit '.d.ts' declaration files.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Solo deben emitirse archivos de declaración ".d.ts".]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.]]></Val>
@@ -8656,7 +8665,7 @@
<Str Cat="Text">
<Val><![CDATA['enum declarations' can only be used in a .ts file.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA["enum declarations" solo se puede usar en un archivo .ts.]]></Val>
<Val><![CDATA[Las declaraciones "enum" solo se pueden usar en un archivo .ts.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -14,7 +14,7 @@
<Cmt Name="LcxAdmin" />
<Cmt Name="Loc" />
<Cmt Name="Note" />
<Cmt Name="RCCX" />
<Cmt Name="Rccx" />
</OwnedComments>
<Settings Name="@vsLocTools@\current\default.lss" Type="LSS" />
<Item ItemId=";String Table" ItemType="0" PsrId="306" Leaf="false">
@@ -5103,6 +5103,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_emit_d_ts_declaration_files_6014" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only emit '.d.ts' declaration files.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['.d.ts' 宣言ファイルのみを生成します。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.]]></Val>
@@ -14,7 +14,7 @@
<Cmt Name="LcxAdmin" />
<Cmt Name="Loc" />
<Cmt Name="Note" />
<Cmt Name="RCCX" />
<Cmt Name="Rccx" />
</OwnedComments>
<Settings Name="@vsLocTools@\current\default.lss" Type="LSS" />
<Item ItemId=";String Table" ItemType="0" PsrId="306" Leaf="false">
@@ -5103,6 +5103,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_emit_d_ts_declaration_files_6014" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only emit '.d.ts' declaration files.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['.d.ts' 선언 파일만 내보냅니다.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.]]></Val>
@@ -8647,7 +8656,7 @@
<Str Cat="Text">
<Val><![CDATA['enum declarations' can only be used in a .ts file.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['enum declarations'는 .ts 파일에서만 사용할 수 있습니다.]]></Val>
<Val><![CDATA['enum 선언'은 .ts 파일에서만 사용할 수 있습니다.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -7,7 +7,7 @@
<Cmt Name="Dev" />
<Cmt Name="LcxAdmin" />
<Cmt Name="Loc" />
<Cmt Name="RCCX" />
<Cmt Name="Rccx" />
</OwnedComments>
<Settings Name="@vsLocTools@\current\default.lss" Type="LSS" />
<Item ItemId=";String Table" ItemType="0" PsrId="306" Leaf="false">
@@ -5093,6 +5093,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_emit_d_ts_declaration_files_6014" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only emit '.d.ts' declaration files.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Emituj tylko pliki deklaracji „d.ts”.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.]]></Val>
@@ -8631,7 +8640,7 @@
<Str Cat="Text">
<Val><![CDATA['enum declarations' can only be used in a .ts file.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Deklaracji wyliczeń można używać tylko w pliku ts.]]></Val>
<Val><![CDATA[Deklaracji enum można używać tylko w pliku ts.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -7,7 +7,7 @@
<Cmt Name="Dev" />
<Cmt Name="LcxAdmin" />
<Cmt Name="Loc" />
<Cmt Name="RCCX" />
<Cmt Name="Rccx" />
</OwnedComments>
<Settings Name="@vsLocTools@\current\default.lss" Type="LSS" />
<Item ItemId=";String Table" ItemType="0" PsrId="306" Leaf="false">
@@ -5093,6 +5093,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_emit_d_ts_declaration_files_6014" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only emit '.d.ts' declaration files.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Emita somente arquivos de declaração '.d.ts'.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.]]></Val>
@@ -13,7 +13,7 @@
<Cmt Name="Dev" />
<Cmt Name="LcxAdmin" />
<Cmt Name="Note" />
<Cmt Name="RCCX" />
<Cmt Name="Rccx" />
</OwnedComments>
<Settings Name="@vsLocTools@\current\default.lss" Type="LSS" />
<Item ItemId=";String Table" ItemType="0" PsrId="306" Leaf="false">
@@ -5102,6 +5102,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_emit_d_ts_declaration_files_6014" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only emit '.d.ts' declaration files.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Порождаются только файлы объявлений ".d.ts".]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.]]></Val>
@@ -8646,7 +8655,7 @@
<Str Cat="Text">
<Val><![CDATA['enum declarations' can only be used in a .ts file.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Объявления перечислений могут использоваться только в TS-файле.]]></Val>
<Val><![CDATA[Объявления перечислений можно использовать только в TS-файле.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -7,7 +7,7 @@
<Cmt Name="Dev" />
<Cmt Name="LcxAdmin" />
<Cmt Name="Loc" />
<Cmt Name="RCCX" />
<Cmt Name="Rccx" />
</OwnedComments>
<Settings Name="@vsLocTools@\current\default.lss" Type="LSS" />
<Item ItemId=";String Table" ItemType="0" PsrId="306" Leaf="false">
@@ -5096,6 +5096,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_emit_d_ts_declaration_files_6014" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only emit '.d.ts' declaration files.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Yalnızca '.d.ts' bildirim dosyalarını yayımla.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.]]></Val>
+10
View File
@@ -22,6 +22,15 @@
"References": {
"match": "^(.*\\/_references\\.js)$",
"exclude": [["^", 1, "$"]]
},
"Datatables.net": {
"match": "^.*\\/(jquery\\.)?dataTables(\\.all)?(\\.min)?\\.js$",
"types": ["datatables.net"]
},
"Ace": {
"match": "^(.*)\\/ace.js",
"exclude": [["^", 1, "/.*"]],
"types": ["ace"]
}
},
"simpleMap": {
@@ -352,6 +361,7 @@
"passport": "passport",
"passport-local": "passport-local",
"path": "pathjs",
"pdfkit":"pdfkit",
"peer": "peerjs",
"peg": "pegjs",
"photoswipe": "photoswipe",
@@ -21,6 +21,8 @@ namespace ts.codefix {
}
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Identifier): void {
changes.replaceNode(sourceFile, token, createPropertyAccess(createThis(), token));
// TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper
suppressLeadingAndTrailingTrivia(token);
changes.replaceRange(sourceFile, { pos: token.getStart(), end: token.end }, createPropertyAccess(createThis(), token));
}
}
+2 -1
View File
@@ -1921,7 +1921,8 @@ namespace ts.Completions {
return isDeclarationName(contextToken)
&& !isJsxAttribute(contextToken.parent)
// Don't block completions if we're in `class C /**/`, because we're *past* the end of the identifier and might want to complete `extends`.
&& !(isClassLike(contextToken.parent) && position > previousToken.end);
// If `contextToken !== previousToken`, this is `class C ex/**/`.
&& !(isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end));
}
function isFunctionLikeButNotConstructor(kind: SyntaxKind) {
+1 -1
View File
@@ -366,7 +366,7 @@ namespace ts.FindAllReferences.Core {
if (node.kind === SyntaxKind.DefaultKeyword) {
addReference(node, symbol, node, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: symbol.parent, exportKind: ExportKind.Default }, state);
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: ExportKind.Default }, state);
}
else {
const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) });
+1 -2
View File
@@ -491,8 +491,7 @@ namespace ts.FindAllReferences {
function getExportAssignmentExport(ex: ExportAssignment): ExportedSymbol {
// Get the symbol for the `export =` node; its parent is the module it's the export of.
const exportingModuleSymbol = ex.symbol.parent;
Debug.assert(!!exportingModuleSymbol);
const exportingModuleSymbol = Debug.assertDefined(ex.symbol.parent, "Expected export symbol to have a parent");
const exportKind = ex.isExportEquals ? ExportKind.ExportEquals : ExportKind.Default;
return { kind: ImportExport.Export, symbol, exportInfo: { exportingModuleSymbol, exportKind } };
}
+7
View File
@@ -335,6 +335,13 @@ namespace ts.refactor.extractSymbol {
Continue = 1 << 1,
Return = 1 << 2
}
// We believe it's true because the node is from the (unmodified) tree.
Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
// For understanding how skipTrivia functioned:
Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) {
return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)];
}
+4 -4
View File
@@ -353,6 +353,7 @@ namespace ts.SignatureHelp {
return children[indexOfOpenerToken + 1];
}
const signatureHelpNodeBuilderFlags = NodeBuilderFlags.OmitParameterModifiers | NodeBuilderFlags.IgnoreErrors;
function createSignatureHelpItems(candidates: Signature[], resolvedSignature: Signature, argumentListInfo: ArgumentListInfo, typeChecker: TypeChecker): SignatureHelpItems {
const { argumentCount, argumentsSpan: applicableSpan, invocation, argumentIndex } = argumentListInfo;
const isTypeParameterList = argumentListInfo.kind === ArgumentListKind.TypeArguments;
@@ -378,9 +379,8 @@ namespace ts.SignatureHelp {
signatureHelpParameters = typeParameters && typeParameters.length > 0 ? map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray;
suffixDisplayParts.push(punctuationPart(SyntaxKind.GreaterThanToken));
const parameterParts = mapToDisplayParts(writer => {
const flags = NodeBuilderFlags.OmitParameterModifiers | NodeBuilderFlags.IgnoreErrors;
const thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : [];
const params = createNodeArray([...thisParameter, ...map(candidateSignature.parameters, param => typeChecker.symbolToParameterDeclaration(param, invocation, flags))]);
const thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : [];
const params = createNodeArray([...thisParameter, ...map(candidateSignature.parameters, param => typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags))]);
printer.writeList(ListFormat.CallExpressionArguments, params, getSourceFileOfNode(getParseTreeNode(invocation)), writer);
});
addRange(suffixDisplayParts, parameterParts);
@@ -435,7 +435,7 @@ namespace ts.SignatureHelp {
function createSignatureHelpParameterForParameter(parameter: Symbol): SignatureHelpParameter {
const displayParts = mapToDisplayParts(writer => {
const param = typeChecker.symbolToParameterDeclaration(parameter, invocation, NodeBuilderFlags.OmitParameterModifiers | NodeBuilderFlags.IgnoreErrors);
const param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags);
printer.writeNode(EmitHint.Unspecified, param, getSourceFileOfNode(getParseTreeNode(invocation)), writer);
});
+1 -1
View File
@@ -1300,7 +1300,7 @@ namespace ts {
export function symbolToDisplayParts(typeChecker: TypeChecker, symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): SymbolDisplayPart[] {
return mapToDisplayParts(writer => {
typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer);
typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | SymbolFormatFlags.UseAliasDefinedOutsideCurrentScope, writer);
});
}