mirror of
https://github.com/microsoft/TypeScript.git
synced 2026-06-18 13:59:04 -05:00
Merge branch 'master' into asyncGenerators
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
/// <reference path="moduleNameResolver.ts"/>
|
||||
/// <reference path="moduleNameResolver.ts"/>
|
||||
/// <reference path="binder.ts"/>
|
||||
|
||||
/* @internal */
|
||||
@@ -60,9 +60,9 @@ namespace ts {
|
||||
|
||||
const emitResolver = createResolver();
|
||||
|
||||
const undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined");
|
||||
const undefinedSymbol = createSymbol(SymbolFlags.Property, "undefined");
|
||||
undefinedSymbol.declarations = [];
|
||||
const argumentsSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "arguments");
|
||||
const argumentsSymbol = createSymbol(SymbolFlags.Property, "arguments");
|
||||
|
||||
const checker: TypeChecker = {
|
||||
getNodeCount: () => sum(host.getSourceFiles(), "nodeCount"),
|
||||
@@ -131,8 +131,8 @@ namespace ts {
|
||||
const indexedAccessTypes = createMap<IndexedAccessType>();
|
||||
const evolvingArrayTypes: EvolvingArrayType[] = [];
|
||||
|
||||
const unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown");
|
||||
const resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__");
|
||||
const unknownSymbol = createSymbol(SymbolFlags.Property, "unknown");
|
||||
const resolvingSymbol = createSymbol(0, "__resolving__");
|
||||
|
||||
const anyType = createIntrinsicType(TypeFlags.Any, "any");
|
||||
const autoType = createIntrinsicType(TypeFlags.Any, "any");
|
||||
@@ -154,7 +154,7 @@ namespace ts {
|
||||
|
||||
const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
|
||||
|
||||
const emptyTypeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral | SymbolFlags.Transient, "__type");
|
||||
const emptyTypeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type");
|
||||
emptyTypeLiteralSymbol.members = createMap<Symbol>();
|
||||
const emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined);
|
||||
|
||||
@@ -404,9 +404,11 @@ namespace ts {
|
||||
diagnostics.add(diagnostic);
|
||||
}
|
||||
|
||||
function createSymbol(flags: SymbolFlags, name: string): Symbol {
|
||||
function createSymbol(flags: SymbolFlags, name: string) {
|
||||
symbolCount++;
|
||||
return new Symbol(flags, name);
|
||||
const symbol = <TransientSymbol>(new Symbol(flags | SymbolFlags.Transient, name));
|
||||
symbol.checkFlags = 0;
|
||||
return symbol;
|
||||
}
|
||||
|
||||
function getExcludedSymbolFlags(flags: SymbolFlags): SymbolFlags {
|
||||
@@ -439,7 +441,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function cloneSymbol(symbol: Symbol): Symbol {
|
||||
const result = createSymbol(symbol.flags | SymbolFlags.Merged, symbol.name);
|
||||
const result = createSymbol(symbol.flags, symbol.name);
|
||||
result.declarations = symbol.declarations.slice(0);
|
||||
result.parent = symbol.parent;
|
||||
if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
|
||||
@@ -496,7 +498,7 @@ namespace ts {
|
||||
target.set(id, sourceSymbol);
|
||||
}
|
||||
else {
|
||||
if (!(targetSymbol.flags & SymbolFlags.Merged)) {
|
||||
if (!(targetSymbol.flags & SymbolFlags.Transient)) {
|
||||
targetSymbol = cloneSymbol(targetSymbol);
|
||||
target.set(id, targetSymbol);
|
||||
}
|
||||
@@ -533,7 +535,7 @@ namespace ts {
|
||||
if (mainModule.flags & SymbolFlags.Namespace) {
|
||||
// if module symbol has already been merged - it is safe to use it.
|
||||
// otherwise clone it
|
||||
mainModule = mainModule.flags & SymbolFlags.Merged ? mainModule : cloneSymbol(mainModule);
|
||||
mainModule = mainModule.flags & SymbolFlags.Transient ? mainModule : cloneSymbol(mainModule);
|
||||
mergeSymbol(mainModule, moduleAugmentation.symbol);
|
||||
}
|
||||
else {
|
||||
@@ -574,6 +576,10 @@ namespace ts {
|
||||
return type.flags & TypeFlags.Object ? (<ObjectType>type).objectFlags : 0;
|
||||
}
|
||||
|
||||
function getCheckFlags(symbol: Symbol): CheckFlags {
|
||||
return symbol.flags & SymbolFlags.Transient ? (<TransientSymbol>symbol).checkFlags : 0;
|
||||
}
|
||||
|
||||
function isGlobalSourceFile(node: Node) {
|
||||
return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(<SourceFile>node);
|
||||
}
|
||||
@@ -582,7 +588,7 @@ namespace ts {
|
||||
if (meaning) {
|
||||
const symbol = symbols.get(name);
|
||||
if (symbol) {
|
||||
Debug.assert((symbol.flags & SymbolFlags.Instantiated) === 0, "Should never get an instantiated symbol here.");
|
||||
Debug.assert((getCheckFlags(symbol) & CheckFlags.Instantiated) === 0, "Should never get an instantiated symbol here.");
|
||||
if (symbol.flags & meaning) {
|
||||
return symbol;
|
||||
}
|
||||
@@ -1416,7 +1422,7 @@ namespace ts {
|
||||
else {
|
||||
Debug.fail("Unknown entity name kind.");
|
||||
}
|
||||
Debug.assert((symbol.flags & SymbolFlags.Instantiated) === 0, "Should never get an instantiated symbol here.");
|
||||
Debug.assert((getCheckFlags(symbol) & CheckFlags.Instantiated) === 0, "Should never get an instantiated symbol here.");
|
||||
return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
|
||||
}
|
||||
|
||||
@@ -1660,23 +1666,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function symbolIsValue(symbol: Symbol): boolean {
|
||||
// If it is an instantiated symbol, then it is a value if the symbol it is an
|
||||
// instantiation of is a value.
|
||||
if (symbol.flags & SymbolFlags.Instantiated) {
|
||||
return symbolIsValue(getSymbolLinks(symbol).target);
|
||||
}
|
||||
|
||||
// If the symbol has the value flag, it is trivially a value.
|
||||
if (symbol.flags & SymbolFlags.Value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If it is an alias, then it is a value if the symbol it resolves to is a value.
|
||||
if (symbol.flags & SymbolFlags.Alias) {
|
||||
return (resolveAlias(symbol).flags & SymbolFlags.Value) !== 0;
|
||||
}
|
||||
|
||||
return false;
|
||||
return !!(symbol.flags & SymbolFlags.Value || symbol.flags & SymbolFlags.Alias && resolveAlias(symbol).flags & SymbolFlags.Value);
|
||||
}
|
||||
|
||||
function findConstructorDeclaration(node: ClassLikeDeclaration): ConstructorDeclaration {
|
||||
@@ -2232,7 +2222,7 @@ namespace ts {
|
||||
if (parentSymbol) {
|
||||
// Write type arguments of instantiated class/interface here
|
||||
if (flags & SymbolFormatFlags.WriteTypeParametersOrArguments) {
|
||||
if (symbol.flags & SymbolFlags.Instantiated) {
|
||||
if (getCheckFlags(symbol) & CheckFlags.Instantiated) {
|
||||
buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol),
|
||||
(<TransientSymbol>symbol).mapper, writer, enclosingDeclaration);
|
||||
}
|
||||
@@ -2689,7 +2679,11 @@ namespace ts {
|
||||
writePunctuation(writer, SyntaxKind.ColonToken);
|
||||
writeSpace(writer);
|
||||
|
||||
buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack);
|
||||
let type = getTypeOfSymbol(p);
|
||||
if (isRequiredInitializedParameter(parameterNode)) {
|
||||
type = includeFalsyTypes(type, TypeFlags.Undefined);
|
||||
}
|
||||
buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack);
|
||||
}
|
||||
|
||||
function buildBindingPatternDisplay(bindingPattern: BindingPattern, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) {
|
||||
@@ -3270,6 +3264,16 @@ namespace ts {
|
||||
return strictNullChecks && optional ? includeFalsyTypes(type, TypeFlags.Undefined) : type;
|
||||
}
|
||||
|
||||
/** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
|
||||
function removeOptionalityFromAnnotation(annotatedType: Type, declaration: VariableLikeDeclaration): Type {
|
||||
const annotationIncludesUndefined = strictNullChecks &&
|
||||
declaration.kind === SyntaxKind.Parameter &&
|
||||
declaration.initializer &&
|
||||
getFalsyFlags(annotatedType) & TypeFlags.Undefined &&
|
||||
!(getFalsyFlags(checkExpression(declaration.initializer)) & TypeFlags.Undefined);
|
||||
return annotationIncludesUndefined ? getNonNullableType(annotatedType) : annotatedType;
|
||||
}
|
||||
|
||||
// Return the inferred type for a variable, parameter, or property declaration
|
||||
function getTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration, includeOptionality: boolean): Type {
|
||||
if (declaration.flags & NodeFlags.JavaScriptFile) {
|
||||
@@ -3304,7 +3308,8 @@ namespace ts {
|
||||
|
||||
// Use type from type annotation if one is present
|
||||
if (declaration.type) {
|
||||
return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality);
|
||||
const declaredType = removeOptionalityFromAnnotation(getTypeFromTypeNode(declaration.type), declaration);
|
||||
return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality);
|
||||
}
|
||||
|
||||
if ((compilerOptions.noImplicitAny || declaration.flags & NodeFlags.JavaScriptFile) &&
|
||||
@@ -3427,8 +3432,8 @@ namespace ts {
|
||||
}
|
||||
|
||||
const text = getTextOfPropertyName(name);
|
||||
const flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0);
|
||||
const symbol = <TransientSymbol>createSymbol(flags, text);
|
||||
const flags = SymbolFlags.Property | (e.initializer ? SymbolFlags.Optional : 0);
|
||||
const symbol = createSymbol(flags, text);
|
||||
symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
|
||||
symbol.bindingElement = e;
|
||||
members.set(symbol.name, symbol);
|
||||
@@ -3726,7 +3731,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getTypeOfSymbol(symbol: Symbol): Type {
|
||||
if (symbol.flags & SymbolFlags.Instantiated) {
|
||||
if (getCheckFlags(symbol) & CheckFlags.Instantiated) {
|
||||
return getTypeOfInstantiatedSymbol(symbol);
|
||||
}
|
||||
if (symbol.flags & (SymbolFlags.Variable | SymbolFlags.Property)) {
|
||||
@@ -3758,9 +3763,9 @@ namespace ts {
|
||||
return getObjectFlags(type) & ObjectFlags.Reference ? (<TypeReference>type).target : type;
|
||||
}
|
||||
|
||||
function hasBaseType(type: BaseType, checkBase: BaseType) {
|
||||
function hasBaseType(type: Type, checkBase: Type) {
|
||||
return check(type);
|
||||
function check(type: BaseType): boolean {
|
||||
function check(type: Type): boolean {
|
||||
if (getObjectFlags(type) & (ObjectFlags.ClassOrInterface | ObjectFlags.Reference)) {
|
||||
const target = <InterfaceType>getTargetType(type);
|
||||
return target === checkBase || forEach(getBaseTypes(target), check);
|
||||
@@ -4531,7 +4536,7 @@ namespace ts {
|
||||
s = cloneSignature(signature);
|
||||
if (forEach(unionSignatures, sig => sig.thisParameter)) {
|
||||
const thisType = getUnionType(map(unionSignatures, sig => getTypeOfSymbol(sig.thisParameter) || anyType), /*subtypeReduction*/ true);
|
||||
s.thisParameter = createTransientSymbol(signature.thisParameter, thisType);
|
||||
s.thisParameter = createSymbolWithType(signature.thisParameter, thisType);
|
||||
}
|
||||
// Clear resolved return type we possibly got from cloneSignature
|
||||
s.resolvedReturnType = undefined;
|
||||
@@ -4728,9 +4733,9 @@ namespace ts {
|
||||
const propName = (<LiteralType>t).text;
|
||||
const modifiersProp = getPropertyOfType(modifiersType, propName);
|
||||
const isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & SymbolFlags.Optional);
|
||||
const prop = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient | (isOptional ? SymbolFlags.Optional : 0), propName);
|
||||
const prop = createSymbol(SymbolFlags.Property | (isOptional ? SymbolFlags.Optional : 0), propName);
|
||||
prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? CheckFlags.Readonly : 0;
|
||||
prop.type = propType;
|
||||
prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp);
|
||||
if (propertySymbol) {
|
||||
prop.mappedTypeOrigin = propertySymbol;
|
||||
}
|
||||
@@ -4961,18 +4966,19 @@ namespace ts {
|
||||
}
|
||||
|
||||
function createUnionOrIntersectionProperty(containingType: UnionOrIntersectionType, name: string): Symbol {
|
||||
const types = containingType.types;
|
||||
const excludeModifiers = containingType.flags & TypeFlags.Union ? ModifierFlags.Private | ModifierFlags.Protected : 0;
|
||||
let props: Symbol[];
|
||||
const types = containingType.types;
|
||||
const isUnion = containingType.flags & TypeFlags.Union;
|
||||
const excludeModifiers = isUnion ? ModifierFlags.NonPublicAccessibilityModifier : 0;
|
||||
// Flags we want to propagate to the result if they exist in all source symbols
|
||||
let commonFlags = (containingType.flags & TypeFlags.Intersection) ? SymbolFlags.Optional : SymbolFlags.None;
|
||||
let isReadonly = false;
|
||||
let isPartial = false;
|
||||
let commonFlags = isUnion ? SymbolFlags.None : SymbolFlags.Optional;
|
||||
let checkFlags = CheckFlags.SyntheticProperty;
|
||||
for (const current of types) {
|
||||
const type = getApparentType(current);
|
||||
if (type !== unknownType) {
|
||||
const prop = getPropertyOfType(type, name);
|
||||
if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & excludeModifiers)) {
|
||||
const modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0;
|
||||
if (prop && !(modifiers & excludeModifiers)) {
|
||||
commonFlags &= prop.flags;
|
||||
if (!props) {
|
||||
props = [prop];
|
||||
@@ -4980,26 +4986,26 @@ namespace ts {
|
||||
else if (!contains(props, prop)) {
|
||||
props.push(prop);
|
||||
}
|
||||
if (isReadonlySymbol(prop)) {
|
||||
isReadonly = true;
|
||||
}
|
||||
|
||||
checkFlags |= (isReadonlySymbol(prop) ? CheckFlags.Readonly : 0) |
|
||||
(!(modifiers & ModifierFlags.NonPublicAccessibilityModifier) ? CheckFlags.ContainsPublic : 0) |
|
||||
(modifiers & ModifierFlags.Protected ? CheckFlags.ContainsProtected : 0) |
|
||||
(modifiers & ModifierFlags.Private ? CheckFlags.ContainsPrivate : 0) |
|
||||
(modifiers & ModifierFlags.Static ? CheckFlags.ContainsStatic : 0);
|
||||
}
|
||||
else if (containingType.flags & TypeFlags.Union) {
|
||||
isPartial = true;
|
||||
else if (isUnion) {
|
||||
checkFlags |= CheckFlags.Partial;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!props) {
|
||||
return undefined;
|
||||
}
|
||||
if (props.length === 1 && !isPartial) {
|
||||
if (props.length === 1 && !(checkFlags & CheckFlags.Partial)) {
|
||||
return props[0];
|
||||
}
|
||||
const propTypes: Type[] = [];
|
||||
const declarations: Declaration[] = [];
|
||||
let commonType: Type = undefined;
|
||||
let hasNonUniformType = false;
|
||||
for (const prop of props) {
|
||||
if (prop.declarations) {
|
||||
addRange(declarations, prop.declarations);
|
||||
@@ -5009,17 +5015,15 @@ namespace ts {
|
||||
commonType = type;
|
||||
}
|
||||
else if (type !== commonType) {
|
||||
hasNonUniformType = true;
|
||||
checkFlags |= CheckFlags.HasNonUniformType;
|
||||
}
|
||||
propTypes.push(type);
|
||||
}
|
||||
const result = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient | SymbolFlags.SyntheticProperty | commonFlags, name);
|
||||
const result = createSymbol(SymbolFlags.Property | commonFlags, name);
|
||||
result.checkFlags = checkFlags;
|
||||
result.containingType = containingType;
|
||||
result.hasNonUniformType = hasNonUniformType;
|
||||
result.isPartial = isPartial;
|
||||
result.declarations = declarations;
|
||||
result.isReadonly = isReadonly;
|
||||
result.type = containingType.flags & TypeFlags.Union ? getUnionType(propTypes) : getIntersectionType(propTypes);
|
||||
result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -5043,7 +5047,7 @@ namespace ts {
|
||||
function getPropertyOfUnionOrIntersectionType(type: UnionOrIntersectionType, name: string): Symbol {
|
||||
const property = getUnionOrIntersectionProperty(type, name);
|
||||
// We need to filter out partial properties in union types
|
||||
return property && !(property.flags & SymbolFlags.SyntheticProperty && (<TransientSymbol>property).isPartial) ? property : undefined;
|
||||
return property && !(getCheckFlags(property) & CheckFlags.Partial) ? property : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -5206,6 +5210,12 @@ namespace ts {
|
||||
Debug.assert(parameterIndex >= 0);
|
||||
return parameterIndex >= signature.minArgumentCount;
|
||||
}
|
||||
const iife = getImmediatelyInvokedFunctionExpression(node.parent);
|
||||
if (iife) {
|
||||
return !node.type &&
|
||||
!node.dotDotDotToken &&
|
||||
indexOf((node.parent as SignatureDeclaration).parameters, node) >= iife.arguments.length;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -5906,7 +5916,7 @@ namespace ts {
|
||||
for (let i = 0; i < arity; i++) {
|
||||
const typeParameter = <TypeParameter>createType(TypeFlags.TypeParameter);
|
||||
typeParameters.push(typeParameter);
|
||||
const property = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "" + i);
|
||||
const property = createSymbol(SymbolFlags.Property, "" + i);
|
||||
property.type = typeParameter;
|
||||
properties.push(property);
|
||||
}
|
||||
@@ -6152,7 +6162,10 @@ namespace ts {
|
||||
if (type.flags & TypeFlags.Union && typeSet.unionIndex === undefined) {
|
||||
typeSet.unionIndex = typeSet.length;
|
||||
}
|
||||
typeSet.push(type);
|
||||
if (!(type.flags & TypeFlags.Object && (<ObjectType>type).objectFlags & ObjectFlags.Anonymous &&
|
||||
type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && containsIdenticalType(typeSet, type))) {
|
||||
typeSet.push(type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6490,13 +6503,13 @@ namespace ts {
|
||||
const rightType = getTypeOfSymbol(rightProp);
|
||||
if (maybeTypeOfKind(rightType, TypeFlags.Undefined) || rightProp.flags & SymbolFlags.Optional) {
|
||||
const declarations: Declaration[] = concatenate(leftProp.declarations, rightProp.declarations);
|
||||
const flags = SymbolFlags.Property | SymbolFlags.Transient | (leftProp.flags & SymbolFlags.Optional);
|
||||
const result = <TransientSymbol>createSymbol(flags, leftProp.name);
|
||||
const flags = SymbolFlags.Property | (leftProp.flags & SymbolFlags.Optional);
|
||||
const result = createSymbol(flags, leftProp.name);
|
||||
result.checkFlags = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp) ? CheckFlags.Readonly : 0;
|
||||
result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, TypeFacts.NEUndefined)]);
|
||||
result.leftSpread = leftProp;
|
||||
result.rightSpread = rightProp;
|
||||
result.declarations = declarations;
|
||||
result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp);
|
||||
members.set(leftProp.name, result);
|
||||
}
|
||||
}
|
||||
@@ -6823,7 +6836,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function instantiateSymbol(symbol: Symbol, mapper: TypeMapper): Symbol {
|
||||
if (symbol.flags & SymbolFlags.Instantiated) {
|
||||
if (getCheckFlags(symbol) & CheckFlags.Instantiated) {
|
||||
const links = getSymbolLinks(symbol);
|
||||
// If symbol being instantiated is itself a instantiation, fetch the original target and combine the
|
||||
// type mappers. This ensures that original type identities are properly preserved and that aliases
|
||||
@@ -6831,10 +6844,10 @@ namespace ts {
|
||||
symbol = links.target;
|
||||
mapper = combineTypeMappers(links.mapper, mapper);
|
||||
}
|
||||
|
||||
// Keep the flags from the symbol we're instantiating. Mark that is instantiated, and
|
||||
// also transient so that we can just store data on it directly.
|
||||
const result = <TransientSymbol>createSymbol(SymbolFlags.Instantiated | SymbolFlags.Transient | symbol.flags, symbol.name);
|
||||
const result = createSymbol(symbol.flags, symbol.name);
|
||||
result.checkFlags = CheckFlags.Instantiated;
|
||||
result.declarations = symbol.declarations;
|
||||
result.parent = symbol.parent;
|
||||
result.target = symbol;
|
||||
@@ -6842,7 +6855,6 @@ namespace ts {
|
||||
if (symbol.valueDeclaration) {
|
||||
result.valueDeclaration = symbol.valueDeclaration;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -8037,6 +8049,12 @@ namespace ts {
|
||||
const sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp);
|
||||
const targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp);
|
||||
if (sourcePropFlags & ModifierFlags.Private || targetPropFlags & ModifierFlags.Private) {
|
||||
if (getCheckFlags(sourceProp) & CheckFlags.ContainsPrivate) {
|
||||
if (reportErrors) {
|
||||
reportError(Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source));
|
||||
}
|
||||
return Ternary.False;
|
||||
}
|
||||
if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
|
||||
if (reportErrors) {
|
||||
if (sourcePropFlags & ModifierFlags.Private && targetPropFlags & ModifierFlags.Private) {
|
||||
@@ -8052,13 +8070,10 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
else if (targetPropFlags & ModifierFlags.Protected) {
|
||||
const sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & SymbolFlags.Class;
|
||||
const sourceClass = sourceDeclaredInClass ? <InterfaceType>getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined;
|
||||
const targetClass = <InterfaceType>getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp));
|
||||
if (!sourceClass || !hasBaseType(sourceClass, targetClass)) {
|
||||
if (!isValidOverrideOf(sourceProp, targetProp)) {
|
||||
if (reportErrors) {
|
||||
reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2,
|
||||
symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass));
|
||||
reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp),
|
||||
typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target));
|
||||
}
|
||||
return Ternary.False;
|
||||
}
|
||||
@@ -8300,6 +8315,49 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
// Invoke the callback for each underlying property symbol of the given symbol and return the first
|
||||
// value that isn't undefined.
|
||||
function forEachProperty<T>(prop: Symbol, callback: (p: Symbol) => T): T {
|
||||
if (getCheckFlags(prop) & CheckFlags.SyntheticProperty) {
|
||||
for (const t of (<TransientSymbol>prop).containingType.types) {
|
||||
const p = getPropertyOfType(t, prop.name);
|
||||
const result = p && forEachProperty(p, callback);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
return callback(prop);
|
||||
}
|
||||
|
||||
// Return the declaring class type of a property or undefined if property not declared in class
|
||||
function getDeclaringClass(prop: Symbol) {
|
||||
return prop.parent && prop.parent.flags & SymbolFlags.Class ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
|
||||
}
|
||||
|
||||
// Return true if some underlying source property is declared in a class that derives
|
||||
// from the given base class.
|
||||
function isPropertyInClassDerivedFrom(prop: Symbol, baseClass: Type) {
|
||||
return forEachProperty(prop, sp => {
|
||||
const sourceClass = getDeclaringClass(sp);
|
||||
return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
|
||||
});
|
||||
}
|
||||
|
||||
// Return true if source property is a valid override of protected parts of target property.
|
||||
function isValidOverrideOf(sourceProp: Symbol, targetProp: Symbol) {
|
||||
return !forEachProperty(targetProp, tp => getDeclarationModifierFlagsFromSymbol(tp) & ModifierFlags.Protected ?
|
||||
!isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false);
|
||||
}
|
||||
|
||||
// Return true if the given class derives from each of the declaring classes of the protected
|
||||
// constituents of the given property.
|
||||
function isClassDerivedFromDeclaringClasses(checkClass: Type, prop: Symbol) {
|
||||
return forEachProperty(prop, p => getDeclarationModifierFlagsFromSymbol(p) & ModifierFlags.Protected ?
|
||||
!hasBaseType(checkClass, getDeclaringClass(p)) : false) ? undefined : checkClass;
|
||||
}
|
||||
|
||||
// Return true if the given type is the constructor type for an abstract class
|
||||
function isAbstractConstructorType(type: Type) {
|
||||
if (getObjectFlags(type) & ObjectFlags.Anonymous) {
|
||||
@@ -8609,7 +8667,7 @@ namespace ts {
|
||||
if (flags & TypeFlags.Void) types.push(voidType);
|
||||
if (flags & TypeFlags.Undefined) types.push(undefinedType);
|
||||
if (flags & TypeFlags.Null) types.push(nullType);
|
||||
return getUnionType(types, /*subtypeReduction*/ true);
|
||||
return getUnionType(types);
|
||||
}
|
||||
|
||||
function removeDefinitelyFalsyTypes(type: Type): Type {
|
||||
@@ -8632,8 +8690,8 @@ namespace ts {
|
||||
getSignaturesOfType(type, SignatureKind.Construct).length === 0;
|
||||
}
|
||||
|
||||
function createTransientSymbol(source: Symbol, type: Type) {
|
||||
const symbol = <TransientSymbol>createSymbol(source.flags | SymbolFlags.Transient, source.name);
|
||||
function createSymbolWithType(source: Symbol, type: Type) {
|
||||
const symbol = createSymbol(source.flags, source.name);
|
||||
symbol.declarations = source.declarations;
|
||||
symbol.parent = source.parent;
|
||||
symbol.type = type;
|
||||
@@ -8649,7 +8707,7 @@ namespace ts {
|
||||
for (const property of getPropertiesOfObjectType(type)) {
|
||||
const original = getTypeOfSymbol(property);
|
||||
const updated = f(original);
|
||||
members.set(property.name, updated === original ? property : createTransientSymbol(property, updated));
|
||||
members.set(property.name, updated === original ? property : createSymbolWithType(property, updated));
|
||||
};
|
||||
return members;
|
||||
}
|
||||
@@ -8887,10 +8945,10 @@ namespace ts {
|
||||
if (!inferredPropType) {
|
||||
return undefined;
|
||||
}
|
||||
const inferredProp = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient | prop.flags & optionalMask, prop.name);
|
||||
const inferredProp = createSymbol(SymbolFlags.Property | prop.flags & optionalMask, prop.name);
|
||||
inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? CheckFlags.Readonly : 0;
|
||||
inferredProp.declarations = prop.declarations;
|
||||
inferredProp.type = inferredPropType;
|
||||
inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop);
|
||||
members.set(prop.name, inferredProp);
|
||||
}
|
||||
if (indexInfo) {
|
||||
@@ -9372,9 +9430,9 @@ namespace ts {
|
||||
function isDiscriminantProperty(type: Type, name: string) {
|
||||
if (type && type.flags & TypeFlags.Union) {
|
||||
const prop = getUnionOrIntersectionProperty(<UnionType>type, name);
|
||||
if (prop && prop.flags & SymbolFlags.SyntheticProperty) {
|
||||
if (prop && getCheckFlags(prop) & CheckFlags.SyntheticProperty) {
|
||||
if ((<TransientSymbol>prop).isDiscriminantProperty === undefined) {
|
||||
(<TransientSymbol>prop).isDiscriminantProperty = (<TransientSymbol>prop).hasNonUniformType && isLiteralType(getTypeOfSymbol(prop));
|
||||
(<TransientSymbol>prop).isDiscriminantProperty = (<TransientSymbol>prop).checkFlags & CheckFlags.HasNonUniformType && isLiteralType(getTypeOfSymbol(prop));
|
||||
}
|
||||
return (<TransientSymbol>prop).isDiscriminantProperty;
|
||||
}
|
||||
@@ -11841,7 +11899,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
typeFlags |= type.flags;
|
||||
const prop = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name);
|
||||
const prop = createSymbol(SymbolFlags.Property | member.flags, member.name);
|
||||
if (inDestructuringPattern) {
|
||||
// If object literal is an assignment pattern and if the assignment pattern specifies a default value
|
||||
// for the property, make the property optional.
|
||||
@@ -12466,7 +12524,22 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getDeclarationModifierFlagsFromSymbol(s: Symbol): ModifierFlags {
|
||||
return s.valueDeclaration ? getCombinedModifierFlags(s.valueDeclaration) : s.flags & SymbolFlags.Prototype ? ModifierFlags.Public | ModifierFlags.Static : 0;
|
||||
if (s.valueDeclaration) {
|
||||
const flags = getCombinedModifierFlags(s.valueDeclaration);
|
||||
return s.parent && s.parent.flags & SymbolFlags.Class ? flags : flags & ~ModifierFlags.AccessibilityModifier;
|
||||
}
|
||||
if (getCheckFlags(s) & CheckFlags.SyntheticProperty) {
|
||||
const checkFlags = (<TransientSymbol>s).checkFlags;
|
||||
const accessModifier = checkFlags & CheckFlags.ContainsPrivate ? ModifierFlags.Private :
|
||||
checkFlags & CheckFlags.ContainsPublic ? ModifierFlags.Public :
|
||||
ModifierFlags.Protected;
|
||||
const staticModifier = checkFlags & CheckFlags.ContainsStatic ? ModifierFlags.Static : 0;
|
||||
return accessModifier | staticModifier;
|
||||
}
|
||||
if (s.flags & SymbolFlags.Prototype) {
|
||||
return ModifierFlags.Public | ModifierFlags.Static;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function getDeclarationNodeFlagsFromSymbol(s: Symbol): NodeFlags {
|
||||
@@ -12481,12 +12554,18 @@ namespace ts {
|
||||
* @param type The type of left.
|
||||
* @param prop The symbol for the right hand side of the property access.
|
||||
*/
|
||||
function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName | VariableLikeDeclaration, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean {
|
||||
function checkPropertyAccessibility(node: PropertyAccessExpression | QualifiedName | VariableLikeDeclaration, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean {
|
||||
const flags = getDeclarationModifierFlagsFromSymbol(prop);
|
||||
const declaringClass = <InterfaceType>getDeclaredTypeOfSymbol(getParentOfSymbol(prop));
|
||||
const errorNode = node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.VariableDeclaration ?
|
||||
(<PropertyAccessExpression | VariableDeclaration>node).name :
|
||||
(<QualifiedName>node).right;
|
||||
|
||||
if (getCheckFlags(prop) & CheckFlags.ContainsPrivate) {
|
||||
// Synthetic property with private constituent property
|
||||
error(errorNode, Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (left.kind === SyntaxKind.SuperKeyword) {
|
||||
// TS 1.0 spec (April 2014): 4.8.2
|
||||
// - In a constructor, instance member function, instance member accessor, or
|
||||
@@ -12505,14 +12584,12 @@ namespace ts {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (flags & ModifierFlags.Abstract) {
|
||||
// A method cannot be accessed in a super property access if the method is abstract.
|
||||
// This error could mask a private property access error. But, a member
|
||||
// cannot simultaneously be private and abstract, so this will trigger an
|
||||
// additional error elsewhere.
|
||||
|
||||
error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass));
|
||||
error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -12528,7 +12605,7 @@ namespace ts {
|
||||
if (flags & ModifierFlags.Private) {
|
||||
const declaringClassDeclaration = <ClassLikeDeclaration>getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
|
||||
if (!isNodeWithinClass(node, declaringClassDeclaration)) {
|
||||
error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass));
|
||||
error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -12541,15 +12618,15 @@ namespace ts {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Get the enclosing class that has the declaring class as its base type
|
||||
// Find the first enclosing class that has the declaring classes of the protected constituents
|
||||
// of the property as base classes
|
||||
const enclosingClass = forEachEnclosingClass(node, enclosingDeclaration => {
|
||||
const enclosingClass = <InterfaceType>getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
|
||||
return hasBaseType(enclosingClass, declaringClass) ? enclosingClass : undefined;
|
||||
return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
|
||||
});
|
||||
|
||||
// A protected property is accessible if the property is within the declaring class or classes derived from it
|
||||
if (!enclosingClass) {
|
||||
error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass));
|
||||
error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
|
||||
return false;
|
||||
}
|
||||
// No further restrictions for static properties
|
||||
@@ -12561,9 +12638,7 @@ namespace ts {
|
||||
// get the original type -- represented as the type constraint of the 'this' type
|
||||
type = getConstraintOfTypeParameter(<TypeParameter>type);
|
||||
}
|
||||
|
||||
// TODO: why is the first part of this check here?
|
||||
if (!(getObjectFlags(getTargetType(type)) & ObjectFlags.ClassOrInterface && hasBaseType(<InterfaceType>type, enclosingClass))) {
|
||||
if (!(getObjectFlags(getTargetType(type)) & ObjectFlags.ClassOrInterface && hasBaseType(type, enclosingClass))) {
|
||||
error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
|
||||
return false;
|
||||
}
|
||||
@@ -12614,9 +12689,8 @@ namespace ts {
|
||||
noUnusedIdentifiers &&
|
||||
(prop.flags & SymbolFlags.ClassMember) &&
|
||||
prop.valueDeclaration && (getModifierFlags(prop.valueDeclaration) & ModifierFlags.Private)) {
|
||||
if (prop.flags & SymbolFlags.Instantiated) {
|
||||
if (getCheckFlags(prop) & CheckFlags.Instantiated) {
|
||||
getSymbolLinks(prop).target.isReferenced = true;
|
||||
|
||||
}
|
||||
else {
|
||||
prop.isReferenced = true;
|
||||
@@ -12666,9 +12740,7 @@ namespace ts {
|
||||
|
||||
getNodeLinks(node).resolvedSymbol = prop;
|
||||
|
||||
if (prop.parent && prop.parent.flags & SymbolFlags.Class) {
|
||||
checkClassPropertyAccess(node, left, apparentType, prop);
|
||||
}
|
||||
checkPropertyAccessibility(node, left, apparentType, prop);
|
||||
|
||||
const propType = getTypeOfSymbol(prop);
|
||||
const assignmentKind = getAssignmentTargetKind(node);
|
||||
@@ -12700,8 +12772,8 @@ namespace ts {
|
||||
const type = checkExpression(left);
|
||||
if (type !== unknownType && !isTypeAny(type)) {
|
||||
const prop = getPropertyOfType(getWidenedType(type), propertyName);
|
||||
if (prop && prop.parent && prop.parent.flags & SymbolFlags.Class) {
|
||||
return checkClassPropertyAccess(node, left, type, prop);
|
||||
if (prop) {
|
||||
return checkPropertyAccessibility(node, left, type, prop);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -14199,7 +14271,7 @@ namespace ts {
|
||||
const parameter = signature.thisParameter;
|
||||
if (!parameter || parameter.valueDeclaration && !(<ParameterDeclaration>parameter.valueDeclaration).type) {
|
||||
if (!parameter) {
|
||||
signature.thisParameter = createTransientSymbol(context.thisParameter, undefined);
|
||||
signature.thisParameter = createSymbolWithType(context.thisParameter, undefined);
|
||||
}
|
||||
assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper);
|
||||
}
|
||||
@@ -14654,11 +14726,11 @@ namespace ts {
|
||||
// Get accessors without matching set accessors
|
||||
// Enum members
|
||||
// Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
|
||||
return symbol.isReadonly ||
|
||||
symbol.flags & SymbolFlags.Property && (getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.Readonly) !== 0 ||
|
||||
symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0 ||
|
||||
return !!(getCheckFlags(symbol) & CheckFlags.Readonly ||
|
||||
symbol.flags & SymbolFlags.Property && getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.Readonly ||
|
||||
symbol.flags & SymbolFlags.Variable && getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const ||
|
||||
symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) ||
|
||||
(symbol.flags & SymbolFlags.EnumMember) !== 0;
|
||||
symbol.flags & SymbolFlags.EnumMember);
|
||||
}
|
||||
|
||||
function isReferenceToReadonlyEntity(expr: Expression, symbol: Symbol): boolean {
|
||||
@@ -17680,8 +17752,8 @@ namespace ts {
|
||||
const name = node.propertyName || <Identifier>node.name;
|
||||
const property = getPropertyOfType(parentType, getTextOfPropertyName(name));
|
||||
markPropertyAsReferenced(property);
|
||||
if (parent.initializer && property && getParentOfSymbol(property)) {
|
||||
checkClassPropertyAccess(parent, parent.initializer, parentType, property);
|
||||
if (parent.initializer && property) {
|
||||
checkPropertyAccessibility(parent, parent.initializer, parentType, property);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18777,7 +18849,7 @@ namespace ts {
|
||||
function getTargetSymbol(s: Symbol) {
|
||||
// if symbol is instantiated its flags are not copied from the 'target'
|
||||
// so we'll need to get back original 'target' symbol to work with correct set of flags
|
||||
return s.flags & SymbolFlags.Instantiated ? getSymbolLinks(s).target : s;
|
||||
return getCheckFlags(s) & CheckFlags.Instantiated ? (<TransientSymbol>s).target : s;
|
||||
}
|
||||
|
||||
function getClassLikeDeclarationOfSymbol(symbol: Symbol): Declaration {
|
||||
@@ -19355,7 +19427,7 @@ namespace ts {
|
||||
// We can detect if augmentation was applied using following rules:
|
||||
// - augmentation for a global scope is always applied
|
||||
// - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
|
||||
const checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & SymbolFlags.Merged);
|
||||
const checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & SymbolFlags.Transient);
|
||||
if (checkBody && node.body) {
|
||||
// body of ambient external module is always a module block
|
||||
for (const statement of (<ModuleBlock>node.body).statements) {
|
||||
@@ -19434,7 +19506,7 @@ namespace ts {
|
||||
// this is done it two steps
|
||||
// 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
|
||||
// 2. main check - report error if value declaration of the parent symbol is module augmentation)
|
||||
let reportError = !(symbol.flags & SymbolFlags.Merged);
|
||||
let reportError = !(symbol.flags & SymbolFlags.Transient);
|
||||
if (!reportError) {
|
||||
// symbol should not originate in augmentation
|
||||
reportError = isExternalModuleAugmentation(symbol.parent.declarations[0]);
|
||||
@@ -20536,7 +20608,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getRootSymbols(symbol: Symbol): Symbol[] {
|
||||
if (symbol.flags & SymbolFlags.SyntheticProperty) {
|
||||
if (getCheckFlags(symbol) & CheckFlags.SyntheticProperty) {
|
||||
const symbols: Symbol[] = [];
|
||||
const name = symbol.name;
|
||||
forEach(getSymbolLinks(symbol).containingType.types, t => {
|
||||
@@ -20837,6 +20909,13 @@ namespace ts {
|
||||
return false;
|
||||
}
|
||||
|
||||
function isRequiredInitializedParameter(parameter: ParameterDeclaration) {
|
||||
return strictNullChecks &&
|
||||
!isOptionalParameter(parameter) &&
|
||||
parameter.initializer &&
|
||||
!(getModifierFlags(parameter) & ModifierFlags.ParameterPropertyModifier);
|
||||
}
|
||||
|
||||
function getNodeCheckFlags(node: Node): NodeCheckFlags {
|
||||
node = getParseTreeNode(node);
|
||||
return node ? getNodeLinks(node).flags : undefined;
|
||||
@@ -20928,10 +21007,12 @@ namespace ts {
|
||||
function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) {
|
||||
// Get type of the symbol if this is the valid symbol otherwise get type at location
|
||||
const symbol = getSymbolOfNode(declaration);
|
||||
const type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature))
|
||||
let type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature))
|
||||
? getWidenedLiteralType(getTypeOfSymbol(symbol))
|
||||
: unknownType;
|
||||
|
||||
if (flags & TypeFormatFlags.AddUndefined) {
|
||||
type = includeFalsyTypes(type, TypeFlags.Undefined);
|
||||
}
|
||||
getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags);
|
||||
}
|
||||
|
||||
@@ -21030,6 +21111,7 @@ namespace ts {
|
||||
isTopLevelValueImportEqualsWithEntityName,
|
||||
isDeclarationVisible,
|
||||
isImplementationOfOverload,
|
||||
isRequiredInitializedParameter,
|
||||
writeTypeOfDeclaration,
|
||||
writeReturnTypeOfSignatureDeclaration,
|
||||
writeTypeOfExpression,
|
||||
@@ -22172,6 +22254,11 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
if (compilerOptions.module !== ModuleKind.ES2015 && compilerOptions.module !== ModuleKind.System && !compilerOptions.noEmit &&
|
||||
!isInAmbientContext(node.parent.parent) && hasModifier(node.parent.parent, ModifierFlags.Export)) {
|
||||
checkESModuleMarker(node.name);
|
||||
}
|
||||
|
||||
const checkLetConstNames = (isLet(node) || isConst(node));
|
||||
|
||||
// 1. LexicalDeclaration : LetOrConst BindingList ;
|
||||
@@ -22184,6 +22271,22 @@ namespace ts {
|
||||
return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
|
||||
}
|
||||
|
||||
function checkESModuleMarker(name: Identifier | BindingPattern): boolean {
|
||||
if (name.kind === SyntaxKind.Identifier) {
|
||||
if (unescapeIdentifier(name.text) === "__esModule") {
|
||||
return grammarErrorOnNode(name, Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
|
||||
}
|
||||
}
|
||||
else {
|
||||
const elements = (<BindingPattern>name).elements;
|
||||
for (const element of elements) {
|
||||
if (!isOmittedExpression(element)) {
|
||||
return checkESModuleMarker(element.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function checkGrammarNameInLetOrConstDeclarations(name: Identifier | BindingPattern): boolean {
|
||||
if (name.kind === SyntaxKind.Identifier) {
|
||||
if ((<Identifier>name).originalKeywordKind === SyntaxKind.LetKeyword) {
|
||||
|
||||
@@ -847,7 +847,7 @@ namespace ts {
|
||||
* @param basePath A root directory to resolve relative path entries in the config
|
||||
* file to. e.g. outDir
|
||||
*/
|
||||
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine {
|
||||
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: JsFileExtensionInfo[] = []): ParsedCommandLine {
|
||||
const errors: Diagnostic[] = [];
|
||||
basePath = normalizeSlashes(basePath);
|
||||
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
|
||||
@@ -1193,7 +1193,7 @@ namespace ts {
|
||||
* @param host The host used to resolve files and directories.
|
||||
* @param errors An array for diagnostic reporting.
|
||||
*/
|
||||
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult {
|
||||
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: JsFileExtensionInfo[]): ExpandResult {
|
||||
basePath = normalizePath(basePath);
|
||||
|
||||
// The exclude spec list is converted into a regular expression, which allows us to quickly
|
||||
@@ -1368,7 +1368,7 @@ namespace ts {
|
||||
*/
|
||||
function hasFileWithHigherPriorityExtension(file: string, literalFiles: Map<string>, wildcardFiles: Map<string>, extensions: string[], keyMapper: (value: string) => string) {
|
||||
const extensionPriority = getExtensionPriority(file, extensions);
|
||||
const adjustedExtensionPriority = adjustExtensionPriority(extensionPriority);
|
||||
const adjustedExtensionPriority = adjustExtensionPriority(extensionPriority, extensions);
|
||||
for (let i = ExtensionPriority.Highest; i < adjustedExtensionPriority; i++) {
|
||||
const higherPriorityExtension = extensions[i];
|
||||
const higherPriorityPath = keyMapper(changeExtension(file, higherPriorityExtension));
|
||||
@@ -1390,7 +1390,7 @@ namespace ts {
|
||||
*/
|
||||
function removeWildcardFilesWithLowerPriorityExtension(file: string, wildcardFiles: Map<string>, extensions: string[], keyMapper: (value: string) => string) {
|
||||
const extensionPriority = getExtensionPriority(file, extensions);
|
||||
const nextExtensionPriority = getNextLowestExtensionPriority(extensionPriority);
|
||||
const nextExtensionPriority = getNextLowestExtensionPriority(extensionPriority, extensions);
|
||||
for (let i = nextExtensionPriority; i < extensions.length; i++) {
|
||||
const lowerPriorityExtension = extensions[i];
|
||||
const lowerPriorityPath = keyMapper(changeExtension(file, lowerPriorityExtension));
|
||||
|
||||
@@ -2020,14 +2020,14 @@ namespace ts {
|
||||
export const supportedJavascriptExtensions = [".js", ".jsx"];
|
||||
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);
|
||||
|
||||
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] {
|
||||
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: JsFileExtensionInfo[]): string[] {
|
||||
const needAllExtensions = options && options.allowJs;
|
||||
if (!extraFileExtensions || extraFileExtensions.length === 0) {
|
||||
if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
|
||||
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
|
||||
}
|
||||
const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0);
|
||||
const extensions = allSupportedExtensions.slice(0);
|
||||
for (const extInfo of extraFileExtensions) {
|
||||
if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) {
|
||||
if (extensions.indexOf(extInfo.extension) === -1) {
|
||||
extensions.push(extInfo.extension);
|
||||
}
|
||||
}
|
||||
@@ -2042,7 +2042,7 @@ namespace ts {
|
||||
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
|
||||
}
|
||||
|
||||
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) {
|
||||
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: JsFileExtensionInfo[]) {
|
||||
if (!fileName) { return false; }
|
||||
|
||||
for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) {
|
||||
@@ -2061,7 +2061,6 @@ namespace ts {
|
||||
export const enum ExtensionPriority {
|
||||
TypeScriptFiles = 0,
|
||||
DeclarationAndJavaScriptFiles = 2,
|
||||
Limit = 5,
|
||||
|
||||
Highest = TypeScriptFiles,
|
||||
Lowest = DeclarationAndJavaScriptFiles,
|
||||
@@ -2070,7 +2069,7 @@ namespace ts {
|
||||
export function getExtensionPriority(path: string, supportedExtensions: string[]): ExtensionPriority {
|
||||
for (let i = supportedExtensions.length - 1; i >= 0; i--) {
|
||||
if (fileExtensionIs(path, supportedExtensions[i])) {
|
||||
return adjustExtensionPriority(<ExtensionPriority>i);
|
||||
return adjustExtensionPriority(<ExtensionPriority>i, supportedExtensions);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2082,27 +2081,26 @@ namespace ts {
|
||||
/**
|
||||
* Adjusts an extension priority to be the highest priority within the same range.
|
||||
*/
|
||||
export function adjustExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority {
|
||||
export function adjustExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: string[]): ExtensionPriority {
|
||||
if (extensionPriority < ExtensionPriority.DeclarationAndJavaScriptFiles) {
|
||||
return ExtensionPriority.TypeScriptFiles;
|
||||
}
|
||||
else if (extensionPriority < ExtensionPriority.Limit) {
|
||||
else if (extensionPriority < supportedExtensions.length) {
|
||||
return ExtensionPriority.DeclarationAndJavaScriptFiles;
|
||||
}
|
||||
else {
|
||||
return ExtensionPriority.Limit;
|
||||
}
|
||||
}
|
||||
return supportedExtensions.length;
|
||||
} }
|
||||
|
||||
/**
|
||||
* Gets the next lowest extension priority for a given priority.
|
||||
*/
|
||||
export function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority {
|
||||
export function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: string[]): ExtensionPriority {
|
||||
if (extensionPriority < ExtensionPriority.DeclarationAndJavaScriptFiles) {
|
||||
return ExtensionPriority.DeclarationAndJavaScriptFiles;
|
||||
}
|
||||
else {
|
||||
return ExtensionPriority.Limit;
|
||||
return supportedExtensions.length;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -324,13 +324,20 @@ namespace ts {
|
||||
function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, type: TypeNode, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) {
|
||||
writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic;
|
||||
write(": ");
|
||||
if (type) {
|
||||
|
||||
// use the checker's type, not the declared type,
|
||||
// for non-optional initialized parameters that aren't a parameter property
|
||||
const shouldUseResolverType = declaration.kind === SyntaxKind.Parameter &&
|
||||
resolver.isRequiredInitializedParameter(declaration as ParameterDeclaration);
|
||||
if (type && !shouldUseResolverType) {
|
||||
// Write the type
|
||||
emitType(type);
|
||||
}
|
||||
else {
|
||||
errorNameNode = declaration.name;
|
||||
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer);
|
||||
const format = TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue |
|
||||
(shouldUseResolverType ? TypeFormatFlags.AddUndefined : 0);
|
||||
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer);
|
||||
errorNameNode = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -675,6 +675,10 @@
|
||||
"category": "Error",
|
||||
"code": 1215
|
||||
},
|
||||
"Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules.": {
|
||||
"category": "Error",
|
||||
"code": 1216
|
||||
},
|
||||
"Export assignment is not supported when '--module' flag is 'system'.": {
|
||||
"category": "Error",
|
||||
"code": 1218
|
||||
@@ -1799,18 +1803,22 @@
|
||||
"category": "Error",
|
||||
"code": 2545
|
||||
},
|
||||
"The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property.": {
|
||||
"Property '{0}' has conflicting declarations and is inaccessible in type '{1}'.": {
|
||||
"category": "Error",
|
||||
"code": 2546
|
||||
},
|
||||
"Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator.": {
|
||||
"The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property.": {
|
||||
"category": "Error",
|
||||
"code": 2547
|
||||
},
|
||||
"Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator.": {
|
||||
"Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator.": {
|
||||
"category": "Error",
|
||||
"code": 2548
|
||||
},
|
||||
"Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator.": {
|
||||
"category": "Error",
|
||||
"code": 2549
|
||||
},
|
||||
"JSX element attributes type '{0}' may not be a union type.": {
|
||||
"category": "Error",
|
||||
"code": 2600
|
||||
@@ -2825,7 +2833,7 @@
|
||||
"category": "Message",
|
||||
"code": 6099
|
||||
},
|
||||
"'package.json' does not have a 'types' or 'main' field.": {
|
||||
"'package.json' does not have a '{0}' field.": {
|
||||
"category": "Message",
|
||||
"code": 6100
|
||||
},
|
||||
@@ -2973,10 +2981,6 @@
|
||||
"category": "Message",
|
||||
"code": 6136
|
||||
},
|
||||
"No types specified in 'package.json', so returning 'main' value of '{0}'": {
|
||||
"category": "Message",
|
||||
"code": 6137
|
||||
},
|
||||
"Property '{0}' is declared but never used.": {
|
||||
"category": "Error",
|
||||
"code": 6138
|
||||
|
||||
@@ -67,40 +67,31 @@ namespace ts {
|
||||
}
|
||||
|
||||
/** Reads from "main" or "types"/"typings" depending on `extensions`. */
|
||||
function tryReadPackageJsonMainOrTypes(extensions: Extensions, packageJsonPath: string, baseDirectory: string, state: ModuleResolutionState): string {
|
||||
function tryReadPackageJsonFields(readTypes: boolean, packageJsonPath: string, baseDirectory: string, state: ModuleResolutionState): string | undefined {
|
||||
const jsonContent = readJson(packageJsonPath, state.host);
|
||||
return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main");
|
||||
|
||||
switch (extensions) {
|
||||
case Extensions.DtsOnly:
|
||||
case Extensions.TypeScript:
|
||||
return tryReadFromField("typings") || tryReadFromField("types");
|
||||
|
||||
case Extensions.JavaScript:
|
||||
if (typeof jsonContent.main === "string") {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main);
|
||||
}
|
||||
return normalizePath(combinePaths(baseDirectory, jsonContent.main));
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function tryReadFromField(fieldName: string) {
|
||||
if (hasProperty(jsonContent, fieldName)) {
|
||||
const typesFile = (<any>jsonContent)[fieldName];
|
||||
if (typeof typesFile === "string") {
|
||||
const typesFilePath = normalizePath(combinePaths(baseDirectory, typesFile));
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath);
|
||||
}
|
||||
return typesFilePath;
|
||||
}
|
||||
else {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
|
||||
}
|
||||
function tryReadFromField(fieldName: "typings" | "types" | "main"): string | undefined {
|
||||
if (!hasProperty(jsonContent, fieldName)) {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const fileName = jsonContent[fieldName];
|
||||
if (typeof fileName !== "string") {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const path = normalizePath(combinePaths(baseDirectory, fileName));
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -698,7 +689,8 @@ namespace ts {
|
||||
return { resolvedModule: undefined, failedLookupLocations };
|
||||
|
||||
function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> {
|
||||
const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state);
|
||||
const loader: ResolutionKindSpecificLoader = (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/true);
|
||||
const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state);
|
||||
if (resolved) {
|
||||
return toSearchResult({ resolved, isExternalLibraryImport: false });
|
||||
}
|
||||
@@ -713,7 +705,7 @@ namespace ts {
|
||||
}
|
||||
else {
|
||||
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
|
||||
const resolved = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state);
|
||||
const resolved = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/true);
|
||||
return resolved && toSearchResult({ resolved, isExternalLibraryImport: false });
|
||||
}
|
||||
}
|
||||
@@ -731,7 +723,7 @@ namespace ts {
|
||||
return real;
|
||||
}
|
||||
|
||||
function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
|
||||
function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson: boolean): Resolved | undefined {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
|
||||
}
|
||||
@@ -759,7 +751,7 @@ namespace ts {
|
||||
onlyRecordFailures = true;
|
||||
}
|
||||
}
|
||||
return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state);
|
||||
return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson);
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -835,50 +827,57 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
|
||||
const packageJsonPath = pathToPackageJson(candidate);
|
||||
function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true): Resolved | undefined {
|
||||
const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
|
||||
|
||||
if (directoryExists && state.host.fileExists(packageJsonPath)) {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath);
|
||||
}
|
||||
const mainOrTypesFile = tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, candidate, state);
|
||||
if (mainOrTypesFile) {
|
||||
const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(mainOrTypesFile), state.host);
|
||||
// A package.json "typings" may specify an exact filename, or may choose to omit an extension.
|
||||
const fromExactFile = tryFile(mainOrTypesFile, failedLookupLocations, onlyRecordFailures, state);
|
||||
if (fromExactFile) {
|
||||
const resolved = fromExactFile && resolvedIfExtensionMatches(extensions, fromExactFile);
|
||||
if (resolved) {
|
||||
return resolved;
|
||||
}
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromExactFile);
|
||||
}
|
||||
}
|
||||
const resolved = tryAddingExtensions(mainOrTypesFile, Extensions.TypeScript, failedLookupLocations, onlyRecordFailures, state);
|
||||
if (resolved) {
|
||||
return resolved;
|
||||
if (considerPackageJson) {
|
||||
const packageJsonPath = pathToPackageJson(candidate);
|
||||
if (directoryExists && state.host.fileExists(packageJsonPath)) {
|
||||
const fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state);
|
||||
if (fromPackageJson) {
|
||||
return fromPackageJson;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.package_json_does_not_have_a_types_or_main_field);
|
||||
if (directoryExists && state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath);
|
||||
}
|
||||
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
|
||||
failedLookupLocations.push(packageJsonPath);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (directoryExists && state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath);
|
||||
}
|
||||
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
|
||||
failedLookupLocations.push(packageJsonPath);
|
||||
}
|
||||
|
||||
return loadModuleFromFile(extensions, combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state);
|
||||
}
|
||||
|
||||
function loadModuleFromPackageJson(packageJsonPath: string, extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, state: ModuleResolutionState): Resolved | undefined {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath);
|
||||
}
|
||||
|
||||
const file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state);
|
||||
if (!file) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(file), state.host);
|
||||
const fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state);
|
||||
if (fromFile) {
|
||||
const resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile);
|
||||
if (resolved) {
|
||||
return resolved;
|
||||
}
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
|
||||
}
|
||||
}
|
||||
|
||||
// Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
|
||||
const nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
|
||||
// Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
|
||||
return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false);
|
||||
}
|
||||
|
||||
/** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
|
||||
function resolvedIfExtensionMatches(extensions: Extensions, path: string): Resolved | undefined {
|
||||
const extension = tryGetExtensionFromPath(path);
|
||||
@@ -1040,7 +1039,6 @@ namespace ts {
|
||||
return value !== undefined ? { value } : undefined;
|
||||
}
|
||||
|
||||
|
||||
/** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */
|
||||
function forEachAncestorDirectory<T>(directory: string, callback: (directory: string) => SearchResult<T>): SearchResult<T> {
|
||||
while (true) {
|
||||
|
||||
@@ -84,6 +84,11 @@ namespace ts {
|
||||
|
||||
const statements: Statement[] = [];
|
||||
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
|
||||
|
||||
if (!currentModuleInfo.exportEquals) {
|
||||
append(statements, createUnderscoreUnderscoreESModule());
|
||||
}
|
||||
|
||||
append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement, /*optional*/ true));
|
||||
addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset));
|
||||
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
|
||||
@@ -95,7 +100,6 @@ namespace ts {
|
||||
// we need to inform the emitter to add the __export helper.
|
||||
addEmitHelper(updated, exportStarHelper);
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
@@ -374,6 +378,10 @@ namespace ts {
|
||||
const statements: Statement[] = [];
|
||||
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
|
||||
|
||||
if (!currentModuleInfo.exportEquals) {
|
||||
append(statements, createUnderscoreUnderscoreESModule());
|
||||
}
|
||||
|
||||
// Visit each statement of the module body.
|
||||
append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement, /*optional*/ true));
|
||||
addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset));
|
||||
@@ -668,6 +676,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
const generatedName = getGeneratedNameForNode(node);
|
||||
|
||||
if (node.exportClause) {
|
||||
const statements: Statement[] = [];
|
||||
// export { x, y } from "mod";
|
||||
@@ -841,6 +850,7 @@ namespace ts {
|
||||
let statements: Statement[];
|
||||
let variables: VariableDeclaration[];
|
||||
let expressions: Expression[];
|
||||
|
||||
if (hasModifier(node, ModifierFlags.Export)) {
|
||||
let modifiers: NodeArray<Modifier>;
|
||||
|
||||
@@ -1130,43 +1140,39 @@ namespace ts {
|
||||
* @param allowComments Whether to allow comments on the export.
|
||||
*/
|
||||
function appendExportStatement(statements: Statement[] | undefined, exportName: Identifier, expression: Expression, location?: TextRange, allowComments?: boolean): Statement[] | undefined {
|
||||
if (exportName.text === "default") {
|
||||
const sourceFile = getOriginalNode(currentSourceFile, isSourceFile);
|
||||
if (sourceFile && !sourceFile.symbol.exports.get("___esModule")) {
|
||||
if (languageVersion === ScriptTarget.ES3) {
|
||||
statements = append(statements,
|
||||
createStatement(
|
||||
createExportExpression(
|
||||
createIdentifier("__esModule"),
|
||||
createTrue()
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
else {
|
||||
statements = append(statements,
|
||||
createStatement(
|
||||
createCall(
|
||||
createPropertyAccess(createIdentifier("Object"), "defineProperty"),
|
||||
/*typeArguments*/ undefined,
|
||||
[
|
||||
createIdentifier("exports"),
|
||||
createLiteral("__esModule"),
|
||||
createObjectLiteral([
|
||||
createPropertyAssignment("value", createTrue())
|
||||
])
|
||||
]
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
statements = append(statements, createExportStatement(exportName, expression, location, allowComments));
|
||||
return statements;
|
||||
}
|
||||
|
||||
function createUnderscoreUnderscoreESModule() {
|
||||
let statement: Statement;
|
||||
if (languageVersion === ScriptTarget.ES3) {
|
||||
statement = createStatement(
|
||||
createExportExpression(
|
||||
createIdentifier("__esModule"),
|
||||
createLiteral(true)
|
||||
)
|
||||
)
|
||||
}
|
||||
else {
|
||||
statement = createStatement(
|
||||
createCall(
|
||||
createPropertyAccess(createIdentifier("Object"), "defineProperty"),
|
||||
/*typeArguments*/ undefined,
|
||||
[
|
||||
createIdentifier("exports"),
|
||||
createLiteral("__esModule"),
|
||||
createObjectLiteral([
|
||||
createPropertyAssignment("value", createLiteral(true))
|
||||
])
|
||||
]
|
||||
)
|
||||
);
|
||||
}
|
||||
setEmitFlags(statement, EmitFlags.CustomPrologue);
|
||||
return statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a call to the current file's export function to export a value.
|
||||
*
|
||||
|
||||
@@ -2482,7 +2482,8 @@
|
||||
InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type
|
||||
InTypeAlias = 0x00000200, // Writing type in type alias declaration
|
||||
UseTypeAliasValue = 0x00000400, // Serialize the type instead of using type-alias. This is needed when we emit declaration file.
|
||||
SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type.
|
||||
SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type.
|
||||
AddUndefined = 0x00001000, // Add undefined to types of initialized, non-optional parameters
|
||||
}
|
||||
|
||||
export const enum SymbolFormatFlags {
|
||||
@@ -2587,6 +2588,7 @@
|
||||
isDeclarationVisible(node: Declaration): boolean;
|
||||
collectLinkedAliases(node: Identifier): Node[];
|
||||
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
|
||||
isRequiredInitializedParameter(node: ParameterDeclaration): boolean;
|
||||
writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
|
||||
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
|
||||
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
|
||||
@@ -2610,37 +2612,34 @@
|
||||
|
||||
export const enum SymbolFlags {
|
||||
None = 0,
|
||||
FunctionScopedVariable = 0x00000001, // Variable (var) or parameter
|
||||
BlockScopedVariable = 0x00000002, // A block-scoped variable (let or const)
|
||||
Property = 0x00000004, // Property or enum member
|
||||
EnumMember = 0x00000008, // Enum member
|
||||
Function = 0x00000010, // Function
|
||||
Class = 0x00000020, // Class
|
||||
Interface = 0x00000040, // Interface
|
||||
ConstEnum = 0x00000080, // Const enum
|
||||
RegularEnum = 0x00000100, // Enum
|
||||
ValueModule = 0x00000200, // Instantiated module
|
||||
NamespaceModule = 0x00000400, // Uninstantiated module
|
||||
TypeLiteral = 0x00000800, // Type Literal or mapped type
|
||||
ObjectLiteral = 0x00001000, // Object Literal
|
||||
Method = 0x00002000, // Method
|
||||
Constructor = 0x00004000, // Constructor
|
||||
GetAccessor = 0x00008000, // Get accessor
|
||||
SetAccessor = 0x00010000, // Set accessor
|
||||
Signature = 0x00020000, // Call, construct, or index signature
|
||||
TypeParameter = 0x00040000, // Type parameter
|
||||
TypeAlias = 0x00080000, // Type alias
|
||||
ExportValue = 0x00100000, // Exported value marker (see comment in declareModuleMember in binder)
|
||||
ExportType = 0x00200000, // Exported type marker (see comment in declareModuleMember in binder)
|
||||
ExportNamespace = 0x00400000, // Exported namespace marker (see comment in declareModuleMember in binder)
|
||||
Alias = 0x00800000, // An alias for another symbol (see comment in isAliasSymbolDeclaration in checker)
|
||||
Instantiated = 0x01000000, // Instantiated symbol
|
||||
Merged = 0x02000000, // Merged symbol (created during program binding)
|
||||
Transient = 0x04000000, // Transient symbol (created during type check)
|
||||
Prototype = 0x08000000, // Prototype property (no source representation)
|
||||
SyntheticProperty = 0x10000000, // Property in union or intersection type
|
||||
Optional = 0x20000000, // Optional property
|
||||
ExportStar = 0x40000000, // Export * declaration
|
||||
FunctionScopedVariable = 1 << 0, // Variable (var) or parameter
|
||||
BlockScopedVariable = 1 << 1, // A block-scoped variable (let or const)
|
||||
Property = 1 << 2, // Property or enum member
|
||||
EnumMember = 1 << 3, // Enum member
|
||||
Function = 1 << 4, // Function
|
||||
Class = 1 << 5, // Class
|
||||
Interface = 1 << 6, // Interface
|
||||
ConstEnum = 1 << 7, // Const enum
|
||||
RegularEnum = 1 << 8, // Enum
|
||||
ValueModule = 1 << 9, // Instantiated module
|
||||
NamespaceModule = 1 << 10, // Uninstantiated module
|
||||
TypeLiteral = 1 << 11, // Type Literal or mapped type
|
||||
ObjectLiteral = 1 << 12, // Object Literal
|
||||
Method = 1 << 13, // Method
|
||||
Constructor = 1 << 14, // Constructor
|
||||
GetAccessor = 1 << 15, // Get accessor
|
||||
SetAccessor = 1 << 16, // Set accessor
|
||||
Signature = 1 << 17, // Call, construct, or index signature
|
||||
TypeParameter = 1 << 18, // Type parameter
|
||||
TypeAlias = 1 << 19, // Type alias
|
||||
ExportValue = 1 << 20, // Exported value marker (see comment in declareModuleMember in binder)
|
||||
ExportType = 1 << 21, // Exported type marker (see comment in declareModuleMember in binder)
|
||||
ExportNamespace = 1 << 22, // Exported namespace marker (see comment in declareModuleMember in binder)
|
||||
Alias = 1 << 23, // An alias for another symbol (see comment in isAliasSymbolDeclaration in checker)
|
||||
Prototype = 1 << 24, // Prototype property (no source representation)
|
||||
ExportStar = 1 << 25, // Export * declaration
|
||||
Optional = 1 << 26, // Optional property
|
||||
Transient = 1 << 27, // Transient symbol (created during type check)
|
||||
|
||||
Enum = RegularEnum | ConstEnum,
|
||||
Variable = FunctionScopedVariable | BlockScopedVariable,
|
||||
@@ -2700,11 +2699,9 @@
|
||||
name: string; // Name of symbol
|
||||
declarations?: Declaration[]; // Declarations associated with this symbol
|
||||
valueDeclaration?: Declaration; // First value declaration of the symbol
|
||||
|
||||
members?: SymbolTable; // Class, interface or literal instance members
|
||||
exports?: SymbolTable; // Module exports
|
||||
globalExports?: SymbolTable; // Conditional global UMD exports
|
||||
/* @internal */ isReadonly?: boolean; // readonly? (set only for intersections and unions)
|
||||
/* @internal */ id?: number; // Unique id (used to look up SymbolLinks)
|
||||
/* @internal */ mergeId?: number; // Merge id (used to look up merged symbol)
|
||||
/* @internal */ parent?: Symbol; // Parent symbol
|
||||
@@ -2729,8 +2726,6 @@
|
||||
leftSpread?: Symbol; // Left source for synthetic spread property
|
||||
rightSpread?: Symbol; // Right source for synthetic spread property
|
||||
mappedTypeOrigin?: Symbol; // For a property on a mapped type, points back to the orignal 'T' from 'keyof T'.
|
||||
hasNonUniformType?: boolean; // True if constituents have non-uniform types
|
||||
isPartial?: boolean; // True if syntheric property of union type occurs in some but not all constituents
|
||||
isDiscriminantProperty?: boolean; // True if discriminant synthetic property
|
||||
resolvedExports?: SymbolTable; // Resolved exports of module
|
||||
exportsChecked?: boolean; // True if exports of external module have been checked
|
||||
@@ -2740,7 +2735,22 @@
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface TransientSymbol extends Symbol, SymbolLinks { }
|
||||
export const enum CheckFlags {
|
||||
Instantiated = 1 << 0, // Instantiated symbol
|
||||
SyntheticProperty = 1 << 1, // Property in union or intersection type
|
||||
Readonly = 1 << 2, // Readonly transient symbol
|
||||
Partial = 1 << 3, // Synthetic property present in some but not all constituents
|
||||
HasNonUniformType = 1 << 4, // Synthetic property with non-uniform type in constituents
|
||||
ContainsPublic = 1 << 5, // Synthetic property with public constituent(s)
|
||||
ContainsProtected = 1 << 6, // Synthetic property with protected constituent(s)
|
||||
ContainsPrivate = 1 << 7, // Synthetic property with private constituent(s)
|
||||
ContainsStatic = 1 << 8, // Synthetic property with static constituent(s)
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface TransientSymbol extends Symbol, SymbolLinks {
|
||||
checkFlags: CheckFlags;
|
||||
}
|
||||
|
||||
export type SymbolTable = Map<Symbol>;
|
||||
|
||||
@@ -3162,9 +3172,8 @@
|
||||
ThisProperty
|
||||
}
|
||||
|
||||
export interface FileExtensionInfo {
|
||||
export interface JsFileExtensionInfo {
|
||||
extension: string;
|
||||
scriptKind: ScriptKind;
|
||||
isMixedContent: boolean;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user