mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-11-18 17:21:48 +00:00
Merge branch 'master' into master-dynamicImport
This commit is contained in:
+2
-2
@@ -21,8 +21,8 @@ branches:
|
||||
- release-2.3
|
||||
|
||||
install:
|
||||
- npm uninstall typescript
|
||||
- npm uninstall tslint
|
||||
- npm uninstall typescript --no-save
|
||||
- npm uninstall tslint --no-save
|
||||
- npm install
|
||||
|
||||
cache:
|
||||
|
||||
+3
-2
@@ -129,6 +129,7 @@ var harnessSources = harnessCoreSources.concat([
|
||||
"initializeTSConfig.ts",
|
||||
"printer.ts",
|
||||
"textChanges.ts",
|
||||
"telemetry.ts",
|
||||
"transform.ts",
|
||||
"customTransforms.ts",
|
||||
].map(function (f) {
|
||||
@@ -1079,7 +1080,7 @@ var loggedIOJsPath = builtLocalDirectory + 'loggedIO.js';
|
||||
file(loggedIOJsPath, [builtLocalDirectory, loggedIOpath], function () {
|
||||
var temp = builtLocalDirectory + 'temp';
|
||||
jake.mkdirP(temp);
|
||||
var options = "--types --outdir " + temp + ' ' + loggedIOpath;
|
||||
var options = "--target es5 --lib es6 --types --outdir " + temp + ' ' + loggedIOpath;
|
||||
var cmd = host + " " + LKGDirectory + compilerFilename + " " + options + " ";
|
||||
console.log(cmd + "\n");
|
||||
var ex = jake.createExec([cmd]);
|
||||
@@ -1093,7 +1094,7 @@ file(loggedIOJsPath, [builtLocalDirectory, loggedIOpath], function () {
|
||||
|
||||
var instrumenterPath = harnessDirectory + 'instrumenter.ts';
|
||||
var instrumenterJsPath = builtLocalDirectory + 'instrumenter.js';
|
||||
compileFile(instrumenterJsPath, [instrumenterPath], [tscFile, instrumenterPath].concat(libraryTargets), [], /*useBuiltCompiler*/ true);
|
||||
compileFile(instrumenterJsPath, [instrumenterPath], [tscFile, instrumenterPath].concat(libraryTargets), [], /*useBuiltCompiler*/ true, { lib: "es6", types: ["node"] });
|
||||
|
||||
desc("Builds an instrumented tsc.js");
|
||||
task('tsc-instrumented', [loggedIOJsPath, instrumenterJsPath, tscFile], function () {
|
||||
|
||||
+3
-3
@@ -2,12 +2,12 @@
|
||||
|
||||
# Set up NVM
|
||||
export NVM_DIR="/home/dotnet-bot/.nvm"
|
||||
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
|
||||
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
|
||||
|
||||
nvm install $1
|
||||
|
||||
npm uninstall typescript
|
||||
npm uninstall tslint
|
||||
npm uninstall typescript --no-save
|
||||
npm uninstall tslint --no-save
|
||||
npm install
|
||||
npm update
|
||||
npm test
|
||||
|
||||
+2
-2
@@ -59,7 +59,7 @@
|
||||
"gulp-insert": "latest",
|
||||
"gulp-newer": "latest",
|
||||
"gulp-sourcemaps": "latest",
|
||||
"gulp-typescript": "3.1.5",
|
||||
"gulp-typescript": "latest",
|
||||
"into-stream": "latest",
|
||||
"istanbul": "latest",
|
||||
"jake": "latest",
|
||||
@@ -74,7 +74,7 @@
|
||||
"through2": "latest",
|
||||
"travis-fold": "latest",
|
||||
"ts-node": "latest",
|
||||
"tslint": "next",
|
||||
"tslint": "latest",
|
||||
"typescript": "next"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -2178,7 +2178,10 @@ namespace ts {
|
||||
case SyntaxKind.JSDocRecordMember:
|
||||
return bindPropertyWorker(node as JSDocRecordMember);
|
||||
case SyntaxKind.JSDocPropertyTag:
|
||||
return declareSymbolAndAddToSymbolTable(node as JSDocPropertyTag, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
|
||||
return declareSymbolAndAddToSymbolTable(node as JSDocPropertyTag,
|
||||
(node as JSDocPropertyTag).isBracketed || ((node as JSDocPropertyTag).typeExpression && (node as JSDocPropertyTag).typeExpression.type.kind === SyntaxKind.JSDocOptionalType) ?
|
||||
SymbolFlags.Property | SymbolFlags.Optional : SymbolFlags.Property,
|
||||
SymbolFlags.PropertyExcludes);
|
||||
case SyntaxKind.JSDocFunctionType:
|
||||
return bindFunctionOrConstructorType(<SignatureDeclaration>node);
|
||||
case SyntaxKind.JSDocTypeLiteral:
|
||||
@@ -3597,4 +3600,4 @@ namespace ts {
|
||||
return TransformFlags.NodeExcludes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+223
-199
@@ -1095,13 +1095,13 @@ namespace ts {
|
||||
if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
|
||||
suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning);
|
||||
if (suggestion) {
|
||||
suggestionCount++;
|
||||
error(errorLocation, suggestedNameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg), suggestion);
|
||||
}
|
||||
}
|
||||
if (!suggestion) {
|
||||
error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg));
|
||||
}
|
||||
suggestionCount++;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
@@ -4117,7 +4117,7 @@ namespace ts {
|
||||
// This elementType will be used if the specific property corresponding to this index is not
|
||||
// present (aka the tuple element property). This call also checks that the parentType is in
|
||||
// fact an iterable or array (depending on target language).
|
||||
const elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterable*/ false);
|
||||
const elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false);
|
||||
if (declaration.dotDotDotToken) {
|
||||
// Rest element has an array type with the same element type as the parent type
|
||||
type = createArrayType(elementType);
|
||||
@@ -5692,6 +5692,7 @@ namespace ts {
|
||||
prop.type = propType;
|
||||
if (propertySymbol) {
|
||||
prop.syntheticOrigin = propertySymbol;
|
||||
prop.declarations = propertySymbol.declarations;
|
||||
}
|
||||
members.set(propName, prop);
|
||||
}
|
||||
@@ -6854,6 +6855,7 @@ namespace ts {
|
||||
case "Object":
|
||||
return anyType;
|
||||
case "Function":
|
||||
case "function":
|
||||
return globalFunctionType;
|
||||
case "Array":
|
||||
case "array":
|
||||
@@ -7952,23 +7954,14 @@ namespace ts {
|
||||
return mapper;
|
||||
}
|
||||
|
||||
function getInferenceMapper(context: InferenceContext): TypeMapper {
|
||||
if (!context.mapper) {
|
||||
const mapper: TypeMapper = t => {
|
||||
const typeParameters = context.signature.typeParameters;
|
||||
for (let i = 0; i < typeParameters.length; i++) {
|
||||
if (t === typeParameters[i]) {
|
||||
context.inferences[i].isFixed = true;
|
||||
return getInferredType(context, i);
|
||||
}
|
||||
}
|
||||
return t;
|
||||
};
|
||||
mapper.mappedTypes = context.signature.typeParameters;
|
||||
mapper.context = context;
|
||||
context.mapper = mapper;
|
||||
}
|
||||
return context.mapper;
|
||||
function isInferenceContext(mapper: TypeMapper): mapper is InferenceContext {
|
||||
return !!(<InferenceContext>mapper).signature;
|
||||
}
|
||||
|
||||
function cloneTypeMapper(mapper: TypeMapper): TypeMapper {
|
||||
return mapper && isInferenceContext(mapper) ?
|
||||
createInferenceContext(mapper.signature, mapper.flags | InferenceFlags.NoDefault, mapper.inferences) :
|
||||
mapper;
|
||||
}
|
||||
|
||||
function identityMapper(type: Type): Type {
|
||||
@@ -10170,23 +10163,45 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function createInferenceContext(signature: Signature, inferUnionTypes: boolean, useAnyForNoInferences: boolean): InferenceContext {
|
||||
const inferences = map(signature.typeParameters, createTypeInferencesObject);
|
||||
function createInferenceContext(signature: Signature, flags: InferenceFlags, baseInferences?: InferenceInfo[]): InferenceContext {
|
||||
const inferences = baseInferences ? map(baseInferences, cloneInferenceInfo) : map(signature.typeParameters, createInferenceInfo);
|
||||
const context = mapper as InferenceContext;
|
||||
context.mappedTypes = signature.typeParameters;
|
||||
context.signature = signature;
|
||||
context.inferences = inferences;
|
||||
context.flags = flags;
|
||||
return context;
|
||||
|
||||
function mapper(t: Type): Type {
|
||||
for (let i = 0; i < inferences.length; i++) {
|
||||
if (t === inferences[i].typeParameter) {
|
||||
inferences[i].isFixed = true;
|
||||
return getInferredType(context, i);
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
function createInferenceInfo(typeParameter: TypeParameter): InferenceInfo {
|
||||
return {
|
||||
signature,
|
||||
inferUnionTypes,
|
||||
inferences,
|
||||
inferredTypes: new Array(signature.typeParameters.length),
|
||||
useAnyForNoInferences
|
||||
typeParameter,
|
||||
candidates: undefined,
|
||||
inferredType: undefined,
|
||||
priority: undefined,
|
||||
topLevel: true,
|
||||
isFixed: false
|
||||
};
|
||||
}
|
||||
|
||||
function createTypeInferencesObject(): TypeInferences {
|
||||
function cloneInferenceInfo(inference: InferenceInfo): InferenceInfo {
|
||||
return {
|
||||
primary: undefined,
|
||||
secondary: undefined,
|
||||
topLevel: true,
|
||||
isFixed: false,
|
||||
typeParameter: inference.typeParameter,
|
||||
candidates: inference.candidates && inference.candidates.slice(),
|
||||
inferredType: inference.inferredType,
|
||||
priority: inference.priority,
|
||||
topLevel: inference.topLevel,
|
||||
isFixed: inference.isFixed
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10223,10 +10238,9 @@ namespace ts {
|
||||
if (properties.length === 0 && !indexInfo) {
|
||||
return undefined;
|
||||
}
|
||||
const typeVariable = <TypeVariable>getIndexedAccessType((<IndexType>getConstraintTypeFromMappedType(target)).type, getTypeParameterFromMappedType(target));
|
||||
const typeVariableArray = [typeVariable];
|
||||
const typeInferences = createTypeInferencesObject();
|
||||
const typeInferencesArray = [typeInferences];
|
||||
const typeParameter = <TypeParameter>getIndexedAccessType((<IndexType>getConstraintTypeFromMappedType(target)).type, getTypeParameterFromMappedType(target));
|
||||
const inference = createInferenceInfo(typeParameter);
|
||||
const inferences = [inference];
|
||||
const templateType = getTemplateTypeFromMappedType(target);
|
||||
const readonlyMask = target.declaration.readonlyToken ? false : true;
|
||||
const optionalMask = target.declaration.questionToken ? 0 : SymbolFlags.Optional;
|
||||
@@ -10252,22 +10266,15 @@ namespace ts {
|
||||
return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined);
|
||||
|
||||
function inferTargetType(sourceType: Type): Type {
|
||||
typeInferences.primary = undefined;
|
||||
typeInferences.secondary = undefined;
|
||||
inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType);
|
||||
const inferences = typeInferences.primary || typeInferences.secondary;
|
||||
return inferences && getUnionType(inferences, /*subtypeReduction*/ true);
|
||||
inference.candidates = undefined;
|
||||
inferTypes(inferences, sourceType, templateType);
|
||||
return inference.candidates && getUnionType(inference.candidates, /*subtypeReduction*/ true);
|
||||
}
|
||||
}
|
||||
|
||||
function inferTypesWithContext(context: InferenceContext, originalSource: Type, originalTarget: Type) {
|
||||
inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget);
|
||||
}
|
||||
|
||||
function inferTypes(typeVariables: TypeVariable[], typeInferences: TypeInferences[], originalSource: Type, originalTarget: Type) {
|
||||
function inferTypes(inferences: InferenceInfo[], originalSource: Type, originalTarget: Type, priority: InferencePriority = 0) {
|
||||
let symbolStack: Symbol[];
|
||||
let visited: Map<boolean>;
|
||||
let inferiority = 0;
|
||||
inferFromTypes(originalSource, originalTarget);
|
||||
|
||||
function inferFromTypes(source: Type, target: Type) {
|
||||
@@ -10327,32 +10334,26 @@ namespace ts {
|
||||
// Because the anyFunctionType is internal, it should not be exposed to the user by adding
|
||||
// it as an inference candidate. Hopefully, a better candidate will come along that does
|
||||
// not contain anyFunctionType when we come back to this argument for its second round
|
||||
// of inference.
|
||||
if (source.flags & TypeFlags.ContainsAnyFunctionType) {
|
||||
// of inference. Also, we exclude inferences for silentNeverType which is used as a wildcard
|
||||
// when constructing types from type parameters that had no inference candidates.
|
||||
if (source.flags & TypeFlags.ContainsAnyFunctionType || source === silentNeverType) {
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < typeVariables.length; i++) {
|
||||
if (target === typeVariables[i]) {
|
||||
const inferences = typeInferences[i];
|
||||
if (!inferences.isFixed) {
|
||||
// Any inferences that are made to a type parameter in a union type are inferior
|
||||
// to inferences made to a flat (non-union) type. This is because if we infer to
|
||||
// T | string[], we really don't know if we should be inferring to T or not (because
|
||||
// the correct constituent on the target side could be string[]). Therefore, we put
|
||||
// such inferior inferences into a secondary bucket, and only use them if the primary
|
||||
// bucket is empty.
|
||||
const candidates = inferiority ?
|
||||
inferences.secondary || (inferences.secondary = []) :
|
||||
inferences.primary || (inferences.primary = []);
|
||||
if (!contains(candidates, source)) {
|
||||
candidates.push(source);
|
||||
}
|
||||
if (target.flags & TypeFlags.TypeParameter && !isTypeParameterAtTopLevel(originalTarget, <TypeParameter>target)) {
|
||||
inferences.topLevel = false;
|
||||
}
|
||||
const inference = getInferenceInfoForType(target);
|
||||
if (inference) {
|
||||
if (!inference.isFixed) {
|
||||
if (!inference.candidates || priority < inference.priority) {
|
||||
inference.candidates = [source];
|
||||
inference.priority = priority;
|
||||
}
|
||||
else if (priority === inference.priority) {
|
||||
inference.candidates.push(source);
|
||||
}
|
||||
if (!(priority & InferencePriority.ReturnType) && target.flags & TypeFlags.TypeParameter && !isTypeParameterAtTopLevel(originalTarget, <TypeParameter>target)) {
|
||||
inference.topLevel = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (<TypeReference>source).target === (<TypeReference>target).target) {
|
||||
@@ -10370,7 +10371,7 @@ namespace ts {
|
||||
let typeVariable: TypeVariable;
|
||||
// First infer to each type in union or intersection that isn't a type variable
|
||||
for (const t of targetTypes) {
|
||||
if (t.flags & TypeFlags.TypeVariable && contains(typeVariables, t)) {
|
||||
if (getInferenceInfoForType(t)) {
|
||||
typeVariable = <TypeVariable>t;
|
||||
typeVariableCount++;
|
||||
}
|
||||
@@ -10382,9 +10383,10 @@ namespace ts {
|
||||
// variable. This gives meaningful results for union types in co-variant positions and intersection
|
||||
// types in contra-variant positions (such as callback parameters).
|
||||
if (typeVariableCount === 1) {
|
||||
inferiority++;
|
||||
const savePriority = priority;
|
||||
priority |= InferencePriority.NakedTypeVariable;
|
||||
inferFromTypes(source, typeVariable);
|
||||
inferiority--;
|
||||
priority = savePriority;
|
||||
}
|
||||
}
|
||||
else if (source.flags & TypeFlags.UnionOrIntersection) {
|
||||
@@ -10424,6 +10426,17 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function getInferenceInfoForType(type: Type) {
|
||||
if (type.flags & TypeFlags.TypeVariable) {
|
||||
for (const inference of inferences) {
|
||||
if (type === inference.typeParameter) {
|
||||
return inference;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function inferFromObjectTypes(source: Type, target: Type) {
|
||||
if (getObjectFlags(target) & ObjectFlags.Mapped) {
|
||||
const constraintType = getConstraintTypeFromMappedType(<MappedType>target);
|
||||
@@ -10432,13 +10445,14 @@ namespace ts {
|
||||
// where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
|
||||
// type and then make a secondary inference from that type to T. We make a secondary inference
|
||||
// such that direct inferences to T get priority over inferences to Partial<T>, for example.
|
||||
const index = indexOf(typeVariables, (<IndexType>constraintType).type);
|
||||
if (index >= 0 && !typeInferences[index].isFixed) {
|
||||
const inference = getInferenceInfoForType((<IndexType>constraintType).type);
|
||||
if (inference && !inference.isFixed) {
|
||||
const inferredType = inferTypeForHomomorphicMappedType(source, <MappedType>target);
|
||||
if (inferredType) {
|
||||
inferiority++;
|
||||
inferFromTypes(inferredType, typeVariables[index]);
|
||||
inferiority--;
|
||||
const savePriority = priority;
|
||||
priority |= InferencePriority.MappedType;
|
||||
inferFromTypes(inferredType, inference.typeParameter);
|
||||
priority = savePriority;
|
||||
}
|
||||
}
|
||||
return;
|
||||
@@ -10537,66 +10551,68 @@ namespace ts {
|
||||
return type.flags & TypeFlags.Union ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes);
|
||||
}
|
||||
|
||||
function getInferenceCandidates(context: InferenceContext, index: number): Type[] {
|
||||
const inferences = context.inferences[index];
|
||||
return inferences.primary || inferences.secondary || emptyArray;
|
||||
}
|
||||
|
||||
function hasPrimitiveConstraint(type: TypeParameter): boolean {
|
||||
const constraint = getConstraintOfTypeParameter(type);
|
||||
return constraint && maybeTypeOfKind(constraint, TypeFlags.Primitive | TypeFlags.Index);
|
||||
}
|
||||
|
||||
function getInferredType(context: InferenceContext, index: number): Type {
|
||||
let inferredType = context.inferredTypes[index];
|
||||
const inference = context.inferences[index];
|
||||
let inferredType = inference.inferredType;
|
||||
let inferenceSucceeded: boolean;
|
||||
if (!inferredType) {
|
||||
const inferences = getInferenceCandidates(context, index);
|
||||
if (inferences.length) {
|
||||
if (inference.candidates) {
|
||||
// We widen inferred literal types if
|
||||
// all inferences were made to top-level ocurrences of the type parameter, and
|
||||
// the type parameter has no constraint or its constraint includes no primitive or literal types, and
|
||||
// the type parameter was fixed during inference or does not occur at top-level in the return type.
|
||||
const signature = context.signature;
|
||||
const widenLiteralTypes = context.inferences[index].topLevel &&
|
||||
!hasPrimitiveConstraint(signature.typeParameters[index]) &&
|
||||
(context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index]));
|
||||
const baseInferences = widenLiteralTypes ? sameMap(inferences, getWidenedLiteralType) : inferences;
|
||||
// Infer widened union or supertype, or the unknown type for no common supertype
|
||||
const unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences);
|
||||
const widenLiteralTypes = inference.topLevel &&
|
||||
!hasPrimitiveConstraint(inference.typeParameter) &&
|
||||
(inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
|
||||
const baseCandidates = widenLiteralTypes ? sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates;
|
||||
// Infer widened union or supertype, or the unknown type for no common supertype. We infer union types
|
||||
// for inferences coming from return types in order to avoid common supertype failures.
|
||||
const unionOrSuperType = context.flags & InferenceFlags.InferUnionTypes || inference.priority & InferencePriority.ReturnType ?
|
||||
getUnionType(baseCandidates, /*subtypeReduction*/ true) : getCommonSupertype(baseCandidates);
|
||||
inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType;
|
||||
inferenceSucceeded = !!unionOrSuperType;
|
||||
}
|
||||
else {
|
||||
// Infer either the default or the empty object type when no inferences were
|
||||
// made. It is important to remember that in this case, inference still
|
||||
// succeeds, meaning there is no error for not having inference candidates. An
|
||||
// inference error only occurs when there are *conflicting* candidates, i.e.
|
||||
// candidates with no common supertype.
|
||||
const defaultType = getDefaultFromTypeParameter(context.signature.typeParameters[index]);
|
||||
if (defaultType) {
|
||||
// Instantiate the default type. Any forward reference to a type
|
||||
// parameter should be instantiated to the empty object type.
|
||||
inferredType = instantiateType(defaultType,
|
||||
combineTypeMappers(
|
||||
createBackreferenceMapper(context.signature.typeParameters, index),
|
||||
getInferenceMapper(context)));
|
||||
if (context.flags & InferenceFlags.NoDefault) {
|
||||
// We use silentNeverType as the wildcard that signals no inferences.
|
||||
inferredType = silentNeverType;
|
||||
}
|
||||
else {
|
||||
inferredType = context.useAnyForNoInferences ? anyType : emptyObjectType;
|
||||
// Infer either the default or the empty object type when no inferences were
|
||||
// made. It is important to remember that in this case, inference still
|
||||
// succeeds, meaning there is no error for not having inference candidates. An
|
||||
// inference error only occurs when there are *conflicting* candidates, i.e.
|
||||
// candidates with no common supertype.
|
||||
const defaultType = getDefaultFromTypeParameter(inference.typeParameter);
|
||||
if (defaultType) {
|
||||
// Instantiate the default type. Any forward reference to a type
|
||||
// parameter should be instantiated to the empty object type.
|
||||
inferredType = instantiateType(defaultType,
|
||||
combineTypeMappers(
|
||||
createBackreferenceMapper(context.signature.typeParameters, index),
|
||||
context));
|
||||
}
|
||||
else {
|
||||
inferredType = context.flags & InferenceFlags.AnyDefault ? anyType : emptyObjectType;
|
||||
}
|
||||
}
|
||||
|
||||
inferenceSucceeded = true;
|
||||
}
|
||||
context.inferredTypes[index] = inferredType;
|
||||
inference.inferredType = inferredType;
|
||||
|
||||
// Only do the constraint check if inference succeeded (to prevent cascading errors)
|
||||
if (inferenceSucceeded) {
|
||||
const constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]);
|
||||
if (constraint) {
|
||||
const instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context));
|
||||
const instantiatedConstraint = instantiateType(constraint, context);
|
||||
if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
|
||||
context.inferredTypes[index] = inferredType = instantiatedConstraint;
|
||||
inference.inferredType = inferredType = instantiatedConstraint;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10611,10 +10627,11 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getInferredTypes(context: InferenceContext): Type[] {
|
||||
for (let i = 0; i < context.inferredTypes.length; i++) {
|
||||
getInferredType(context, i);
|
||||
const result: Type[] = [];
|
||||
for (let i = 0; i < context.inferences.length; i++) {
|
||||
result.push(getInferredType(context, i));
|
||||
}
|
||||
return context.inferredTypes;
|
||||
return result;
|
||||
}
|
||||
|
||||
// EXPRESSION TYPE CHECKING
|
||||
@@ -10877,12 +10894,12 @@ namespace ts {
|
||||
|
||||
function getTypeOfDestructuredArrayElement(type: Type, index: number) {
|
||||
return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) ||
|
||||
checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) ||
|
||||
checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) ||
|
||||
unknownType;
|
||||
}
|
||||
|
||||
function getTypeOfDestructuredSpreadExpression(type: Type) {
|
||||
return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType);
|
||||
return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType);
|
||||
}
|
||||
|
||||
function getAssignedTypeOfBinaryExpression(node: BinaryExpression): Type {
|
||||
@@ -12856,7 +12873,7 @@ namespace ts {
|
||||
const index = indexOf(arrayLiteral.elements, node);
|
||||
return getTypeOfPropertyOfContextualType(type, "" + index)
|
||||
|| getIndexTypeOfContextualType(type, IndexKind.Number)
|
||||
|| getIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false, /*checkAssignability*/ false);
|
||||
|| getIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -13094,7 +13111,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
const arrayOrIterableType = checkExpression(node.expression, checkMode);
|
||||
return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterable*/ false);
|
||||
return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false);
|
||||
}
|
||||
|
||||
function hasDefaultValue(node: BindingElement | Expression): boolean {
|
||||
@@ -13123,7 +13140,7 @@ namespace ts {
|
||||
// if there is no index type / iterated type.
|
||||
const restArrayType = checkExpression((<SpreadElement>e).expression, checkMode);
|
||||
const restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) ||
|
||||
getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false, /*checkAssignability*/ false);
|
||||
getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false);
|
||||
if (restElementType) {
|
||||
elementTypes.push(restElementType);
|
||||
}
|
||||
@@ -14870,26 +14887,25 @@ namespace ts {
|
||||
|
||||
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
|
||||
function instantiateSignatureInContextOf(signature: Signature, contextualSignature: Signature, contextualMapper: TypeMapper): Signature {
|
||||
const context = createInferenceContext(signature, /*inferUnionTypes*/ true, /*useAnyForNoInferences*/ false);
|
||||
const context = createInferenceContext(signature, InferenceFlags.InferUnionTypes);
|
||||
forEachMatchingParameterType(contextualSignature, signature, (source, target) => {
|
||||
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
|
||||
inferTypesWithContext(context, instantiateType(source, contextualMapper), target);
|
||||
inferTypes(context.inferences, instantiateType(source, contextualMapper), target);
|
||||
});
|
||||
return getSignatureInstantiation(signature, getInferredTypes(context));
|
||||
}
|
||||
|
||||
function inferTypeArguments(node: CallLikeExpression, signature: Signature, args: Expression[], excludeArgument: boolean[], context: InferenceContext): void {
|
||||
const typeParameters = signature.typeParameters;
|
||||
const inferenceMapper = getInferenceMapper(context);
|
||||
function inferTypeArguments(node: CallLikeExpression, signature: Signature, args: Expression[], excludeArgument: boolean[], context: InferenceContext): Type[] {
|
||||
const inferences = context.inferences;
|
||||
|
||||
// Clear out all the inference results from the last time inferTypeArguments was called on this context
|
||||
for (let i = 0; i < typeParameters.length; i++) {
|
||||
for (let i = 0; i < inferences.length; i++) {
|
||||
// As an optimization, we don't have to clear (and later recompute) inferred types
|
||||
// for type parameters that have already been fixed on the previous call to inferTypeArguments.
|
||||
// It would be just as correct to reset all of them. But then we'd be repeating the same work
|
||||
// for the type parameters that were fixed, namely the work done by getInferredType.
|
||||
if (!context.inferences[i].isFixed) {
|
||||
context.inferredTypes[i] = undefined;
|
||||
if (!inferences[i].isFixed) {
|
||||
inferences[i].inferredType = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14904,11 +14920,29 @@ namespace ts {
|
||||
context.failedTypeParameterIndex = undefined;
|
||||
}
|
||||
|
||||
// If a contextual type is available, infer from that type to the return type of the call expression. For
|
||||
// example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
|
||||
// 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
|
||||
// return type of 'wrap'.
|
||||
if (isExpression(node)) {
|
||||
const contextualType = getContextualType(node);
|
||||
if (contextualType) {
|
||||
// We clone the contextual mapper to avoid disturbing a resolution in progress for an
|
||||
// outer call expression. Effectively we just want a snapshot of whatever has been
|
||||
// inferred for any outer call expression so far.
|
||||
const mapper = cloneTypeMapper(getContextualMapper(node));
|
||||
const instantiatedType = instantiateType(contextualType, mapper);
|
||||
const returnType = getReturnTypeOfSignature(signature);
|
||||
// Inferences made from return types have lower priority than all other inferences.
|
||||
inferTypes(context.inferences, instantiatedType, returnType, InferencePriority.ReturnType);
|
||||
}
|
||||
}
|
||||
|
||||
const thisType = getThisTypeOfSignature(signature);
|
||||
if (thisType) {
|
||||
const thisArgumentNode = getThisArgumentOfCall(node);
|
||||
const thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
|
||||
inferTypesWithContext(context, thisArgumentType, thisType);
|
||||
inferTypes(context.inferences, thisArgumentType, thisType);
|
||||
}
|
||||
|
||||
// We perform two passes over the arguments. In the first pass we infer from all arguments, but use
|
||||
@@ -14926,11 +14960,11 @@ namespace ts {
|
||||
if (argType === undefined) {
|
||||
// For context sensitive arguments we pass the identityMapper, which is a signal to treat all
|
||||
// context sensitive function expressions as wildcards
|
||||
const mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper;
|
||||
const mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
|
||||
argType = checkExpressionWithContextualType(arg, paramType, mapper);
|
||||
}
|
||||
|
||||
inferTypesWithContext(context, argType, paramType);
|
||||
inferTypes(context.inferences, argType, paramType);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14945,12 +14979,11 @@ namespace ts {
|
||||
if (excludeArgument[i] === false) {
|
||||
const arg = args[i];
|
||||
const paramType = getTypeAtPosition(signature, i);
|
||||
inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType);
|
||||
inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getInferredTypes(context);
|
||||
return getInferredTypes(context);
|
||||
}
|
||||
|
||||
function checkTypeArguments(signature: Signature, typeArgumentNodes: TypeNode[], typeArgumentTypes: Type[], reportErrors: boolean, headMessage?: DiagnosticMessage): boolean {
|
||||
@@ -15532,7 +15565,7 @@ namespace ts {
|
||||
else {
|
||||
Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0);
|
||||
const failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex];
|
||||
const inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex);
|
||||
const inferenceCandidates = resultOfFailedInference.inferences[resultOfFailedInference.failedTypeParameterIndex].candidates;
|
||||
|
||||
let diagnosticChainHead = chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError
|
||||
Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly,
|
||||
@@ -15605,7 +15638,7 @@ namespace ts {
|
||||
let candidate: Signature;
|
||||
let typeArgumentsAreValid: boolean;
|
||||
const inferenceContext = originalCandidate.typeParameters
|
||||
? createInferenceContext(originalCandidate, /*inferUnionTypes*/ false, /*useAnyForNoInferences*/ isInJavaScriptFile(node))
|
||||
? createInferenceContext(originalCandidate, /*flags*/ isInJavaScriptFile(node) ? InferenceFlags.AnyDefault : 0)
|
||||
: undefined;
|
||||
|
||||
while (true) {
|
||||
@@ -15617,8 +15650,7 @@ namespace ts {
|
||||
typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false);
|
||||
}
|
||||
else {
|
||||
inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
|
||||
typeArgumentTypes = inferenceContext.inferredTypes;
|
||||
typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
|
||||
typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined;
|
||||
}
|
||||
if (!typeArgumentsAreValid) {
|
||||
@@ -16221,7 +16253,7 @@ namespace ts {
|
||||
for (let i = 0; i < len; i++) {
|
||||
const declaration = <ParameterDeclaration>signature.parameters[i].valueDeclaration;
|
||||
if (declaration.type) {
|
||||
inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i));
|
||||
inferTypes((<InferenceContext>mapper).inferences, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16307,7 +16339,7 @@ namespace ts {
|
||||
// T in the second overload so that we do not infer Base as a candidate for T
|
||||
// (inferring Base would make type argument inference inconsistent between the two
|
||||
// overloads).
|
||||
inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper));
|
||||
inferTypes((<InferenceContext>mapper).inferences, links.type, instantiateType(contextualType, mapper));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16994,7 +17026,7 @@ namespace ts {
|
||||
// This elementType will be used if the specific property corresponding to this index is not
|
||||
// present (aka the tuple element property). This call also checks that the parentType is in
|
||||
// fact an iterable or array (depending on target language).
|
||||
const elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType;
|
||||
const elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType;
|
||||
const elements = node.elements;
|
||||
for (let i = 0; i < elements.length; i++) {
|
||||
checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
|
||||
@@ -20142,12 +20174,12 @@ namespace ts {
|
||||
return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined);
|
||||
}
|
||||
|
||||
function checkIteratedTypeOrElementType(inputType: Type, errorNode: Node, allowStringInput: boolean, allowAsyncIterable: boolean): Type {
|
||||
function checkIteratedTypeOrElementType(inputType: Type, errorNode: Node, allowStringInput: boolean, allowAsyncIterables: boolean): Type {
|
||||
if (isTypeAny(inputType)) {
|
||||
return inputType;
|
||||
}
|
||||
|
||||
return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, /*checkAssignability*/ true) || anyType;
|
||||
return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -20155,16 +20187,16 @@ namespace ts {
|
||||
* we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
|
||||
* of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
|
||||
*/
|
||||
function getIteratedTypeOrElementType(inputType: Type, errorNode: Node, allowStringInput: boolean, allowAsyncIterable: boolean, checkAssignability: boolean): Type {
|
||||
function getIteratedTypeOrElementType(inputType: Type, errorNode: Node, allowStringInput: boolean, allowAsyncIterables: boolean, checkAssignability: boolean): Type {
|
||||
const uplevelIteration = languageVersion >= ScriptTarget.ES2015;
|
||||
const downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
|
||||
|
||||
// Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
|
||||
// or higher, when inside of an async generator or for-await-if, or when
|
||||
// downlevelIteration is requested.
|
||||
if (uplevelIteration || downlevelIteration || allowAsyncIterable) {
|
||||
if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
|
||||
// We only report errors for an invalid iterable type in ES2015 or higher.
|
||||
const iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterable, allowAsyncIterable, checkAssignability);
|
||||
const iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability);
|
||||
if (iteratedType || uplevelIteration) {
|
||||
return iteratedType;
|
||||
}
|
||||
@@ -20278,79 +20310,75 @@ namespace ts {
|
||||
* For a **for-await-of** statement or a `yield*` in an async generator we will look for
|
||||
* the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
|
||||
*/
|
||||
function getIteratedTypeOfIterable(type: Type, errorNode: Node | undefined, isAsyncIterable: boolean, allowNonAsyncIterables: boolean, checkAssignability: boolean): Type | undefined {
|
||||
function getIteratedTypeOfIterable(type: Type, errorNode: Node | undefined, allowAsyncIterables: boolean, allowSyncIterables: boolean, checkAssignability: boolean): Type | undefined {
|
||||
if (isTypeAny(type)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const typeAsIterable = <IterableOrIteratorType>type;
|
||||
if (isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable) {
|
||||
return isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable;
|
||||
}
|
||||
return mapType(type, getIteratedType);
|
||||
|
||||
if (isAsyncIterable) {
|
||||
// As an optimization, if the type is an instantiation of the global `AsyncIterable<T>`
|
||||
// or the global `AsyncIterableIterator<T>` then just grab its type argument.
|
||||
if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) ||
|
||||
isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) {
|
||||
return typeAsIterable.iteratedTypeOfAsyncIterable = (<GenericType>type).typeArguments[0];
|
||||
function getIteratedType(type: Type) {
|
||||
const typeAsIterable = <IterableOrIteratorType>type;
|
||||
if (allowAsyncIterables) {
|
||||
if (typeAsIterable.iteratedTypeOfAsyncIterable) {
|
||||
return typeAsIterable.iteratedTypeOfAsyncIterable;
|
||||
}
|
||||
|
||||
// As an optimization, if the type is an instantiation of the global `AsyncIterable<T>`
|
||||
// or the global `AsyncIterableIterator<T>` then just grab its type argument.
|
||||
if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) ||
|
||||
isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) {
|
||||
return typeAsIterable.iteratedTypeOfAsyncIterable = (<GenericType>type).typeArguments[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!isAsyncIterable || allowNonAsyncIterables) {
|
||||
// As an optimization, if the type is an instantiation of the global `Iterable<T>` or
|
||||
// `IterableIterator<T>` then just grab its type argument.
|
||||
if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) ||
|
||||
isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) {
|
||||
return isAsyncIterable
|
||||
? typeAsIterable.iteratedTypeOfAsyncIterable = (<GenericType>type).typeArguments[0]
|
||||
: typeAsIterable.iteratedTypeOfIterable = (<GenericType>type).typeArguments[0];
|
||||
if (allowSyncIterables) {
|
||||
if (typeAsIterable.iteratedTypeOfIterable) {
|
||||
return typeAsIterable.iteratedTypeOfIterable;
|
||||
}
|
||||
|
||||
// As an optimization, if the type is an instantiation of the global `Iterable<T>` or
|
||||
// `IterableIterator<T>` then just grab its type argument.
|
||||
if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) ||
|
||||
isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) {
|
||||
return typeAsIterable.iteratedTypeOfIterable = (<GenericType>type).typeArguments[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let iteratorMethodSignatures: Signature[];
|
||||
let isNonAsyncIterable = false;
|
||||
if (isAsyncIterable) {
|
||||
const iteratorMethod = getTypeOfPropertyOfType(type, getPropertyNameForKnownSymbolName("asyncIterator"));
|
||||
if (isTypeAny(iteratorMethod)) {
|
||||
const asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, getPropertyNameForKnownSymbolName("asyncIterator"));
|
||||
const methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, getPropertyNameForKnownSymbolName("iterator")));
|
||||
if (isTypeAny(methodType)) {
|
||||
return undefined;
|
||||
}
|
||||
iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, SignatureKind.Call);
|
||||
}
|
||||
|
||||
if (!isAsyncIterable || (allowNonAsyncIterables && !some(iteratorMethodSignatures))) {
|
||||
const iteratorMethod = getTypeOfPropertyOfType(type, getPropertyNameForKnownSymbolName("iterator"));
|
||||
if (isTypeAny(iteratorMethod)) {
|
||||
const signatures = methodType && getSignaturesOfType(methodType, SignatureKind.Call);
|
||||
if (!some(signatures)) {
|
||||
if (errorNode) {
|
||||
error(errorNode,
|
||||
allowAsyncIterables
|
||||
? Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
|
||||
: Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator);
|
||||
// only report on the first error
|
||||
errorNode = undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, SignatureKind.Call);
|
||||
isNonAsyncIterable = true;
|
||||
}
|
||||
|
||||
if (some(iteratorMethodSignatures)) {
|
||||
const iteratorMethodReturnType = getUnionType(map(iteratorMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true);
|
||||
const iteratedType = getIteratedTypeOfIterator(iteratorMethodReturnType, errorNode, /*isAsyncIterator*/ !isNonAsyncIterable);
|
||||
const returnType = getUnionType(map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true);
|
||||
const iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType);
|
||||
if (checkAssignability && errorNode && iteratedType) {
|
||||
// If `checkAssignability` was specified, we were called from
|
||||
// `checkIteratedTypeOrElementType`. As such, we need to validate that
|
||||
// the type passed in is actually an Iterable.
|
||||
checkTypeAssignableTo(type, isNonAsyncIterable
|
||||
? createIterableType(iteratedType)
|
||||
: createAsyncIterableType(iteratedType), errorNode);
|
||||
checkTypeAssignableTo(type, asyncMethodType
|
||||
? createAsyncIterableType(iteratedType)
|
||||
: createIterableType(iteratedType), errorNode);
|
||||
}
|
||||
return isAsyncIterable
|
||||
|
||||
return asyncMethodType
|
||||
? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType
|
||||
: typeAsIterable.iteratedTypeOfIterable = iteratedType;
|
||||
}
|
||||
|
||||
if (errorNode) {
|
||||
error(errorNode,
|
||||
isAsyncIterable
|
||||
? Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
|
||||
: Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -20450,7 +20478,7 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, isAsyncGenerator, /*allowNonAsyncIterables*/ false, /*checkAssignability*/ false)
|
||||
return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false)
|
||||
|| getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator);
|
||||
}
|
||||
|
||||
@@ -21097,10 +21125,6 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function isAccessor(kind: SyntaxKind): boolean {
|
||||
return kind === SyntaxKind.GetAccessor || kind === SyntaxKind.SetAccessor;
|
||||
}
|
||||
|
||||
function checkInheritedPropertiesAreIdentical(type: InterfaceType, typeNode: Node): boolean {
|
||||
const baseTypes = getBaseTypes(type);
|
||||
if (baseTypes.length < 2) {
|
||||
@@ -22660,7 +22684,7 @@ namespace ts {
|
||||
Debug.assert(expr.parent.kind === SyntaxKind.ArrayLiteralExpression);
|
||||
// [{ property1: p1, property2 }] = elems;
|
||||
const typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(<Expression>expr.parent);
|
||||
const elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType;
|
||||
const elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType;
|
||||
return checkArrayLiteralDestructuringElementAssignment(<ArrayLiteralExpression>expr.parent, typeOfArrayLiteral,
|
||||
indexOf((<ArrayLiteralExpression>expr.parent).elements, expr), elementType || unknownType);
|
||||
}
|
||||
@@ -24570,7 +24594,7 @@ namespace ts {
|
||||
function checkGrammarStatementInAmbientContext(node: Node): boolean {
|
||||
if (isInAmbientContext(node)) {
|
||||
// An accessors is already reported about the ambient context
|
||||
if (isAccessor(node.parent.kind)) {
|
||||
if (isAccessor(node.parent)) {
|
||||
return getNodeLinks(node).hasReportedStatementInAmbientContext = true;
|
||||
}
|
||||
|
||||
|
||||
@@ -693,8 +693,7 @@ namespace ts {
|
||||
return typeAcquisition;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function getOptionNameMap(): OptionNameMap {
|
||||
function getOptionNameMap(): OptionNameMap {
|
||||
if (optionNameMapCache) {
|
||||
return optionNameMapCache;
|
||||
}
|
||||
@@ -747,7 +746,6 @@ namespace ts {
|
||||
const options: CompilerOptions = {};
|
||||
const fileNames: string[] = [];
|
||||
const errors: Diagnostic[] = [];
|
||||
const { optionNameMap, shortOptionNames } = getOptionNameMap();
|
||||
|
||||
parseStrings(commandLine);
|
||||
return {
|
||||
@@ -759,21 +757,13 @@ namespace ts {
|
||||
function parseStrings(args: string[]) {
|
||||
let i = 0;
|
||||
while (i < args.length) {
|
||||
let s = args[i];
|
||||
const s = args[i];
|
||||
i++;
|
||||
if (s.charCodeAt(0) === CharacterCodes.at) {
|
||||
parseResponseFile(s.slice(1));
|
||||
}
|
||||
else if (s.charCodeAt(0) === CharacterCodes.minus) {
|
||||
s = s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase();
|
||||
|
||||
// Try to translate short option names to their full equivalents.
|
||||
const short = shortOptionNames.get(s);
|
||||
if (short !== undefined) {
|
||||
s = short;
|
||||
}
|
||||
|
||||
const opt = optionNameMap.get(s);
|
||||
const opt = getOptionFromName(s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1), /*allowShort*/ true);
|
||||
if (opt) {
|
||||
if (opt.isTSConfigOnly) {
|
||||
errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name));
|
||||
@@ -861,6 +851,19 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function getOptionFromName(optionName: string, allowShort = false): CommandLineOption | undefined {
|
||||
optionName = optionName.toLowerCase();
|
||||
const { optionNameMap, shortOptionNames } = getOptionNameMap();
|
||||
// Try to translate short option names to their full equivalents.
|
||||
if (allowShort) {
|
||||
const short = shortOptionNames.get(optionName);
|
||||
if (short !== undefined) {
|
||||
optionName = short;
|
||||
}
|
||||
}
|
||||
return optionNameMap.get(optionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read tsconfig.json file
|
||||
* @param fileName The path to the config file
|
||||
@@ -1040,7 +1043,7 @@ namespace ts {
|
||||
for (let i = 0; i < nameColumn.length; i++) {
|
||||
const optionName = nameColumn[i];
|
||||
const description = descriptionColumn[i];
|
||||
result.push(tab + tab + optionName + makePadding(marginLength - optionName.length + 2) + description);
|
||||
result.push(optionName && `${tab}${tab}${optionName}${ description && (makePadding(marginLength - optionName.length + 2) + description)}`);
|
||||
}
|
||||
if (configurations.files && configurations.files.length) {
|
||||
result.push(`${tab}},`);
|
||||
@@ -1706,4 +1709,42 @@ namespace ts {
|
||||
function caseInsensitiveKeyMapper(key: string) {
|
||||
return key.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed.
|
||||
* Also converts enum values back to strings.
|
||||
*/
|
||||
/* @internal */
|
||||
export function convertCompilerOptionsForTelemetry(opts: ts.CompilerOptions): ts.CompilerOptions {
|
||||
const out: ts.CompilerOptions = {};
|
||||
for (const key in opts) if (opts.hasOwnProperty(key)) {
|
||||
const type = getOptionFromName(key);
|
||||
if (type !== undefined) { // Ignore unknown options
|
||||
out[key] = getOptionValueWithEmptyStrings(opts[key], type);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function getOptionValueWithEmptyStrings(value: any, option: CommandLineOption): {} {
|
||||
switch (option.type) {
|
||||
case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
|
||||
return "";
|
||||
case "string": // Could be any arbitrary string -- use empty string instead.
|
||||
return "";
|
||||
case "number": // Allow numbers, but be sure to check it's actually a number.
|
||||
return typeof value === "number" ? value : "";
|
||||
case "boolean":
|
||||
return typeof value === "boolean" ? value : "";
|
||||
case "list":
|
||||
const elementType = (option as CommandLineOptionOfListType).element;
|
||||
return ts.isArray(value) ? value.map(v => getOptionValueWithEmptyStrings(v, elementType)) : "";
|
||||
default:
|
||||
return ts.forEachEntry(option.type, (optionEnumValue, optionStringValue) => {
|
||||
if (optionEnumValue === value) {
|
||||
return optionStringValue;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+89
-21
@@ -521,6 +521,18 @@ namespace ts {
|
||||
return result || array;
|
||||
}
|
||||
|
||||
export function mapDefined<T>(array: ReadonlyArray<T>, mapFn: (x: T, i: number) => T | undefined): ReadonlyArray<T> {
|
||||
const result: T[] = [];
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
const item = array[i];
|
||||
const mapped = mapFn(item, i);
|
||||
if (mapped !== undefined) {
|
||||
result.push(mapped);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the first matching span of elements and returns a tuple of the first span
|
||||
* and the remaining elements.
|
||||
@@ -740,6 +752,14 @@ namespace ts {
|
||||
return to;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the actual offset into an array for a relative offset. Negative offsets indicate a
|
||||
* position offset from the end of the array.
|
||||
*/
|
||||
function toOffset(array: any[], offset: number) {
|
||||
return offset < 0 ? array.length + offset : offset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a range of value to an array, returning the array.
|
||||
*
|
||||
@@ -747,11 +767,19 @@ namespace ts {
|
||||
* is created if `value` was appended.
|
||||
* @param from The values to append to the array. If `from` is `undefined`, nothing is
|
||||
* appended. If an element of `from` is `undefined`, that element is not appended.
|
||||
* @param start The offset in `from` at which to start copying values.
|
||||
* @param end The offset in `from` at which to stop copying values (non-inclusive).
|
||||
*/
|
||||
export function addRange<T>(to: T[] | undefined, from: T[] | undefined): T[] | undefined {
|
||||
export function addRange<T>(to: T[] | undefined, from: T[] | undefined, start?: number, end?: number): T[] | undefined {
|
||||
if (from === undefined) return to;
|
||||
for (const v of from) {
|
||||
to = append(to, v);
|
||||
if (to === undefined) return from.slice(start, end);
|
||||
start = start === undefined ? 0 : toOffset(from, start);
|
||||
end = end === undefined ? from.length : toOffset(from, end);
|
||||
for (let i = start; i < end && i < from.length; i++) {
|
||||
const v = from[i];
|
||||
if (v !== undefined) {
|
||||
to.push(from[i]);
|
||||
}
|
||||
}
|
||||
return to;
|
||||
}
|
||||
@@ -776,28 +804,38 @@ namespace ts {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
|
||||
* A negative offset indicates the element should be retrieved from the end of the array.
|
||||
*/
|
||||
export function elementAt<T>(array: T[] | undefined, offset: number): T | undefined {
|
||||
if (array) {
|
||||
offset = toOffset(array, offset);
|
||||
if (offset < array.length) {
|
||||
return array[offset];
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first element of an array if non-empty, `undefined` otherwise.
|
||||
*/
|
||||
export function firstOrUndefined<T>(array: T[]): T {
|
||||
return array && array.length > 0
|
||||
? array[0]
|
||||
: undefined;
|
||||
export function firstOrUndefined<T>(array: T[]): T | undefined {
|
||||
return elementAt(array, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last element of an array if non-empty, `undefined` otherwise.
|
||||
*/
|
||||
export function lastOrUndefined<T>(array: T[]): T {
|
||||
return array && array.length > 0
|
||||
? array[array.length - 1]
|
||||
: undefined;
|
||||
export function lastOrUndefined<T>(array: T[]): T | undefined {
|
||||
return elementAt(array, -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the only element of an array if it contains only one element, `undefined` otherwise.
|
||||
*/
|
||||
export function singleOrUndefined<T>(array: T[]): T {
|
||||
export function singleOrUndefined<T>(array: T[]): T | undefined {
|
||||
return array && array.length === 1
|
||||
? array[0]
|
||||
: undefined;
|
||||
@@ -1125,6 +1163,15 @@ namespace ts {
|
||||
return Array.isArray ? Array.isArray(value) : value instanceof Array;
|
||||
}
|
||||
|
||||
export function tryCast<TOut extends TIn, TIn = any>(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut | undefined {
|
||||
return value !== undefined && test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
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)}'.`);
|
||||
}
|
||||
|
||||
/** Does nothing. */
|
||||
export function noop(): void {}
|
||||
|
||||
@@ -2210,8 +2257,11 @@ namespace ts {
|
||||
this.declarations = undefined;
|
||||
}
|
||||
|
||||
function Type(this: Type, _checker: TypeChecker, flags: TypeFlags) {
|
||||
function Type(this: Type, checker: TypeChecker, flags: TypeFlags) {
|
||||
this.flags = flags;
|
||||
if (Debug.isDebugging) {
|
||||
this.checker = checker;
|
||||
}
|
||||
}
|
||||
|
||||
function Signature() {
|
||||
@@ -2248,24 +2298,42 @@ namespace ts {
|
||||
|
||||
export namespace Debug {
|
||||
export let currentAssertionLevel = AssertionLevel.None;
|
||||
export let isDebugging = false;
|
||||
|
||||
export function shouldAssert(level: AssertionLevel): boolean {
|
||||
return currentAssertionLevel >= level;
|
||||
}
|
||||
|
||||
export function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void {
|
||||
export function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string, stackCrawlMark?: Function): void {
|
||||
if (!expression) {
|
||||
let verboseDebugString = "";
|
||||
if (verboseDebugInfo) {
|
||||
verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo();
|
||||
message += "\r\nVerbose Debug Information: " + verboseDebugInfo();
|
||||
}
|
||||
debugger;
|
||||
throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString);
|
||||
fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert);
|
||||
}
|
||||
}
|
||||
|
||||
export function fail(message?: string): void {
|
||||
Debug.assert(/*expression*/ false, message);
|
||||
export function fail(message?: string, stackCrawlMark?: Function): void {
|
||||
debugger;
|
||||
const e = new Error(message ? `Debug Failure. ` : "Debug Failure.");
|
||||
if ((<any>Error).captureStackTrace) {
|
||||
(<any>Error).captureStackTrace(e, stackCrawlMark || fail);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
export function getFunctionName(func: Function) {
|
||||
if (typeof func !== "function") {
|
||||
return "";
|
||||
}
|
||||
else if (func.hasOwnProperty("name")) {
|
||||
return (<any>func).name;
|
||||
}
|
||||
else {
|
||||
const text = Function.prototype.toString.call(func);
|
||||
const match = /^function\s+([\w\$]+)\s*\(/.exec(text);
|
||||
return match ? match[1] : "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2431,4 +2499,4 @@ namespace ts {
|
||||
export function isCheckJsEnabledForFile(sourceFile: SourceFile, compilerOptions: CompilerOptions) {
|
||||
return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3012,7 +3012,7 @@ namespace ts {
|
||||
NoInterveningComments = 1 << 17, // Do not emit comments between each node
|
||||
|
||||
// Precomputed Formats
|
||||
Modifiers = SingleLine | SpaceBetweenSiblings,
|
||||
Modifiers = SingleLine | SpaceBetweenSiblings | NoInterveningComments,
|
||||
HeritageClauses = SingleLine | SpaceBetweenSiblings,
|
||||
SingleLineTypeLiteralMembers = SingleLine | SpaceBetweenBraces | SpaceBetweenSiblings | Indented,
|
||||
MultiLineTypeLiteralMembers = MultiLine | Indented,
|
||||
|
||||
+81
-23
@@ -303,7 +303,7 @@ namespace ts {
|
||||
: node;
|
||||
}
|
||||
|
||||
export function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression) {
|
||||
export function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) {
|
||||
const node = <PropertyDeclaration>createSynthesizedNode(SyntaxKind.PropertyDeclaration);
|
||||
node.decorators = asNodeArray(decorators);
|
||||
node.modifiers = asNodeArray(modifiers);
|
||||
@@ -314,7 +314,7 @@ namespace ts {
|
||||
return node;
|
||||
}
|
||||
|
||||
export function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression) {
|
||||
export function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression | undefined) {
|
||||
return node.decorators !== decorators
|
||||
|| node.modifiers !== modifiers
|
||||
|| node.name !== name
|
||||
@@ -2134,6 +2134,24 @@ namespace ts {
|
||||
|
||||
// Compound nodes
|
||||
|
||||
export function createImmediatelyInvokedFunctionExpression(statements: Statement[]): CallExpression;
|
||||
export function createImmediatelyInvokedFunctionExpression(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression;
|
||||
export function createImmediatelyInvokedFunctionExpression(statements: Statement[], param?: ParameterDeclaration, paramValue?: Expression) {
|
||||
return createCall(
|
||||
createFunctionExpression(
|
||||
/*modifiers*/ undefined,
|
||||
/*asteriskToken*/ undefined,
|
||||
/*name*/ undefined,
|
||||
/*typeParameters*/ undefined,
|
||||
/*parameters*/ param ? [param] : [],
|
||||
/*type*/ undefined,
|
||||
createBlock(statements, /*multiLine*/ true)
|
||||
),
|
||||
/*typeArguments*/ undefined,
|
||||
/*argumentsArray*/ paramValue ? [paramValue] : []
|
||||
);
|
||||
}
|
||||
|
||||
export function createComma(left: Expression, right: Expression) {
|
||||
return <Expression>createBinary(left, SyntaxKind.CommaToken, right);
|
||||
}
|
||||
@@ -3216,6 +3234,26 @@ namespace ts {
|
||||
return isBlock(node) ? node : setTextRange(createBlock([setTextRange(createReturn(node), node)], multiLine), node);
|
||||
}
|
||||
|
||||
export function convertFunctionDeclarationToExpression(node: FunctionDeclaration) {
|
||||
Debug.assert(!!node.body);
|
||||
const updated = createFunctionExpression(
|
||||
node.modifiers,
|
||||
node.asteriskToken,
|
||||
node.name,
|
||||
node.typeParameters,
|
||||
node.parameters,
|
||||
node.type,
|
||||
node.body
|
||||
);
|
||||
setOriginalNode(updated, node);
|
||||
setTextRange(updated, node);
|
||||
if (node.startsOnNewLine) {
|
||||
updated.startsOnNewLine = true;
|
||||
}
|
||||
aggregateTransformFlags(updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
function isUseStrictPrologue(node: ExpressionStatement): boolean {
|
||||
return (node.expression as StringLiteral).text === "use strict";
|
||||
}
|
||||
@@ -3614,7 +3652,7 @@ namespace ts {
|
||||
if (kind === SyntaxKind.FunctionExpression || kind === SyntaxKind.ArrowFunction) {
|
||||
const mutableCall = getMutableClone(emittedExpression);
|
||||
mutableCall.expression = setTextRange(createParen(callee), callee);
|
||||
return recreatePartiallyEmittedExpressions(expression, mutableCall);
|
||||
return recreateOuterExpressions(expression, mutableCall, OuterExpressionKinds.PartiallyEmittedExpressions);
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -3656,22 +3694,6 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clones a series of not-emitted expressions with a new inner expression.
|
||||
*
|
||||
* @param originalOuterExpression The original outer expression.
|
||||
* @param newInnerExpression The new inner expression.
|
||||
*/
|
||||
function recreatePartiallyEmittedExpressions(originalOuterExpression: Expression, newInnerExpression: Expression) {
|
||||
if (isPartiallyEmittedExpression(originalOuterExpression)) {
|
||||
const clone = getMutableClone(originalOuterExpression);
|
||||
clone.expression = recreatePartiallyEmittedExpressions(clone.expression, newInnerExpression);
|
||||
return clone;
|
||||
}
|
||||
|
||||
return newInnerExpression;
|
||||
}
|
||||
|
||||
function getLeftmostExpression(node: Expression): Expression {
|
||||
while (true) {
|
||||
switch (node.kind) {
|
||||
@@ -3718,6 +3740,22 @@ namespace ts {
|
||||
All = Parentheses | Assertions | PartiallyEmittedExpressions
|
||||
}
|
||||
|
||||
export type OuterExpression = ParenthesizedExpression | TypeAssertion | AsExpression | NonNullExpression | PartiallyEmittedExpression;
|
||||
|
||||
export function isOuterExpression(node: Node, kinds = OuterExpressionKinds.All): node is OuterExpression {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.ParenthesizedExpression:
|
||||
return (kinds & OuterExpressionKinds.Parentheses) !== 0;
|
||||
case SyntaxKind.TypeAssertionExpression:
|
||||
case SyntaxKind.AsExpression:
|
||||
case SyntaxKind.NonNullExpression:
|
||||
return (kinds & OuterExpressionKinds.Assertions) !== 0;
|
||||
case SyntaxKind.PartiallyEmittedExpression:
|
||||
return (kinds & OuterExpressionKinds.PartiallyEmittedExpressions) !== 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function skipOuterExpressions(node: Expression, kinds?: OuterExpressionKinds): Expression;
|
||||
export function skipOuterExpressions(node: Node, kinds?: OuterExpressionKinds): Node;
|
||||
export function skipOuterExpressions(node: Node, kinds = OuterExpressionKinds.All) {
|
||||
@@ -3754,8 +3792,8 @@ namespace ts {
|
||||
export function skipAssertions(node: Expression): Expression;
|
||||
export function skipAssertions(node: Node): Node;
|
||||
export function skipAssertions(node: Node): Node {
|
||||
while (isAssertionExpression(node)) {
|
||||
node = (<AssertionExpression>node).expression;
|
||||
while (isAssertionExpression(node) || node.kind === SyntaxKind.NonNullExpression) {
|
||||
node = (<AssertionExpression | NonNullExpression>node).expression;
|
||||
}
|
||||
|
||||
return node;
|
||||
@@ -3771,6 +3809,26 @@ namespace ts {
|
||||
return node;
|
||||
}
|
||||
|
||||
function updateOuterExpression(outerExpression: OuterExpression, expression: Expression) {
|
||||
switch (outerExpression.kind) {
|
||||
case SyntaxKind.ParenthesizedExpression: return updateParen(outerExpression, expression);
|
||||
case SyntaxKind.TypeAssertionExpression: return updateTypeAssertion(outerExpression, outerExpression.type, expression);
|
||||
case SyntaxKind.AsExpression: return updateAsExpression(outerExpression, expression, outerExpression.type);
|
||||
case SyntaxKind.NonNullExpression: return updateNonNullExpression(outerExpression, expression);
|
||||
case SyntaxKind.PartiallyEmittedExpression: return updatePartiallyEmittedExpression(outerExpression, expression);
|
||||
}
|
||||
}
|
||||
|
||||
export function recreateOuterExpressions(outerExpression: Expression | undefined, innerExpression: Expression, kinds = OuterExpressionKinds.All): Expression {
|
||||
if (outerExpression && isOuterExpression(outerExpression, kinds)) {
|
||||
return updateOuterExpression(
|
||||
outerExpression,
|
||||
recreateOuterExpressions(outerExpression.expression, innerExpression)
|
||||
);
|
||||
}
|
||||
return innerExpression;
|
||||
}
|
||||
|
||||
export function startOnNewLine<T extends Node>(node: T): T {
|
||||
node.startsOnNewLine = true;
|
||||
return node;
|
||||
@@ -3908,7 +3966,7 @@ namespace ts {
|
||||
return bindingElement.right;
|
||||
}
|
||||
|
||||
if (isSpreadExpression(bindingElement)) {
|
||||
if (isSpreadElement(bindingElement)) {
|
||||
// Recovery consistent with existing emit.
|
||||
return getInitializerOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.expression);
|
||||
}
|
||||
@@ -3976,7 +4034,7 @@ namespace ts {
|
||||
return getTargetOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.left);
|
||||
}
|
||||
|
||||
if (isSpreadExpression(bindingElement)) {
|
||||
if (isSpreadElement(bindingElement)) {
|
||||
// `a` in `[...a] = ...`
|
||||
return getTargetOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.expression);
|
||||
}
|
||||
|
||||
+27
-29
@@ -6092,7 +6092,10 @@ namespace ts {
|
||||
case SyntaxKind.OpenBraceToken:
|
||||
return parseJSDocRecordType();
|
||||
case SyntaxKind.FunctionKeyword:
|
||||
return parseJSDocFunctionType();
|
||||
if (lookAhead(nextTokenIsOpenParen)) {
|
||||
return parseJSDocFunctionType();
|
||||
}
|
||||
break;
|
||||
case SyntaxKind.DotDotDotToken:
|
||||
return parseJSDocVariadicType();
|
||||
case SyntaxKind.NewKeyword:
|
||||
@@ -6108,7 +6111,6 @@ namespace ts {
|
||||
case SyntaxKind.NullKeyword:
|
||||
case SyntaxKind.UndefinedKeyword:
|
||||
case SyntaxKind.NeverKeyword:
|
||||
case SyntaxKind.ObjectKeyword:
|
||||
return parseTokenNode<JSDocType>();
|
||||
case SyntaxKind.StringLiteral:
|
||||
case SyntaxKind.NumericLiteral:
|
||||
@@ -6337,6 +6339,12 @@ namespace ts {
|
||||
comment.parent = parent;
|
||||
}
|
||||
|
||||
if (isInJavaScriptFile(parent)) {
|
||||
if (!sourceFile.jsDocDiagnostics) {
|
||||
sourceFile.jsDocDiagnostics = [];
|
||||
}
|
||||
sourceFile.jsDocDiagnostics.push(...parseDiagnostics);
|
||||
}
|
||||
currentToken = saveToken;
|
||||
parseDiagnostics.length = saveParseDiagnosticsLength;
|
||||
parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
|
||||
@@ -6525,7 +6533,7 @@ namespace ts {
|
||||
case "arg":
|
||||
case "argument":
|
||||
case "param":
|
||||
tag = parseParamTag(atToken, tagName);
|
||||
tag = parseParameterOrPropertyTag(atToken, tagName, /*shouldParseParamTag*/ true);
|
||||
break;
|
||||
case "return":
|
||||
case "returns":
|
||||
@@ -6648,10 +6656,7 @@ namespace ts {
|
||||
});
|
||||
}
|
||||
|
||||
function parseParamTag(atToken: AtToken, tagName: Identifier) {
|
||||
let typeExpression = tryParseTypeExpression();
|
||||
skipWhitespace();
|
||||
|
||||
function parseBracketNameInPropertyAndParamTag() {
|
||||
let name: Identifier;
|
||||
let isBracketed: boolean;
|
||||
// Looking for something like '[foo]' or 'foo'
|
||||
@@ -6670,6 +6675,15 @@ namespace ts {
|
||||
else if (tokenIsIdentifierOrKeyword(token())) {
|
||||
name = parseJSDocIdentifierName();
|
||||
}
|
||||
return { name, isBracketed };
|
||||
}
|
||||
|
||||
function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, shouldParseParamTag: boolean): JSDocPropertyTag | JSDocParameterTag {
|
||||
let typeExpression = tryParseTypeExpression();
|
||||
skipWhitespace();
|
||||
|
||||
const { name, isBracketed } = parseBracketNameInPropertyAndParamTag();
|
||||
skipWhitespace();
|
||||
|
||||
if (!name) {
|
||||
parseErrorAtPosition(scanner.getStartPos(), 0, Diagnostics.Identifier_expected);
|
||||
@@ -6688,13 +6702,15 @@ namespace ts {
|
||||
typeExpression = tryParseTypeExpression();
|
||||
}
|
||||
|
||||
const result = <JSDocParameterTag>createNode(SyntaxKind.JSDocParameterTag, atToken.pos);
|
||||
const result = shouldParseParamTag ?
|
||||
<JSDocParameterTag>createNode(SyntaxKind.JSDocParameterTag, atToken.pos) :
|
||||
<JSDocPropertyTag>createNode(SyntaxKind.JSDocPropertyTag, atToken.pos);
|
||||
result.atToken = atToken;
|
||||
result.tagName = tagName;
|
||||
result.preParameterName = preName;
|
||||
result.typeExpression = typeExpression;
|
||||
result.postParameterName = postName;
|
||||
result.parameterName = postName || preName;
|
||||
result.name = postName || preName;
|
||||
result.isBracketed = isBracketed;
|
||||
return finishNode(result);
|
||||
}
|
||||
@@ -6723,24 +6739,6 @@ namespace ts {
|
||||
return finishNode(result);
|
||||
}
|
||||
|
||||
function parsePropertyTag(atToken: AtToken, tagName: Identifier): JSDocPropertyTag {
|
||||
const typeExpression = tryParseTypeExpression();
|
||||
skipWhitespace();
|
||||
const name = parseJSDocIdentifierName();
|
||||
skipWhitespace();
|
||||
if (!name) {
|
||||
parseErrorAtPosition(scanner.getStartPos(), /*length*/ 0, Diagnostics.Identifier_expected);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const result = <JSDocPropertyTag>createNode(SyntaxKind.JSDocPropertyTag, atToken.pos);
|
||||
result.atToken = atToken;
|
||||
result.tagName = tagName;
|
||||
result.name = name;
|
||||
result.typeExpression = typeExpression;
|
||||
return finishNode(result);
|
||||
}
|
||||
|
||||
function parseAugmentsTag(atToken: AtToken, tagName: Identifier): JSDocAugmentsTag {
|
||||
const typeExpression = tryParseTypeExpression();
|
||||
|
||||
@@ -6779,7 +6777,7 @@ namespace ts {
|
||||
const jsDocTypeReference = <JSDocTypeReference>typeExpression.type;
|
||||
if (jsDocTypeReference.name.kind === SyntaxKind.Identifier) {
|
||||
const name = <Identifier>jsDocTypeReference.name;
|
||||
if (name.text === "Object") {
|
||||
if (name.text === "Object" || name.text === "object") {
|
||||
typedefTag.jsDocTypeLiteral = scanChildTags();
|
||||
}
|
||||
}
|
||||
@@ -6877,7 +6875,7 @@ namespace ts {
|
||||
return true;
|
||||
case "prop":
|
||||
case "property":
|
||||
const propertyTag = parsePropertyTag(atToken, tagName);
|
||||
const propertyTag = parseParameterOrPropertyTag(atToken, tagName, /*shouldParseParamTag*/ false) as JSDocPropertyTag;
|
||||
if (propertyTag) {
|
||||
if (!parentTag.jsDocPropertyTags) {
|
||||
parentTag.jsDocPropertyTags = <NodeArray<JSDocPropertyTag>>[];
|
||||
|
||||
@@ -1021,6 +1021,9 @@ namespace ts {
|
||||
if (isSourceFileJavaScript(sourceFile)) {
|
||||
if (!sourceFile.additionalSyntacticDiagnostics) {
|
||||
sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile);
|
||||
if (isCheckJsEnabledForFile(sourceFile, options)) {
|
||||
sourceFile.additionalSyntacticDiagnostics = concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics);
|
||||
}
|
||||
}
|
||||
return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
|
||||
}
|
||||
|
||||
+17
-5
@@ -429,6 +429,7 @@ namespace ts {
|
||||
case CharacterCodes.slash:
|
||||
// starts of normal trivia
|
||||
case CharacterCodes.lessThan:
|
||||
case CharacterCodes.bar:
|
||||
case CharacterCodes.equals:
|
||||
case CharacterCodes.greaterThan:
|
||||
// Starts of conflict marker trivia
|
||||
@@ -496,6 +497,7 @@ namespace ts {
|
||||
break;
|
||||
|
||||
case CharacterCodes.lessThan:
|
||||
case CharacterCodes.bar:
|
||||
case CharacterCodes.equals:
|
||||
case CharacterCodes.greaterThan:
|
||||
if (isConflictMarkerTrivia(text, pos)) {
|
||||
@@ -562,12 +564,12 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
else {
|
||||
Debug.assert(ch === CharacterCodes.equals);
|
||||
// Consume everything from the start of the mid-conflict marker to the start of the next
|
||||
// end-conflict marker.
|
||||
Debug.assert(ch === CharacterCodes.bar || ch === CharacterCodes.equals);
|
||||
// Consume everything from the start of a ||||||| or ======= marker to the start
|
||||
// of the next ======= or >>>>>>> marker.
|
||||
while (pos < len) {
|
||||
const ch = text.charCodeAt(pos);
|
||||
if (ch === CharacterCodes.greaterThan && isConflictMarkerTrivia(text, pos)) {
|
||||
const currentChar = text.charCodeAt(pos);
|
||||
if ((currentChar === CharacterCodes.equals || currentChar === CharacterCodes.greaterThan) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1562,6 +1564,16 @@ namespace ts {
|
||||
pos++;
|
||||
return token = SyntaxKind.OpenBraceToken;
|
||||
case CharacterCodes.bar:
|
||||
if (isConflictMarkerTrivia(text, pos)) {
|
||||
pos = scanConflictMarkerTrivia(text, pos, error);
|
||||
if (skipTrivia) {
|
||||
continue;
|
||||
}
|
||||
else {
|
||||
return token = SyntaxKind.ConflictMarkerTrivia;
|
||||
}
|
||||
}
|
||||
|
||||
if (text.charCodeAt(pos + 1) === CharacterCodes.bar) {
|
||||
return pos += 2, token = SyntaxKind.BarBarToken;
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ namespace ts {
|
||||
realpath?(path: string): string;
|
||||
/*@internal*/ getEnvironmentVariable(name: string): string;
|
||||
/*@internal*/ tryEnableSourceMapsForHost?(): void;
|
||||
/*@internal*/ debugMode?: boolean;
|
||||
setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any;
|
||||
clearTimeout?(timeoutId: any): void;
|
||||
}
|
||||
@@ -428,6 +429,7 @@ namespace ts {
|
||||
realpath(path: string): string {
|
||||
return _fs.realpathSync(path);
|
||||
},
|
||||
debugMode: some(<string[]>process.execArgv, arg => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)),
|
||||
tryEnableSourceMapsForHost() {
|
||||
try {
|
||||
require("source-map-support").install();
|
||||
@@ -517,4 +519,7 @@ namespace ts {
|
||||
? AssertionLevel.Normal
|
||||
: AssertionLevel.None;
|
||||
}
|
||||
if (sys && sys.debugMode) {
|
||||
Debug.isDebugging = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,11 +339,64 @@ namespace ts {
|
||||
&& !(<ReturnStatement>node).expression;
|
||||
}
|
||||
|
||||
function isClassLikeVariableStatement(node: Node) {
|
||||
if (!isVariableStatement(node)) return false;
|
||||
const variable = singleOrUndefined((<VariableStatement>node).declarationList.declarations);
|
||||
return variable
|
||||
&& variable.initializer
|
||||
&& isIdentifier(variable.name)
|
||||
&& (isClassLike(variable.initializer)
|
||||
|| (isAssignmentExpression(variable.initializer)
|
||||
&& isIdentifier(variable.initializer.left)
|
||||
&& isClassLike(variable.initializer.right)));
|
||||
}
|
||||
|
||||
function isTypeScriptClassWrapper(node: Node) {
|
||||
const call = tryCast(node, isCallExpression);
|
||||
if (!call || isParseTreeNode(call) ||
|
||||
some(call.typeArguments) ||
|
||||
some(call.arguments)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const func = tryCast(skipOuterExpressions(call.expression), isFunctionExpression);
|
||||
if (!func || isParseTreeNode(func) ||
|
||||
some(func.typeParameters) ||
|
||||
some(func.parameters) ||
|
||||
func.type ||
|
||||
!func.body) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const statements = func.body.statements;
|
||||
if (statements.length < 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const firstStatement = statements[0];
|
||||
if (isParseTreeNode(firstStatement) ||
|
||||
!isClassLike(firstStatement) &&
|
||||
!isClassLikeVariableStatement(firstStatement)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const lastStatement = elementAt(statements, -1);
|
||||
const returnStatement = tryCast(isVariableStatement(lastStatement) ? elementAt(statements, -2) : lastStatement, isReturnStatement);
|
||||
if (!returnStatement ||
|
||||
!returnStatement.expression ||
|
||||
!isIdentifier(skipOuterExpressions(returnStatement.expression))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function shouldVisitNode(node: Node): boolean {
|
||||
return (node.transformFlags & TransformFlags.ContainsES2015) !== 0
|
||||
|| convertedLoopState !== undefined
|
||||
|| (hierarchyFacts & HierarchyFacts.ConstructorWithCapturedSuper && isStatement(node))
|
||||
|| (isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node));
|
||||
|| (isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node))
|
||||
|| isTypeScriptClassWrapper(node);
|
||||
}
|
||||
|
||||
function visitor(node: Node): VisitResult<Node> {
|
||||
@@ -3251,6 +3304,10 @@ namespace ts {
|
||||
* @param node a CallExpression.
|
||||
*/
|
||||
function visitCallExpression(node: CallExpression) {
|
||||
if (isTypeScriptClassWrapper(node)) {
|
||||
return visitTypeScriptClassWrapper(node);
|
||||
}
|
||||
|
||||
if (node.transformFlags & TransformFlags.ES2015) {
|
||||
return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
|
||||
}
|
||||
@@ -3262,6 +3319,163 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
function visitTypeScriptClassWrapper(node: CallExpression) {
|
||||
// This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
|
||||
// The wrapper has a form similar to:
|
||||
//
|
||||
// (function() {
|
||||
// class C { // 1
|
||||
// }
|
||||
// C.x = 1; // 2
|
||||
// return C;
|
||||
// }())
|
||||
//
|
||||
// When we transform the class, we end up with something like this:
|
||||
//
|
||||
// (function () {
|
||||
// var C = (function () { // 3
|
||||
// function C() {
|
||||
// }
|
||||
// return C; // 4
|
||||
// }());
|
||||
// C.x = 1;
|
||||
// return C;
|
||||
// }())
|
||||
//
|
||||
// We want to simplify the two nested IIFEs to end up with something like this:
|
||||
//
|
||||
// (function () {
|
||||
// function C() {
|
||||
// }
|
||||
// C.x = 1;
|
||||
// return C;
|
||||
// }())
|
||||
|
||||
// We skip any outer expressions in a number of places to get to the innermost
|
||||
// expression, but we will restore them later to preserve comments and source maps.
|
||||
const body = cast(skipOuterExpressions(node.expression), isFunctionExpression).body;
|
||||
|
||||
// The class statements are the statements generated by visiting the first statement of the
|
||||
// body (1), while all other statements are added to remainingStatements (2)
|
||||
const classStatements = visitNodes(body.statements, visitor, isStatement, 0, 1);
|
||||
const remainingStatements = visitNodes(body.statements, visitor, isStatement, 1, body.statements.length - 1);
|
||||
const varStatement = cast(firstOrUndefined(classStatements), isVariableStatement);
|
||||
|
||||
// We know there is only one variable declaration here as we verified this in an
|
||||
// earlier call to isTypeScriptClassWrapper
|
||||
const variable = varStatement.declarationList.declarations[0];
|
||||
const initializer = skipOuterExpressions(variable.initializer);
|
||||
|
||||
// Under certain conditions, the 'ts' transformer may introduce a class alias, which
|
||||
// we see as an assignment, for example:
|
||||
//
|
||||
// (function () {
|
||||
// var C = C_1 = (function () {
|
||||
// function C() {
|
||||
// }
|
||||
// C.x = function () { return C_1; }
|
||||
// return C;
|
||||
// }());
|
||||
// C = C_1 = __decorate([dec], C);
|
||||
// return C;
|
||||
// var C_1;
|
||||
// }())
|
||||
//
|
||||
const aliasAssignment = tryCast(initializer, isAssignmentExpression);
|
||||
|
||||
// The underlying call (3) is another IIFE that may contain a '_super' argument.
|
||||
const call = cast(aliasAssignment ? skipOuterExpressions(aliasAssignment.right) : initializer, isCallExpression);
|
||||
const func = cast(skipOuterExpressions(call.expression), isFunctionExpression);
|
||||
|
||||
const funcStatements = func.body.statements;
|
||||
let classBodyStart = 0;
|
||||
let classBodyEnd = -1;
|
||||
|
||||
const statements: Statement[] = [];
|
||||
if (aliasAssignment) {
|
||||
// If we have a class alias assignment, we need to move it to the down-level constructor
|
||||
// function we generated for the class.
|
||||
const extendsCall = tryCast(funcStatements[classBodyStart], isExpressionStatement);
|
||||
if (extendsCall) {
|
||||
statements.push(extendsCall);
|
||||
classBodyStart++;
|
||||
}
|
||||
|
||||
// We reuse the comment and source-map positions from the original variable statement
|
||||
// and class alias, while converting the function declaration for the class constructor
|
||||
// into an expression.
|
||||
statements.push(
|
||||
updateVariableStatement(
|
||||
varStatement,
|
||||
/*modifiers*/ undefined,
|
||||
updateVariableDeclarationList(varStatement.declarationList, [
|
||||
updateVariableDeclaration(variable,
|
||||
variable.name,
|
||||
/*type*/ undefined,
|
||||
updateBinary(aliasAssignment,
|
||||
aliasAssignment.left,
|
||||
convertFunctionDeclarationToExpression(
|
||||
cast(funcStatements[classBodyStart], isFunctionDeclaration)
|
||||
)
|
||||
)
|
||||
)
|
||||
])
|
||||
)
|
||||
);
|
||||
classBodyStart++;
|
||||
}
|
||||
|
||||
// Find the trailing 'return' statement (4)
|
||||
while (!isReturnStatement(elementAt(funcStatements, classBodyEnd))) {
|
||||
classBodyEnd--;
|
||||
}
|
||||
|
||||
// When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
|
||||
// as we already have one that has been introduced by the 'ts' transformer.
|
||||
addRange(statements, funcStatements, classBodyStart, classBodyEnd);
|
||||
|
||||
if (classBodyEnd < -1) {
|
||||
// If there were any hoisted declarations following the return statement, we should
|
||||
// append them.
|
||||
addRange(statements, funcStatements, classBodyEnd + 1);
|
||||
}
|
||||
|
||||
// Add the remaining statements of the outer wrapper.
|
||||
addRange(statements, remainingStatements);
|
||||
|
||||
// The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
|
||||
// after the remaining statements from the 'ts' transformer.
|
||||
addRange(statements, classStatements, /*start*/ 1);
|
||||
|
||||
// Recreate any outer parentheses or partially-emitted expressions to preserve source map
|
||||
// and comment locations.
|
||||
return recreateOuterExpressions(node.expression,
|
||||
recreateOuterExpressions(variable.initializer,
|
||||
recreateOuterExpressions(aliasAssignment && aliasAssignment.right,
|
||||
updateCall(call,
|
||||
recreateOuterExpressions(call.expression,
|
||||
updateFunctionExpression(
|
||||
func,
|
||||
/*modifiers*/ undefined,
|
||||
/*asteriskToken*/ undefined,
|
||||
/*name*/ undefined,
|
||||
/*typeParameters*/ undefined,
|
||||
func.parameters,
|
||||
/*type*/ undefined,
|
||||
updateBlock(
|
||||
func.body,
|
||||
statements
|
||||
)
|
||||
)
|
||||
),
|
||||
/*typeArguments*/ undefined,
|
||||
call.arguments
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function visitImmediateSuperCallInBody(node: CallExpression) {
|
||||
return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
|
||||
}
|
||||
@@ -3396,7 +3610,7 @@ namespace ts {
|
||||
else {
|
||||
if (segments.length === 1) {
|
||||
const firstElement = elements[0];
|
||||
return needsUniqueCopy && isSpreadExpression(firstElement) && firstElement.expression.kind !== SyntaxKind.ArrayLiteralExpression
|
||||
return needsUniqueCopy && isSpreadElement(firstElement) && firstElement.expression.kind !== SyntaxKind.ArrayLiteralExpression
|
||||
? createArraySlice(segments[0])
|
||||
: segments[0];
|
||||
}
|
||||
@@ -3407,7 +3621,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function partitionSpread(node: Expression) {
|
||||
return isSpreadExpression(node)
|
||||
return isSpreadElement(node)
|
||||
? visitSpanOfSpreads
|
||||
: visitSpanOfNonSpreads;
|
||||
}
|
||||
@@ -3806,9 +4020,7 @@ namespace ts {
|
||||
return false;
|
||||
}
|
||||
if (isClassElement(currentNode) && currentNode.parent === declaration) {
|
||||
// we are in the class body, but we treat static fields as outside of the class body
|
||||
return currentNode.kind !== SyntaxKind.PropertyDeclaration
|
||||
|| (getModifierFlags(currentNode) & ModifierFlags.Static) === 0;
|
||||
return true;
|
||||
}
|
||||
currentNode = currentNode.parent;
|
||||
}
|
||||
|
||||
@@ -1526,7 +1526,7 @@ namespace ts {
|
||||
if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
|
||||
return hasExportedReferenceInDestructuringTarget(node.left);
|
||||
}
|
||||
else if (isSpreadExpression(node)) {
|
||||
else if (isSpreadElement(node)) {
|
||||
return hasExportedReferenceInDestructuringTarget(node.expression);
|
||||
}
|
||||
else if (isObjectLiteralExpression(node)) {
|
||||
|
||||
+108
-38
@@ -18,6 +18,23 @@ namespace ts {
|
||||
NonQualifiedEnumMembers = 1 << 3
|
||||
}
|
||||
|
||||
const enum ClassFacts {
|
||||
None = 0,
|
||||
HasStaticInitializedProperties = 1 << 0,
|
||||
HasConstructorDecorators = 1 << 1,
|
||||
HasMemberDecorators = 1 << 2,
|
||||
IsExportOfNamespace = 1 << 3,
|
||||
IsNamedExternalExport = 1 << 4,
|
||||
IsDefaultExternalExport = 1 << 5,
|
||||
HasExtendsClause = 1 << 6,
|
||||
UseImmediatelyInvokedFunctionExpression = 1 << 7,
|
||||
|
||||
HasAnyDecorators = HasConstructorDecorators | HasMemberDecorators,
|
||||
NeedsName = HasStaticInitializedProperties | HasMemberDecorators,
|
||||
MayNeedImmediatelyInvokedFunctionExpression = HasAnyDecorators | HasStaticInitializedProperties,
|
||||
IsExported = IsExportOfNamespace | IsDefaultExternalExport | IsNamedExternalExport,
|
||||
}
|
||||
|
||||
export function transformTypeScript(context: TransformationContext) {
|
||||
const {
|
||||
startLexicalEnvironment,
|
||||
@@ -505,6 +522,19 @@ namespace ts {
|
||||
return parameter.decorators !== undefined && parameter.decorators.length > 0;
|
||||
}
|
||||
|
||||
function getClassFacts(node: ClassDeclaration, staticProperties: PropertyDeclaration[]) {
|
||||
let facts = ClassFacts.None;
|
||||
if (some(staticProperties)) facts |= ClassFacts.HasStaticInitializedProperties;
|
||||
if (getClassExtendsHeritageClauseElement(node)) facts |= ClassFacts.HasExtendsClause;
|
||||
if (shouldEmitDecorateCallForClass(node)) facts |= ClassFacts.HasConstructorDecorators;
|
||||
if (childIsDecorated(node)) facts |= ClassFacts.HasMemberDecorators;
|
||||
if (isExportOfNamespace(node)) facts |= ClassFacts.IsExportOfNamespace;
|
||||
else if (isDefaultExternalModuleExport(node)) facts |= ClassFacts.IsDefaultExternalExport;
|
||||
else if (isNamedExternalModuleExport(node)) facts |= ClassFacts.IsNamedExternalExport;
|
||||
if (languageVersion <= ScriptTarget.ES5 && (facts & ClassFacts.MayNeedImmediatelyInvokedFunctionExpression)) facts |= ClassFacts.UseImmediatelyInvokedFunctionExpression;
|
||||
return facts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a class declaration with TypeScript syntax into compatible ES6.
|
||||
*
|
||||
@@ -518,32 +548,26 @@ namespace ts {
|
||||
*/
|
||||
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
|
||||
const staticProperties = getInitializedProperties(node, /*isStatic*/ true);
|
||||
const hasExtendsClause = getClassExtendsHeritageClauseElement(node) !== undefined;
|
||||
const isDecoratedClass = shouldEmitDecorateCallForClass(node);
|
||||
const facts = getClassFacts(node, staticProperties);
|
||||
|
||||
// emit name if
|
||||
// - node has a name
|
||||
// - node has static initializers
|
||||
// - node has a member that is decorated
|
||||
//
|
||||
let name = node.name;
|
||||
if (!name && (staticProperties.length > 0 || childIsDecorated(node))) {
|
||||
name = getGeneratedNameForNode(node);
|
||||
if (facts & ClassFacts.UseImmediatelyInvokedFunctionExpression) {
|
||||
context.startLexicalEnvironment();
|
||||
}
|
||||
|
||||
const classStatement = isDecoratedClass
|
||||
? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause)
|
||||
: createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0);
|
||||
const name = node.name || (facts & ClassFacts.NeedsName ? getGeneratedNameForNode(node) : undefined);
|
||||
const classStatement = facts & ClassFacts.HasConstructorDecorators
|
||||
? createClassDeclarationHeadWithDecorators(node, name, facts)
|
||||
: createClassDeclarationHeadWithoutDecorators(node, name, facts);
|
||||
|
||||
const statements: Statement[] = [classStatement];
|
||||
let statements: Statement[] = [classStatement];
|
||||
|
||||
// Emit static property assignment. Because classDeclaration is lexically evaluated,
|
||||
// it is safe to emit static property assignment after classDeclaration
|
||||
// From ES6 specification:
|
||||
// HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
|
||||
// a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
|
||||
if (staticProperties.length) {
|
||||
addInitializedPropertyStatements(statements, staticProperties, getLocalName(node));
|
||||
if (facts & ClassFacts.HasStaticInitializedProperties) {
|
||||
addInitializedPropertyStatements(statements, staticProperties, facts & ClassFacts.UseImmediatelyInvokedFunctionExpression ? getInternalName(node) : getLocalName(node));
|
||||
}
|
||||
|
||||
// Write any decorators of the node.
|
||||
@@ -551,17 +575,63 @@ namespace ts {
|
||||
addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
|
||||
addConstructorDecorationStatement(statements, node);
|
||||
|
||||
if (facts & ClassFacts.UseImmediatelyInvokedFunctionExpression) {
|
||||
// When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
|
||||
// 'es2015' transformer can properly nest static initializers and decorators. The result
|
||||
// looks something like:
|
||||
//
|
||||
// var C = function () {
|
||||
// class C {
|
||||
// }
|
||||
// C.static_prop = 1;
|
||||
// return C;
|
||||
// }();
|
||||
//
|
||||
const closingBraceLocation = createTokenRange(skipTrivia(currentSourceFile.text, node.members.end), SyntaxKind.CloseBraceToken);
|
||||
const localName = getInternalName(node);
|
||||
|
||||
// The following partially-emitted expression exists purely to align our sourcemap
|
||||
// emit with the original emitter.
|
||||
const outer = createPartiallyEmittedExpression(localName);
|
||||
outer.end = closingBraceLocation.end;
|
||||
setEmitFlags(outer, EmitFlags.NoComments);
|
||||
|
||||
const statement = createReturn(outer);
|
||||
statement.pos = closingBraceLocation.pos;
|
||||
setEmitFlags(statement, EmitFlags.NoComments | EmitFlags.NoTokenSourceMaps);
|
||||
statements.push(statement);
|
||||
|
||||
addRange(statements, context.endLexicalEnvironment());
|
||||
|
||||
const varStatement = createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(
|
||||
getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false),
|
||||
/*type*/ undefined,
|
||||
createImmediatelyInvokedFunctionExpression(statements)
|
||||
)
|
||||
])
|
||||
);
|
||||
|
||||
setOriginalNode(varStatement, node);
|
||||
setCommentRange(varStatement, node);
|
||||
setSourceMapRange(varStatement, moveRangePastDecorators(node));
|
||||
startOnNewLine(varStatement);
|
||||
statements = [varStatement];
|
||||
}
|
||||
|
||||
// If the class is exported as part of a TypeScript namespace, emit the namespace export.
|
||||
// Otherwise, if the class was exported at the top level and was decorated, emit an export
|
||||
// declaration or export default for the class.
|
||||
if (isNamespaceExport(node)) {
|
||||
if (facts & ClassFacts.IsExportOfNamespace) {
|
||||
addExportMemberAssignment(statements, node);
|
||||
}
|
||||
else if (isDecoratedClass) {
|
||||
if (isDefaultExternalModuleExport(node)) {
|
||||
else if (facts & ClassFacts.UseImmediatelyInvokedFunctionExpression || facts & ClassFacts.HasConstructorDecorators) {
|
||||
if (facts & ClassFacts.IsDefaultExternalExport) {
|
||||
statements.push(createExportDefault(getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
|
||||
}
|
||||
else if (isNamedExternalModuleExport(node)) {
|
||||
else if (facts & ClassFacts.IsNamedExternalExport) {
|
||||
statements.push(createExternalModuleExport(getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
|
||||
}
|
||||
}
|
||||
@@ -580,26 +650,31 @@ namespace ts {
|
||||
*
|
||||
* @param node A ClassDeclaration node.
|
||||
* @param name The name of the class.
|
||||
* @param hasExtendsClause A value indicating whether the class has an extends clause.
|
||||
* @param hasStaticProperties A value indicating whether the class has static properties.
|
||||
* @param facts Precomputed facts about the class.
|
||||
*/
|
||||
function createClassDeclarationHeadWithoutDecorators(node: ClassDeclaration, name: Identifier, hasExtendsClause: boolean, hasStaticProperties: boolean) {
|
||||
function createClassDeclarationHeadWithoutDecorators(node: ClassDeclaration, name: Identifier, facts: ClassFacts) {
|
||||
// ${modifiers} class ${name} ${heritageClauses} {
|
||||
// ${members}
|
||||
// }
|
||||
|
||||
// we do not emit modifiers on the declaration if we are emitting an IIFE
|
||||
const modifiers = !(facts & ClassFacts.UseImmediatelyInvokedFunctionExpression)
|
||||
? visitNodes(node.modifiers, modifierVisitor, isModifier)
|
||||
: undefined;
|
||||
|
||||
const classDeclaration = createClassDeclaration(
|
||||
/*decorators*/ undefined,
|
||||
visitNodes(node.modifiers, modifierVisitor, isModifier),
|
||||
modifiers,
|
||||
name,
|
||||
/*typeParameters*/ undefined,
|
||||
visitNodes(node.heritageClauses, visitor, isHeritageClause),
|
||||
transformClassMembers(node, hasExtendsClause)
|
||||
transformClassMembers(node, (facts & ClassFacts.HasExtendsClause) !== 0)
|
||||
);
|
||||
|
||||
// To better align with the old emitter, we should not emit a trailing source map
|
||||
// entry if the class has static properties.
|
||||
let emitFlags = getEmitFlags(node);
|
||||
if (hasStaticProperties) {
|
||||
if (facts & ClassFacts.HasStaticInitializedProperties) {
|
||||
emitFlags |= EmitFlags.NoTrailingSourceMap;
|
||||
}
|
||||
|
||||
@@ -612,13 +687,8 @@ namespace ts {
|
||||
/**
|
||||
* Transforms a decorated class declaration and appends the resulting statements. If
|
||||
* the class requires an alias to avoid issues with double-binding, the alias is returned.
|
||||
*
|
||||
* @param statements A statement list to which to add the declaration.
|
||||
* @param node A ClassDeclaration node.
|
||||
* @param name The name of the class.
|
||||
* @param hasExtendsClause A value indicating whether the class has an extends clause.
|
||||
*/
|
||||
function createClassDeclarationHeadWithDecorators(node: ClassDeclaration, name: Identifier, hasExtendsClause: boolean) {
|
||||
function createClassDeclarationHeadWithDecorators(node: ClassDeclaration, name: Identifier, facts: ClassFacts) {
|
||||
// When we emit an ES6 class that has a class decorator, we must tailor the
|
||||
// emit to certain specific cases.
|
||||
//
|
||||
@@ -713,7 +783,7 @@ namespace ts {
|
||||
// ${members}
|
||||
// }
|
||||
const heritageClauses = visitNodes(node.heritageClauses, visitor, isHeritageClause);
|
||||
const members = transformClassMembers(node, hasExtendsClause);
|
||||
const members = transformClassMembers(node, (facts & ClassFacts.HasExtendsClause) !== 0);
|
||||
const classExpression = createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
|
||||
setOriginalNode(classExpression, node);
|
||||
setTextRange(classExpression, location);
|
||||
@@ -2163,7 +2233,7 @@ namespace ts {
|
||||
/*type*/ undefined,
|
||||
visitFunctionBody(node.body, visitor, context) || createBlock([])
|
||||
);
|
||||
if (isNamespaceExport(node)) {
|
||||
if (isExportOfNamespace(node)) {
|
||||
const statements: Statement[] = [updated];
|
||||
addExportMemberAssignment(statements, node);
|
||||
return statements;
|
||||
@@ -2256,7 +2326,7 @@ namespace ts {
|
||||
* - The node is exported from a TypeScript namespace.
|
||||
*/
|
||||
function visitVariableStatement(node: VariableStatement): Statement {
|
||||
if (isNamespaceExport(node)) {
|
||||
if (isExportOfNamespace(node)) {
|
||||
const variables = getInitializedVariables(node.declarationList);
|
||||
if (variables.length === 0) {
|
||||
// elide statement if there are no initialized variables.
|
||||
@@ -2560,7 +2630,7 @@ namespace ts {
|
||||
* or `exports.x`).
|
||||
*/
|
||||
function hasNamespaceQualifiedExportName(node: Node) {
|
||||
return isNamespaceExport(node)
|
||||
return isExportOfNamespace(node)
|
||||
|| (isExternalModuleExport(node)
|
||||
&& moduleKind !== ModuleKind.ES2015
|
||||
&& moduleKind !== ModuleKind.System);
|
||||
@@ -3002,7 +3072,7 @@ namespace ts {
|
||||
const moduleReference = createExpressionFromEntityName(<EntityName>node.moduleReference);
|
||||
setEmitFlags(moduleReference, EmitFlags.NoComments | EmitFlags.NoNestedComments);
|
||||
|
||||
if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) {
|
||||
if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
|
||||
// export var ${name} = ${moduleReference};
|
||||
// var ${name} = ${moduleReference};
|
||||
return setOriginalNode(
|
||||
@@ -3043,7 +3113,7 @@ namespace ts {
|
||||
*
|
||||
* @param node The node to test.
|
||||
*/
|
||||
function isNamespaceExport(node: Node) {
|
||||
function isExportOfNamespace(node: Node) {
|
||||
return currentNamespace !== undefined && hasModifier(node, ModifierFlags.Export);
|
||||
}
|
||||
|
||||
|
||||
+64
-46
@@ -2117,6 +2117,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export interface JSDocTag extends Node {
|
||||
parent: JSDoc;
|
||||
atToken: AtToken;
|
||||
tagName: Identifier;
|
||||
comment: string | undefined;
|
||||
@@ -2147,6 +2148,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export interface JSDocTypedefTag extends JSDocTag, NamedDeclaration {
|
||||
parent: JSDoc;
|
||||
kind: SyntaxKind.JSDocTypedefTag;
|
||||
fullName?: JSDocNamespaceDeclaration | Identifier;
|
||||
name?: Identifier;
|
||||
@@ -2155,9 +2157,15 @@ namespace ts {
|
||||
}
|
||||
|
||||
export interface JSDocPropertyTag extends JSDocTag, TypeElement {
|
||||
parent: JSDoc;
|
||||
kind: SyntaxKind.JSDocPropertyTag;
|
||||
name: Identifier;
|
||||
/** the parameter name, if provided *before* the type (TypeScript-style) */
|
||||
preParameterName?: Identifier;
|
||||
/** the parameter name, if provided *after* the type (JSDoc-standard) */
|
||||
postParameterName?: Identifier;
|
||||
typeExpression: JSDocTypeExpression;
|
||||
isBracketed: boolean;
|
||||
}
|
||||
|
||||
export interface JSDocTypeLiteral extends JSDocType {
|
||||
@@ -2174,7 +2182,7 @@ namespace ts {
|
||||
/** the parameter name, if provided *after* the type (JSDoc-standard) */
|
||||
postParameterName?: Identifier;
|
||||
/** the parameter name, regardless of the location it was provided */
|
||||
parameterName: Identifier;
|
||||
name: Identifier;
|
||||
isBracketed: boolean;
|
||||
}
|
||||
|
||||
@@ -2323,16 +2331,19 @@ namespace ts {
|
||||
/* @internal */ identifierCount: number;
|
||||
/* @internal */ symbolCount: number;
|
||||
|
||||
// File level diagnostics reported by the parser (includes diagnostics about /// references
|
||||
// File-level diagnostics reported by the parser (includes diagnostics about /// references
|
||||
// as well as code diagnostics).
|
||||
/* @internal */ parseDiagnostics: Diagnostic[];
|
||||
|
||||
// Stores additional file level diagnostics reported by the program
|
||||
/* @internal */ additionalSyntacticDiagnostics?: Diagnostic[];
|
||||
|
||||
// File level diagnostics reported by the binder.
|
||||
// File-level diagnostics reported by the binder.
|
||||
/* @internal */ bindDiagnostics: Diagnostic[];
|
||||
|
||||
// File-level JSDoc diagnostics reported by the JSDoc parser
|
||||
/* @internal */ jsDocDiagnostics?: Diagnostic[];
|
||||
|
||||
// Stores additional file-level diagnostics reported by the program
|
||||
/* @internal */ additionalSyntacticDiagnostics?: Diagnostic[];
|
||||
|
||||
// Stores a line map for the file.
|
||||
// This field should never be used directly to obtain line map, use getLineMap function instead.
|
||||
/* @internal */ lineMap: number[];
|
||||
@@ -3094,6 +3105,7 @@ namespace ts {
|
||||
export interface Type {
|
||||
flags: TypeFlags; // Flags
|
||||
/* @internal */ id: number; // Unique ID
|
||||
/* @internal */ checker: TypeChecker;
|
||||
symbol?: Symbol; // Symbol associated with type (if any)
|
||||
pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any)
|
||||
aliasSymbol?: Symbol; // Alias associated with type
|
||||
@@ -3354,30 +3366,36 @@ namespace ts {
|
||||
(t: TypeParameter): Type;
|
||||
mappedTypes?: Type[]; // Types mapped by this mapper
|
||||
instantiations?: Type[]; // Cache of instantiations created using this type mapper.
|
||||
context?: InferenceContext; // The inference context this mapper was created from.
|
||||
// Only inference mappers have this set (in createInferenceMapper).
|
||||
// The identity mapper and regular instantiation mappers do not need it.
|
||||
}
|
||||
|
||||
export const enum InferencePriority {
|
||||
NakedTypeVariable = 1 << 0, // Naked type variable in union or intersection type
|
||||
MappedType = 1 << 1, // Reverse inference for mapped type
|
||||
ReturnType = 1 << 2, // Inference made from return type of generic function
|
||||
}
|
||||
|
||||
export interface InferenceInfo {
|
||||
typeParameter: TypeParameter;
|
||||
candidates: Type[];
|
||||
inferredType: Type;
|
||||
priority: InferencePriority;
|
||||
topLevel: boolean;
|
||||
isFixed: boolean;
|
||||
}
|
||||
|
||||
export const enum InferenceFlags {
|
||||
InferUnionTypes = 1 << 0, // Infer union types for disjoint candidates (otherwise unknownType)
|
||||
NoDefault = 1 << 1, // Infer unknownType for no inferences (otherwise anyType or emptyObjectType)
|
||||
AnyDefault = 1 << 2, // Infer anyType for no inferences (otherwise emptyObjectType)
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface TypeInferences {
|
||||
primary: Type[]; // Inferences made directly to a type parameter
|
||||
secondary: Type[]; // Inferences made to a type parameter in a union type
|
||||
topLevel: boolean; // True if all inferences were made from top-level (not nested in object type) locations
|
||||
isFixed: boolean; // Whether the type parameter is fixed, as defined in section 4.12.2 of the TypeScript spec
|
||||
// If a type parameter is fixed, no more inferences can be made for the type parameter
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface InferenceContext {
|
||||
export interface InferenceContext extends TypeMapper {
|
||||
signature: Signature; // Generic signature for which inferences are made
|
||||
inferUnionTypes: boolean; // Infer union types for disjoint candidates (otherwise undefinedType)
|
||||
inferences: TypeInferences[]; // Inferences made for each type parameter
|
||||
inferredTypes: Type[]; // Inferred type for each type parameter
|
||||
mapper?: TypeMapper; // Type mapper for this inference context
|
||||
inferences: InferenceInfo[]; // Inferences made for each type parameter
|
||||
flags: InferenceFlags; // Inference flags
|
||||
failedTypeParameterIndex?: number; // Index of type parameter for which inference failed
|
||||
// It is optional because in contextual signature instantiation, nothing fails
|
||||
useAnyForNoInferences?: boolean; // Use any instead of {} for no inferences
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -4003,34 +4021,34 @@ namespace ts {
|
||||
}
|
||||
|
||||
export const enum EmitFlags {
|
||||
SingleLine = 1 << 0, // The contents of this node should be emitted on a single line.
|
||||
AdviseOnEmitNode = 1 << 1, // The printer should invoke the onEmitNode callback when printing this node.
|
||||
NoSubstitution = 1 << 2, // Disables further substitution of an expression.
|
||||
CapturesThis = 1 << 3, // The function captures a lexical `this`
|
||||
NoLeadingSourceMap = 1 << 4, // Do not emit a leading source map location for this node.
|
||||
NoTrailingSourceMap = 1 << 5, // Do not emit a trailing source map location for this node.
|
||||
SingleLine = 1 << 0, // The contents of this node should be emitted on a single line.
|
||||
AdviseOnEmitNode = 1 << 1, // The printer should invoke the onEmitNode callback when printing this node.
|
||||
NoSubstitution = 1 << 2, // Disables further substitution of an expression.
|
||||
CapturesThis = 1 << 3, // The function captures a lexical `this`
|
||||
NoLeadingSourceMap = 1 << 4, // Do not emit a leading source map location for this node.
|
||||
NoTrailingSourceMap = 1 << 5, // Do not emit a trailing source map location for this node.
|
||||
NoSourceMap = NoLeadingSourceMap | NoTrailingSourceMap, // Do not emit a source map location for this node.
|
||||
NoNestedSourceMaps = 1 << 6, // Do not emit source map locations for children of this node.
|
||||
NoTokenLeadingSourceMaps = 1 << 7, // Do not emit leading source map location for token nodes.
|
||||
NoTokenTrailingSourceMaps = 1 << 8, // Do not emit trailing source map location for token nodes.
|
||||
NoNestedSourceMaps = 1 << 6, // Do not emit source map locations for children of this node.
|
||||
NoTokenLeadingSourceMaps = 1 << 7, // Do not emit leading source map location for token nodes.
|
||||
NoTokenTrailingSourceMaps = 1 << 8, // Do not emit trailing source map location for token nodes.
|
||||
NoTokenSourceMaps = NoTokenLeadingSourceMaps | NoTokenTrailingSourceMaps, // Do not emit source map locations for tokens of this node.
|
||||
NoLeadingComments = 1 << 9, // Do not emit leading comments for this node.
|
||||
NoTrailingComments = 1 << 10, // Do not emit trailing comments for this node.
|
||||
NoLeadingComments = 1 << 9, // Do not emit leading comments for this node.
|
||||
NoTrailingComments = 1 << 10, // Do not emit trailing comments for this node.
|
||||
NoComments = NoLeadingComments | NoTrailingComments, // Do not emit comments for this node.
|
||||
NoNestedComments = 1 << 11,
|
||||
HelperName = 1 << 12,
|
||||
ExportName = 1 << 13, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal).
|
||||
LocalName = 1 << 14, // Ensure an export prefix is not added for an identifier that points to an exported declaration.
|
||||
InternalName = 1 << 15, // The name is internal to an ES5 class body function.
|
||||
Indented = 1 << 16, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter).
|
||||
NoIndentation = 1 << 17, // Do not indent the node.
|
||||
ExportName = 1 << 13, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal).
|
||||
LocalName = 1 << 14, // Ensure an export prefix is not added for an identifier that points to an exported declaration.
|
||||
InternalName = 1 << 15, // The name is internal to an ES5 class body function.
|
||||
Indented = 1 << 16, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter).
|
||||
NoIndentation = 1 << 17, // Do not indent the node.
|
||||
AsyncFunctionBody = 1 << 18,
|
||||
ReuseTempVariableScope = 1 << 19, // Reuse the existing temp variable scope during emit.
|
||||
CustomPrologue = 1 << 20, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed).
|
||||
NoHoisting = 1 << 21, // Do not hoist this declaration in --module system
|
||||
HasEndOfDeclarationMarker = 1 << 22, // Declaration has an associated NotEmittedStatement to mark the end of the declaration
|
||||
Iterator = 1 << 23, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable.
|
||||
NoAsciiEscaping = 1 << 24, // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions.
|
||||
ReuseTempVariableScope = 1 << 19, // Reuse the existing temp variable scope during emit.
|
||||
CustomPrologue = 1 << 20, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed).
|
||||
NoHoisting = 1 << 21, // Do not hoist this declaration in --module system
|
||||
HasEndOfDeclarationMarker = 1 << 22, // Declaration has an associated NotEmittedStatement to mark the end of the declaration
|
||||
Iterator = 1 << 23, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable.
|
||||
NoAsciiEscaping = 1 << 24, // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions.
|
||||
}
|
||||
|
||||
export interface EmitHelper {
|
||||
|
||||
+1400
-827
File diff suppressed because it is too large
Load Diff
+58
-35
@@ -1517,57 +1517,80 @@ namespace ts {
|
||||
}
|
||||
|
||||
export namespace Debug {
|
||||
if (isDebugging) {
|
||||
// Add additional properties in debug mode to assist with debugging.
|
||||
Object.defineProperties(objectAllocator.getSymbolConstructor().prototype, {
|
||||
"__debugFlags": { get(this: Symbol) { return formatSymbolFlags(this.flags); } }
|
||||
});
|
||||
|
||||
Object.defineProperties(objectAllocator.getTypeConstructor().prototype, {
|
||||
"__debugFlags": { get(this: Type) { return formatTypeFlags(this.flags); } },
|
||||
"__debugObjectFlags": { get(this: Type) { return this.flags & TypeFlags.Object ? formatObjectFlags((<ObjectType>this).objectFlags) : ""; } },
|
||||
"__debugTypeToString": { value(this: Type) { return this.checker.typeToString(this); } },
|
||||
});
|
||||
|
||||
for (const ctor of [objectAllocator.getNodeConstructor(), objectAllocator.getIdentifierConstructor(), objectAllocator.getTokenConstructor(), objectAllocator.getSourceFileConstructor()]) {
|
||||
if (!ctor.prototype.hasOwnProperty("__debugKind")) {
|
||||
Object.defineProperties(ctor.prototype, {
|
||||
"__debugKind": { get(this: Node) { return formatSyntaxKind(this.kind); } },
|
||||
"__debugModifierFlags": { get(this: Node) { return formatModifierFlags(getModifierFlagsNoCache(this)); } },
|
||||
"__debugTransformFlags": { get(this: Node) { return formatTransformFlags(this.transformFlags); } },
|
||||
"__debugEmitFlags": { get(this: Node) { return formatEmitFlags(getEmitFlags(this)); } },
|
||||
"__debugGetText": { value(this: Node, includeTrivia?: boolean) {
|
||||
if (nodeIsSynthesized(this)) return "";
|
||||
const parseNode = getParseTreeNode(this);
|
||||
const sourceFile = parseNode && getSourceFileOfNode(parseNode);
|
||||
return sourceFile ? getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
|
||||
} }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const failBadSyntaxKind = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, message?: string) => assert(false, message || "Unexpected node.", () => `Node ${formatSyntaxKind(node.kind)} was unexpected.`)
|
||||
? (node: Node, message?: string): void => fail(
|
||||
`${message || "Unexpected node."}\r\nNode ${formatSyntaxKind(node.kind)} was unexpected.`,
|
||||
failBadSyntaxKind)
|
||||
: noop;
|
||||
|
||||
export const assertEachNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (nodes: Node[], test: (node: Node) => boolean, message?: string) => assert(
|
||||
test === undefined || every(nodes, test),
|
||||
message || "Unexpected node.",
|
||||
() => `Node array did not pass test '${getFunctionName(test)}'.`)
|
||||
? (nodes: Node[], test: (node: Node) => boolean, message?: string): void => assert(
|
||||
test === undefined || every(nodes, test),
|
||||
message || "Unexpected node.",
|
||||
() => `Node array did not pass test '${getFunctionName(test)}'.`,
|
||||
assertEachNode)
|
||||
: noop;
|
||||
|
||||
export const assertNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, test: (node: Node) => boolean, message?: string) => assert(
|
||||
test === undefined || test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`)
|
||||
? (node: Node, test: (node: Node) => boolean, message?: string): void => assert(
|
||||
test === undefined || test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`,
|
||||
assertNode)
|
||||
: noop;
|
||||
|
||||
export const assertOptionalNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, test: (node: Node) => boolean, message?: string) => assert(
|
||||
test === undefined || node === undefined || test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`)
|
||||
? (node: Node, test: (node: Node) => boolean, message?: string): void => assert(
|
||||
test === undefined || node === undefined || test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`,
|
||||
assertOptionalNode)
|
||||
: noop;
|
||||
|
||||
export const assertOptionalToken = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, kind: SyntaxKind, message?: string) => assert(
|
||||
kind === undefined || node === undefined || node.kind === kind,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} was not a '${formatSyntaxKind(kind)}' token.`)
|
||||
? (node: Node, kind: SyntaxKind, message?: string): void => assert(
|
||||
kind === undefined || node === undefined || node.kind === kind,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} was not a '${formatSyntaxKind(kind)}' token.`,
|
||||
assertOptionalToken)
|
||||
: noop;
|
||||
|
||||
export const assertMissingNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, message?: string) => assert(
|
||||
node === undefined,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`)
|
||||
? (node: Node, message?: string): void => assert(
|
||||
node === undefined,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`,
|
||||
assertMissingNode)
|
||||
: noop;
|
||||
|
||||
function getFunctionName(func: Function) {
|
||||
if (typeof func !== "function") {
|
||||
return "";
|
||||
}
|
||||
else if (func.hasOwnProperty("name")) {
|
||||
return (<any>func).name;
|
||||
}
|
||||
else {
|
||||
const text = Function.prototype.toString.call(func);
|
||||
const match = /^function\s+([\w\$]+)\s*\(/.exec(text);
|
||||
return match ? match[1] : "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
declare const require: any, process: any;
|
||||
const fs: any = require("fs");
|
||||
const path: any = require("path");
|
||||
|
||||
|
||||
@@ -127,6 +127,7 @@
|
||||
"./unittests/printer.ts",
|
||||
"./unittests/transform.ts",
|
||||
"./unittests/customTransforms.ts",
|
||||
"./unittests/textChanges.ts"
|
||||
"./unittests/textChanges.ts",
|
||||
"./unittests/telemetry.ts"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -14,7 +14,9 @@ namespace ts {
|
||||
|
||||
describe("printFile", () => {
|
||||
const printsCorrectly = makePrintsCorrectly("printsFileCorrectly");
|
||||
const sourceFile = createSourceFile("source.ts", `
|
||||
// Avoid eagerly creating the sourceFile so that `createSourceFile` doesn't run unless one of these tests is run.
|
||||
let sourceFile: SourceFile;
|
||||
before(() => sourceFile = createSourceFile("source.ts", `
|
||||
interface A<T> {
|
||||
// comment1
|
||||
readonly prop?: T;
|
||||
@@ -48,8 +50,7 @@ namespace ts {
|
||||
|
||||
// comment10
|
||||
function functionWithDefaultArgValue(argument: string = "defaultValue"): void { }
|
||||
`, ScriptTarget.ES2015);
|
||||
|
||||
`, ScriptTarget.ES2015));
|
||||
printsCorrectly("default", {}, printer => printer.printFile(sourceFile));
|
||||
printsCorrectly("removeComments", { removeComments: true }, printer => printer.printFile(sourceFile));
|
||||
|
||||
@@ -59,7 +60,8 @@ namespace ts {
|
||||
|
||||
describe("printBundle", () => {
|
||||
const printsCorrectly = makePrintsCorrectly("printsBundleCorrectly");
|
||||
const bundle = createBundle([
|
||||
let bundle: Bundle;
|
||||
before(() => bundle = createBundle([
|
||||
createSourceFile("a.ts", `
|
||||
/*! [a.ts] */
|
||||
|
||||
@@ -72,14 +74,15 @@ namespace ts {
|
||||
// comment1
|
||||
const b = 2;
|
||||
`, ScriptTarget.ES2015)
|
||||
]);
|
||||
]));
|
||||
printsCorrectly("default", {}, printer => printer.printBundle(bundle));
|
||||
printsCorrectly("removeComments", { removeComments: true }, printer => printer.printBundle(bundle));
|
||||
});
|
||||
|
||||
describe("printNode", () => {
|
||||
const printsCorrectly = makePrintsCorrectly("printsNodeCorrectly");
|
||||
const sourceFile = createSourceFile("source.ts", "", ScriptTarget.ES2015);
|
||||
let sourceFile: SourceFile;
|
||||
before(() => sourceFile = createSourceFile("source.ts", "", ScriptTarget.ES2015));
|
||||
// tslint:disable boolean-trivia
|
||||
const syntheticNode = createClassDeclaration(
|
||||
undefined,
|
||||
|
||||
@@ -424,6 +424,50 @@ class D { }\r\n\
|
||||
comment("=======\r\nclass D { }\r\n"),
|
||||
comment(">>>>>>> Branch - a"),
|
||||
finalEndOfLineState(ts.EndOfLineState.None));
|
||||
|
||||
testLexicalClassification(
|
||||
"class C {\r\n\
|
||||
<<<<<<< HEAD\r\n\
|
||||
v = 1;\r\n\
|
||||
||||||| merged common ancestors\r\n\
|
||||
v = 3;\r\n\
|
||||
=======\r\n\
|
||||
v = 2;\r\n\
|
||||
>>>>>>> Branch - a\r\n\
|
||||
}",
|
||||
ts.EndOfLineState.None,
|
||||
keyword("class"),
|
||||
identifier("C"),
|
||||
punctuation("{"),
|
||||
comment("<<<<<<< HEAD"),
|
||||
identifier("v"),
|
||||
operator("="),
|
||||
numberLiteral("1"),
|
||||
punctuation(";"),
|
||||
comment("||||||| merged common ancestors\r\n v = 3;\r\n"),
|
||||
comment("=======\r\n v = 2;\r\n"),
|
||||
comment(">>>>>>> Branch - a"),
|
||||
punctuation("}"),
|
||||
finalEndOfLineState(ts.EndOfLineState.None));
|
||||
|
||||
testLexicalClassification(
|
||||
"<<<<<<< HEAD\r\n\
|
||||
class C { }\r\n\
|
||||
||||||| merged common ancestors\r\n\
|
||||
class E { }\r\n\
|
||||
=======\r\n\
|
||||
class D { }\r\n\
|
||||
>>>>>>> Branch - a\r\n",
|
||||
ts.EndOfLineState.None,
|
||||
comment("<<<<<<< HEAD"),
|
||||
keyword("class"),
|
||||
identifier("C"),
|
||||
punctuation("{"),
|
||||
punctuation("}"),
|
||||
comment("||||||| merged common ancestors\r\nclass E { }\r\n"),
|
||||
comment("=======\r\nclass D { }\r\n"),
|
||||
comment(">>>>>>> Branch - a"),
|
||||
finalEndOfLineState(ts.EndOfLineState.None));
|
||||
});
|
||||
|
||||
it("'of' keyword", function () {
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
/// <reference path="../harness.ts" />
|
||||
/// <reference path="./tsserverProjectSystem.ts" />
|
||||
|
||||
namespace ts.projectSystem {
|
||||
describe("project telemetry", () => {
|
||||
it("does nothing for inferred project", () => {
|
||||
const file = makeFile("/a.js");
|
||||
const et = new EventTracker([file]);
|
||||
et.service.openClientFile(file.path);
|
||||
assert.equal(et.getEvents().length, 0);
|
||||
});
|
||||
it("only sends an event once", () => {
|
||||
const file = makeFile("/a.ts");
|
||||
const tsconfig = makeFile("/tsconfig.json", {});
|
||||
|
||||
const et = new EventTracker([file, tsconfig]);
|
||||
et.service.openClientFile(file.path);
|
||||
et.assertProjectInfoTelemetryEvent({});
|
||||
|
||||
et.service.closeClientFile(file.path);
|
||||
checkNumberOfProjects(et.service, { configuredProjects: 0 });
|
||||
|
||||
et.service.openClientFile(file.path);
|
||||
checkNumberOfProjects(et.service, { configuredProjects: 1 });
|
||||
|
||||
assert.equal(et.getEvents().length, 0);
|
||||
});
|
||||
|
||||
it("counts files by extension", () => {
|
||||
const files = ["ts.ts", "tsx.tsx", "moo.ts", "dts.d.ts", "jsx.jsx", "js.js", "badExtension.badExtension"].map(f => makeFile(`/src/${f}`));
|
||||
const notIncludedFile = makeFile("/bin/ts.js");
|
||||
const compilerOptions: ts.CompilerOptions = { allowJs: true };
|
||||
const tsconfig = makeFile("/tsconfig.json", { compilerOptions, include: ["src"] });
|
||||
|
||||
const et = new EventTracker([...files, notIncludedFile, tsconfig]);
|
||||
et.service.openClientFile(files[0].path);
|
||||
et.assertProjectInfoTelemetryEvent({
|
||||
fileStats: { ts: 2, tsx: 1, js: 1, jsx: 1, dts: 1 },
|
||||
compilerOptions,
|
||||
include: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("works with external project", () => {
|
||||
const file1 = makeFile("/a.ts");
|
||||
const et = new EventTracker([file1]);
|
||||
const compilerOptions: ts.CompilerOptions = { strict: true };
|
||||
|
||||
const projectFileName = "foo.csproj";
|
||||
|
||||
open();
|
||||
|
||||
// TODO: Apparently compilerOptions is mutated, so have to repeat it here!
|
||||
et.assertProjectInfoTelemetryEvent({
|
||||
compilerOptions: { strict: true },
|
||||
compileOnSave: true,
|
||||
// These properties can't be present for an external project, so they are undefined instead of false.
|
||||
extends: undefined,
|
||||
files: undefined,
|
||||
include: undefined,
|
||||
exclude: undefined,
|
||||
configFileName: "other",
|
||||
projectType: "external",
|
||||
});
|
||||
|
||||
// Also test that opening an external project only sends an event once.
|
||||
|
||||
et.service.closeExternalProject(projectFileName);
|
||||
checkNumberOfProjects(et.service, { externalProjects: 0 });
|
||||
|
||||
open();
|
||||
assert.equal(et.getEvents().length, 0);
|
||||
|
||||
function open(): void {
|
||||
et.service.openExternalProject({
|
||||
rootFiles: toExternalFiles([file1.path]),
|
||||
options: compilerOptions,
|
||||
projectFileName: projectFileName,
|
||||
});
|
||||
checkNumberOfProjects(et.service, { externalProjects: 1 });
|
||||
}
|
||||
});
|
||||
|
||||
it("does not expose paths", () => {
|
||||
const file = makeFile("/a.ts");
|
||||
|
||||
const compilerOptions: ts.CompilerOptions = {
|
||||
project: "",
|
||||
outFile: "hunter2.js",
|
||||
outDir: "hunter2",
|
||||
rootDir: "hunter2",
|
||||
baseUrl: "hunter2",
|
||||
rootDirs: ["hunter2"],
|
||||
typeRoots: ["hunter2"],
|
||||
types: ["hunter2"],
|
||||
sourceRoot: "hunter2",
|
||||
mapRoot: "hunter2",
|
||||
jsxFactory: "hunter2",
|
||||
out: "hunter2",
|
||||
reactNamespace: "hunter2",
|
||||
charset: "hunter2",
|
||||
locale: "hunter2",
|
||||
declarationDir: "hunter2",
|
||||
paths: {
|
||||
"*": ["hunter2"],
|
||||
},
|
||||
|
||||
// Boolean / number options get through
|
||||
declaration: true,
|
||||
|
||||
// List of string enum gets through -- but only if legitimately a member of the enum
|
||||
lib: ["es6", "dom", "hunter2"],
|
||||
|
||||
// Sensitive data doesn't get through even if sent to an option of safe type
|
||||
checkJs: "hunter2" as any as boolean,
|
||||
};
|
||||
const safeCompilerOptions: ts.CompilerOptions = {
|
||||
project: "",
|
||||
outFile: "",
|
||||
outDir: "",
|
||||
rootDir: "",
|
||||
baseUrl: "",
|
||||
rootDirs: [""],
|
||||
typeRoots: [""],
|
||||
types: [""],
|
||||
sourceRoot: "",
|
||||
mapRoot: "",
|
||||
jsxFactory: "",
|
||||
out: "",
|
||||
reactNamespace: "",
|
||||
charset: "",
|
||||
locale: "",
|
||||
declarationDir: "",
|
||||
paths: "" as any,
|
||||
|
||||
declaration: true,
|
||||
|
||||
lib: ["es6", "dom"],
|
||||
|
||||
checkJs: "" as any as boolean,
|
||||
};
|
||||
(compilerOptions as any).unknownCompilerOption = "hunter2"; // These are always ignored.
|
||||
const tsconfig = makeFile("/tsconfig.json", { compilerOptions, files: ["/a.ts"] });
|
||||
|
||||
const et = new EventTracker([file, tsconfig]);
|
||||
et.service.openClientFile(file.path);
|
||||
|
||||
et.assertProjectInfoTelemetryEvent({
|
||||
compilerOptions: safeCompilerOptions,
|
||||
files: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("sends telemetry for extends, files, include, exclude, and compileOnSave", () => {
|
||||
const file = makeFile("/hunter2/a.ts");
|
||||
const tsconfig = makeFile("/tsconfig.json", {
|
||||
compilerOptions: {},
|
||||
extends: "hunter2.json",
|
||||
files: ["hunter2/a.ts"],
|
||||
include: ["hunter2"],
|
||||
exclude: ["hunter2"],
|
||||
compileOnSave: true,
|
||||
});
|
||||
|
||||
const et = new EventTracker([tsconfig, file]);
|
||||
et.service.openClientFile(file.path);
|
||||
et.assertProjectInfoTelemetryEvent({
|
||||
extends: true,
|
||||
files: true,
|
||||
include: true,
|
||||
exclude: true,
|
||||
compileOnSave: true,
|
||||
});
|
||||
});
|
||||
|
||||
const autoJsCompilerOptions = {
|
||||
// Apparently some options are added by default.
|
||||
allowJs: true,
|
||||
allowSyntheticDefaultImports: true,
|
||||
maxNodeModuleJsDepth: 2,
|
||||
skipLibCheck: true,
|
||||
};
|
||||
|
||||
it("sends telemetry for typeAcquisition settings", () => {
|
||||
const file = makeFile("/a.js");
|
||||
const jsconfig = makeFile("/jsconfig.json", {
|
||||
compilerOptions: {},
|
||||
typeAcquisition: {
|
||||
enable: true,
|
||||
enableAutoDiscovery: false,
|
||||
include: ["hunter2", "hunter3"],
|
||||
exclude: [],
|
||||
},
|
||||
});
|
||||
const et = new EventTracker([jsconfig, file]);
|
||||
et.service.openClientFile(file.path);
|
||||
et.assertProjectInfoTelemetryEvent({
|
||||
fileStats: fileStats({ js: 1 }),
|
||||
compilerOptions: autoJsCompilerOptions,
|
||||
typeAcquisition: {
|
||||
enable: true,
|
||||
include: true,
|
||||
exclude: false,
|
||||
},
|
||||
configFileName: "jsconfig.json",
|
||||
});
|
||||
});
|
||||
|
||||
it("detects whether language service was disabled", () => {
|
||||
const file = makeFile("/a.js");
|
||||
const tsconfig = makeFile("/jsconfig.json", {});
|
||||
const et = new EventTracker([tsconfig, file]);
|
||||
et.host.getFileSize = () => server.maxProgramSizeForNonTsFiles + 1;
|
||||
et.service.openClientFile(file.path);
|
||||
et.getEvent<server.ProjectLanguageServiceStateEvent>(server.ProjectLanguageServiceStateEvent, /*mayBeMore*/ true);
|
||||
et.assertProjectInfoTelemetryEvent({
|
||||
fileStats: fileStats({ js: 1 }),
|
||||
compilerOptions: autoJsCompilerOptions,
|
||||
configFileName: "jsconfig.json",
|
||||
typeAcquisition: {
|
||||
enable: true,
|
||||
include: false,
|
||||
exclude: false,
|
||||
},
|
||||
languageServiceEnabled: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class EventTracker {
|
||||
private events: server.ProjectServiceEvent[] = [];
|
||||
readonly service: TestProjectService;
|
||||
readonly host: projectSystem.TestServerHost;
|
||||
|
||||
constructor(files: projectSystem.FileOrFolder[]) {
|
||||
this.host = createServerHost(files);
|
||||
this.service = createProjectService(this.host, {
|
||||
eventHandler: event => {
|
||||
this.events.push(event);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
getEvents(): ReadonlyArray<server.ProjectServiceEvent> {
|
||||
const events = this.events;
|
||||
this.events = [];
|
||||
return events;
|
||||
}
|
||||
|
||||
assertProjectInfoTelemetryEvent(partial: Partial<server.ProjectInfoTelemetryEventData>): void {
|
||||
assert.deepEqual(this.getEvent<server.ProjectInfoTelemetryEvent>(ts.server.ProjectInfoTelemetryEvent), makePayload(partial));
|
||||
}
|
||||
|
||||
getEvent<T extends server.ProjectServiceEvent>(eventName: T["eventName"], mayBeMore = false): T["data"] {
|
||||
if (mayBeMore) assert(this.events.length !== 0); else assert.equal(this.events.length, 1);
|
||||
const event = this.events.shift();
|
||||
assert.equal(event.eventName, eventName);
|
||||
return event.data;
|
||||
}
|
||||
}
|
||||
|
||||
function makePayload(partial: Partial<server.ProjectInfoTelemetryEventData>): server.ProjectInfoTelemetryEventData {
|
||||
return {
|
||||
fileStats: fileStats({ ts: 1 }),
|
||||
compilerOptions: {},
|
||||
extends: false,
|
||||
files: false,
|
||||
include: false,
|
||||
exclude: false,
|
||||
compileOnSave: false,
|
||||
typeAcquisition: {
|
||||
enable: false,
|
||||
exclude: false,
|
||||
include: false,
|
||||
},
|
||||
configFileName: "tsconfig.json",
|
||||
projectType: "configured",
|
||||
languageServiceEnabled: true,
|
||||
version: ts.version,
|
||||
...partial
|
||||
};
|
||||
}
|
||||
|
||||
function makeFile(path: string, content: {} = ""): projectSystem.FileOrFolder {
|
||||
return { path, content: typeof content === "string" ? "" : JSON.stringify(content) };
|
||||
}
|
||||
|
||||
function fileStats(nonZeroStats: Partial<server.FileStats>): server.FileStats {
|
||||
return { ts: 0, tsx: 0, dts: 0, js: 0, jsx: 0, ...nonZeroStats };
|
||||
}
|
||||
}
|
||||
@@ -2234,7 +2234,7 @@ namespace ts.projectSystem {
|
||||
|
||||
let lastEvent: server.ProjectLanguageServiceStateEvent;
|
||||
const session = createSession(host, /*typingsInstaller*/ undefined, e => {
|
||||
if (e.eventName === server.ConfigFileDiagEvent || e.eventName === server.ContextEvent) {
|
||||
if (e.eventName === server.ConfigFileDiagEvent || e.eventName === server.ContextEvent || e.eventName === server.ProjectInfoTelemetryEvent) {
|
||||
return;
|
||||
}
|
||||
assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent);
|
||||
@@ -2284,7 +2284,7 @@ namespace ts.projectSystem {
|
||||
filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath);
|
||||
let lastEvent: server.ProjectLanguageServiceStateEvent;
|
||||
const session = createSession(host, /*typingsInstaller*/ undefined, e => {
|
||||
if (e.eventName === server.ConfigFileDiagEvent) {
|
||||
if (e.eventName === server.ConfigFileDiagEvent || e.eventName === server.ProjectInfoTelemetryEvent) {
|
||||
return;
|
||||
}
|
||||
assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent);
|
||||
|
||||
@@ -44,7 +44,7 @@ namespace ts.projectSystem {
|
||||
});
|
||||
}
|
||||
|
||||
import typingsName = server.typingsInstaller.typingsName;
|
||||
import typingsName = TI.typingsName;
|
||||
|
||||
describe("local module", () => {
|
||||
it("should not be picked up", () => {
|
||||
@@ -73,7 +73,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { typesRegistry: createTypesRegistry("config"), globalTypingsCacheLocation: typesCache });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, _cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, _cb: TI.RequestCompletedAction) {
|
||||
assert(false, "should not be called");
|
||||
}
|
||||
})();
|
||||
@@ -121,7 +121,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { typesRegistry: createTypesRegistry("jquery") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
const installedTypings = ["@types/jquery"];
|
||||
const typingFiles = [jquery];
|
||||
executeCommand(this, host, installedTypings, typingFiles, cb);
|
||||
@@ -165,7 +165,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { typesRegistry: createTypesRegistry("jquery") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
const installedTypings = ["@types/jquery"];
|
||||
const typingFiles = [jquery];
|
||||
executeCommand(this, host, installedTypings, typingFiles, cb);
|
||||
@@ -672,7 +672,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("jquery") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
const installedTypings = ["@types/jquery"];
|
||||
const typingFiles = [jqueryDTS];
|
||||
executeCommand(this, host, installedTypings, typingFiles, cb);
|
||||
@@ -718,7 +718,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("jquery") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
const installedTypings = ["@types/jquery"];
|
||||
const typingFiles = [jqueryDTS];
|
||||
executeCommand(this, host, installedTypings, typingFiles, cb);
|
||||
@@ -765,7 +765,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("jquery") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
const installedTypings = ["@types/jquery"];
|
||||
const typingFiles = [jqueryDTS];
|
||||
executeCommand(this, host, installedTypings, typingFiles, cb);
|
||||
@@ -808,7 +808,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
const installedTypings = ["@types/commander"];
|
||||
const typingFiles = [commander];
|
||||
executeCommand(this, host, installedTypings, typingFiles, cb);
|
||||
@@ -849,7 +849,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("node", "commander") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
const installedTypings = ["@types/node", "@types/commander"];
|
||||
const typingFiles = [node, commander];
|
||||
executeCommand(this, host, installedTypings, typingFiles, cb);
|
||||
@@ -888,7 +888,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("foo") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
executeCommand(this, host, ["foo"], [], cb);
|
||||
}
|
||||
})();
|
||||
@@ -996,7 +996,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { globalTypingsCacheLocation: "/tmp" }, { isEnabled: () => true, writeLine: msg => messages.push(msg) });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, _cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, _cb: TI.RequestCompletedAction) {
|
||||
assert(false, "runCommand should not be invoked");
|
||||
}
|
||||
})();
|
||||
@@ -1060,7 +1060,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
const installedTypings = ["@types/commander"];
|
||||
const typingFiles = [commander];
|
||||
executeCommand(this, host, installedTypings, typingFiles, cb);
|
||||
@@ -1110,7 +1110,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
const installedTypings = ["@types/commander"];
|
||||
const typingFiles = [commander];
|
||||
executeCommand(this, host, installedTypings, typingFiles, cb);
|
||||
@@ -1157,7 +1157,7 @@ namespace ts.projectSystem {
|
||||
constructor() {
|
||||
super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry("commander") });
|
||||
}
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
|
||||
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) {
|
||||
executeCommand(this, host, "", [], cb);
|
||||
}
|
||||
sendResponse(response: server.SetTypings | server.InvalidateCachedTypings | server.BeginInstallTypes | server.EndInstallTypes) {
|
||||
|
||||
@@ -13,6 +13,7 @@ namespace ts.server {
|
||||
export const ContextEvent = "context";
|
||||
export const ConfigFileDiagEvent = "configFileDiag";
|
||||
export const ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
|
||||
export const ProjectInfoTelemetryEvent = "projectInfo";
|
||||
|
||||
export interface ContextEvent {
|
||||
eventName: typeof ContextEvent;
|
||||
@@ -29,7 +30,52 @@ namespace ts.server {
|
||||
data: { project: Project, languageServiceEnabled: boolean };
|
||||
}
|
||||
|
||||
export type ProjectServiceEvent = ContextEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent;
|
||||
/** This will be converted to the payload of a protocol.TelemetryEvent in session.defaultEventHandler. */
|
||||
export interface ProjectInfoTelemetryEvent {
|
||||
readonly eventName: typeof ProjectInfoTelemetryEvent;
|
||||
readonly data: ProjectInfoTelemetryEventData;
|
||||
}
|
||||
|
||||
export interface ProjectInfoTelemetryEventData {
|
||||
/** Count of file extensions seen in the project. */
|
||||
readonly fileStats: FileStats;
|
||||
/**
|
||||
* Any compiler options that might contain paths will be taken out.
|
||||
* Enum compiler options will be converted to strings.
|
||||
*/
|
||||
readonly compilerOptions: ts.CompilerOptions;
|
||||
// "extends", "files", "include", or "exclude" will be undefined if an external config is used.
|
||||
// Otherwise, we will use "true" if the property is present and "false" if it is missing.
|
||||
readonly extends: boolean | undefined;
|
||||
readonly files: boolean | undefined;
|
||||
readonly include: boolean | undefined;
|
||||
readonly exclude: boolean | undefined;
|
||||
readonly compileOnSave: boolean;
|
||||
readonly typeAcquisition: ProjectInfoTypeAcquisitionData;
|
||||
|
||||
readonly configFileName: "tsconfig.json" | "jsconfig.json" | "other";
|
||||
readonly projectType: "external" | "configured";
|
||||
readonly languageServiceEnabled: boolean;
|
||||
/** TypeScript version used by the server. */
|
||||
readonly version: string;
|
||||
}
|
||||
|
||||
export interface ProjectInfoTypeAcquisitionData {
|
||||
readonly enable: boolean;
|
||||
// Actual values of include/exclude entries are scrubbed.
|
||||
readonly include: boolean;
|
||||
readonly exclude: boolean;
|
||||
}
|
||||
|
||||
export interface FileStats {
|
||||
readonly js: number;
|
||||
readonly jsx: number;
|
||||
readonly ts: number;
|
||||
readonly tsx: number;
|
||||
readonly dts: number;
|
||||
}
|
||||
|
||||
export type ProjectServiceEvent = ContextEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent;
|
||||
|
||||
export interface ProjectServiceEventHandler {
|
||||
(event: ProjectServiceEvent): void;
|
||||
@@ -345,6 +391,9 @@ namespace ts.server {
|
||||
public readonly pluginProbeLocations: ReadonlyArray<string>;
|
||||
public readonly allowLocalPluginLoads: boolean;
|
||||
|
||||
/** Tracks projects that we have already sent telemetry for. */
|
||||
private readonly seenProjects = createMap<true>();
|
||||
|
||||
constructor(opts: ProjectServiceOptions) {
|
||||
this.host = opts.host;
|
||||
this.logger = opts.logger;
|
||||
@@ -934,7 +983,10 @@ namespace ts.server {
|
||||
const projectOptions: ProjectOptions = {
|
||||
files: parsedCommandLine.fileNames,
|
||||
compilerOptions: parsedCommandLine.options,
|
||||
configHasFilesProperty: config["files"] !== undefined,
|
||||
configHasExtendsProperty: config.extends !== undefined,
|
||||
configHasFilesProperty: config.files !== undefined,
|
||||
configHasIncludeProperty: config.include !== undefined,
|
||||
configHasExcludeProperty: config.exclude !== undefined,
|
||||
wildcardDirectories: createMapFromTemplate(parsedCommandLine.wildcardDirectories),
|
||||
typeAcquisition: parsedCommandLine.typeAcquisition,
|
||||
compileOnSave: parsedCommandLine.compileOnSave
|
||||
@@ -984,9 +1036,53 @@ namespace ts.server {
|
||||
|
||||
this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, /*clientFileName*/ undefined, typeAcquisition, /*configFileErrors*/ undefined);
|
||||
this.externalProjects.push(project);
|
||||
this.sendProjectTelemetry(project.externalProjectName, project);
|
||||
return project;
|
||||
}
|
||||
|
||||
private sendProjectTelemetry(projectKey: string, project: server.ExternalProject | server.ConfiguredProject, projectOptions?: ProjectOptions): void {
|
||||
if (this.seenProjects.has(projectKey)) {
|
||||
return;
|
||||
}
|
||||
this.seenProjects.set(projectKey, true);
|
||||
|
||||
if (!this.eventHandler) return;
|
||||
|
||||
const data: ProjectInfoTelemetryEventData = {
|
||||
fileStats: countEachFileTypes(project.getScriptInfos()),
|
||||
compilerOptions: convertCompilerOptionsForTelemetry(project.getCompilerOptions()),
|
||||
typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()),
|
||||
extends: projectOptions && projectOptions.configHasExtendsProperty,
|
||||
files: projectOptions && projectOptions.configHasFilesProperty,
|
||||
include: projectOptions && projectOptions.configHasIncludeProperty,
|
||||
exclude: projectOptions && projectOptions.configHasExcludeProperty,
|
||||
compileOnSave: project.compileOnSaveEnabled,
|
||||
configFileName: configFileName(),
|
||||
projectType: project instanceof server.ExternalProject ? "external" : "configured",
|
||||
languageServiceEnabled: project.languageServiceEnabled,
|
||||
version: ts.version,
|
||||
};
|
||||
this.eventHandler({ eventName: ProjectInfoTelemetryEvent, data });
|
||||
|
||||
function configFileName(): ProjectInfoTelemetryEventData["configFileName"] {
|
||||
if (!(project instanceof server.ConfiguredProject)) {
|
||||
return "other";
|
||||
}
|
||||
|
||||
const configFilePath = project instanceof server.ConfiguredProject && project.getConfigFilePath();
|
||||
const base = ts.getBaseFileName(configFilePath);
|
||||
return base === "tsconfig.json" || base === "jsconfig.json" ? base : "other";
|
||||
}
|
||||
|
||||
function convertTypeAcquisition({ enable, include, exclude }: TypeAcquisition): ProjectInfoTypeAcquisitionData {
|
||||
return {
|
||||
enable,
|
||||
include: include !== undefined && include.length !== 0,
|
||||
exclude: exclude !== undefined && exclude.length !== 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile: string) {
|
||||
if (!this.eventHandler) {
|
||||
return;
|
||||
@@ -1020,6 +1116,7 @@ namespace ts.server {
|
||||
project.watchTypeRoots((project, path) => this.onTypeRootFileChanged(project, path));
|
||||
|
||||
this.configuredProjects.push(project);
|
||||
this.sendProjectTelemetry(project.getConfigFilePath(), project, projectOptions);
|
||||
return project;
|
||||
}
|
||||
|
||||
@@ -1052,7 +1149,7 @@ namespace ts.server {
|
||||
const conversionResult = this.convertConfigFileContentToProjectOptions(configFileName);
|
||||
const projectOptions: ProjectOptions = conversionResult.success
|
||||
? conversionResult.projectOptions
|
||||
: { files: [], compilerOptions: {}, typeAcquisition: { enable: false } };
|
||||
: { files: [], compilerOptions: {}, configHasExtendsProperty: false, configHasFilesProperty: false, configHasIncludeProperty: false, configHasExcludeProperty: false, typeAcquisition: { enable: false } };
|
||||
const project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName);
|
||||
return {
|
||||
success: conversionResult.success,
|
||||
|
||||
+15
-1
@@ -13,7 +13,8 @@ namespace ts.server {
|
||||
External
|
||||
}
|
||||
|
||||
function countEachFileTypes(infos: ScriptInfo[]): { js: number, jsx: number, ts: number, tsx: number, dts: number } {
|
||||
/* @internal */
|
||||
export function countEachFileTypes(infos: ScriptInfo[]): FileStats {
|
||||
const result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 };
|
||||
for (const info of infos) {
|
||||
switch (info.scriptKind) {
|
||||
@@ -730,6 +731,10 @@ namespace ts.server {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If a file is opened and no tsconfig (or jsconfig) is found,
|
||||
* the file and its imports/references are put into an InferredProject.
|
||||
*/
|
||||
export class InferredProject extends Project {
|
||||
|
||||
private static newName = (() => {
|
||||
@@ -823,6 +828,11 @@ namespace ts.server {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If a file is opened, the server will look for a tsconfig (or jsconfig)
|
||||
* and if successfull create a ConfiguredProject for it.
|
||||
* Otherwise it will create an InferredProject.
|
||||
*/
|
||||
export class ConfiguredProject extends Project {
|
||||
private typeAcquisition: TypeAcquisition;
|
||||
private projectFileWatcher: FileWatcher;
|
||||
@@ -1048,6 +1058,10 @@ namespace ts.server {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Project whose configuration is handled externally, such as in a '.csproj'.
|
||||
* These are created only if a host explicitly calls `openExternalProject`.
|
||||
*/
|
||||
export class ExternalProject extends Project {
|
||||
private typeAcquisition: TypeAcquisition;
|
||||
constructor(public externalProjectName: string,
|
||||
|
||||
+23
-15
@@ -13,6 +13,7 @@ namespace ts.server {
|
||||
globalTypingsCacheLocation: string;
|
||||
logger: Logger;
|
||||
typingSafeListLocation: string;
|
||||
npmLocation: string | undefined;
|
||||
telemetryEnabled: boolean;
|
||||
globalPlugins: string[];
|
||||
pluginProbeLocations: string[];
|
||||
@@ -44,6 +45,8 @@ namespace ts.server {
|
||||
os.tmpdir();
|
||||
return combinePaths(normalizeSlashes(basePath), "Microsoft/TypeScript");
|
||||
}
|
||||
case "openbsd":
|
||||
case "freebsd":
|
||||
case "darwin":
|
||||
case "linux":
|
||||
case "android": {
|
||||
@@ -234,6 +237,7 @@ namespace ts.server {
|
||||
eventPort: number,
|
||||
readonly globalTypingsCacheLocation: string,
|
||||
readonly typingSafeListLocation: string,
|
||||
private readonly npmLocation: string | undefined,
|
||||
private newLine: string) {
|
||||
this.throttledOperations = new ThrottledOperations(host);
|
||||
if (eventPort) {
|
||||
@@ -278,19 +282,21 @@ namespace ts.server {
|
||||
if (this.typingSafeListLocation) {
|
||||
args.push(Arguments.TypingSafeListLocation, this.typingSafeListLocation);
|
||||
}
|
||||
if (this.npmLocation) {
|
||||
args.push(Arguments.NpmLocation, this.npmLocation);
|
||||
}
|
||||
|
||||
const execArgv: string[] = [];
|
||||
{
|
||||
for (const arg of process.execArgv) {
|
||||
const match = /^--(debug|inspect)(=(\d+))?$/.exec(arg);
|
||||
if (match) {
|
||||
// if port is specified - use port + 1
|
||||
// otherwise pick a default port depending on if 'debug' or 'inspect' and use its value + 1
|
||||
const currentPort = match[3] !== undefined
|
||||
? +match[3]
|
||||
: match[1] === "debug" ? 5858 : 9229;
|
||||
execArgv.push(`--${match[1]}=${currentPort + 1}`);
|
||||
break;
|
||||
}
|
||||
for (const arg of process.execArgv) {
|
||||
const match = /^--(debug|inspect)(=(\d+))?$/.exec(arg);
|
||||
if (match) {
|
||||
// if port is specified - use port + 1
|
||||
// otherwise pick a default port depending on if 'debug' or 'inspect' and use its value + 1
|
||||
const currentPort = match[3] !== undefined
|
||||
? +match[3]
|
||||
: match[1] === "debug" ? 5858 : 9229;
|
||||
execArgv.push(`--${match[1]}=${currentPort + 1}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -389,10 +395,10 @@ namespace ts.server {
|
||||
|
||||
class IOSession extends Session {
|
||||
constructor(options: IOSessionOptions) {
|
||||
const { host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, canUseEvents } = options;
|
||||
const { host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, npmLocation, canUseEvents } = options;
|
||||
const typingsInstaller = disableAutomaticTypingAcquisition
|
||||
? undefined
|
||||
: new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, host.newLine);
|
||||
: new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, npmLocation, host.newLine);
|
||||
|
||||
super({
|
||||
host,
|
||||
@@ -741,7 +747,8 @@ namespace ts.server {
|
||||
validateLocaleAndSetLanguage(localeStr, sys);
|
||||
}
|
||||
|
||||
const typingSafeListLocation = findArgument("--typingSafeListLocation");
|
||||
const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation);
|
||||
const npmLocation = findArgument(Arguments.NpmLocation);
|
||||
|
||||
const globalPlugins = (findArgument("--globalPlugins") || "").split(",");
|
||||
const pluginProbeLocations = (findArgument("--pluginProbeLocations") || "").split(",");
|
||||
@@ -760,6 +767,7 @@ namespace ts.server {
|
||||
disableAutomaticTypingAcquisition,
|
||||
globalTypingsCacheLocation: getGlobalTypingsCacheLocation(),
|
||||
typingSafeListLocation,
|
||||
npmLocation,
|
||||
telemetryEnabled,
|
||||
logger,
|
||||
globalPlugins,
|
||||
|
||||
+10
-1
@@ -337,13 +337,22 @@ namespace ts.server {
|
||||
const { triggerFile, configFileName, diagnostics } = event.data;
|
||||
this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics);
|
||||
break;
|
||||
case ProjectLanguageServiceStateEvent:
|
||||
case ProjectLanguageServiceStateEvent: {
|
||||
const eventName: protocol.ProjectLanguageServiceStateEventName = "projectLanguageServiceState";
|
||||
this.event<protocol.ProjectLanguageServiceStateEventBody>({
|
||||
projectName: event.data.project.getProjectName(),
|
||||
languageServiceEnabled: event.data.languageServiceEnabled
|
||||
}, eventName);
|
||||
break;
|
||||
}
|
||||
case ProjectInfoTelemetryEvent: {
|
||||
const eventName: protocol.TelemetryEventName = "telemetry";
|
||||
this.event<protocol.TelemetryEventBody>({
|
||||
telemetryEventName: event.eventName,
|
||||
payload: event.data,
|
||||
}, eventName);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,13 +12,18 @@ namespace ts.server {
|
||||
export const LogFile = "--logFile";
|
||||
export const EnableTelemetry = "--enableTelemetry";
|
||||
export const TypingSafeListLocation = "--typingSafeListLocation";
|
||||
/**
|
||||
* This argument specifies the location of the NPM executable.
|
||||
* typingsInstaller will run the command with `${npmLocation} install ...`.
|
||||
*/
|
||||
export const NpmLocation = "--npmLocation";
|
||||
}
|
||||
|
||||
export function hasArgument(argumentName: string) {
|
||||
return sys.args.indexOf(argumentName) >= 0;
|
||||
}
|
||||
|
||||
export function findArgument(argumentName: string) {
|
||||
export function findArgument(argumentName: string): string | undefined {
|
||||
const index = sys.args.indexOf(argumentName);
|
||||
return index >= 0 && index < sys.args.length - 1
|
||||
? sys.args[index + 1]
|
||||
|
||||
@@ -30,7 +30,8 @@ namespace ts.server.typingsInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
function getNPMLocation(processName: string) {
|
||||
/** Used if `--npmLocation` is not passed. */
|
||||
function getDefaultNPMLocation(processName: string) {
|
||||
if (path.basename(processName).indexOf("node") === 0) {
|
||||
return `"${path.join(path.dirname(process.argv[0]), "npm")}"`;
|
||||
}
|
||||
@@ -76,17 +77,23 @@ namespace ts.server.typingsInstaller {
|
||||
|
||||
private delayedInitializationError: InitializationFailedResponse;
|
||||
|
||||
constructor(globalTypingsCacheLocation: string, typingSafeListLocation: string, throttleLimit: number, log: Log) {
|
||||
constructor(globalTypingsCacheLocation: string, typingSafeListLocation: string, npmLocation: string | undefined, throttleLimit: number, log: Log) {
|
||||
super(
|
||||
sys,
|
||||
globalTypingsCacheLocation,
|
||||
typingSafeListLocation ? toPath(typingSafeListLocation, "", createGetCanonicalFileName(sys.useCaseSensitiveFileNames)) : toPath("typingSafeList.json", __dirname, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)),
|
||||
throttleLimit,
|
||||
log);
|
||||
this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0]);
|
||||
|
||||
// If the NPM path contains spaces and isn't wrapped in quotes, do so.
|
||||
if (this.npmPath.indexOf(" ") !== -1 && this.npmPath[0] !== `"`) {
|
||||
this.npmPath = `"${this.npmPath}"`;
|
||||
}
|
||||
if (this.log.isEnabled()) {
|
||||
this.log.writeLine(`Process id: ${process.pid}`);
|
||||
this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`);
|
||||
}
|
||||
this.npmPath = getNPMLocation(process.argv[0]);
|
||||
({ execSync: this.execSync } = require("child_process"));
|
||||
|
||||
this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
|
||||
@@ -168,6 +175,7 @@ namespace ts.server.typingsInstaller {
|
||||
const logFilePath = findArgument(server.Arguments.LogFile);
|
||||
const globalTypingsCacheLocation = findArgument(server.Arguments.GlobalCacheLocation);
|
||||
const typingSafeListLocation = findArgument(server.Arguments.TypingSafeListLocation);
|
||||
const npmLocation = findArgument(server.Arguments.NpmLocation);
|
||||
|
||||
const log = new FileLog(logFilePath);
|
||||
if (log.isEnabled()) {
|
||||
@@ -181,6 +189,6 @@ namespace ts.server.typingsInstaller {
|
||||
}
|
||||
process.exit(0);
|
||||
});
|
||||
const installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, /*throttleLimit*/5, log);
|
||||
const installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, npmLocation, /*throttleLimit*/5, log);
|
||||
installer.listen();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,10 +164,13 @@ namespace ts.server {
|
||||
}
|
||||
|
||||
export interface ProjectOptions {
|
||||
configHasExtendsProperty: boolean;
|
||||
/**
|
||||
* true if config file explicitly listed files
|
||||
*/
|
||||
configHasFilesProperty?: boolean;
|
||||
configHasFilesProperty: boolean;
|
||||
configHasIncludeProperty: boolean;
|
||||
configHasExcludeProperty: boolean;
|
||||
/**
|
||||
* these fields can be present in the project file
|
||||
*/
|
||||
|
||||
@@ -685,9 +685,9 @@ namespace ts {
|
||||
continue;
|
||||
}
|
||||
|
||||
// for the ======== add a comment for the first line, and then lex all
|
||||
// subsequent lines up until the end of the conflict marker.
|
||||
Debug.assert(ch === CharacterCodes.equals);
|
||||
// for the ||||||| and ======== markers, add a comment for the first line,
|
||||
// and then lex all subsequent lines up until the end of the conflict marker.
|
||||
Debug.assert(ch === CharacterCodes.bar || ch === CharacterCodes.equals);
|
||||
classifyDisabledMergeCode(text, start, end);
|
||||
}
|
||||
}
|
||||
@@ -782,8 +782,8 @@ namespace ts {
|
||||
}
|
||||
|
||||
function classifyDisabledMergeCode(text: string, start: number, end: number) {
|
||||
// Classify the line that the ======= marker is on as a comment. Then just lex
|
||||
// all further tokens and add them to the result.
|
||||
// Classify the line that the ||||||| or ======= marker is on as a comment.
|
||||
// Then just lex all further tokens and add them to the result.
|
||||
let i: number;
|
||||
for (i = start; i < end; i++) {
|
||||
if (isLineBreak(text.charCodeAt(i))) {
|
||||
|
||||
@@ -386,7 +386,7 @@ namespace ts.FindAllReferences.Core {
|
||||
const searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), symbol.declarations);
|
||||
|
||||
const result: SymbolAndEntries[] = [];
|
||||
const state = createState(sourceFiles, node, checker, cancellationToken, searchMeaning, options, result);
|
||||
const state = new State(sourceFiles, /*isForConstructor*/ node.kind === SyntaxKind.ConstructorKeyword, checker, cancellationToken, searchMeaning, options, result);
|
||||
const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) });
|
||||
|
||||
// Try to get the smallest valid scope that we can limit our search to;
|
||||
@@ -446,35 +446,9 @@ namespace ts.FindAllReferences.Core {
|
||||
* Holds all state needed for the finding references.
|
||||
* Unlike `Search`, there is only one `State`.
|
||||
*/
|
||||
interface State extends Options {
|
||||
/** True if we're searching for constructor references. */
|
||||
readonly isForConstructor: boolean;
|
||||
|
||||
readonly sourceFiles: SourceFile[];
|
||||
readonly checker: TypeChecker;
|
||||
readonly cancellationToken: CancellationToken;
|
||||
readonly searchMeaning: SemanticMeaning;
|
||||
|
||||
class State {
|
||||
/** Cache for `explicitlyinheritsFrom`. */
|
||||
readonly inheritsFromCache: Map<boolean>;
|
||||
|
||||
/** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
|
||||
getImportSearches(exportSymbol: Symbol, exportInfo: ExportInfo): ImportsResult;
|
||||
|
||||
/** @param allSearchSymbols set of additinal symbols for use by `includes`. */
|
||||
createSearch(location: Node, symbol: Symbol, comingFrom: ImportExport | undefined, searchOptions?: { text?: string, allSearchSymbols?: Symbol[] }): Search;
|
||||
|
||||
/**
|
||||
* Callback to add references for a particular searched symbol.
|
||||
* This initializes a reference group, so only call this if you will add at least one reference.
|
||||
*/
|
||||
referenceAdder(searchSymbol: Symbol, searchLocation: Node): (node: Node) => void;
|
||||
|
||||
/** Add a reference with no associated definition. */
|
||||
addStringOrCommentReference(fileName: string, textSpan: TextSpan): void;
|
||||
|
||||
/** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */
|
||||
markSearchedSymbol(sourceFile: SourceFile, symbol: Symbol): boolean;
|
||||
readonly inheritsFromCache = createMap<boolean>();
|
||||
|
||||
/**
|
||||
* Type nodes can contain multiple references to the same type. For example:
|
||||
@@ -483,7 +457,7 @@ namespace ts.FindAllReferences.Core {
|
||||
* duplicate entries would be returned here as each of the type references is part of
|
||||
* the same implementation. For that reason, check before we add a new entry.
|
||||
*/
|
||||
markSeenContainingTypeReference(containingTypeReference: Node): boolean;
|
||||
readonly markSeenContainingTypeReference = nodeSeenTracker();
|
||||
|
||||
/**
|
||||
* It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once.
|
||||
@@ -496,33 +470,31 @@ namespace ts.FindAllReferences.Core {
|
||||
* But another reference to it may appear in the same source file.
|
||||
* See `tests/cases/fourslash/transitiveExportImports3.ts`.
|
||||
*/
|
||||
markSeenReExportRHS(rhs: Identifier): boolean;
|
||||
}
|
||||
readonly markSeenReExportRHS = nodeSeenTracker();
|
||||
|
||||
function createState(sourceFiles: SourceFile[], originalLocation: Node, checker: TypeChecker, cancellationToken: CancellationToken, searchMeaning: SemanticMeaning, options: Options, result: Push<SymbolAndEntries>): State {
|
||||
const symbolIdToReferences: Entry[][] = [];
|
||||
const inheritsFromCache = createMap<boolean>();
|
||||
// Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
|
||||
const sourceFileToSeenSymbols: Array<Array<true>> = [];
|
||||
const isForConstructor = originalLocation.kind === SyntaxKind.ConstructorKeyword;
|
||||
let importTracker: ImportTracker | undefined;
|
||||
constructor(
|
||||
readonly sourceFiles: SourceFile[],
|
||||
/** True if we're searching for constructor references. */
|
||||
readonly isForConstructor: boolean,
|
||||
readonly checker: TypeChecker,
|
||||
readonly cancellationToken: CancellationToken,
|
||||
readonly searchMeaning: SemanticMeaning,
|
||||
readonly options: Options,
|
||||
private readonly result: Push<SymbolAndEntries>) {}
|
||||
|
||||
return {
|
||||
...options,
|
||||
sourceFiles, isForConstructor, checker, cancellationToken, searchMeaning, inheritsFromCache, getImportSearches, createSearch, referenceAdder, addStringOrCommentReference,
|
||||
markSearchedSymbol, markSeenContainingTypeReference: nodeSeenTracker(), markSeenReExportRHS: nodeSeenTracker(),
|
||||
};
|
||||
|
||||
function getImportSearches(exportSymbol: Symbol, exportInfo: ExportInfo): ImportsResult {
|
||||
if (!importTracker) importTracker = createImportTracker(sourceFiles, checker, cancellationToken);
|
||||
return importTracker(exportSymbol, exportInfo, options.isForRename);
|
||||
private importTracker: ImportTracker | undefined;
|
||||
/** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */
|
||||
getImportSearches(exportSymbol: Symbol, exportInfo: ExportInfo): ImportsResult {
|
||||
if (!this.importTracker) this.importTracker = createImportTracker(this.sourceFiles, this.checker, this.cancellationToken);
|
||||
return this.importTracker(exportSymbol, exportInfo, this.options.isForRename);
|
||||
}
|
||||
|
||||
function createSearch(location: Node, symbol: Symbol, comingFrom: ImportExport, searchOptions: { text?: string, allSearchSymbols?: Symbol[] } = {}): Search {
|
||||
/** @param allSearchSymbols set of additinal symbols for use by `includes`. */
|
||||
createSearch(location: Node, symbol: Symbol, comingFrom: ImportExport | undefined, searchOptions: { text?: string, allSearchSymbols?: Symbol[] } = {}): Search {
|
||||
// Note: if this is an external module symbol, the name doesn't include quotes.
|
||||
const { text = stripQuotes(getDeclaredName(checker, symbol, location)), allSearchSymbols = undefined } = searchOptions;
|
||||
const { text = stripQuotes(getDeclaredName(this.checker, symbol, location)), allSearchSymbols = undefined } = searchOptions;
|
||||
const escapedText = escapeIdentifier(text);
|
||||
const parents = options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, checker);
|
||||
const parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker);
|
||||
return { location, symbol, comingFrom, text, escapedText, parents, includes };
|
||||
|
||||
function includes(referenceSymbol: Symbol): boolean {
|
||||
@@ -530,27 +502,36 @@ namespace ts.FindAllReferences.Core {
|
||||
}
|
||||
}
|
||||
|
||||
function referenceAdder(referenceSymbol: Symbol, searchLocation: Node): (node: Node) => void {
|
||||
const symbolId = getSymbolId(referenceSymbol);
|
||||
let references = symbolIdToReferences[symbolId];
|
||||
private readonly symbolIdToReferences: Entry[][] = [];
|
||||
/**
|
||||
* Callback to add references for a particular searched symbol.
|
||||
* This initializes a reference group, so only call this if you will add at least one reference.
|
||||
*/
|
||||
referenceAdder(searchSymbol: Symbol, searchLocation: Node): (node: Node) => void {
|
||||
const symbolId = getSymbolId(searchSymbol);
|
||||
let references = this.symbolIdToReferences[symbolId];
|
||||
if (!references) {
|
||||
references = symbolIdToReferences[symbolId] = [];
|
||||
result.push({ definition: { type: "symbol", symbol: referenceSymbol, node: searchLocation }, references });
|
||||
references = this.symbolIdToReferences[symbolId] = [];
|
||||
this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references });
|
||||
}
|
||||
return node => references.push(nodeEntry(node));
|
||||
}
|
||||
|
||||
function addStringOrCommentReference(fileName: string, textSpan: TextSpan): void {
|
||||
result.push({
|
||||
/** Add a reference with no associated definition. */
|
||||
addStringOrCommentReference(fileName: string, textSpan: TextSpan): void {
|
||||
this.result.push({
|
||||
definition: undefined,
|
||||
references: [{ type: "span", fileName, textSpan }]
|
||||
});
|
||||
}
|
||||
|
||||
function markSearchedSymbol(sourceFile: SourceFile, symbol: Symbol): boolean {
|
||||
// Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
|
||||
private readonly sourceFileToSeenSymbols: Array<Array<true>> = [];
|
||||
/** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */
|
||||
markSearchedSymbol(sourceFile: SourceFile, symbol: Symbol): boolean {
|
||||
const sourceId = getNodeId(sourceFile);
|
||||
const symbolId = getSymbolId(symbol);
|
||||
const seenSymbols = sourceFileToSeenSymbols[sourceId] || (sourceFileToSeenSymbols[sourceId] = []);
|
||||
const seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = []);
|
||||
return !seenSymbols[symbolId] && (seenSymbols[symbolId] = true);
|
||||
}
|
||||
}
|
||||
@@ -580,7 +561,7 @@ namespace ts.FindAllReferences.Core {
|
||||
break;
|
||||
case ExportKind.Default:
|
||||
// Search for a property access to '.default'. This can't be renamed.
|
||||
indirectSearch = state.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, ImportExport.Export, { text: "default" });
|
||||
indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, ImportExport.Export, { text: "default" });
|
||||
break;
|
||||
case ExportKind.ExportEquals:
|
||||
break;
|
||||
@@ -650,10 +631,12 @@ namespace ts.FindAllReferences.Core {
|
||||
|
||||
// If this is private property or method, the scope is the containing class
|
||||
if (flags & (SymbolFlags.Property | SymbolFlags.Method)) {
|
||||
const privateDeclaration = find(declarations, d => !!(getModifierFlags(d) & ModifierFlags.Private));
|
||||
const privateDeclaration = find(declarations, d => hasModifier(d, ModifierFlags.Private));
|
||||
if (privateDeclaration) {
|
||||
return getAncestor(privateDeclaration, SyntaxKind.ClassDeclaration);
|
||||
}
|
||||
// Else this is a public property and could be accessed from anywhere.
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// If symbol is of object binding pattern element without property name we would want to
|
||||
@@ -669,11 +652,6 @@ namespace ts.FindAllReferences.Core {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// If this is a synthetic property, it's a property and must be searched for globally.
|
||||
if ((flags & SymbolFlags.Transient && (<TransientSymbol>symbol).checkFlags & CheckFlags.Synthetic)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let scope: Node | undefined;
|
||||
for (const declaration of declarations) {
|
||||
const container = getContainerNode(declaration);
|
||||
@@ -806,7 +784,8 @@ namespace ts.FindAllReferences.Core {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments || container.jsDoc !== undefined)) {
|
||||
const fullStart = state.options.findInComments || container.jsDoc !== undefined || forEach(search.symbol.declarations, d => d.kind === ts.SyntaxKind.JSDocTypedefTag);
|
||||
for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container, fullStart)) {
|
||||
getReferencesAtLocation(sourceFile, position, search, state);
|
||||
}
|
||||
}
|
||||
@@ -818,7 +797,7 @@ namespace ts.FindAllReferences.Core {
|
||||
// This wasn't the start of a token. Check to see if it might be a
|
||||
// match in a comment or string if that's what the caller is asking
|
||||
// for.
|
||||
if (!state.implementations && (state.findInStrings && isInString(sourceFile, position) || state.findInComments && isInNonReferenceComment(sourceFile, position))) {
|
||||
if (!state.options.implementations && (state.options.findInStrings && isInString(sourceFile, position) || state.options.findInComments && isInNonReferenceComment(sourceFile, position))) {
|
||||
// In the case where we're looking inside comments/strings, we don't have
|
||||
// an actual definition. So just use 'undefined' here. Features like
|
||||
// 'Rename' won't care (as they ignore the definitions), and features like
|
||||
@@ -884,7 +863,7 @@ namespace ts.FindAllReferences.Core {
|
||||
addRef();
|
||||
}
|
||||
|
||||
if (!state.isForRename && state.markSeenReExportRHS(name)) {
|
||||
if (!state.options.isForRename && state.markSeenReExportRHS(name)) {
|
||||
addReference(name, referenceSymbol, name, state);
|
||||
}
|
||||
}
|
||||
@@ -895,7 +874,7 @@ namespace ts.FindAllReferences.Core {
|
||||
}
|
||||
|
||||
// For `export { foo as bar }`, rename `foo`, but not `bar`.
|
||||
if (!(referenceLocation === propertyName && state.isForRename)) {
|
||||
if (!(referenceLocation === propertyName && state.options.isForRename)) {
|
||||
const exportKind = (referenceLocation as Identifier).originalKeywordKind === ts.SyntaxKind.DefaultKeyword ? ExportKind.Default : ExportKind.Named;
|
||||
const exportInfo = getExportInfo(referenceSymbol, exportKind, state.checker);
|
||||
Debug.assert(!!exportInfo);
|
||||
@@ -937,7 +916,7 @@ namespace ts.FindAllReferences.Core {
|
||||
const { symbol } = importOrExport;
|
||||
|
||||
if (importOrExport.kind === ImportExport.Import) {
|
||||
if (!state.isForRename || importOrExport.isNamedImport) {
|
||||
if (!state.options.isForRename || importOrExport.isNamedImport) {
|
||||
searchForImportedSymbol(symbol, state);
|
||||
}
|
||||
}
|
||||
@@ -963,7 +942,7 @@ namespace ts.FindAllReferences.Core {
|
||||
|
||||
function addReference(referenceLocation: Node, relatedSymbol: Symbol, searchLocation: Node, state: State): void {
|
||||
const addRef = state.referenceAdder(relatedSymbol, searchLocation);
|
||||
if (state.implementations) {
|
||||
if (state.options.implementations) {
|
||||
addImplementationReferences(referenceLocation, addRef, state);
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace ts.GoToDefinition {
|
||||
if (referenceFile) {
|
||||
return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)];
|
||||
}
|
||||
return undefined;
|
||||
// Might still be on jsdoc, so keep looking.
|
||||
}
|
||||
|
||||
// Type reference directives
|
||||
|
||||
@@ -39,13 +39,14 @@ namespace ts {
|
||||
case SyntaxKind.TypeLiteral:
|
||||
return SemanticMeaning.Type;
|
||||
|
||||
case SyntaxKind.JSDocTypedefTag:
|
||||
// If it has no name node, it shares the name with the value declaration below it.
|
||||
return (node as JSDocTypedefTag).name === undefined ? SemanticMeaning.Value | SemanticMeaning.Type : SemanticMeaning.Type;
|
||||
|
||||
case SyntaxKind.EnumMember:
|
||||
case SyntaxKind.ClassDeclaration:
|
||||
return SemanticMeaning.Value | SemanticMeaning.Type;
|
||||
|
||||
case SyntaxKind.EnumDeclaration:
|
||||
return SemanticMeaning.All;
|
||||
|
||||
case SyntaxKind.ModuleDeclaration:
|
||||
if (isAmbientModule(<ModuleDeclaration>node)) {
|
||||
return SemanticMeaning.Namespace | SemanticMeaning.Value;
|
||||
@@ -57,6 +58,7 @@ namespace ts {
|
||||
return SemanticMeaning.Namespace;
|
||||
}
|
||||
|
||||
case SyntaxKind.EnumDeclaration:
|
||||
case SyntaxKind.NamedImports:
|
||||
case SyntaxKind.ImportSpecifier:
|
||||
case SyntaxKind.ImportEqualsDeclaration:
|
||||
@@ -70,7 +72,7 @@ namespace ts {
|
||||
return SemanticMeaning.Namespace | SemanticMeaning.Value;
|
||||
}
|
||||
|
||||
return SemanticMeaning.Value | SemanticMeaning.Type | SemanticMeaning.Namespace;
|
||||
return SemanticMeaning.All;
|
||||
}
|
||||
|
||||
export function getMeaningFromLocation(node: Node): SemanticMeaning {
|
||||
@@ -78,7 +80,7 @@ namespace ts {
|
||||
return SemanticMeaning.Value;
|
||||
}
|
||||
else if (node.parent.kind === SyntaxKind.ExportAssignment) {
|
||||
return SemanticMeaning.Value | SemanticMeaning.Type | SemanticMeaning.Namespace;
|
||||
return SemanticMeaning.All;
|
||||
}
|
||||
else if (isInRightSideOfImport(node)) {
|
||||
return getMeaningFromRightHandSideOfImportEquals(node);
|
||||
@@ -162,10 +164,22 @@ namespace ts {
|
||||
node = node.parent;
|
||||
}
|
||||
|
||||
return node.parent.kind === SyntaxKind.TypeReference ||
|
||||
(node.parent.kind === SyntaxKind.ExpressionWithTypeArguments && !isExpressionWithTypeArgumentsInClassExtendsClause(<ExpressionWithTypeArguments>node.parent)) ||
|
||||
(node.kind === SyntaxKind.ThisKeyword && !isPartOfExpression(node)) ||
|
||||
node.kind === SyntaxKind.ThisType;
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.ThisKeyword:
|
||||
return !isPartOfExpression(node);
|
||||
case SyntaxKind.ThisType:
|
||||
return true;
|
||||
}
|
||||
|
||||
switch (node.parent.kind) {
|
||||
case SyntaxKind.TypeReference:
|
||||
case SyntaxKind.JSDocTypeReference:
|
||||
return true;
|
||||
case SyntaxKind.ExpressionWithTypeArguments:
|
||||
return !isExpressionWithTypeArgumentsInClassExtendsClause(<ExpressionWithTypeArguments>node.parent);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isCallExpressionTarget(node: Node): boolean {
|
||||
|
||||
+2
-2
@@ -28,9 +28,9 @@ var Point = (function () {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
Point.Origin = { x: 0, y: 0 };
|
||||
return Point;
|
||||
}());
|
||||
Point.Origin = { x: 0, y: 0 };
|
||||
(function (Point) {
|
||||
Point.Origin = ""; //expected duplicate identifier error
|
||||
})(Point || (Point = {}));
|
||||
@@ -41,9 +41,9 @@ var A;
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
Point.Origin = { x: 0, y: 0 };
|
||||
return Point;
|
||||
}());
|
||||
Point.Origin = { x: 0, y: 0 };
|
||||
A.Point = Point;
|
||||
(function (Point) {
|
||||
Point.Origin = ""; //expected duplicate identifier error
|
||||
|
||||
+2
-2
@@ -28,9 +28,9 @@ var Point = (function () {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
Point.Origin = { x: 0, y: 0 };
|
||||
return Point;
|
||||
}());
|
||||
Point.Origin = { x: 0, y: 0 };
|
||||
(function (Point) {
|
||||
var Origin = ""; // not an error, since not exported
|
||||
})(Point || (Point = {}));
|
||||
@@ -41,9 +41,9 @@ var A;
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
Point.Origin = { x: 0, y: 0 };
|
||||
return Point;
|
||||
}());
|
||||
Point.Origin = { x: 0, y: 0 };
|
||||
A.Point = Point;
|
||||
(function (Point) {
|
||||
var Origin = ""; // not an error since not exported
|
||||
|
||||
@@ -7,6 +7,6 @@ class AtomicNumbers {
|
||||
var AtomicNumbers = (function () {
|
||||
function AtomicNumbers() {
|
||||
}
|
||||
AtomicNumbers.H = 1;
|
||||
return AtomicNumbers;
|
||||
}());
|
||||
AtomicNumbers.H = 1;
|
||||
|
||||
+3
-3
@@ -6,7 +6,7 @@
|
||||
"0": {
|
||||
"kind": "JSDocParameterTag",
|
||||
"pos": 8,
|
||||
"end": 27,
|
||||
"end": 28,
|
||||
"atToken": {
|
||||
"kind": "AtToken",
|
||||
"pos": 8,
|
||||
@@ -34,7 +34,7 @@
|
||||
"end": 27,
|
||||
"text": "name1"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 22,
|
||||
"end": 27,
|
||||
@@ -44,6 +44,6 @@
|
||||
},
|
||||
"length": 1,
|
||||
"pos": 8,
|
||||
"end": 27
|
||||
"end": 28
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -6,7 +6,7 @@
|
||||
"0": {
|
||||
"kind": "JSDocParameterTag",
|
||||
"pos": 8,
|
||||
"end": 32,
|
||||
"end": 33,
|
||||
"atToken": {
|
||||
"kind": "AtToken",
|
||||
"pos": 8,
|
||||
@@ -34,7 +34,7 @@
|
||||
"end": 32,
|
||||
"text": "name1"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 27,
|
||||
"end": 32,
|
||||
@@ -44,6 +44,6 @@
|
||||
},
|
||||
"length": 1,
|
||||
"pos": 8,
|
||||
"end": 32
|
||||
"end": 33
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
"0": {
|
||||
"kind": "JSDocParameterTag",
|
||||
"pos": 8,
|
||||
"end": 29,
|
||||
"end": 30,
|
||||
"atToken": {
|
||||
"kind": "AtToken",
|
||||
"pos": 8,
|
||||
@@ -34,7 +34,7 @@
|
||||
"end": 29,
|
||||
"text": "name1"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 24,
|
||||
"end": 29,
|
||||
@@ -44,6 +44,6 @@
|
||||
},
|
||||
"length": 1,
|
||||
"pos": 8,
|
||||
"end": 29
|
||||
"end": 30
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
"0": {
|
||||
"kind": "JSDocParameterTag",
|
||||
"pos": 8,
|
||||
"end": 29,
|
||||
"end": 30,
|
||||
"atToken": {
|
||||
"kind": "AtToken",
|
||||
"pos": 8,
|
||||
@@ -34,7 +34,7 @@
|
||||
"end": 29,
|
||||
"text": "name1"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 24,
|
||||
"end": 29,
|
||||
@@ -44,6 +44,6 @@
|
||||
},
|
||||
"length": 1,
|
||||
"pos": 8,
|
||||
"end": 29
|
||||
"end": 30
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -34,7 +34,7 @@
|
||||
"end": 30,
|
||||
"text": "name1"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 25,
|
||||
"end": 30,
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@
|
||||
"end": 31,
|
||||
"text": "name1"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 26,
|
||||
"end": 31,
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@
|
||||
"end": 28
|
||||
}
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 15,
|
||||
"end": 20,
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@
|
||||
"end": 28
|
||||
}
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 15,
|
||||
"end": 20,
|
||||
|
||||
+3
-3
@@ -6,7 +6,7 @@
|
||||
"0": {
|
||||
"kind": "JSDocParameterTag",
|
||||
"pos": 8,
|
||||
"end": 18,
|
||||
"end": 19,
|
||||
"atToken": {
|
||||
"kind": "AtToken",
|
||||
"pos": 8,
|
||||
@@ -24,7 +24,7 @@
|
||||
"end": 18,
|
||||
"text": "foo"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 15,
|
||||
"end": 18,
|
||||
@@ -34,6 +34,6 @@
|
||||
},
|
||||
"length": 1,
|
||||
"pos": 8,
|
||||
"end": 18
|
||||
"end": 19
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -6,7 +6,7 @@
|
||||
"0": {
|
||||
"kind": "JSDocParameterTag",
|
||||
"pos": 8,
|
||||
"end": 29,
|
||||
"end": 32,
|
||||
"atToken": {
|
||||
"kind": "AtToken",
|
||||
"pos": 8,
|
||||
@@ -34,7 +34,7 @@
|
||||
"end": 29,
|
||||
"text": "name1"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 24,
|
||||
"end": 29,
|
||||
@@ -45,7 +45,7 @@
|
||||
"1": {
|
||||
"kind": "JSDocParameterTag",
|
||||
"pos": 34,
|
||||
"end": 55,
|
||||
"end": 56,
|
||||
"atToken": {
|
||||
"kind": "AtToken",
|
||||
"pos": 34,
|
||||
@@ -73,7 +73,7 @@
|
||||
"end": 55,
|
||||
"text": "name2"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 50,
|
||||
"end": 55,
|
||||
@@ -83,6 +83,6 @@
|
||||
},
|
||||
"length": 2,
|
||||
"pos": 8,
|
||||
"end": 55
|
||||
"end": 56
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -6,7 +6,7 @@
|
||||
"0": {
|
||||
"kind": "JSDocParameterTag",
|
||||
"pos": 8,
|
||||
"end": 29,
|
||||
"end": 30,
|
||||
"atToken": {
|
||||
"kind": "AtToken",
|
||||
"pos": 8,
|
||||
@@ -34,7 +34,7 @@
|
||||
"end": 29,
|
||||
"text": "name1"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 24,
|
||||
"end": 29,
|
||||
@@ -45,7 +45,7 @@
|
||||
"1": {
|
||||
"kind": "JSDocParameterTag",
|
||||
"pos": 30,
|
||||
"end": 51,
|
||||
"end": 52,
|
||||
"atToken": {
|
||||
"kind": "AtToken",
|
||||
"pos": 30,
|
||||
@@ -73,7 +73,7 @@
|
||||
"end": 51,
|
||||
"text": "name2"
|
||||
},
|
||||
"parameterName": {
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 46,
|
||||
"end": 51,
|
||||
@@ -83,6 +83,6 @@
|
||||
},
|
||||
"length": 2,
|
||||
"pos": 8,
|
||||
"end": 51
|
||||
"end": 52
|
||||
}
|
||||
}
|
||||
+24
-12
@@ -82,12 +82,6 @@
|
||||
"end": 56,
|
||||
"text": "property"
|
||||
},
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 66,
|
||||
"end": 69,
|
||||
"text": "age"
|
||||
},
|
||||
"typeExpression": {
|
||||
"kind": "JSDocTypeExpression",
|
||||
"pos": 57,
|
||||
@@ -97,6 +91,18 @@
|
||||
"pos": 58,
|
||||
"end": 64
|
||||
}
|
||||
},
|
||||
"postParameterName": {
|
||||
"kind": "Identifier",
|
||||
"pos": 66,
|
||||
"end": 69,
|
||||
"text": "age"
|
||||
},
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 66,
|
||||
"end": 69,
|
||||
"text": "age"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -114,12 +120,6 @@
|
||||
"end": 83,
|
||||
"text": "property"
|
||||
},
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 93,
|
||||
"end": 97,
|
||||
"text": "name"
|
||||
},
|
||||
"typeExpression": {
|
||||
"kind": "JSDocTypeExpression",
|
||||
"pos": 84,
|
||||
@@ -129,6 +129,18 @@
|
||||
"pos": 85,
|
||||
"end": 91
|
||||
}
|
||||
},
|
||||
"postParameterName": {
|
||||
"kind": "Identifier",
|
||||
"pos": 93,
|
||||
"end": 97,
|
||||
"text": "name"
|
||||
},
|
||||
"name": {
|
||||
"kind": "Identifier",
|
||||
"pos": 93,
|
||||
"end": 97,
|
||||
"text": "name"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -4,5 +4,4 @@ export const a = 1;
|
||||
|
||||
//// [alwaysStrictModule3.js]
|
||||
// module ES2015
|
||||
// module ES2015
|
||||
export var a = 1;
|
||||
|
||||
@@ -4,5 +4,4 @@ export const a = 1;
|
||||
|
||||
//// [alwaysStrictModule5.js]
|
||||
// Targeting ES6
|
||||
// Targeting ES6
|
||||
export const a = 1;
|
||||
|
||||
@@ -39,9 +39,9 @@ define(["require", "exports"], function (require, exports) {
|
||||
function C1() {
|
||||
this.m1 = 42;
|
||||
}
|
||||
C1.s1 = true;
|
||||
return C1;
|
||||
}());
|
||||
C1.s1 = true;
|
||||
exports.C1 = C1;
|
||||
var E1;
|
||||
(function (E1) {
|
||||
|
||||
@@ -42,9 +42,9 @@ var Point = (function () {
|
||||
Point.prototype.getDist = function () {
|
||||
return Math.sqrt(this.x * this.x + this.y * this.y);
|
||||
};
|
||||
Point.origin = new Point(0, 0);
|
||||
return Point;
|
||||
}());
|
||||
Point.origin = new Point(0, 0);
|
||||
var Point3D = (function (_super) {
|
||||
__extends(Point3D, _super);
|
||||
function Point3D(x, y, z, m) {
|
||||
|
||||
@@ -27,9 +27,9 @@ var C;
|
||||
var Name = (function () {
|
||||
function Name(parameters) {
|
||||
}
|
||||
Name.funcData = A.AA.func();
|
||||
Name.someConst = A.AA.foo;
|
||||
return Name;
|
||||
}());
|
||||
Name.funcData = A.AA.func();
|
||||
Name.someConst = A.AA.foo;
|
||||
C.Name = Name;
|
||||
})(C || (C = {}));
|
||||
|
||||
@@ -177,9 +177,9 @@ function foo10() {
|
||||
var A = (function () {
|
||||
function A() {
|
||||
}
|
||||
A.a = x;
|
||||
return A;
|
||||
}());
|
||||
A.a = x;
|
||||
var x;
|
||||
}
|
||||
function foo11() {
|
||||
|
||||
@@ -144,7 +144,6 @@ for (const y = 0; y < 1;) {
|
||||
|
||||
//// [capturedLetConstInLoop4_ES6.js]
|
||||
//======let
|
||||
//======let
|
||||
export function exportedFoo() {
|
||||
return v0 + v00 + v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
//// [0.js]
|
||||
// @ts-check
|
||||
/**
|
||||
* @param {number=} n
|
||||
* @param {string} [s]
|
||||
*/
|
||||
function foo(n, s) {}
|
||||
|
||||
foo();
|
||||
foo(1);
|
||||
foo(1, "hi");
|
||||
|
||||
//// [0.js]
|
||||
// @ts-check
|
||||
/**
|
||||
* @param {number=} n
|
||||
* @param {string} [s]
|
||||
*/
|
||||
function foo(n, s) { }
|
||||
foo();
|
||||
foo(1);
|
||||
foo(1, "hi");
|
||||
@@ -0,0 +1,20 @@
|
||||
=== tests/cases/conformance/jsdoc/0.js ===
|
||||
// @ts-check
|
||||
/**
|
||||
* @param {number=} n
|
||||
* @param {string} [s]
|
||||
*/
|
||||
function foo(n, s) {}
|
||||
>foo : Symbol(foo, Decl(0.js, 0, 0))
|
||||
>n : Symbol(n, Decl(0.js, 5, 13))
|
||||
>s : Symbol(s, Decl(0.js, 5, 15))
|
||||
|
||||
foo();
|
||||
>foo : Symbol(foo, Decl(0.js, 0, 0))
|
||||
|
||||
foo(1);
|
||||
>foo : Symbol(foo, Decl(0.js, 0, 0))
|
||||
|
||||
foo(1, "hi");
|
||||
>foo : Symbol(foo, Decl(0.js, 0, 0))
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
=== tests/cases/conformance/jsdoc/0.js ===
|
||||
// @ts-check
|
||||
/**
|
||||
* @param {number=} n
|
||||
* @param {string} [s]
|
||||
*/
|
||||
function foo(n, s) {}
|
||||
>foo : (n?: number, s?: string) => void
|
||||
>n : number
|
||||
>s : string
|
||||
|
||||
foo();
|
||||
>foo() : void
|
||||
>foo : (n?: number, s?: string) => void
|
||||
|
||||
foo(1);
|
||||
>foo(1) : void
|
||||
>foo : (n?: number, s?: string) => void
|
||||
>1 : 1
|
||||
|
||||
foo(1, "hi");
|
||||
>foo(1, "hi") : void
|
||||
>foo : (n?: number, s?: string) => void
|
||||
>1 : 1
|
||||
>"hi" : "hi"
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
//// [returns.js]
|
||||
// @ts-check
|
||||
/**
|
||||
* @returns {string} This comment is not currently exposed
|
||||
*/
|
||||
function f() {
|
||||
return "hello";
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string=} This comment is not currently exposed
|
||||
*/
|
||||
function f1() {
|
||||
return "hello world";
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string|number} This comment is not currently exposed
|
||||
*/
|
||||
function f2() {
|
||||
return 5 || "hello";
|
||||
}
|
||||
|
||||
//// [dummy.js]
|
||||
// @ts-check
|
||||
/**
|
||||
* @returns {string} This comment is not currently exposed
|
||||
*/
|
||||
function f() {
|
||||
return "hello";
|
||||
}
|
||||
/**
|
||||
* @returns {string=} This comment is not currently exposed
|
||||
*/
|
||||
function f1() {
|
||||
return "hello world";
|
||||
}
|
||||
/**
|
||||
* @returns {string|number} This comment is not currently exposed
|
||||
*/
|
||||
function f2() {
|
||||
return 5 || "hello";
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
=== tests/cases/conformance/jsdoc/returns.js ===
|
||||
// @ts-check
|
||||
/**
|
||||
* @returns {string} This comment is not currently exposed
|
||||
*/
|
||||
function f() {
|
||||
>f : Symbol(f, Decl(returns.js, 0, 0))
|
||||
|
||||
return "hello";
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string=} This comment is not currently exposed
|
||||
*/
|
||||
function f1() {
|
||||
>f1 : Symbol(f1, Decl(returns.js, 6, 1))
|
||||
|
||||
return "hello world";
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string|number} This comment is not currently exposed
|
||||
*/
|
||||
function f2() {
|
||||
>f2 : Symbol(f2, Decl(returns.js, 13, 1))
|
||||
|
||||
return 5 || "hello";
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
=== tests/cases/conformance/jsdoc/returns.js ===
|
||||
// @ts-check
|
||||
/**
|
||||
* @returns {string} This comment is not currently exposed
|
||||
*/
|
||||
function f() {
|
||||
>f : () => string
|
||||
|
||||
return "hello";
|
||||
>"hello" : "hello"
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string=} This comment is not currently exposed
|
||||
*/
|
||||
function f1() {
|
||||
>f1 : () => string
|
||||
|
||||
return "hello world";
|
||||
>"hello world" : "hello world"
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string|number} This comment is not currently exposed
|
||||
*/
|
||||
function f2() {
|
||||
>f2 : () => string | number
|
||||
|
||||
return 5 || "hello";
|
||||
>5 || "hello" : "hello" | 5
|
||||
>5 : 5
|
||||
>"hello" : "hello"
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//// [returns.js]
|
||||
// @ts-check
|
||||
/**
|
||||
* @returns {string} This comment is not currently exposed
|
||||
*/
|
||||
function f() {
|
||||
return 5;
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string | number} This comment is not currently exposed
|
||||
*/
|
||||
function f1() {
|
||||
return 5 || true;
|
||||
}
|
||||
|
||||
//// [dummy.js]
|
||||
// @ts-check
|
||||
/**
|
||||
* @returns {string} This comment is not currently exposed
|
||||
*/
|
||||
function f() {
|
||||
return 5;
|
||||
}
|
||||
/**
|
||||
* @returns {string | number} This comment is not currently exposed
|
||||
*/
|
||||
function f1() {
|
||||
return 5 || true;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
=== tests/cases/conformance/jsdoc/returns.js ===
|
||||
// @ts-check
|
||||
/**
|
||||
* @returns {string} This comment is not currently exposed
|
||||
*/
|
||||
function f() {
|
||||
>f : Symbol(f, Decl(returns.js, 0, 0))
|
||||
|
||||
return 5;
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string | number} This comment is not currently exposed
|
||||
*/
|
||||
function f1() {
|
||||
>f1 : Symbol(f1, Decl(returns.js, 6, 1))
|
||||
|
||||
return 5 || true;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
=== tests/cases/conformance/jsdoc/returns.js ===
|
||||
// @ts-check
|
||||
/**
|
||||
* @returns {string} This comment is not currently exposed
|
||||
*/
|
||||
function f() {
|
||||
>f : () => string
|
||||
|
||||
return 5;
|
||||
>5 : 5
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string | number} This comment is not currently exposed
|
||||
*/
|
||||
function f1() {
|
||||
>f1 : () => string | number
|
||||
|
||||
return 5 || true;
|
||||
>5 || true : true | 5
|
||||
>5 : 5
|
||||
>true : true
|
||||
}
|
||||
+19
@@ -1,7 +1,14 @@
|
||||
//// [0.js]
|
||||
// @ts-check
|
||||
/** @type {String} */
|
||||
var S = "hello world";
|
||||
|
||||
/** @type {number} */
|
||||
var n = 10;
|
||||
|
||||
/** @type {*} */
|
||||
var anyT = 2;
|
||||
anyT = "hello";
|
||||
|
||||
/** @type {?} */
|
||||
var anyT1 = 2;
|
||||
@@ -11,6 +18,10 @@ anyT1 = "hi";
|
||||
const x = (a) => a + 1;
|
||||
x(1);
|
||||
|
||||
/** @type {function} */
|
||||
const y = (a) => a + 1;
|
||||
x(1);
|
||||
|
||||
/** @type {function (number)} */
|
||||
const x1 = (a) => a + 1;
|
||||
x1(0);
|
||||
@@ -21,14 +32,22 @@ x2(0);
|
||||
|
||||
//// [0.js]
|
||||
// @ts-check
|
||||
/** @type {String} */
|
||||
var S = "hello world";
|
||||
/** @type {number} */
|
||||
var n = 10;
|
||||
/** @type {*} */
|
||||
var anyT = 2;
|
||||
anyT = "hello";
|
||||
/** @type {?} */
|
||||
var anyT1 = 2;
|
||||
anyT1 = "hi";
|
||||
/** @type {Function} */
|
||||
var x = function (a) { return a + 1; };
|
||||
x(1);
|
||||
/** @type {function} */
|
||||
var y = function (a) { return a + 1; };
|
||||
x(1);
|
||||
/** @type {function (number)} */
|
||||
var x1 = function (a) { return a + 1; };
|
||||
x1(0);
|
||||
@@ -0,0 +1,60 @@
|
||||
=== tests/cases/conformance/jsdoc/0.js ===
|
||||
// @ts-check
|
||||
/** @type {String} */
|
||||
var S = "hello world";
|
||||
>S : Symbol(S, Decl(0.js, 2, 3))
|
||||
|
||||
/** @type {number} */
|
||||
var n = 10;
|
||||
>n : Symbol(n, Decl(0.js, 5, 3))
|
||||
|
||||
/** @type {*} */
|
||||
var anyT = 2;
|
||||
>anyT : Symbol(anyT, Decl(0.js, 8, 3))
|
||||
|
||||
anyT = "hello";
|
||||
>anyT : Symbol(anyT, Decl(0.js, 8, 3))
|
||||
|
||||
/** @type {?} */
|
||||
var anyT1 = 2;
|
||||
>anyT1 : Symbol(anyT1, Decl(0.js, 12, 3))
|
||||
|
||||
anyT1 = "hi";
|
||||
>anyT1 : Symbol(anyT1, Decl(0.js, 12, 3))
|
||||
|
||||
/** @type {Function} */
|
||||
const x = (a) => a + 1;
|
||||
>x : Symbol(x, Decl(0.js, 16, 5))
|
||||
>a : Symbol(a, Decl(0.js, 16, 11))
|
||||
>a : Symbol(a, Decl(0.js, 16, 11))
|
||||
|
||||
x(1);
|
||||
>x : Symbol(x, Decl(0.js, 16, 5))
|
||||
|
||||
/** @type {function} */
|
||||
const y = (a) => a + 1;
|
||||
>y : Symbol(y, Decl(0.js, 20, 5))
|
||||
>a : Symbol(a, Decl(0.js, 20, 11))
|
||||
>a : Symbol(a, Decl(0.js, 20, 11))
|
||||
|
||||
x(1);
|
||||
>x : Symbol(x, Decl(0.js, 16, 5))
|
||||
|
||||
/** @type {function (number)} */
|
||||
const x1 = (a) => a + 1;
|
||||
>x1 : Symbol(x1, Decl(0.js, 24, 5))
|
||||
>a : Symbol(a, Decl(0.js, 24, 12))
|
||||
>a : Symbol(a, Decl(0.js, 24, 12))
|
||||
|
||||
x1(0);
|
||||
>x1 : Symbol(x1, Decl(0.js, 24, 5))
|
||||
|
||||
/** @type {function (number): number} */
|
||||
const x2 = (a) => a + 1;
|
||||
>x2 : Symbol(x2, Decl(0.js, 28, 5))
|
||||
>a : Symbol(a, Decl(0.js, 28, 12))
|
||||
>a : Symbol(a, Decl(0.js, 28, 12))
|
||||
|
||||
x2(0);
|
||||
>x2 : Symbol(x2, Decl(0.js, 28, 5))
|
||||
|
||||
+30
-1
@@ -1,10 +1,25 @@
|
||||
=== tests/cases/conformance/salsa/0.js ===
|
||||
=== tests/cases/conformance/jsdoc/0.js ===
|
||||
// @ts-check
|
||||
/** @type {String} */
|
||||
var S = "hello world";
|
||||
>S : string
|
||||
>"hello world" : "hello world"
|
||||
|
||||
/** @type {number} */
|
||||
var n = 10;
|
||||
>n : number
|
||||
>10 : 10
|
||||
|
||||
/** @type {*} */
|
||||
var anyT = 2;
|
||||
>anyT : any
|
||||
>2 : 2
|
||||
|
||||
anyT = "hello";
|
||||
>anyT = "hello" : "hello"
|
||||
>anyT : any
|
||||
>"hello" : "hello"
|
||||
|
||||
/** @type {?} */
|
||||
var anyT1 = 2;
|
||||
>anyT1 : any
|
||||
@@ -29,6 +44,20 @@ x(1);
|
||||
>x : Function
|
||||
>1 : 1
|
||||
|
||||
/** @type {function} */
|
||||
const y = (a) => a + 1;
|
||||
>y : Function
|
||||
>(a) => a + 1 : (a: any) => any
|
||||
>a : any
|
||||
>a + 1 : any
|
||||
>a : any
|
||||
>1 : 1
|
||||
|
||||
x(1);
|
||||
>x(1) : any
|
||||
>x : Function
|
||||
>1 : 1
|
||||
|
||||
/** @type {function (number)} */
|
||||
const x1 = (a) => a + 1;
|
||||
>x1 : (arg0: number) => any
|
||||
@@ -0,0 +1,42 @@
|
||||
tests/cases/conformance/jsdoc/0.js(3,5): error TS2322: Type 'true' is not assignable to type 'string'.
|
||||
tests/cases/conformance/jsdoc/0.js(6,5): error TS2322: Type '"hello"' is not assignable to type 'number'.
|
||||
tests/cases/conformance/jsdoc/0.js(10,4): error TS2345: Argument of type '"string"' is not assignable to parameter of type 'number'.
|
||||
tests/cases/conformance/jsdoc/0.js(13,7): error TS2451: Cannot redeclare block-scoped variable 'x2'.
|
||||
tests/cases/conformance/jsdoc/0.js(17,1): error TS2322: Type 'number' is not assignable to type 'string'.
|
||||
tests/cases/conformance/jsdoc/0.js(20,7): error TS2451: Cannot redeclare block-scoped variable 'x2'.
|
||||
|
||||
|
||||
==== tests/cases/conformance/jsdoc/0.js (6 errors) ====
|
||||
// @ts-check
|
||||
/** @type {String} */
|
||||
var S = true;
|
||||
~
|
||||
!!! error TS2322: Type 'true' is not assignable to type 'string'.
|
||||
|
||||
/** @type {number} */
|
||||
var n = "hello";
|
||||
~
|
||||
!!! error TS2322: Type '"hello"' is not assignable to type 'number'.
|
||||
|
||||
/** @type {function (number)} */
|
||||
const x1 = (a) => a + 1;
|
||||
x1("string");
|
||||
~~~~~~~~
|
||||
!!! error TS2345: Argument of type '"string"' is not assignable to parameter of type 'number'.
|
||||
|
||||
/** @type {function (number): number} */
|
||||
const x2 = (a) => a + 1;
|
||||
~~
|
||||
!!! error TS2451: Cannot redeclare block-scoped variable 'x2'.
|
||||
|
||||
/** @type {string} */
|
||||
var a;
|
||||
a = x2(0);
|
||||
~
|
||||
!!! error TS2322: Type 'number' is not assignable to type 'string'.
|
||||
|
||||
/** @type {function (number): number} */
|
||||
const x2 = (a) => a.concat("hi");
|
||||
~~
|
||||
!!! error TS2451: Cannot redeclare block-scoped variable 'x2'.
|
||||
x2(0);
|
||||
@@ -0,0 +1,40 @@
|
||||
//// [0.js]
|
||||
// @ts-check
|
||||
/** @type {String} */
|
||||
var S = true;
|
||||
|
||||
/** @type {number} */
|
||||
var n = "hello";
|
||||
|
||||
/** @type {function (number)} */
|
||||
const x1 = (a) => a + 1;
|
||||
x1("string");
|
||||
|
||||
/** @type {function (number): number} */
|
||||
const x2 = (a) => a + 1;
|
||||
|
||||
/** @type {string} */
|
||||
var a;
|
||||
a = x2(0);
|
||||
|
||||
/** @type {function (number): number} */
|
||||
const x2 = (a) => a.concat("hi");
|
||||
x2(0);
|
||||
|
||||
//// [0.js]
|
||||
// @ts-check
|
||||
/** @type {String} */
|
||||
var S = true;
|
||||
/** @type {number} */
|
||||
var n = "hello";
|
||||
/** @type {function (number)} */
|
||||
var x1 = function (a) { return a + 1; };
|
||||
x1("string");
|
||||
/** @type {function (number): number} */
|
||||
var x2 = function (a) { return a + 1; };
|
||||
/** @type {string} */
|
||||
var a;
|
||||
a = x2(0);
|
||||
/** @type {function (number): number} */
|
||||
var x2 = function (a) { return a.concat("hi"); };
|
||||
x2(0);
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
tests/cases/conformance/salsa/0.js(5,4): error TS2345: Argument of type '"string"' is not assignable to parameter of type 'number'.
|
||||
tests/cases/conformance/salsa/0.js(12,1): error TS2322: Type 'number' is not assignable to type 'string'.
|
||||
tests/cases/conformance/jsdoc/0.js(5,4): error TS2345: Argument of type '"string"' is not assignable to parameter of type 'number'.
|
||||
tests/cases/conformance/jsdoc/0.js(12,1): error TS2322: Type 'number' is not assignable to type 'string'.
|
||||
|
||||
|
||||
==== tests/cases/conformance/salsa/0.js (2 errors) ====
|
||||
==== tests/cases/conformance/jsdoc/0.js (2 errors) ====
|
||||
// @ts-check
|
||||
|
||||
/** @type {function (number)} */
|
||||
@@ -0,0 +1,84 @@
|
||||
//// [0.js]
|
||||
// @ts-check
|
||||
/**
|
||||
* @typedef {Object} Opts
|
||||
* @property {string} x
|
||||
* @property {string=} y
|
||||
* @property {string} [z]
|
||||
* @property {string} [w="hi"]
|
||||
*
|
||||
* @param {Opts} opts
|
||||
*/
|
||||
function foo(opts) {
|
||||
opts.x;
|
||||
}
|
||||
|
||||
foo({x: 'abc'});
|
||||
|
||||
/**
|
||||
* @typedef {Object} AnotherOpts
|
||||
* @property anotherX {string}
|
||||
* @property anotherY {string=}
|
||||
*
|
||||
* @param {AnotherOpts} opts
|
||||
*/
|
||||
function foo1(opts) {
|
||||
opts.anotherX;
|
||||
}
|
||||
|
||||
foo1({anotherX: "world"});
|
||||
|
||||
/**
|
||||
* @typedef {object} Opts1
|
||||
* @property {string} x
|
||||
* @property {string=} y
|
||||
* @property {string} [z]
|
||||
* @property {string} [w="hi"]
|
||||
*
|
||||
* @param {Opts1} opts
|
||||
*/
|
||||
function foo2(opts) {
|
||||
opts.x;
|
||||
}
|
||||
foo2({x: 'abc'});
|
||||
|
||||
|
||||
//// [0.js]
|
||||
// @ts-check
|
||||
/**
|
||||
* @typedef {Object} Opts
|
||||
* @property {string} x
|
||||
* @property {string=} y
|
||||
* @property {string} [z]
|
||||
* @property {string} [w="hi"]
|
||||
*
|
||||
* @param {Opts} opts
|
||||
*/
|
||||
function foo(opts) {
|
||||
opts.x;
|
||||
}
|
||||
foo({ x: 'abc' });
|
||||
/**
|
||||
* @typedef {Object} AnotherOpts
|
||||
* @property anotherX {string}
|
||||
* @property anotherY {string=}
|
||||
*
|
||||
* @param {AnotherOpts} opts
|
||||
*/
|
||||
function foo1(opts) {
|
||||
opts.anotherX;
|
||||
}
|
||||
foo1({ anotherX: "world" });
|
||||
/**
|
||||
* @typedef {object} Opts1
|
||||
* @property {string} x
|
||||
* @property {string=} y
|
||||
* @property {string} [z]
|
||||
* @property {string} [w="hi"]
|
||||
*
|
||||
* @param {Opts1} opts
|
||||
*/
|
||||
function foo2(opts) {
|
||||
opts.x;
|
||||
}
|
||||
foo2({ x: 'abc' });
|
||||
@@ -0,0 +1,68 @@
|
||||
=== tests/cases/conformance/jsdoc/0.js ===
|
||||
// @ts-check
|
||||
/**
|
||||
* @typedef {Object} Opts
|
||||
* @property {string} x
|
||||
* @property {string=} y
|
||||
* @property {string} [z]
|
||||
* @property {string} [w="hi"]
|
||||
*
|
||||
* @param {Opts} opts
|
||||
*/
|
||||
function foo(opts) {
|
||||
>foo : Symbol(foo, Decl(0.js, 0, 0))
|
||||
>opts : Symbol(opts, Decl(0.js, 10, 13))
|
||||
|
||||
opts.x;
|
||||
>opts.x : Symbol(x, Decl(0.js, 3, 3))
|
||||
>opts : Symbol(opts, Decl(0.js, 10, 13))
|
||||
>x : Symbol(x, Decl(0.js, 3, 3))
|
||||
}
|
||||
|
||||
foo({x: 'abc'});
|
||||
>foo : Symbol(foo, Decl(0.js, 0, 0))
|
||||
>x : Symbol(x, Decl(0.js, 14, 5))
|
||||
|
||||
/**
|
||||
* @typedef {Object} AnotherOpts
|
||||
* @property anotherX {string}
|
||||
* @property anotherY {string=}
|
||||
*
|
||||
* @param {AnotherOpts} opts
|
||||
*/
|
||||
function foo1(opts) {
|
||||
>foo1 : Symbol(foo1, Decl(0.js, 14, 16))
|
||||
>opts : Symbol(opts, Decl(0.js, 23, 14))
|
||||
|
||||
opts.anotherX;
|
||||
>opts.anotherX : Symbol(anotherX, Decl(0.js, 18, 3))
|
||||
>opts : Symbol(opts, Decl(0.js, 23, 14))
|
||||
>anotherX : Symbol(anotherX, Decl(0.js, 18, 3))
|
||||
}
|
||||
|
||||
foo1({anotherX: "world"});
|
||||
>foo1 : Symbol(foo1, Decl(0.js, 14, 16))
|
||||
>anotherX : Symbol(anotherX, Decl(0.js, 27, 6))
|
||||
|
||||
/**
|
||||
* @typedef {object} Opts1
|
||||
* @property {string} x
|
||||
* @property {string=} y
|
||||
* @property {string} [z]
|
||||
* @property {string} [w="hi"]
|
||||
*
|
||||
* @param {Opts1} opts
|
||||
*/
|
||||
function foo2(opts) {
|
||||
>foo2 : Symbol(foo2, Decl(0.js, 27, 26))
|
||||
>opts : Symbol(opts, Decl(0.js, 38, 14))
|
||||
|
||||
opts.x;
|
||||
>opts.x : Symbol(x, Decl(0.js, 31, 3))
|
||||
>opts : Symbol(opts, Decl(0.js, 38, 14))
|
||||
>x : Symbol(x, Decl(0.js, 31, 3))
|
||||
}
|
||||
foo2({x: 'abc'});
|
||||
>foo2 : Symbol(foo2, Decl(0.js, 27, 26))
|
||||
>x : Symbol(x, Decl(0.js, 41, 6))
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
=== tests/cases/conformance/jsdoc/0.js ===
|
||||
// @ts-check
|
||||
/**
|
||||
* @typedef {Object} Opts
|
||||
* @property {string} x
|
||||
* @property {string=} y
|
||||
* @property {string} [z]
|
||||
* @property {string} [w="hi"]
|
||||
*
|
||||
* @param {Opts} opts
|
||||
*/
|
||||
function foo(opts) {
|
||||
>foo : (opts: { x: string; y?: string; z?: string; w?: string; }) => void
|
||||
>opts : { x: string; y?: string; z?: string; w?: string; }
|
||||
|
||||
opts.x;
|
||||
>opts.x : string
|
||||
>opts : { x: string; y?: string; z?: string; w?: string; }
|
||||
>x : string
|
||||
}
|
||||
|
||||
foo({x: 'abc'});
|
||||
>foo({x: 'abc'}) : void
|
||||
>foo : (opts: { x: string; y?: string; z?: string; w?: string; }) => void
|
||||
>{x: 'abc'} : { x: string; }
|
||||
>x : string
|
||||
>'abc' : "abc"
|
||||
|
||||
/**
|
||||
* @typedef {Object} AnotherOpts
|
||||
* @property anotherX {string}
|
||||
* @property anotherY {string=}
|
||||
*
|
||||
* @param {AnotherOpts} opts
|
||||
*/
|
||||
function foo1(opts) {
|
||||
>foo1 : (opts: { anotherX: string; anotherY?: string; }) => void
|
||||
>opts : { anotherX: string; anotherY?: string; }
|
||||
|
||||
opts.anotherX;
|
||||
>opts.anotherX : string
|
||||
>opts : { anotherX: string; anotherY?: string; }
|
||||
>anotherX : string
|
||||
}
|
||||
|
||||
foo1({anotherX: "world"});
|
||||
>foo1({anotherX: "world"}) : void
|
||||
>foo1 : (opts: { anotherX: string; anotherY?: string; }) => void
|
||||
>{anotherX: "world"} : { anotherX: string; }
|
||||
>anotherX : string
|
||||
>"world" : "world"
|
||||
|
||||
/**
|
||||
* @typedef {object} Opts1
|
||||
* @property {string} x
|
||||
* @property {string=} y
|
||||
* @property {string} [z]
|
||||
* @property {string} [w="hi"]
|
||||
*
|
||||
* @param {Opts1} opts
|
||||
*/
|
||||
function foo2(opts) {
|
||||
>foo2 : (opts: { x: string; y?: string; z?: string; w?: string; }) => void
|
||||
>opts : { x: string; y?: string; z?: string; w?: string; }
|
||||
|
||||
opts.x;
|
||||
>opts.x : string
|
||||
>opts : { x: string; y?: string; z?: string; w?: string; }
|
||||
>x : string
|
||||
}
|
||||
foo2({x: 'abc'});
|
||||
>foo2({x: 'abc'}) : void
|
||||
>foo2 : (opts: { x: string; y?: string; z?: string; w?: string; }) => void
|
||||
>{x: 'abc'} : { x: string; }
|
||||
>x : string
|
||||
>'abc' : "abc"
|
||||
|
||||
@@ -5,6 +5,6 @@ class foo { constructor() { static f = 3; } }
|
||||
var foo = (function () {
|
||||
function foo() {
|
||||
}
|
||||
foo.f = 3;
|
||||
return foo;
|
||||
}());
|
||||
foo.f = 3;
|
||||
|
||||
@@ -62,9 +62,9 @@ function f(b) {
|
||||
Foo.prototype.m = function () {
|
||||
new Foo();
|
||||
};
|
||||
Foo.y = new Foo();
|
||||
return Foo;
|
||||
}());
|
||||
Foo_1.y = new Foo_1();
|
||||
new Foo_1();
|
||||
}
|
||||
var _a;
|
||||
|
||||
@@ -12,10 +12,10 @@ var v = ;
|
||||
var C = (function () {
|
||||
function C() {
|
||||
}
|
||||
C.p = 1;
|
||||
C = __decorate([
|
||||
decorate
|
||||
], C);
|
||||
return C;
|
||||
}());
|
||||
C.p = 1;
|
||||
C = __decorate([
|
||||
decorate
|
||||
], C);
|
||||
;
|
||||
|
||||
@@ -27,9 +27,9 @@ var CCC = (function () {
|
||||
this.y = aaa;
|
||||
this.y = ''; // was: error, cannot assign string to number
|
||||
}
|
||||
CCC.staticY = aaa; // This shouldnt be error
|
||||
return CCC;
|
||||
}());
|
||||
CCC.staticY = aaa; // This shouldnt be error
|
||||
// above is equivalent to this:
|
||||
var aaaa = 1;
|
||||
var CCCC = (function () {
|
||||
|
||||
@@ -40,12 +40,12 @@ var Test = (function () {
|
||||
console.log(field); // Using field here shouldnt be error
|
||||
};
|
||||
}
|
||||
Test.staticMessageHandler = function () {
|
||||
var field = Test.field;
|
||||
console.log(field); // Using field here shouldnt be error
|
||||
};
|
||||
return Test;
|
||||
}());
|
||||
Test.staticMessageHandler = function () {
|
||||
var field = Test.field;
|
||||
console.log(field); // Using field here shouldnt be error
|
||||
};
|
||||
var field1;
|
||||
var Test1 = (function () {
|
||||
function Test1(field1) {
|
||||
@@ -56,8 +56,8 @@ var Test1 = (function () {
|
||||
// it would resolve to private field1 and thats not what user intended here.
|
||||
};
|
||||
}
|
||||
Test1.staticMessageHandler = function () {
|
||||
console.log(field1); // This shouldnt be error as its a static property
|
||||
};
|
||||
return Test1;
|
||||
}());
|
||||
Test1.staticMessageHandler = function () {
|
||||
console.log(field1); // This shouldnt be error as its a static property
|
||||
};
|
||||
|
||||
@@ -32,9 +32,9 @@ var C = (function () {
|
||||
}
|
||||
C.prototype.c = function () { return ''; };
|
||||
C.f = function () { return ''; };
|
||||
C.g = function () { return ''; };
|
||||
return C;
|
||||
}());
|
||||
C.g = function () { return ''; };
|
||||
var c = new C();
|
||||
var r1 = c.x;
|
||||
var r2 = c.a;
|
||||
|
||||
@@ -47,9 +47,9 @@ var C = (function () {
|
||||
}
|
||||
C.prototype.c = function () { return ''; };
|
||||
C.f = function () { return ''; };
|
||||
C.g = function () { return ''; };
|
||||
return C;
|
||||
}());
|
||||
C.g = function () { return ''; };
|
||||
var D = (function (_super) {
|
||||
__extends(D, _super);
|
||||
function D() {
|
||||
|
||||
@@ -30,9 +30,9 @@ var C = (function () {
|
||||
}
|
||||
C.prototype.c = function () { return ''; };
|
||||
C.f = function () { return ''; };
|
||||
C.g = function () { return ''; };
|
||||
return C;
|
||||
}());
|
||||
C.g = function () { return ''; };
|
||||
// all of these are valid
|
||||
var c = new C();
|
||||
var r1 = c.x;
|
||||
|
||||
@@ -16,10 +16,10 @@ module Clod {
|
||||
var Clod = (function () {
|
||||
function Clod() {
|
||||
}
|
||||
Clod.x = 10;
|
||||
Clod.y = 10;
|
||||
return Clod;
|
||||
}());
|
||||
Clod.x = 10;
|
||||
Clod.y = 10;
|
||||
(function (Clod) {
|
||||
var p = Clod.x;
|
||||
var q = x;
|
||||
|
||||
@@ -29,19 +29,19 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
||||
var Remote = (function () {
|
||||
function Remote() {
|
||||
}
|
||||
Remote = __decorate([
|
||||
decorator("hello")
|
||||
], Remote);
|
||||
return Remote;
|
||||
}());
|
||||
Remote = __decorate([
|
||||
decorator("hello")
|
||||
], Remote);
|
||||
/**
|
||||
* Floating Comment
|
||||
*/
|
||||
var AnotherRomote = (function () {
|
||||
function AnotherRomote() {
|
||||
}
|
||||
AnotherRomote = __decorate([
|
||||
decorator("hi")
|
||||
], AnotherRomote);
|
||||
return AnotherRomote;
|
||||
}());
|
||||
AnotherRomote = __decorate([
|
||||
decorator("hi")
|
||||
], AnotherRomote);
|
||||
|
||||
@@ -23,13 +23,13 @@ class test {
|
||||
var test = (function () {
|
||||
function test() {
|
||||
}
|
||||
/**
|
||||
* p1 comment appears in output
|
||||
*/
|
||||
test.p1 = "";
|
||||
/**
|
||||
* p3 comment appears in output
|
||||
*/
|
||||
test.p3 = "";
|
||||
return test;
|
||||
}());
|
||||
/**
|
||||
* p1 comment appears in output
|
||||
*/
|
||||
test.p1 = "";
|
||||
/**
|
||||
* p3 comment appears in output
|
||||
*/
|
||||
test.p3 = "";
|
||||
|
||||
@@ -20,9 +20,9 @@ var C1 = (function () {
|
||||
function C1() {
|
||||
this.m1 = 42;
|
||||
}
|
||||
C1.s1 = true;
|
||||
return C1;
|
||||
}());
|
||||
C1.s1 = true;
|
||||
exports.C1 = C1;
|
||||
//// [foo_1.js]
|
||||
"use strict";
|
||||
|
||||
@@ -38,9 +38,9 @@ var C1 = (function () {
|
||||
function C1() {
|
||||
this.m1 = 42;
|
||||
}
|
||||
C1.s1 = true;
|
||||
return C1;
|
||||
}());
|
||||
C1.s1 = true;
|
||||
exports.C1 = C1;
|
||||
var E1;
|
||||
(function (E1) {
|
||||
|
||||
@@ -26,6 +26,6 @@ var C = (function () {
|
||||
this[s + n] = 2;
|
||||
this["hello bye"] = 0;
|
||||
}
|
||||
C["hello " + a + " bye"] = 0;
|
||||
return C;
|
||||
}());
|
||||
C["hello " + a + " bye"] = 0;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
tests/cases/compiler/conflictMarkerDiff3Trivia1.ts(2,1): error TS1185: Merge conflict marker encountered.
|
||||
tests/cases/compiler/conflictMarkerDiff3Trivia1.ts(4,1): error TS1185: Merge conflict marker encountered.
|
||||
tests/cases/compiler/conflictMarkerDiff3Trivia1.ts(6,1): error TS1185: Merge conflict marker encountered.
|
||||
tests/cases/compiler/conflictMarkerDiff3Trivia1.ts(8,1): error TS1185: Merge conflict marker encountered.
|
||||
|
||||
|
||||
==== tests/cases/compiler/conflictMarkerDiff3Trivia1.ts (4 errors) ====
|
||||
class C {
|
||||
<<<<<<< HEAD
|
||||
~~~~~~~
|
||||
!!! error TS1185: Merge conflict marker encountered.
|
||||
v = 1;
|
||||
||||||| merged common ancestors
|
||||
~~~~~~~
|
||||
!!! error TS1185: Merge conflict marker encountered.
|
||||
v = 3;
|
||||
=======
|
||||
~~~~~~~
|
||||
!!! error TS1185: Merge conflict marker encountered.
|
||||
v = 2;
|
||||
>>>>>>> Branch-a
|
||||
~~~~~~~
|
||||
!!! error TS1185: Merge conflict marker encountered.
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//// [conflictMarkerDiff3Trivia1.ts]
|
||||
class C {
|
||||
<<<<<<< HEAD
|
||||
v = 1;
|
||||
||||||| merged common ancestors
|
||||
v = 3;
|
||||
=======
|
||||
v = 2;
|
||||
>>>>>>> Branch-a
|
||||
}
|
||||
|
||||
//// [conflictMarkerDiff3Trivia1.js]
|
||||
var C = (function () {
|
||||
function C() {
|
||||
this.v = 1;
|
||||
}
|
||||
return C;
|
||||
}());
|
||||
@@ -0,0 +1,34 @@
|
||||
tests/cases/compiler/conflictMarkerDiff3Trivia2.ts(3,1): error TS1185: Merge conflict marker encountered.
|
||||
tests/cases/compiler/conflictMarkerDiff3Trivia2.ts(4,6): error TS2304: Cannot find name 'a'.
|
||||
tests/cases/compiler/conflictMarkerDiff3Trivia2.ts(6,1): error TS1185: Merge conflict marker encountered.
|
||||
tests/cases/compiler/conflictMarkerDiff3Trivia2.ts(9,1): error TS1185: Merge conflict marker encountered.
|
||||
tests/cases/compiler/conflictMarkerDiff3Trivia2.ts(12,1): error TS1185: Merge conflict marker encountered.
|
||||
|
||||
|
||||
==== tests/cases/compiler/conflictMarkerDiff3Trivia2.ts (5 errors) ====
|
||||
class C {
|
||||
foo() {
|
||||
<<<<<<< B
|
||||
~~~~~~~
|
||||
!!! error TS1185: Merge conflict marker encountered.
|
||||
a();
|
||||
~
|
||||
!!! error TS2304: Cannot find name 'a'.
|
||||
}
|
||||
||||||| merged common ancestors
|
||||
~~~~~~~
|
||||
!!! error TS1185: Merge conflict marker encountered.
|
||||
c();
|
||||
}
|
||||
=======
|
||||
~~~~~~~
|
||||
!!! error TS1185: Merge conflict marker encountered.
|
||||
b();
|
||||
}
|
||||
>>>>>>> A
|
||||
~~~~~~~
|
||||
!!! error TS1185: Merge conflict marker encountered.
|
||||
|
||||
public bar() { }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//// [conflictMarkerDiff3Trivia2.ts]
|
||||
class C {
|
||||
foo() {
|
||||
<<<<<<< B
|
||||
a();
|
||||
}
|
||||
||||||| merged common ancestors
|
||||
c();
|
||||
}
|
||||
=======
|
||||
b();
|
||||
}
|
||||
>>>>>>> A
|
||||
|
||||
public bar() { }
|
||||
}
|
||||
|
||||
|
||||
//// [conflictMarkerDiff3Trivia2.js]
|
||||
var C = (function () {
|
||||
function C() {
|
||||
}
|
||||
C.prototype.foo = function () {
|
||||
a();
|
||||
};
|
||||
C.prototype.bar = function () { };
|
||||
return C;
|
||||
}());
|
||||
@@ -22,8 +22,8 @@ var CtorDtor = (function () {
|
||||
var C = (function () {
|
||||
function C() {
|
||||
}
|
||||
C = __decorate([
|
||||
CtorDtor
|
||||
], C);
|
||||
return C;
|
||||
}());
|
||||
C = __decorate([
|
||||
CtorDtor
|
||||
], C);
|
||||
|
||||
@@ -39,10 +39,10 @@ var C = (function () {
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
});
|
||||
C.x = 1;
|
||||
C.y = 1;
|
||||
return C;
|
||||
}());
|
||||
C.x = 1;
|
||||
C.y = 1;
|
||||
|
||||
|
||||
//// [declFilePrivateStatic.d.ts]
|
||||
|
||||
@@ -24,8 +24,8 @@ var C = (function () {
|
||||
function C() {
|
||||
}
|
||||
C.m = function () { };
|
||||
C = __decorate([
|
||||
dec
|
||||
], C);
|
||||
return C;
|
||||
}());
|
||||
C = __decorate([
|
||||
dec
|
||||
], C);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user