Merge branch 'master' into FixObjectCreate

This commit is contained in:
Mohamed Hegazy
2017-02-13 20:41:19 -08:00
2016 changed files with 8949 additions and 3471 deletions
+31 -169
View File
@@ -6,6 +6,8 @@ var path = require("path");
var child_process = require("child_process");
var fold = require("travis-fold");
var runTestsInParallel = require("./scripts/mocha-parallel").runTestsInParallel;
var ts = require("./lib/typescript");
// Variables
var compilerDirectory = "src/compiler/";
@@ -34,6 +36,24 @@ if (process.env.path !== undefined) {
process.env.PATH = nodeModulesPathPrefix + process.env.PATH;
}
function filesFromConfig(configPath) {
var configText = fs.readFileSync(configPath).toString();
var config = ts.parseConfigFileTextToJson(configPath, configText, /*stripComments*/ true);
if (config.error) {
throw new Error(diagnosticsToString([config.error]));
}
const configFileContent = ts.parseJsonConfigFileContent(config.config, ts.sys, path.dirname(configPath));
if (configFileContent.errors && configFileContent.errors.length) {
throw new Error(diagnosticsToString(configFileContent.errors));
}
return configFileContent.fileNames;
function diagnosticsToString(s) {
return s.map(function(e) { return ts.flattenDiagnosticMessageText(e.messageText, ts.sys.newLine); }).join(ts.sys.newLine);
}
}
function toNs(diff) {
return diff[0] * 1e9 + diff[1];
}
@@ -56,173 +76,12 @@ function measure(marker) {
console.log("travis_time:end:" + marker.id + ":start=" + toNs(marker.stamp) + ",finish=" + toNs(total) + ",duration=" + toNs(diff) + "\r");
}
var compilerSources = [
"core.ts",
"performance.ts",
"sys.ts",
"types.ts",
"scanner.ts",
"parser.ts",
"utilities.ts",
"binder.ts",
"checker.ts",
"factory.ts",
"visitor.ts",
"transformers/destructuring.ts",
"transformers/ts.ts",
"transformers/jsx.ts",
"transformers/esnext.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
"transformers/generators.ts",
"transformers/es5.ts",
"transformers/module/es2015.ts",
"transformers/module/system.ts",
"transformers/module/module.ts",
"transformer.ts",
"sourcemap.ts",
"comments.ts",
"declarationEmitter.ts",
"emitter.ts",
"program.ts",
"commandLineParser.ts",
"tsc.ts",
"diagnosticInformationMap.generated.ts"
].map(function (f) {
return path.join(compilerDirectory, f);
});
var servicesSources = [
"core.ts",
"performance.ts",
"sys.ts",
"types.ts",
"scanner.ts",
"parser.ts",
"utilities.ts",
"binder.ts",
"checker.ts",
"factory.ts",
"visitor.ts",
"transformers/destructuring.ts",
"transformers/ts.ts",
"transformers/jsx.ts",
"transformers/esnext.ts",
"transformers/es2017.ts",
"transformers/es2016.ts",
"transformers/es2015.ts",
"transformers/generators.ts",
"transformers/es5.ts",
"transformers/module/es2015.ts",
"transformers/module/system.ts",
"transformers/module/module.ts",
"transformer.ts",
"sourcemap.ts",
"comments.ts",
"declarationEmitter.ts",
"emitter.ts",
"program.ts",
"commandLineParser.ts",
"diagnosticInformationMap.generated.ts"
].map(function (f) {
return path.join(compilerDirectory, f);
}).concat([
"types.ts",
"utilities.ts",
"breakpoints.ts",
"classifier.ts",
"completions.ts",
"documentHighlights.ts",
"documentRegistry.ts",
"findAllReferences.ts",
"goToDefinition.ts",
"goToImplementation.ts",
"jsDoc.ts",
"jsTyping.ts",
"navigateTo.ts",
"navigationBar.ts",
"outliningElementsCollector.ts",
"patternMatcher.ts",
"preProcess.ts",
"rename.ts",
"services.ts",
"shims.ts",
"signatureHelp.ts",
"symbolDisplay.ts",
"transpile.ts",
// Formatting
"formatting/formatting.ts",
"formatting/formattingContext.ts",
"formatting/formattingRequestKind.ts",
"formatting/formattingScanner.ts",
"formatting/references.ts",
"formatting/rule.ts",
"formatting/ruleAction.ts",
"formatting/ruleDescriptor.ts",
"formatting/ruleFlag.ts",
"formatting/ruleOperation.ts",
"formatting/ruleOperationContext.ts",
"formatting/rules.ts",
"formatting/rulesMap.ts",
"formatting/rulesProvider.ts",
"formatting/smartIndenter.ts",
"formatting/tokenRange.ts",
// CodeFixes
"codeFixProvider.ts",
"codefixes/fixes.ts",
"codefixes/fixExtendsInterfaceBecomesImplements.ts",
"codefixes/fixClassIncorrectlyImplementsInterface.ts",
"codefixes/fixClassDoesntImplementInheritedAbstractMember.ts",
"codefixes/fixClassSuperMustPrecedeThisAccess.ts",
"codefixes/fixConstructorForDerivedNeedSuperCall.ts",
"codefixes/helpers.ts",
"codefixes/importFixes.ts",
"codefixes/unusedIdentifierFixes.ts"
].map(function (f) {
return path.join(servicesDirectory, f);
}));
var baseServerCoreSources = [
"builder.ts",
"editorServices.ts",
"lsHost.ts",
"project.ts",
"protocol.ts",
"scriptInfo.ts",
"scriptVersionCache.ts",
"session.ts",
"shared.ts",
"types.ts",
"typingsCache.ts",
"utilities.ts",
].map(function (f) {
return path.join(serverDirectory, f);
});
var serverCoreSources = [
"server.ts"
].map(function (f) {
return path.join(serverDirectory, f);
}).concat(baseServerCoreSources);
var cancellationTokenSources = [
"cancellationToken.ts"
].map(function (f) {
return path.join(cancellationTokenDirectory, f);
});
var typingsInstallerSources = [
"../types.ts",
"../shared.ts",
"typingsInstaller.ts",
"nodeTypingsInstaller.ts"
].map(function (f) {
return path.join(typingsInstallerDirectory, f);
});
var serverSources = serverCoreSources.concat(servicesSources);
var languageServiceLibrarySources = baseServerCoreSources.concat(servicesSources);
var compilerSources = filesFromConfig("./src/compiler/tsconfig.json");
var servicesSources = filesFromConfig("./src/services/tsconfig.json");
var cancellationTokenSources = filesFromConfig(path.join(serverDirectory, "cancellationToken/tsconfig.json"));
var typingsInstallerSources = filesFromConfig(path.join(serverDirectory, "typingsInstaller/tsconfig.json"));
var serverSources = filesFromConfig(path.join(serverDirectory, "tsconfig.json"))
var languageServiceLibrarySources = filesFromConfig(path.join(serverDirectory, "tsconfig.library.json"));
var harnessCoreSources = [
"harness.ts",
@@ -1230,13 +1089,16 @@ var lintTargets = compilerSources
.concat(harnessSources)
// Other harness sources
.concat(["instrumenter.ts"].map(function (f) { return path.join(harnessDirectory, f) }))
.concat(serverCoreSources)
.concat(serverSources)
.concat(tslintRulesFiles)
.concat(servicesSources)
.concat(typingsInstallerSources)
.concat(cancellationTokenSources)
.concat(["Gulpfile.ts"])
.concat([nodeServerInFile, perftscPath, "tests/perfsys.ts", webhostPath]);
.concat([nodeServerInFile, perftscPath, "tests/perfsys.ts", webhostPath])
.map(function (p) { return path.resolve(p) });
// keep only unique items
lintTargets = Array.from(new Set(lintTargets));
function sendNextFile(files, child, callback, failures) {
var file = files.pop();
+34 -1
View File
@@ -1045,7 +1045,35 @@ namespace ts {
if (node.finallyBlock) {
// in finally flow is combined from pre-try/flow from try/flow from catch
// pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable
addAntecedent(preFinallyLabel, preTryFlow);
// also for finally blocks we inject two extra edges into the flow graph.
// first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it
// second -> edge that represents post-finally flow.
// these edges are used in following scenario:
// let a; (1)
// try { a = someOperation(); (2)}
// finally { (3) console.log(a) } (4)
// (5) a
// flow graph for this case looks roughly like this (arrows show ):
// (1-pre-try-flow) <--.. <-- (2-post-try-flow)
// ^ ^
// |*****(3-pre-finally-label) -----|
// ^
// |-- ... <-- (4-post-finally-label) <--- (5)
// In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account
// since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5)
// then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable
// Simply speaking code inside finally block is treated as reachable as pre-try-flow
// since we conservatively assume that any line in try block can throw or return in which case we'll enter finally.
// However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from
// final flows of these blocks without taking pre-try flow into account.
//
// extra edges that we inject allows to control this behavior
// if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped.
const preFinallyFlow: PreFinallyFlow = { flags: FlowFlags.PreFinally, antecedent: preTryFlow, lock: {} };
addAntecedent(preFinallyLabel, preFinallyFlow);
currentFlow = finishFlowLabel(preFinallyLabel);
bind(node.finallyBlock);
// if flow after finally is unreachable - keep it
@@ -1061,6 +1089,11 @@ namespace ts {
: unreachableFlow;
}
}
if (!(currentFlow.flags & FlowFlags.Unreachable)) {
const afterFinallyFlow: AfterFinallyFlow = { flags: FlowFlags.AfterFinally, antecedent: currentFlow };
preFinallyFlow.lock = afterFinallyFlow;
currentFlow = afterFinallyFlow;
}
}
else {
currentFlow = finishFlowLabel(preFinallyLabel);
+309 -145
View File
@@ -1,4 +1,4 @@
/// <reference path="moduleNameResolver.ts"/>
/// <reference path="moduleNameResolver.ts"/>
/// <reference path="binder.ts"/>
/* @internal */
@@ -60,9 +60,9 @@ namespace ts {
const emitResolver = createResolver();
const undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined");
const undefinedSymbol = createSymbol(SymbolFlags.Property, "undefined");
undefinedSymbol.declarations = [];
const argumentsSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "arguments");
const argumentsSymbol = createSymbol(SymbolFlags.Property, "arguments");
const checker: TypeChecker = {
getNodeCount: () => sum(host.getSourceFiles(), "nodeCount"),
@@ -131,8 +131,8 @@ namespace ts {
const indexedAccessTypes = createMap<IndexedAccessType>();
const evolvingArrayTypes: EvolvingArrayType[] = [];
const unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown");
const resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__");
const unknownSymbol = createSymbol(SymbolFlags.Property, "unknown");
const resolvingSymbol = createSymbol(0, "__resolving__");
const anyType = createIntrinsicType(TypeFlags.Any, "any");
const autoType = createIntrinsicType(TypeFlags.Any, "any");
@@ -154,7 +154,7 @@ namespace ts {
const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
const emptyTypeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral | SymbolFlags.Transient, "__type");
const emptyTypeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type");
emptyTypeLiteralSymbol.members = createMap<Symbol>();
const emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined);
@@ -326,7 +326,6 @@ namespace ts {
"object": TypeFacts.TypeofEQObject,
"function": TypeFacts.TypeofEQFunction
});
const typeofNEFacts = createMapFromTemplate({
"string": TypeFacts.TypeofNEString,
"number": TypeFacts.TypeofNENumber,
@@ -336,7 +335,6 @@ namespace ts {
"object": TypeFacts.TypeofNEObject,
"function": TypeFacts.TypeofNEFunction
});
const typeofTypesByName = createMapFromTemplate<Type>({
"string": stringType,
"number": numberType,
@@ -344,6 +342,7 @@ namespace ts {
"symbol": esSymbolType,
"undefined": undefinedType
});
const typeofType = createTypeofType();
let jsxElementType: Type;
let _jsxNamespace: string;
@@ -416,9 +415,11 @@ namespace ts {
diagnostics.add(diagnostic);
}
function createSymbol(flags: SymbolFlags, name: string): Symbol {
function createSymbol(flags: SymbolFlags, name: string) {
symbolCount++;
return new Symbol(flags, name);
const symbol = <TransientSymbol>(new Symbol(flags | SymbolFlags.Transient, name));
symbol.checkFlags = 0;
return symbol;
}
function getExcludedSymbolFlags(flags: SymbolFlags): SymbolFlags {
@@ -451,7 +452,7 @@ namespace ts {
}
function cloneSymbol(symbol: Symbol): Symbol {
const result = createSymbol(symbol.flags | SymbolFlags.Merged, symbol.name);
const result = createSymbol(symbol.flags, symbol.name);
result.declarations = symbol.declarations.slice(0);
result.parent = symbol.parent;
if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
@@ -508,7 +509,7 @@ namespace ts {
target.set(id, sourceSymbol);
}
else {
if (!(targetSymbol.flags & SymbolFlags.Merged)) {
if (!(targetSymbol.flags & SymbolFlags.Transient)) {
targetSymbol = cloneSymbol(targetSymbol);
target.set(id, targetSymbol);
}
@@ -545,7 +546,7 @@ namespace ts {
if (mainModule.flags & SymbolFlags.Namespace) {
// if module symbol has already been merged - it is safe to use it.
// otherwise clone it
mainModule = mainModule.flags & SymbolFlags.Merged ? mainModule : cloneSymbol(mainModule);
mainModule = mainModule.flags & SymbolFlags.Transient ? mainModule : cloneSymbol(mainModule);
mergeSymbol(mainModule, moduleAugmentation.symbol);
}
else {
@@ -586,6 +587,10 @@ namespace ts {
return type.flags & TypeFlags.Object ? (<ObjectType>type).objectFlags : 0;
}
function getCheckFlags(symbol: Symbol): CheckFlags {
return symbol.flags & SymbolFlags.Transient ? (<TransientSymbol>symbol).checkFlags : 0;
}
function isGlobalSourceFile(node: Node) {
return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(<SourceFile>node);
}
@@ -594,7 +599,7 @@ namespace ts {
if (meaning) {
const symbol = symbols.get(name);
if (symbol) {
Debug.assert((symbol.flags & SymbolFlags.Instantiated) === 0, "Should never get an instantiated symbol here.");
Debug.assert((getCheckFlags(symbol) & CheckFlags.Instantiated) === 0, "Should never get an instantiated symbol here.");
if (symbol.flags & meaning) {
return symbol;
}
@@ -1428,7 +1433,7 @@ namespace ts {
else {
Debug.fail("Unknown entity name kind.");
}
Debug.assert((symbol.flags & SymbolFlags.Instantiated) === 0, "Should never get an instantiated symbol here.");
Debug.assert((getCheckFlags(symbol) & CheckFlags.Instantiated) === 0, "Should never get an instantiated symbol here.");
return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
}
@@ -1672,23 +1677,7 @@ namespace ts {
}
function symbolIsValue(symbol: Symbol): boolean {
// If it is an instantiated symbol, then it is a value if the symbol it is an
// instantiation of is a value.
if (symbol.flags & SymbolFlags.Instantiated) {
return symbolIsValue(getSymbolLinks(symbol).target);
}
// If the symbol has the value flag, it is trivially a value.
if (symbol.flags & SymbolFlags.Value) {
return true;
}
// If it is an alias, then it is a value if the symbol it resolves to is a value.
if (symbol.flags & SymbolFlags.Alias) {
return (resolveAlias(symbol).flags & SymbolFlags.Value) !== 0;
}
return false;
return !!(symbol.flags & SymbolFlags.Value || symbol.flags & SymbolFlags.Alias && resolveAlias(symbol).flags & SymbolFlags.Value);
}
function findConstructorDeclaration(node: ClassLikeDeclaration): ConstructorDeclaration {
@@ -1727,6 +1716,10 @@ namespace ts {
return type;
}
function createTypeofType() {
return getUnionType(convertToArray(typeofEQFacts.keys(), s => getLiteralTypeForText(TypeFlags.StringLiteral, s)));
}
// A reserved member name starts with two underscores, but the third character cannot be an underscore
// or the @ symbol. A third underscore indicates an escaped form of an identifer that started
// with at least two underscores. The @ character indicates that the name is denoted by a well known ES
@@ -2240,7 +2233,7 @@ namespace ts {
if (parentSymbol) {
// Write type arguments of instantiated class/interface here
if (flags & SymbolFormatFlags.WriteTypeParametersOrArguments) {
if (symbol.flags & SymbolFlags.Instantiated) {
if (getCheckFlags(symbol) & CheckFlags.Instantiated) {
buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol),
(<TransientSymbol>symbol).mapper, writer, enclosingDeclaration);
}
@@ -2697,7 +2690,11 @@ namespace ts {
writePunctuation(writer, SyntaxKind.ColonToken);
writeSpace(writer);
buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack);
let type = getTypeOfSymbol(p);
if (isRequiredInitializedParameter(parameterNode)) {
type = includeFalsyTypes(type, TypeFlags.Undefined);
}
buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack);
}
function buildBindingPatternDisplay(bindingPattern: BindingPattern, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) {
@@ -3256,7 +3253,7 @@ namespace ts {
type;
}
function getTypeForVariableLikeDeclarationFromJSDocComment(declaration: VariableLikeDeclaration) {
function getTypeForDeclarationFromJSDocComment(declaration: Node ) {
const jsdocType = getJSDocType(declaration);
if (jsdocType) {
return getTypeFromTypeNode(jsdocType);
@@ -3278,13 +3275,23 @@ namespace ts {
return strictNullChecks && optional ? includeFalsyTypes(type, TypeFlags.Undefined) : type;
}
/** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
function removeOptionalityFromAnnotation(annotatedType: Type, declaration: VariableLikeDeclaration): Type {
const annotationIncludesUndefined = strictNullChecks &&
declaration.kind === SyntaxKind.Parameter &&
declaration.initializer &&
getFalsyFlags(annotatedType) & TypeFlags.Undefined &&
!(getFalsyFlags(checkExpression(declaration.initializer)) & TypeFlags.Undefined);
return annotationIncludesUndefined ? getNonNullableType(annotatedType) : annotatedType;
}
// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration, includeOptionality: boolean): Type {
if (declaration.flags & NodeFlags.JavaScriptFile) {
// If this is a variable in a JavaScript file, then use the JSDoc type (if it has
// one as its type), otherwise fallback to the below standard TS codepaths to
// try to figure it out.
const type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration);
const type = getTypeForDeclarationFromJSDocComment(declaration);
if (type && type !== unknownType) {
return type;
}
@@ -3311,7 +3318,8 @@ namespace ts {
// Use type from type annotation if one is present
if (declaration.type) {
return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality);
const declaredType = removeOptionalityFromAnnotation(getTypeFromTypeNode(declaration.type), declaration);
return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality);
}
if ((compilerOptions.noImplicitAny || declaration.flags & NodeFlags.JavaScriptFile) &&
@@ -3379,6 +3387,27 @@ namespace ts {
return undefined;
}
// Return the inferred type for a variable, parameter, or property declaration
function getTypeForJSSpecialPropertyDeclaration(declaration: Declaration): Type {
const expression = declaration.kind === SyntaxKind.BinaryExpression ? <BinaryExpression>declaration :
declaration.kind === SyntaxKind.PropertyAccessExpression ? <BinaryExpression>getAncestor(declaration, SyntaxKind.BinaryExpression) :
undefined;
if (!expression) {
return unknownType;
}
if (expression.flags & NodeFlags.JavaScriptFile) {
// If there is a JSDoc type, use it
const type = getTypeForDeclarationFromJSDocComment(expression.parent);
if (type && type !== unknownType) {
return getWidenedType(type);
}
}
return getWidenedLiteralType(checkExpressionCached(expression.right));
}
// Return the type implied by a binding pattern element. This is the type of the initializer of the element if
// one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
// pattern. Otherwise, it is the type any.
@@ -3413,8 +3442,8 @@ namespace ts {
}
const text = getTextOfPropertyName(name);
const flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0);
const symbol = <TransientSymbol>createSymbol(flags, text);
const flags = SymbolFlags.Property | (e.initializer ? SymbolFlags.Optional : 0);
const symbol = createSymbol(flags, text);
symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
symbol.bindingElement = e;
members.set(symbol.name, symbol);
@@ -3533,18 +3562,7 @@ namespace ts {
// * className.prototype.method = expr
if (declaration.kind === SyntaxKind.BinaryExpression ||
declaration.kind === SyntaxKind.PropertyAccessExpression && declaration.parent.kind === SyntaxKind.BinaryExpression) {
// Use JS Doc type if present on parent expression statement
if (declaration.flags & NodeFlags.JavaScriptFile) {
const jsdocType = getJSDocType(declaration.parent);
if (jsdocType) {
return links.type = getTypeFromTypeNode(jsdocType);
}
}
const declaredTypes = map(symbol.declarations,
decl => decl.kind === SyntaxKind.BinaryExpression ?
checkExpressionCached((<BinaryExpression>decl).right) :
checkExpressionCached((<BinaryExpression>decl.parent).right));
type = getUnionType(declaredTypes, /*subtypeReduction*/ true);
type = getWidenedType(getUnionType(map(symbol.declarations, getTypeForJSSpecialPropertyDeclaration), /*subtypeReduction*/ true));
}
else {
type = getWidenedTypeForVariableLikeDeclaration(<VariableLikeDeclaration>declaration, /*reportErrors*/ true);
@@ -3587,7 +3605,7 @@ namespace ts {
const setter = <AccessorDeclaration>getDeclarationOfKind(symbol, SyntaxKind.SetAccessor);
if (getter && getter.flags & NodeFlags.JavaScriptFile) {
const jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter);
const jsDocType = getTypeForDeclarationFromJSDocComment(getter);
if (jsDocType) {
return links.type = jsDocType;
}
@@ -3723,7 +3741,7 @@ namespace ts {
}
function getTypeOfSymbol(symbol: Symbol): Type {
if (symbol.flags & SymbolFlags.Instantiated) {
if (getCheckFlags(symbol) & CheckFlags.Instantiated) {
return getTypeOfInstantiatedSymbol(symbol);
}
if (symbol.flags & (SymbolFlags.Variable | SymbolFlags.Property)) {
@@ -3748,9 +3766,9 @@ namespace ts {
return getObjectFlags(type) & ObjectFlags.Reference ? (<TypeReference>type).target : type;
}
function hasBaseType(type: BaseType, checkBase: BaseType) {
function hasBaseType(type: Type, checkBase: Type) {
return check(type);
function check(type: BaseType): boolean {
function check(type: Type): boolean {
if (getObjectFlags(type) & (ObjectFlags.ClassOrInterface | ObjectFlags.Reference)) {
const target = <InterfaceType>getTargetType(type);
return target === checkBase || forEach(getBaseTypes(target), check);
@@ -4521,7 +4539,7 @@ namespace ts {
s = cloneSignature(signature);
if (forEach(unionSignatures, sig => sig.thisParameter)) {
const thisType = getUnionType(map(unionSignatures, sig => getTypeOfSymbol(sig.thisParameter) || anyType), /*subtypeReduction*/ true);
s.thisParameter = createTransientSymbol(signature.thisParameter, thisType);
s.thisParameter = createSymbolWithType(signature.thisParameter, thisType);
}
// Clear resolved return type we possibly got from cloneSignature
s.resolvedReturnType = undefined;
@@ -4718,9 +4736,9 @@ namespace ts {
const propName = (<LiteralType>t).text;
const modifiersProp = getPropertyOfType(modifiersType, propName);
const isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & SymbolFlags.Optional);
const prop = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient | (isOptional ? SymbolFlags.Optional : 0), propName);
const prop = createSymbol(SymbolFlags.Property | (isOptional ? SymbolFlags.Optional : 0), propName);
prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? CheckFlags.Readonly : 0;
prop.type = propType;
prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp);
if (propertySymbol) {
prop.mappedTypeOrigin = propertySymbol;
}
@@ -4951,18 +4969,19 @@ namespace ts {
}
function createUnionOrIntersectionProperty(containingType: UnionOrIntersectionType, name: string): Symbol {
const types = containingType.types;
const excludeModifiers = containingType.flags & TypeFlags.Union ? ModifierFlags.Private | ModifierFlags.Protected : 0;
let props: Symbol[];
const types = containingType.types;
const isUnion = containingType.flags & TypeFlags.Union;
const excludeModifiers = isUnion ? ModifierFlags.NonPublicAccessibilityModifier : 0;
// Flags we want to propagate to the result if they exist in all source symbols
let commonFlags = (containingType.flags & TypeFlags.Intersection) ? SymbolFlags.Optional : SymbolFlags.None;
let isReadonly = false;
let isPartial = false;
let commonFlags = isUnion ? SymbolFlags.None : SymbolFlags.Optional;
let checkFlags = CheckFlags.SyntheticProperty;
for (const current of types) {
const type = getApparentType(current);
if (type !== unknownType) {
const prop = getPropertyOfType(type, name);
if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & excludeModifiers)) {
const modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0;
if (prop && !(modifiers & excludeModifiers)) {
commonFlags &= prop.flags;
if (!props) {
props = [prop];
@@ -4970,26 +4989,26 @@ namespace ts {
else if (!contains(props, prop)) {
props.push(prop);
}
if (isReadonlySymbol(prop)) {
isReadonly = true;
}
checkFlags |= (isReadonlySymbol(prop) ? CheckFlags.Readonly : 0) |
(!(modifiers & ModifierFlags.NonPublicAccessibilityModifier) ? CheckFlags.ContainsPublic : 0) |
(modifiers & ModifierFlags.Protected ? CheckFlags.ContainsProtected : 0) |
(modifiers & ModifierFlags.Private ? CheckFlags.ContainsPrivate : 0) |
(modifiers & ModifierFlags.Static ? CheckFlags.ContainsStatic : 0);
}
else if (containingType.flags & TypeFlags.Union) {
isPartial = true;
else if (isUnion) {
checkFlags |= CheckFlags.Partial;
}
}
}
if (!props) {
return undefined;
}
if (props.length === 1 && !isPartial) {
if (props.length === 1 && !(checkFlags & CheckFlags.Partial)) {
return props[0];
}
const propTypes: Type[] = [];
const declarations: Declaration[] = [];
let commonType: Type = undefined;
let hasNonUniformType = false;
for (const prop of props) {
if (prop.declarations) {
addRange(declarations, prop.declarations);
@@ -4999,17 +5018,15 @@ namespace ts {
commonType = type;
}
else if (type !== commonType) {
hasNonUniformType = true;
checkFlags |= CheckFlags.HasNonUniformType;
}
propTypes.push(type);
}
const result = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient | SymbolFlags.SyntheticProperty | commonFlags, name);
const result = createSymbol(SymbolFlags.Property | commonFlags, name);
result.checkFlags = checkFlags;
result.containingType = containingType;
result.hasNonUniformType = hasNonUniformType;
result.isPartial = isPartial;
result.declarations = declarations;
result.isReadonly = isReadonly;
result.type = containingType.flags & TypeFlags.Union ? getUnionType(propTypes) : getIntersectionType(propTypes);
result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
return result;
}
@@ -5033,7 +5050,7 @@ namespace ts {
function getPropertyOfUnionOrIntersectionType(type: UnionOrIntersectionType, name: string): Symbol {
const property = getUnionOrIntersectionProperty(type, name);
// We need to filter out partial properties in union types
return property && !(property.flags & SymbolFlags.SyntheticProperty && (<TransientSymbol>property).isPartial) ? property : undefined;
return property && !(getCheckFlags(property) & CheckFlags.Partial) ? property : undefined;
}
/**
@@ -5196,6 +5213,12 @@ namespace ts {
Debug.assert(parameterIndex >= 0);
return parameterIndex >= signature.minArgumentCount;
}
const iife = getImmediatelyInvokedFunctionExpression(node.parent);
if (iife) {
return !node.type &&
!node.dotDotDotToken &&
indexOf((node.parent as SignatureDeclaration).parameters, node) >= iife.arguments.length;
}
return false;
}
@@ -5228,6 +5251,7 @@ namespace ts {
let hasThisParameter: boolean;
const iife = getImmediatelyInvokedFunctionExpression(declaration);
const isJSConstructSignature = isJSDocConstructSignature(declaration);
const isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && isInJavaScriptFile(declaration) && !hasJSDocParameterTags(declaration);
// If this is a JSDoc construct signature, then skip the first parameter in the
// parameter list. The first parameter represents the return type of the construct
@@ -5256,7 +5280,8 @@ namespace ts {
// Record a new minimum argument count if this is not an optional parameter
const isOptionalParameter = param.initializer || param.questionToken || param.dotDotDotToken ||
iife && parameters.length > iife.arguments.length && !param.type ||
isJSDocOptionalParameter(param);
isJSDocOptionalParameter(param) ||
isUntypedSignatureInJSFile;
if (!isOptionalParameter) {
minArgumentCount = parameters.length;
}
@@ -5837,7 +5862,7 @@ namespace ts {
for (let i = 0; i < arity; i++) {
const typeParameter = <TypeParameter>createType(TypeFlags.TypeParameter);
typeParameters.push(typeParameter);
const property = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "" + i);
const property = createSymbol(SymbolFlags.Property, "" + i);
property.type = typeParameter;
properties.push(property);
}
@@ -6083,7 +6108,10 @@ namespace ts {
if (type.flags & TypeFlags.Union && typeSet.unionIndex === undefined) {
typeSet.unionIndex = typeSet.length;
}
typeSet.push(type);
if (!(type.flags & TypeFlags.Object && (<ObjectType>type).objectFlags & ObjectFlags.Anonymous &&
type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && containsIdenticalType(typeSet, type))) {
typeSet.push(type);
}
}
}
@@ -6421,13 +6449,13 @@ namespace ts {
const rightType = getTypeOfSymbol(rightProp);
if (maybeTypeOfKind(rightType, TypeFlags.Undefined) || rightProp.flags & SymbolFlags.Optional) {
const declarations: Declaration[] = concatenate(leftProp.declarations, rightProp.declarations);
const flags = SymbolFlags.Property | SymbolFlags.Transient | (leftProp.flags & SymbolFlags.Optional);
const result = <TransientSymbol>createSymbol(flags, leftProp.name);
const flags = SymbolFlags.Property | (leftProp.flags & SymbolFlags.Optional);
const result = createSymbol(flags, leftProp.name);
result.checkFlags = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp) ? CheckFlags.Readonly : 0;
result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, TypeFacts.NEUndefined)]);
result.leftSpread = leftProp;
result.rightSpread = rightProp;
result.declarations = declarations;
result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp);
members.set(leftProp.name, result);
}
}
@@ -6754,7 +6782,7 @@ namespace ts {
}
function instantiateSymbol(symbol: Symbol, mapper: TypeMapper): Symbol {
if (symbol.flags & SymbolFlags.Instantiated) {
if (getCheckFlags(symbol) & CheckFlags.Instantiated) {
const links = getSymbolLinks(symbol);
// If symbol being instantiated is itself a instantiation, fetch the original target and combine the
// type mappers. This ensures that original type identities are properly preserved and that aliases
@@ -6762,10 +6790,10 @@ namespace ts {
symbol = links.target;
mapper = combineTypeMappers(links.mapper, mapper);
}
// Keep the flags from the symbol we're instantiating. Mark that is instantiated, and
// also transient so that we can just store data on it directly.
const result = <TransientSymbol>createSymbol(SymbolFlags.Instantiated | SymbolFlags.Transient | symbol.flags, symbol.name);
const result = createSymbol(symbol.flags, symbol.name);
result.checkFlags = CheckFlags.Instantiated;
result.declarations = symbol.declarations;
result.parent = symbol.parent;
result.target = symbol;
@@ -6773,7 +6801,6 @@ namespace ts {
if (symbol.valueDeclaration) {
result.valueDeclaration = symbol.valueDeclaration;
}
return result;
}
@@ -7756,16 +7783,36 @@ namespace ts {
if (target.flags & TypeFlags.Union && containsType(targetTypes, source)) {
return Ternary.True;
}
const len = targetTypes.length;
for (let i = 0; i < len; i++) {
const related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1);
for (const type of targetTypes) {
const related = isRelatedTo(source, type, /*reportErrors*/ false);
if (related) {
return related;
}
}
if (reportErrors) {
const discriminantType = findMatchingDiscriminantType(source, target);
isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
}
return Ternary.False;
}
function findMatchingDiscriminantType(source: Type, target: UnionOrIntersectionType) {
const sourceProperties = getPropertiesOfObjectType(source);
if (sourceProperties) {
for (const sourceProperty of sourceProperties) {
if (isDiscriminantProperty(target, sourceProperty.name)) {
const sourceType = getTypeOfSymbol(sourceProperty);
for (const type of target.types) {
const targetType = getTypeOfPropertyOfType(type, sourceProperty.name);
if (targetType && isRelatedTo(sourceType, targetType)) {
return type;
}
}
}
}
}
}
function typeRelatedToEachType(source: Type, target: UnionOrIntersectionType, reportErrors: boolean): Ternary {
let result = Ternary.True;
const targetTypes = target.types;
@@ -7968,6 +8015,12 @@ namespace ts {
const sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp);
const targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp);
if (sourcePropFlags & ModifierFlags.Private || targetPropFlags & ModifierFlags.Private) {
if (getCheckFlags(sourceProp) & CheckFlags.ContainsPrivate) {
if (reportErrors) {
reportError(Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source));
}
return Ternary.False;
}
if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
if (reportErrors) {
if (sourcePropFlags & ModifierFlags.Private && targetPropFlags & ModifierFlags.Private) {
@@ -7983,13 +8036,10 @@ namespace ts {
}
}
else if (targetPropFlags & ModifierFlags.Protected) {
const sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & SymbolFlags.Class;
const sourceClass = sourceDeclaredInClass ? <InterfaceType>getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined;
const targetClass = <InterfaceType>getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp));
if (!sourceClass || !hasBaseType(sourceClass, targetClass)) {
if (!isValidOverrideOf(sourceProp, targetProp)) {
if (reportErrors) {
reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2,
symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass));
reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp),
typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target));
}
return Ternary.False;
}
@@ -8231,6 +8281,49 @@ namespace ts {
}
}
// Invoke the callback for each underlying property symbol of the given symbol and return the first
// value that isn't undefined.
function forEachProperty<T>(prop: Symbol, callback: (p: Symbol) => T): T {
if (getCheckFlags(prop) & CheckFlags.SyntheticProperty) {
for (const t of (<TransientSymbol>prop).containingType.types) {
const p = getPropertyOfType(t, prop.name);
const result = p && forEachProperty(p, callback);
if (result) {
return result;
}
}
return undefined;
}
return callback(prop);
}
// Return the declaring class type of a property or undefined if property not declared in class
function getDeclaringClass(prop: Symbol) {
return prop.parent && prop.parent.flags & SymbolFlags.Class ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
}
// Return true if some underlying source property is declared in a class that derives
// from the given base class.
function isPropertyInClassDerivedFrom(prop: Symbol, baseClass: Type) {
return forEachProperty(prop, sp => {
const sourceClass = getDeclaringClass(sp);
return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
});
}
// Return true if source property is a valid override of protected parts of target property.
function isValidOverrideOf(sourceProp: Symbol, targetProp: Symbol) {
return !forEachProperty(targetProp, tp => getDeclarationModifierFlagsFromSymbol(tp) & ModifierFlags.Protected ?
!isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false);
}
// Return true if the given class derives from each of the declaring classes of the protected
// constituents of the given property.
function isClassDerivedFromDeclaringClasses(checkClass: Type, prop: Symbol) {
return forEachProperty(prop, p => getDeclarationModifierFlagsFromSymbol(p) & ModifierFlags.Protected ?
!hasBaseType(checkClass, getDeclaringClass(p)) : false) ? undefined : checkClass;
}
// Return true if the given type is the constructor type for an abstract class
function isAbstractConstructorType(type: Type) {
if (getObjectFlags(type) & ObjectFlags.Anonymous) {
@@ -8540,7 +8633,7 @@ namespace ts {
if (flags & TypeFlags.Void) types.push(voidType);
if (flags & TypeFlags.Undefined) types.push(undefinedType);
if (flags & TypeFlags.Null) types.push(nullType);
return getUnionType(types, /*subtypeReduction*/ true);
return getUnionType(types);
}
function removeDefinitelyFalsyTypes(type: Type): Type {
@@ -8563,8 +8656,8 @@ namespace ts {
getSignaturesOfType(type, SignatureKind.Construct).length === 0;
}
function createTransientSymbol(source: Symbol, type: Type) {
const symbol = <TransientSymbol>createSymbol(source.flags | SymbolFlags.Transient, source.name);
function createSymbolWithType(source: Symbol, type: Type) {
const symbol = createSymbol(source.flags, source.name);
symbol.declarations = source.declarations;
symbol.parent = source.parent;
symbol.type = type;
@@ -8580,7 +8673,7 @@ namespace ts {
for (const property of getPropertiesOfObjectType(type)) {
const original = getTypeOfSymbol(property);
const updated = f(original);
members.set(property.name, updated === original ? property : createTransientSymbol(property, updated));
members.set(property.name, updated === original ? property : createSymbolWithType(property, updated));
};
return members;
}
@@ -8818,10 +8911,10 @@ namespace ts {
if (!inferredPropType) {
return undefined;
}
const inferredProp = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient | prop.flags & optionalMask, prop.name);
const inferredProp = createSymbol(SymbolFlags.Property | prop.flags & optionalMask, prop.name);
inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? CheckFlags.Readonly : 0;
inferredProp.declarations = prop.declarations;
inferredProp.type = inferredPropType;
inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop);
members.set(prop.name, inferredProp);
}
if (indexInfo) {
@@ -9303,9 +9396,9 @@ namespace ts {
function isDiscriminantProperty(type: Type, name: string) {
if (type && type.flags & TypeFlags.Union) {
const prop = getUnionOrIntersectionProperty(<UnionType>type, name);
if (prop && prop.flags & SymbolFlags.SyntheticProperty) {
if (prop && getCheckFlags(prop) & CheckFlags.SyntheticProperty) {
if ((<TransientSymbol>prop).isDiscriminantProperty === undefined) {
(<TransientSymbol>prop).isDiscriminantProperty = (<TransientSymbol>prop).hasNonUniformType && isLiteralType(getTypeOfSymbol(prop));
(<TransientSymbol>prop).isDiscriminantProperty = (<TransientSymbol>prop).checkFlags & CheckFlags.HasNonUniformType && isLiteralType(getTypeOfSymbol(prop));
}
return (<TransientSymbol>prop).isDiscriminantProperty;
}
@@ -9469,11 +9562,19 @@ namespace ts {
}
function getAssignedTypeOfBinaryExpression(node: BinaryExpression): Type {
return node.parent.kind === SyntaxKind.ArrayLiteralExpression || node.parent.kind === SyntaxKind.PropertyAssignment ?
const isDestructuringDefaultAssignment =
node.parent.kind === SyntaxKind.ArrayLiteralExpression && isDestructuringAssignmentTarget(node.parent) ||
node.parent.kind === SyntaxKind.PropertyAssignment && isDestructuringAssignmentTarget(node.parent.parent);
return isDestructuringDefaultAssignment ?
getTypeWithDefault(getAssignedType(node), node.right) :
getTypeOfExpression(node.right);
}
function isDestructuringAssignmentTarget(parent: Node) {
return parent.parent.kind === SyntaxKind.BinaryExpression && (parent.parent as BinaryExpression).left === parent ||
parent.parent.kind === SyntaxKind.ForOfStatement && (parent.parent as ForOfStatement).initializer === parent;
}
function getAssignedTypeOfArrayLiteralElement(node: ArrayLiteralExpression, element: Expression): Type {
return getTypeOfDestructuredArrayElement(getAssignedType(node), indexOf(node.elements, element));
}
@@ -9815,7 +9916,19 @@ namespace ts {
}
}
let type: FlowType;
if (flow.flags & FlowFlags.Assignment) {
if (flow.flags & FlowFlags.AfterFinally) {
// block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement
(<AfterFinallyFlow>flow).locked = true;
type = getTypeAtFlowNode((<AfterFinallyFlow>flow).antecedent);
(<AfterFinallyFlow>flow).locked = false;
}
else if (flow.flags & FlowFlags.PreFinally) {
// locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel
// so here just redirect to antecedent
flow = (<PreFinallyFlow>flow).antecedent;
continue;
}
else if (flow.flags & FlowFlags.Assignment) {
type = getTypeAtFlowAssignment(<FlowAssignment>flow);
if (!type) {
flow = (<FlowAssignment>flow).antecedent;
@@ -9971,6 +10084,12 @@ namespace ts {
let subtypeReduction = false;
let seenIncomplete = false;
for (const antecedent of flow.antecedents) {
if (antecedent.flags & FlowFlags.PreFinally && (<PreFinallyFlow>antecedent).lock.locked) {
// if flow correspond to branch from pre-try to finally and this branch is locked - this means that
// we initially have started following the flow outside the finally block.
// in this case we should ignore this branch.
continue;
}
const flowType = getTypeAtFlowNode(antecedent);
const type = getTypeFromFlowType(flowType);
// If the type at a particular antecedent path is the declared type and the
@@ -11762,7 +11881,7 @@ namespace ts {
}
typeFlags |= type.flags;
const prop = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name);
const prop = createSymbol(SymbolFlags.Property | member.flags, member.name);
if (inDestructuringPattern) {
// If object literal is an assignment pattern and if the assignment pattern specifies a default value
// for the property, make the property optional.
@@ -12387,7 +12506,22 @@ namespace ts {
}
function getDeclarationModifierFlagsFromSymbol(s: Symbol): ModifierFlags {
return s.valueDeclaration ? getCombinedModifierFlags(s.valueDeclaration) : s.flags & SymbolFlags.Prototype ? ModifierFlags.Public | ModifierFlags.Static : 0;
if (s.valueDeclaration) {
const flags = getCombinedModifierFlags(s.valueDeclaration);
return s.parent && s.parent.flags & SymbolFlags.Class ? flags : flags & ~ModifierFlags.AccessibilityModifier;
}
if (getCheckFlags(s) & CheckFlags.SyntheticProperty) {
const checkFlags = (<TransientSymbol>s).checkFlags;
const accessModifier = checkFlags & CheckFlags.ContainsPrivate ? ModifierFlags.Private :
checkFlags & CheckFlags.ContainsPublic ? ModifierFlags.Public :
ModifierFlags.Protected;
const staticModifier = checkFlags & CheckFlags.ContainsStatic ? ModifierFlags.Static : 0;
return accessModifier | staticModifier;
}
if (s.flags & SymbolFlags.Prototype) {
return ModifierFlags.Public | ModifierFlags.Static;
}
return 0;
}
function getDeclarationNodeFlagsFromSymbol(s: Symbol): NodeFlags {
@@ -12402,12 +12536,18 @@ namespace ts {
* @param type The type of left.
* @param prop The symbol for the right hand side of the property access.
*/
function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName | VariableLikeDeclaration, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean {
function checkPropertyAccessibility(node: PropertyAccessExpression | QualifiedName | VariableLikeDeclaration, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean {
const flags = getDeclarationModifierFlagsFromSymbol(prop);
const declaringClass = <InterfaceType>getDeclaredTypeOfSymbol(getParentOfSymbol(prop));
const errorNode = node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.VariableDeclaration ?
(<PropertyAccessExpression | VariableDeclaration>node).name :
(<QualifiedName>node).right;
if (getCheckFlags(prop) & CheckFlags.ContainsPrivate) {
// Synthetic property with private constituent property
error(errorNode, Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type));
return false;
}
if (left.kind === SyntaxKind.SuperKeyword) {
// TS 1.0 spec (April 2014): 4.8.2
// - In a constructor, instance member function, instance member accessor, or
@@ -12426,14 +12566,12 @@ namespace ts {
return false;
}
}
if (flags & ModifierFlags.Abstract) {
// A method cannot be accessed in a super property access if the method is abstract.
// This error could mask a private property access error. But, a member
// cannot simultaneously be private and abstract, so this will trigger an
// additional error elsewhere.
error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass));
error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
return false;
}
}
@@ -12449,7 +12587,7 @@ namespace ts {
if (flags & ModifierFlags.Private) {
const declaringClassDeclaration = <ClassLikeDeclaration>getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
if (!isNodeWithinClass(node, declaringClassDeclaration)) {
error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass));
error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
return false;
}
return true;
@@ -12462,15 +12600,15 @@ namespace ts {
return true;
}
// Get the enclosing class that has the declaring class as its base type
// Find the first enclosing class that has the declaring classes of the protected constituents
// of the property as base classes
const enclosingClass = forEachEnclosingClass(node, enclosingDeclaration => {
const enclosingClass = <InterfaceType>getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
return hasBaseType(enclosingClass, declaringClass) ? enclosingClass : undefined;
return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
});
// A protected property is accessible if the property is within the declaring class or classes derived from it
if (!enclosingClass) {
error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass));
error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
return false;
}
// No further restrictions for static properties
@@ -12482,9 +12620,7 @@ namespace ts {
// get the original type -- represented as the type constraint of the 'this' type
type = getConstraintOfTypeParameter(<TypeParameter>type);
}
// TODO: why is the first part of this check here?
if (!(getObjectFlags(getTargetType(type)) & ObjectFlags.ClassOrInterface && hasBaseType(<InterfaceType>type, enclosingClass))) {
if (!(getObjectFlags(getTargetType(type)) & ObjectFlags.ClassOrInterface && hasBaseType(type, enclosingClass))) {
error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
return false;
}
@@ -12535,9 +12671,8 @@ namespace ts {
noUnusedIdentifiers &&
(prop.flags & SymbolFlags.ClassMember) &&
prop.valueDeclaration && (getModifierFlags(prop.valueDeclaration) & ModifierFlags.Private)) {
if (prop.flags & SymbolFlags.Instantiated) {
if (getCheckFlags(prop) & CheckFlags.Instantiated) {
getSymbolLinks(prop).target.isReferenced = true;
}
else {
prop.isReferenced = true;
@@ -12587,9 +12722,7 @@ namespace ts {
getNodeLinks(node).resolvedSymbol = prop;
if (prop.parent && prop.parent.flags & SymbolFlags.Class) {
checkClassPropertyAccess(node, left, apparentType, prop);
}
checkPropertyAccessibility(node, left, apparentType, prop);
const propType = getTypeOfSymbol(prop);
const assignmentKind = getAssignmentTargetKind(node);
@@ -12621,8 +12754,8 @@ namespace ts {
const type = checkExpression(left);
if (type !== unknownType && !isTypeAny(type)) {
const prop = getPropertyOfType(getWidenedType(type), propertyName);
if (prop && prop.parent && prop.parent.flags & SymbolFlags.Class) {
return checkClassPropertyAccess(node, left, type, prop);
if (prop) {
return checkPropertyAccessibility(node, left, type, prop);
}
}
return true;
@@ -14116,7 +14249,7 @@ namespace ts {
const parameter = signature.thisParameter;
if (!parameter || parameter.valueDeclaration && !(<ParameterDeclaration>parameter.valueDeclaration).type) {
if (!parameter) {
signature.thisParameter = createTransientSymbol(context.thisParameter, undefined);
signature.thisParameter = createSymbolWithType(context.thisParameter, undefined);
}
assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper);
}
@@ -14558,11 +14691,11 @@ namespace ts {
// Get accessors without matching set accessors
// Enum members
// Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
return symbol.isReadonly ||
symbol.flags & SymbolFlags.Property && (getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.Readonly) !== 0 ||
symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0 ||
return !!(getCheckFlags(symbol) & CheckFlags.Readonly ||
symbol.flags & SymbolFlags.Property && getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.Readonly ||
symbol.flags & SymbolFlags.Variable && getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const ||
symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) ||
(symbol.flags & SymbolFlags.EnumMember) !== 0;
symbol.flags & SymbolFlags.EnumMember);
}
function isReferenceToReadonlyEntity(expr: Expression, symbol: Symbol): boolean {
@@ -14626,7 +14759,7 @@ namespace ts {
function checkTypeOfExpression(node: TypeOfExpression): Type {
checkExpression(node.expression);
return stringType;
return typeofType;
}
function checkVoidExpression(node: VoidExpression): Type {
@@ -17561,8 +17694,8 @@ namespace ts {
const name = node.propertyName || <Identifier>node.name;
const property = getPropertyOfType(parentType, getTextOfPropertyName(name));
markPropertyAsReferenced(property);
if (parent.initializer && property && getParentOfSymbol(property)) {
checkClassPropertyAccess(parent, parent.initializer, parentType, property);
if (parent.initializer && property) {
checkPropertyAccessibility(parent, parent.initializer, parentType, property);
}
}
@@ -18568,7 +18701,7 @@ namespace ts {
function getTargetSymbol(s: Symbol) {
// if symbol is instantiated its flags are not copied from the 'target'
// so we'll need to get back original 'target' symbol to work with correct set of flags
return s.flags & SymbolFlags.Instantiated ? getSymbolLinks(s).target : s;
return getCheckFlags(s) & CheckFlags.Instantiated ? (<TransientSymbol>s).target : s;
}
function getClassLikeDeclarationOfSymbol(symbol: Symbol): Declaration {
@@ -19146,7 +19279,7 @@ namespace ts {
// We can detect if augmentation was applied using following rules:
// - augmentation for a global scope is always applied
// - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
const checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & SymbolFlags.Merged);
const checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & SymbolFlags.Transient);
if (checkBody && node.body) {
// body of ambient external module is always a module block
for (const statement of (<ModuleBlock>node.body).statements) {
@@ -19225,7 +19358,7 @@ namespace ts {
// this is done it two steps
// 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
// 2. main check - report error if value declaration of the parent symbol is module augmentation)
let reportError = !(symbol.flags & SymbolFlags.Merged);
let reportError = !(symbol.flags & SymbolFlags.Transient);
if (!reportError) {
// symbol should not originate in augmentation
reportError = isExternalModuleAugmentation(symbol.parent.declarations[0]);
@@ -20327,7 +20460,7 @@ namespace ts {
}
function getRootSymbols(symbol: Symbol): Symbol[] {
if (symbol.flags & SymbolFlags.SyntheticProperty) {
if (getCheckFlags(symbol) & CheckFlags.SyntheticProperty) {
const symbols: Symbol[] = [];
const name = symbol.name;
forEach(getSymbolLinks(symbol).containingType.types, t => {
@@ -20628,6 +20761,13 @@ namespace ts {
return false;
}
function isRequiredInitializedParameter(parameter: ParameterDeclaration) {
return strictNullChecks &&
!isOptionalParameter(parameter) &&
parameter.initializer &&
!(getModifierFlags(parameter) & ModifierFlags.ParameterPropertyModifier);
}
function getNodeCheckFlags(node: Node): NodeCheckFlags {
node = getParseTreeNode(node);
return node ? getNodeLinks(node).flags : undefined;
@@ -20719,10 +20859,12 @@ namespace ts {
function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) {
// Get type of the symbol if this is the valid symbol otherwise get type at location
const symbol = getSymbolOfNode(declaration);
const type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature))
let type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature))
? getWidenedLiteralType(getTypeOfSymbol(symbol))
: unknownType;
if (flags & TypeFormatFlags.AddUndefined) {
type = includeFalsyTypes(type, TypeFlags.Undefined);
}
getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags);
}
@@ -20821,6 +20963,7 @@ namespace ts {
isTopLevelValueImportEqualsWithEntityName,
isDeclarationVisible,
isImplementationOfOverload,
isRequiredInitializedParameter,
writeTypeOfDeclaration,
writeReturnTypeOfSignatureDeclaration,
writeTypeOfExpression,
@@ -21078,7 +21221,7 @@ namespace ts {
function createThenableType() {
// build the thenable type that is used to verify against a non-promise "thenable" operand to `await`.
const thenPropertySymbol = createSymbol(SymbolFlags.Transient | SymbolFlags.Property, "then");
const thenPropertySymbol = createSymbol(SymbolFlags.Property, "then");
getSymbolLinks(thenPropertySymbol).type = globalFunctionType;
const thenableType = <ResolvedType>createObjectType(ObjectFlags.Anonymous);
@@ -22010,6 +22153,11 @@ namespace ts {
}
}
if (compilerOptions.module !== ModuleKind.ES2015 && compilerOptions.module !== ModuleKind.System && !compilerOptions.noEmit &&
!isInAmbientContext(node.parent.parent) && hasModifier(node.parent.parent, ModifierFlags.Export)) {
checkESModuleMarker(node.name);
}
const checkLetConstNames = (isLet(node) || isConst(node));
// 1. LexicalDeclaration : LetOrConst BindingList ;
@@ -22022,6 +22170,22 @@ namespace ts {
return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
}
function checkESModuleMarker(name: Identifier | BindingPattern): boolean {
if (name.kind === SyntaxKind.Identifier) {
if (unescapeIdentifier(name.text) === "__esModule") {
return grammarErrorOnNode(name, Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
}
}
else {
const elements = (<BindingPattern>name).elements;
for (const element of elements) {
if (!isOmittedExpression(element)) {
return checkESModuleMarker(element.name);
}
}
}
}
function checkGrammarNameInLetOrConstDeclarations(name: Identifier | BindingPattern): boolean {
if (name.kind === SyntaxKind.Identifier) {
if ((<Identifier>name).originalKeywordKind === SyntaxKind.LetKeyword) {
+4 -4
View File
@@ -840,7 +840,7 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine {
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: JsFileExtensionInfo[] = []): ParsedCommandLine {
const errors: Diagnostic[] = [];
basePath = normalizeSlashes(basePath);
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
@@ -1186,7 +1186,7 @@ namespace ts {
* @param host The host used to resolve files and directories.
* @param errors An array for diagnostic reporting.
*/
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult {
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: JsFileExtensionInfo[]): ExpandResult {
basePath = normalizePath(basePath);
// The exclude spec list is converted into a regular expression, which allows us to quickly
@@ -1361,7 +1361,7 @@ namespace ts {
*/
function hasFileWithHigherPriorityExtension(file: string, literalFiles: Map<string>, wildcardFiles: Map<string>, extensions: string[], keyMapper: (value: string) => string) {
const extensionPriority = getExtensionPriority(file, extensions);
const adjustedExtensionPriority = adjustExtensionPriority(extensionPriority);
const adjustedExtensionPriority = adjustExtensionPriority(extensionPriority, extensions);
for (let i = ExtensionPriority.Highest; i < adjustedExtensionPriority; i++) {
const higherPriorityExtension = extensions[i];
const higherPriorityPath = keyMapper(changeExtension(file, higherPriorityExtension));
@@ -1383,7 +1383,7 @@ namespace ts {
*/
function removeWildcardFilesWithLowerPriorityExtension(file: string, wildcardFiles: Map<string>, extensions: string[], keyMapper: (value: string) => string) {
const extensionPriority = getExtensionPriority(file, extensions);
const nextExtensionPriority = getNextLowestExtensionPriority(extensionPriority);
const nextExtensionPriority = getNextLowestExtensionPriority(extensionPriority, extensions);
for (let i = nextExtensionPriority; i < extensions.length; i++) {
const lowerPriorityExtension = extensions[i];
const lowerPriorityPath = keyMapper(changeExtension(file, lowerPriorityExtension));
+10
View File
@@ -9,6 +9,7 @@ namespace ts {
emitNodeWithComments(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void;
emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void;
emitTrailingCommentsOfPosition(pos: number): void;
emitLeadingCommentsOfPosition(pos: number): void;
}
export function createCommentWriter(printerOptions: PrinterOptions, emitPos: ((pos: number) => void) | undefined): CommentWriter {
@@ -32,6 +33,7 @@ namespace ts {
emitNodeWithComments,
emitBodyWithDetachedComments,
emitTrailingCommentsOfPosition,
emitLeadingCommentsOfPosition,
};
function emitNodeWithComments(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) {
@@ -210,6 +212,14 @@ namespace ts {
}
}
function emitLeadingCommentsOfPosition(pos: number) {
if (disabled || pos === -1) {
return;
}
emitLeadingComments(pos, /*isEmittedNode*/ true);
}
function emitTrailingComments(pos: number) {
forEachTrailingCommentToEmit(pos, emitTrailingComment);
}
+20 -14
View File
@@ -895,6 +895,14 @@ namespace ts {
return result;
}
export function convertToArray<T, U>(iterator: Iterator<T>, f: (value: T) => U) {
const result: U[] = [];
for (let { value, done } = iterator.next(); !done; { value, done } = iterator.next()) {
result.push(f(value));
}
return result;
}
/**
* Calls `callback` for each entry in the map, returning the first truthy result.
* Use `map.forEach` instead for normal iteration.
@@ -2012,14 +2020,14 @@ namespace ts {
export const supportedJavascriptExtensions = [".js", ".jsx"];
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] {
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: JsFileExtensionInfo[]): string[] {
const needAllExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
}
const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0);
const extensions = allSupportedExtensions.slice(0);
for (const extInfo of extraFileExtensions) {
if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) {
if (extensions.indexOf(extInfo.extension) === -1) {
extensions.push(extInfo.extension);
}
}
@@ -2034,7 +2042,7 @@ namespace ts {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) {
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: JsFileExtensionInfo[]) {
if (!fileName) { return false; }
for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) {
@@ -2053,7 +2061,6 @@ namespace ts {
export const enum ExtensionPriority {
TypeScriptFiles = 0,
DeclarationAndJavaScriptFiles = 2,
Limit = 5,
Highest = TypeScriptFiles,
Lowest = DeclarationAndJavaScriptFiles,
@@ -2062,7 +2069,7 @@ namespace ts {
export function getExtensionPriority(path: string, supportedExtensions: string[]): ExtensionPriority {
for (let i = supportedExtensions.length - 1; i >= 0; i--) {
if (fileExtensionIs(path, supportedExtensions[i])) {
return adjustExtensionPriority(<ExtensionPriority>i);
return adjustExtensionPriority(<ExtensionPriority>i, supportedExtensions);
}
}
@@ -2074,27 +2081,26 @@ namespace ts {
/**
* Adjusts an extension priority to be the highest priority within the same range.
*/
export function adjustExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority {
export function adjustExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: string[]): ExtensionPriority {
if (extensionPriority < ExtensionPriority.DeclarationAndJavaScriptFiles) {
return ExtensionPriority.TypeScriptFiles;
}
else if (extensionPriority < ExtensionPriority.Limit) {
else if (extensionPriority < supportedExtensions.length) {
return ExtensionPriority.DeclarationAndJavaScriptFiles;
}
else {
return ExtensionPriority.Limit;
}
}
return supportedExtensions.length;
} }
/**
* Gets the next lowest extension priority for a given priority.
*/
export function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority {
export function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: string[]): ExtensionPriority {
if (extensionPriority < ExtensionPriority.DeclarationAndJavaScriptFiles) {
return ExtensionPriority.DeclarationAndJavaScriptFiles;
}
else {
return ExtensionPriority.Limit;
return supportedExtensions.length;
}
}
+9 -2
View File
@@ -324,13 +324,20 @@ namespace ts {
function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, type: TypeNode, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) {
writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic;
write(": ");
if (type) {
// use the checker's type, not the declared type,
// for non-optional initialized parameters that aren't a parameter property
const shouldUseResolverType = declaration.kind === SyntaxKind.Parameter &&
resolver.isRequiredInitializedParameter(declaration as ParameterDeclaration);
if (type && !shouldUseResolverType) {
// Write the type
emitType(type);
}
else {
errorNameNode = declaration.name;
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer);
const format = TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue |
(shouldUseResolverType ? TypeFormatFlags.AddUndefined : 0);
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer);
errorNameNode = undefined;
}
}
+9 -5
View File
@@ -671,6 +671,10 @@
"category": "Error",
"code": 1215
},
"Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules.": {
"category": "Error",
"code": 1216
},
"Export assignment is not supported when '--module' flag is 'system'.": {
"category": "Error",
"code": 1218
@@ -1787,6 +1791,10 @@
"category": "Error",
"code": 2545
},
"Property '{0}' has conflicting declarations and is inaccessible in type '{1}'.": {
"category": "Error",
"code": 2546
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@@ -2801,7 +2809,7 @@
"category": "Message",
"code": 6099
},
"'package.json' does not have a 'types' or 'main' field.": {
"'package.json' does not have a '{0}' field.": {
"category": "Message",
"code": 6100
},
@@ -2949,10 +2957,6 @@
"category": "Message",
"code": 6136
},
"No types specified in 'package.json', so returning 'main' value of '{0}'": {
"category": "Message",
"code": 6137
},
"Property '{0}' is declared but never used.": {
"category": "Error",
"code": 6138
+26 -1
View File
@@ -1,4 +1,4 @@
/// <reference path="checker.ts" />
/// <reference path="checker.ts" />
/// <reference path="transformer.ts" />
/// <reference path="declarationEmitter.ts" />
/// <reference path="sourcemap.ts" />
@@ -211,6 +211,7 @@ namespace ts {
emitNodeWithComments,
emitBodyWithDetachedComments,
emitTrailingCommentsOfPosition,
emitLeadingCommentsOfPosition,
} = comments;
let currentSourceFile: SourceFile;
@@ -1346,6 +1347,10 @@ namespace ts {
else {
writeToken(SyntaxKind.OpenBraceToken, node.pos, /*contextNode*/ node);
emitBlockStatements(node);
// We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted
increaseIndent();
emitLeadingCommentsOfPosition(node.statements.end);
decreaseIndent();
writeToken(SyntaxKind.CloseBraceToken, node.statements.end, /*contextNode*/ node);
}
}
@@ -2228,6 +2233,15 @@ namespace ts {
// Write the delimiter if this is not the first node.
if (previousSibling) {
// i.e
// function commentedParameters(
// /* Parameter a */
// a
// /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
// ,
if (delimiter && previousSibling.end !== parentNode.end) {
emitLeadingCommentsOfPosition(previousSibling.end);
}
write(delimiter);
// Write either a line terminator or whitespace to separate the elements.
@@ -2274,6 +2288,17 @@ namespace ts {
write(",");
}
// Emit any trailing comment of the last element in the list
// i.e
// var array = [...
// 2
// /* end of element 2 */
// ];
if (previousSibling && delimiter && previousSibling.end !== parentNode.end) {
emitLeadingCommentsOfPosition(previousSibling.end);
}
// Decrease the indent, if requested.
if (format & ListFormat.Indented) {
decreaseIndent();
+65 -67
View File
@@ -67,40 +67,31 @@ namespace ts {
}
/** Reads from "main" or "types"/"typings" depending on `extensions`. */
function tryReadPackageJsonMainOrTypes(extensions: Extensions, packageJsonPath: string, baseDirectory: string, state: ModuleResolutionState): string {
function tryReadPackageJsonFields(readTypes: boolean, packageJsonPath: string, baseDirectory: string, state: ModuleResolutionState): string | undefined {
const jsonContent = readJson(packageJsonPath, state.host);
return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main");
switch (extensions) {
case Extensions.DtsOnly:
case Extensions.TypeScript:
return tryReadFromField("typings") || tryReadFromField("types");
case Extensions.JavaScript:
if (typeof jsonContent.main === "string") {
if (state.traceEnabled) {
trace(state.host, Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main);
}
return normalizePath(combinePaths(baseDirectory, jsonContent.main));
}
return undefined;
}
function tryReadFromField(fieldName: string) {
if (hasProperty(jsonContent, fieldName)) {
const typesFile = (<any>jsonContent)[fieldName];
if (typeof typesFile === "string") {
const typesFilePath = normalizePath(combinePaths(baseDirectory, typesFile));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath);
}
return typesFilePath;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
}
function tryReadFromField(fieldName: "typings" | "types" | "main"): string | undefined {
if (!hasProperty(jsonContent, fieldName)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName);
}
return;
}
const fileName = jsonContent[fieldName];
if (typeof fileName !== "string") {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName);
}
return;
}
const path = normalizePath(combinePaths(baseDirectory, fileName));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
}
return path;
}
}
@@ -698,7 +689,8 @@ namespace ts {
return { resolvedModule: undefined, failedLookupLocations };
function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> {
const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state);
const loader: ResolutionKindSpecificLoader = (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/true);
const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state);
if (resolved) {
return toSearchResult({ resolved, isExternalLibraryImport: false });
}
@@ -713,7 +705,7 @@ namespace ts {
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
const resolved = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state);
const resolved = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/true);
return resolved && toSearchResult({ resolved, isExternalLibraryImport: false });
}
}
@@ -731,7 +723,7 @@ namespace ts {
return real;
}
function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson: boolean): Resolved | undefined {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
}
@@ -759,7 +751,7 @@ namespace ts {
onlyRecordFailures = true;
}
}
return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state);
return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson);
}
/* @internal */
@@ -835,50 +827,57 @@ namespace ts {
return undefined;
}
function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
const packageJsonPath = pathToPackageJson(candidate);
function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true): Resolved | undefined {
const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
if (directoryExists && state.host.fileExists(packageJsonPath)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath);
}
const mainOrTypesFile = tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, candidate, state);
if (mainOrTypesFile) {
const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(mainOrTypesFile), state.host);
// A package.json "typings" may specify an exact filename, or may choose to omit an extension.
const fromExactFile = tryFile(mainOrTypesFile, failedLookupLocations, onlyRecordFailures, state);
if (fromExactFile) {
const resolved = fromExactFile && resolvedIfExtensionMatches(extensions, fromExactFile);
if (resolved) {
return resolved;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromExactFile);
}
}
const resolved = tryAddingExtensions(mainOrTypesFile, Extensions.TypeScript, failedLookupLocations, onlyRecordFailures, state);
if (resolved) {
return resolved;
if (considerPackageJson) {
const packageJsonPath = pathToPackageJson(candidate);
if (directoryExists && state.host.fileExists(packageJsonPath)) {
const fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state);
if (fromPackageJson) {
return fromPackageJson;
}
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_does_not_have_a_types_or_main_field);
if (directoryExists && state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath);
}
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
failedLookupLocations.push(packageJsonPath);
}
}
else {
if (directoryExists && state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath);
}
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
failedLookupLocations.push(packageJsonPath);
}
return loadModuleFromFile(extensions, combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state);
}
function loadModuleFromPackageJson(packageJsonPath: string, extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, state: ModuleResolutionState): Resolved | undefined {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath);
}
const file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state);
if (!file) {
return undefined;
}
const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(file), state.host);
const fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state);
if (fromFile) {
const resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile);
if (resolved) {
return resolved;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
}
}
// Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
const nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
// Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false);
}
/** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
function resolvedIfExtensionMatches(extensions: Extensions, path: string): Resolved | undefined {
const extension = tryGetExtensionFromPath(path);
@@ -1040,7 +1039,6 @@ namespace ts {
return value !== undefined ? { value } : undefined;
}
/** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */
function forEachAncestorDirectory<T>(directory: string, callback: (directory: string) => SearchResult<T>): SearchResult<T> {
while (true) {
+8 -1
View File
@@ -485,7 +485,10 @@ namespace ts {
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
let options: any;
if (!directoryExists(directoryName)) {
if (!directoryExists(directoryName) || (isUNCPath(directoryName) && process.platform === "win32")) {
// do nothing if either
// - target folder does not exist
// - this is UNC path on Windows (https://github.com/Microsoft/TypeScript/issues/13874)
return noOpFileWatcher;
}
@@ -509,6 +512,10 @@ namespace ts {
};
}
);
function isUNCPath(s: string): boolean {
return s.length > 2 && s.charCodeAt(0) === CharacterCodes.slash && s.charCodeAt(1) === CharacterCodes.slash;
}
},
resolvePath: function(path: string): string {
return _path.resolve(path);
+40 -34
View File
@@ -83,6 +83,11 @@ namespace ts {
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
if (!currentModuleInfo.exportEquals) {
append(statements, createUnderscoreUnderscoreESModule());
}
append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement, /*optional*/ true));
addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset));
addRange(statements, endLexicalEnvironment());
@@ -92,7 +97,6 @@ namespace ts {
if (currentModuleInfo.hasExportStarsToExportValues) {
addEmitHelper(updated, exportStarHelper);
}
return updated;
}
@@ -371,6 +375,10 @@ namespace ts {
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
if (!currentModuleInfo.exportEquals) {
append(statements, createUnderscoreUnderscoreESModule());
}
// Visit each statement of the module body.
append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement, /*optional*/ true));
addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset));
@@ -665,6 +673,7 @@ namespace ts {
}
const generatedName = getGeneratedNameForNode(node);
if (node.exportClause) {
const statements: Statement[] = [];
// export { x, y } from "mod";
@@ -838,6 +847,7 @@ namespace ts {
let statements: Statement[];
let variables: VariableDeclaration[];
let expressions: Expression[];
if (hasModifier(node, ModifierFlags.Export)) {
let modifiers: NodeArray<Modifier>;
@@ -1127,43 +1137,39 @@ namespace ts {
* @param allowComments Whether to allow comments on the export.
*/
function appendExportStatement(statements: Statement[] | undefined, exportName: Identifier, expression: Expression, location?: TextRange, allowComments?: boolean): Statement[] | undefined {
if (exportName.text === "default") {
const sourceFile = getOriginalNode(currentSourceFile, isSourceFile);
if (sourceFile && !sourceFile.symbol.exports.get("___esModule")) {
if (languageVersion === ScriptTarget.ES3) {
statements = append(statements,
createStatement(
createExportExpression(
createIdentifier("__esModule"),
createTrue()
)
)
);
}
else {
statements = append(statements,
createStatement(
createCall(
createPropertyAccess(createIdentifier("Object"), "defineProperty"),
/*typeArguments*/ undefined,
[
createIdentifier("exports"),
createLiteral("__esModule"),
createObjectLiteral([
createPropertyAssignment("value", createTrue())
])
]
)
)
);
}
}
}
statements = append(statements, createExportStatement(exportName, expression, location, allowComments));
return statements;
}
function createUnderscoreUnderscoreESModule() {
let statement: Statement;
if (languageVersion === ScriptTarget.ES3) {
statement = createStatement(
createExportExpression(
createIdentifier("__esModule"),
createLiteral(true)
)
)
}
else {
statement = createStatement(
createCall(
createPropertyAccess(createIdentifier("Object"), "defineProperty"),
/*typeArguments*/ undefined,
[
createIdentifier("exports"),
createLiteral("__esModule"),
createObjectLiteral([
createPropertyAssignment("value", createLiteral(true))
])
]
)
);
}
setEmitFlags(statement, EmitFlags.CustomPrologue);
return statement;
}
/**
* Creates a call to the current file's export function to export a value.
*
+63 -39
View File
@@ -2071,10 +2071,25 @@
ArrayMutation = 1 << 8, // Potential array mutation
Referenced = 1 << 9, // Referenced as antecedent once
Shared = 1 << 10, // Referenced as antecedent more than once
PreFinally = 1 << 11, // Injected edge that links pre-finally label and pre-try flow
AfterFinally = 1 << 12, // Injected edge that links post-finally flow with the rest of the graph
Label = BranchLabel | LoopLabel,
Condition = TrueCondition | FalseCondition
}
export interface FlowLock {
locked?: boolean;
}
export interface AfterFinallyFlow extends FlowNode, FlowLock {
antecedent: FlowNode;
}
export interface PreFinallyFlow extends FlowNode {
antecedent: FlowNode;
lock: FlowLock;
}
export interface FlowNode {
flags: FlowFlags;
id?: number; // Node id used by flow type cache in checker
@@ -2474,7 +2489,8 @@
InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type
InTypeAlias = 0x00000200, // Writing type in type alias declaration
UseTypeAliasValue = 0x00000400, // Serialize the type instead of using type-alias. This is needed when we emit declaration file.
SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type.
SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type.
AddUndefined = 0x00001000, // Add undefined to types of initialized, non-optional parameters
}
export const enum SymbolFormatFlags {
@@ -2579,6 +2595,7 @@
isDeclarationVisible(node: Declaration): boolean;
collectLinkedAliases(node: Identifier): Node[];
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
isRequiredInitializedParameter(node: ParameterDeclaration): boolean;
writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
@@ -2602,37 +2619,34 @@
export const enum SymbolFlags {
None = 0,
FunctionScopedVariable = 0x00000001, // Variable (var) or parameter
BlockScopedVariable = 0x00000002, // A block-scoped variable (let or const)
Property = 0x00000004, // Property or enum member
EnumMember = 0x00000008, // Enum member
Function = 0x00000010, // Function
Class = 0x00000020, // Class
Interface = 0x00000040, // Interface
ConstEnum = 0x00000080, // Const enum
RegularEnum = 0x00000100, // Enum
ValueModule = 0x00000200, // Instantiated module
NamespaceModule = 0x00000400, // Uninstantiated module
TypeLiteral = 0x00000800, // Type Literal or mapped type
ObjectLiteral = 0x00001000, // Object Literal
Method = 0x00002000, // Method
Constructor = 0x00004000, // Constructor
GetAccessor = 0x00008000, // Get accessor
SetAccessor = 0x00010000, // Set accessor
Signature = 0x00020000, // Call, construct, or index signature
TypeParameter = 0x00040000, // Type parameter
TypeAlias = 0x00080000, // Type alias
ExportValue = 0x00100000, // Exported value marker (see comment in declareModuleMember in binder)
ExportType = 0x00200000, // Exported type marker (see comment in declareModuleMember in binder)
ExportNamespace = 0x00400000, // Exported namespace marker (see comment in declareModuleMember in binder)
Alias = 0x00800000, // An alias for another symbol (see comment in isAliasSymbolDeclaration in checker)
Instantiated = 0x01000000, // Instantiated symbol
Merged = 0x02000000, // Merged symbol (created during program binding)
Transient = 0x04000000, // Transient symbol (created during type check)
Prototype = 0x08000000, // Prototype property (no source representation)
SyntheticProperty = 0x10000000, // Property in union or intersection type
Optional = 0x20000000, // Optional property
ExportStar = 0x40000000, // Export * declaration
FunctionScopedVariable = 1 << 0, // Variable (var) or parameter
BlockScopedVariable = 1 << 1, // A block-scoped variable (let or const)
Property = 1 << 2, // Property or enum member
EnumMember = 1 << 3, // Enum member
Function = 1 << 4, // Function
Class = 1 << 5, // Class
Interface = 1 << 6, // Interface
ConstEnum = 1 << 7, // Const enum
RegularEnum = 1 << 8, // Enum
ValueModule = 1 << 9, // Instantiated module
NamespaceModule = 1 << 10, // Uninstantiated module
TypeLiteral = 1 << 11, // Type Literal or mapped type
ObjectLiteral = 1 << 12, // Object Literal
Method = 1 << 13, // Method
Constructor = 1 << 14, // Constructor
GetAccessor = 1 << 15, // Get accessor
SetAccessor = 1 << 16, // Set accessor
Signature = 1 << 17, // Call, construct, or index signature
TypeParameter = 1 << 18, // Type parameter
TypeAlias = 1 << 19, // Type alias
ExportValue = 1 << 20, // Exported value marker (see comment in declareModuleMember in binder)
ExportType = 1 << 21, // Exported type marker (see comment in declareModuleMember in binder)
ExportNamespace = 1 << 22, // Exported namespace marker (see comment in declareModuleMember in binder)
Alias = 1 << 23, // An alias for another symbol (see comment in isAliasSymbolDeclaration in checker)
Prototype = 1 << 24, // Prototype property (no source representation)
ExportStar = 1 << 25, // Export * declaration
Optional = 1 << 26, // Optional property
Transient = 1 << 27, // Transient symbol (created during type check)
Enum = RegularEnum | ConstEnum,
Variable = FunctionScopedVariable | BlockScopedVariable,
@@ -2692,11 +2706,9 @@
name: string; // Name of symbol
declarations?: Declaration[]; // Declarations associated with this symbol
valueDeclaration?: Declaration; // First value declaration of the symbol
members?: SymbolTable; // Class, interface or literal instance members
exports?: SymbolTable; // Module exports
globalExports?: SymbolTable; // Conditional global UMD exports
/* @internal */ isReadonly?: boolean; // readonly? (set only for intersections and unions)
/* @internal */ id?: number; // Unique id (used to look up SymbolLinks)
/* @internal */ mergeId?: number; // Merge id (used to look up merged symbol)
/* @internal */ parent?: Symbol; // Parent symbol
@@ -2721,8 +2733,6 @@
leftSpread?: Symbol; // Left source for synthetic spread property
rightSpread?: Symbol; // Right source for synthetic spread property
mappedTypeOrigin?: Symbol; // For a property on a mapped type, points back to the orignal 'T' from 'keyof T'.
hasNonUniformType?: boolean; // True if constituents have non-uniform types
isPartial?: boolean; // True if syntheric property of union type occurs in some but not all constituents
isDiscriminantProperty?: boolean; // True if discriminant synthetic property
resolvedExports?: SymbolTable; // Resolved exports of module
exportsChecked?: boolean; // True if exports of external module have been checked
@@ -2732,7 +2742,22 @@
}
/* @internal */
export interface TransientSymbol extends Symbol, SymbolLinks { }
export const enum CheckFlags {
Instantiated = 1 << 0, // Instantiated symbol
SyntheticProperty = 1 << 1, // Property in union or intersection type
Readonly = 1 << 2, // Readonly transient symbol
Partial = 1 << 3, // Synthetic property present in some but not all constituents
HasNonUniformType = 1 << 4, // Synthetic property with non-uniform type in constituents
ContainsPublic = 1 << 5, // Synthetic property with public constituent(s)
ContainsProtected = 1 << 6, // Synthetic property with protected constituent(s)
ContainsPrivate = 1 << 7, // Synthetic property with private constituent(s)
ContainsStatic = 1 << 8, // Synthetic property with static constituent(s)
}
/* @internal */
export interface TransientSymbol extends Symbol, SymbolLinks {
checkFlags: CheckFlags;
}
export type SymbolTable = Map<Symbol>;
@@ -3145,9 +3170,8 @@
ThisProperty
}
export interface FileExtensionInfo {
export interface JsFileExtensionInfo {
extension: string;
scriptKind: ScriptKind;
isMixedContent: boolean;
}
+5
View File
@@ -1518,6 +1518,11 @@ namespace ts {
return map(getJSDocs(node), doc => doc.comment);
}
export function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration) {
const parameterTags = getJSDocTags(node, SyntaxKind.JSDocParameterTag);
return parameterTags && parameterTags.length > 0;
}
function getJSDocTags(node: Node, kind: SyntaxKind): JSDocTag[] {
const docs = getJSDocs(node);
if (docs) {
+93 -30
View File
@@ -183,7 +183,7 @@ namespace FourSlash {
// The current caret position in the active file
public currentCaretPosition = 0;
public lastKnownMarker: string = "";
public lastKnownMarker = "";
// The file that's currently 'opened'
public activeFile: FourSlashFile;
@@ -452,7 +452,8 @@ namespace FourSlash {
}
private messageAtLastKnownMarker(message: string) {
return "Marker: " + this.lastKnownMarker + "\n" + message;
const locationDescription = this.lastKnownMarker ? this.lastKnownMarker : this.getLineColStringAtPosition(this.currentCaretPosition);
return `At ${locationDescription}: ${message}`;
}
private assertionMessageAtLastKnownMarker(msg: string) {
@@ -562,7 +563,7 @@ namespace FourSlash {
}
public verifyGoToDefinitionIs(endMarker: string | string[]) {
this.verifyGoToXWorker(endMarker instanceof Array ? endMarker : [endMarker], () => this.getGoToDefinition());
this.verifyGoToXWorker(toArray(endMarker), () => this.getGoToDefinition());
}
public verifyGoToDefinition(arg0: any, endMarkerNames?: string | string[]) {
@@ -582,7 +583,7 @@ namespace FourSlash {
if (endMarkerNames) {
this.verifyGoToXPlain(arg0, endMarkerNames, getDefs);
}
else if (arg0 instanceof Array) {
else if (ts.isArray(arg0)) {
const pairs: [string | string[], string | string[]][] = arg0;
for (const [start, end] of pairs) {
this.verifyGoToXPlain(start, end, getDefs);
@@ -599,13 +600,8 @@ namespace FourSlash {
}
private verifyGoToXPlain(startMarkerNames: string | string[], endMarkerNames: string | string[], getDefs: () => ts.DefinitionInfo[] | undefined) {
if (startMarkerNames instanceof Array) {
for (const start of startMarkerNames) {
this.verifyGoToXSingle(start, endMarkerNames, getDefs);
}
}
else {
this.verifyGoToXSingle(startMarkerNames, endMarkerNames, getDefs);
for (const start of toArray(startMarkerNames)) {
this.verifyGoToXSingle(start, endMarkerNames, getDefs);
}
}
@@ -617,7 +613,7 @@ namespace FourSlash {
private verifyGoToXSingle(startMarkerName: string, endMarkerNames: string | string[], getDefs: () => ts.DefinitionInfo[] | undefined) {
this.goToMarker(startMarkerName);
this.verifyGoToXWorker(endMarkerNames instanceof Array ? endMarkerNames : [endMarkerNames], getDefs);
this.verifyGoToXWorker(toArray(endMarkerNames), getDefs);
}
private verifyGoToXWorker(endMarkers: string[], getDefs: () => ts.DefinitionInfo[] | undefined) {
@@ -899,8 +895,74 @@ namespace FourSlash {
}
}
public verifyRangesWithSameTextReferenceEachOther() {
this.rangesByText().forEach(ranges => this.verifyRangesReferenceEachOther(ranges));
public verifyReferenceGroups(startRanges: Range | Range[], parts: Array<{ definition: string, ranges: Range[] }>): void {
interface ReferenceJson { definition: string; ranges: ts.ReferenceEntry[]; }
type ReferencesJson = ReferenceJson[];
const fullExpected = parts.map<ReferenceJson>(({ definition, ranges }) => ({ definition, ranges: ranges.map(rangeToReferenceEntry) }));
for (const startRange of toArray(startRanges)) {
this.goToRangeStart(startRange);
const fullActual = this.findReferencesAtCaret().map<ReferenceJson>(({ definition, references }) => ({
definition: definition.displayParts.map(d => d.text).join(""),
ranges: references
}));
this.assertObjectsEqual<ReferencesJson>(fullActual, fullExpected);
}
function rangeToReferenceEntry(r: Range) {
let { isWriteAccess, isDefinition } = (r.marker && r.marker.data) || { isWriteAccess: false, isDefinition: false };
isWriteAccess = !!isWriteAccess; isDefinition = !!isDefinition;
return { fileName: r.fileName, textSpan: { start: r.start, length: r.end - r.start }, isWriteAccess, isDefinition }
}
}
public verifyNoReferences(markerNameOrRange?: string | Range) {
if (markerNameOrRange) {
if (typeof markerNameOrRange === "string") {
this.goToMarker(markerNameOrRange);
}
else {
this.goToRangeStart(markerNameOrRange);
}
}
const refs = this.getReferencesAtCaret();
if (refs && refs.length) {
console.log(refs);
this.raiseError("Expected getReferences to fail");
}
}
public verifySingleReferenceGroup(definition: string, ranges?: Range[]) {
ranges = ranges || this.getRanges();
this.verifyReferenceGroups(ranges, [{ definition, ranges }]);
}
private assertObjectsEqual<T>(fullActual: T, fullExpected: T, msgPrefix = ""): void {
const recur = <U>(actual: U, expected: U, path: string) => {
const fail = (msg: string) => {
console.log("Expected:", stringify(fullExpected));
console.log("Actual: ", stringify(fullActual));
this.raiseError(`${msgPrefix}At ${path}: ${msg}`);
};
for (const key in actual) if (ts.hasProperty(actual as any, key)) {
const ak = actual[key], ek = expected[key];
if (typeof ak === "object" && typeof ek === "object") {
recur(ak, ek, path ? path + "." + key : key);
}
else if (ak !== ek) {
fail(`Expected '${key}' to be '${ek}', got '${ak}'`);
}
}
for (const key in expected) if (ts.hasProperty(expected as any, key)) {
if (!ts.hasProperty(actual as any, key)) {
fail(`${msgPrefix}Missing property '${key}'`);
}
}
};
recur(fullActual, fullExpected, "");
}
public verifyDisplayPartsOfReferencedSymbol(expected: ts.SymbolDisplayPart[]) {
@@ -974,7 +1036,7 @@ namespace FourSlash {
public verifyQuickInfos(namesAndTexts: { [name: string]: string | [string, string] }) {
for (const name in namesAndTexts) if (ts.hasProperty(namesAndTexts, name)) {
const text = namesAndTexts[name];
if (text instanceof Array) {
if (ts.isArray(text)) {
assert(text.length === 2);
const [expectedText, expectedDocumentation] = text;
this.verifyQuickInfoAt(name, expectedText, expectedDocumentation);
@@ -1411,13 +1473,6 @@ namespace FourSlash {
Harness.IO.log(membersString);
}
public printReferences() {
const references = this.getReferencesAtCaret();
ts.forEach(references, entry => {
Harness.IO.log(stringify(entry));
});
}
public printContext() {
ts.forEach(this.languageServiceAdapterHost.getFilenames(), Harness.IO.log);
}
@@ -3082,6 +3137,10 @@ ${code}
}
return ts.arrayFrom(set.keys());
}
function toArray<T>(x: T | T[]): T[] {
return ts.isArray(x) ? x : [x];
}
}
namespace FourSlashInterface {
@@ -3346,6 +3405,18 @@ namespace FourSlashInterface {
this.state.verifyReferencesOf(start, references);
}
public referenceGroups(startRanges: FourSlash.Range[], parts: Array<{ definition: string, ranges: FourSlash.Range[] }>) {
this.state.verifyReferenceGroups(startRanges, parts);
}
public noReferences(markerNameOrRange?: string | FourSlash.Range) {
this.state.verifyNoReferences(markerNameOrRange);
}
public singleReferenceGroup(definition: string, ranges?: FourSlash.Range[]) {
this.state.verifySingleReferenceGroup(definition, ranges);
}
public rangesReferenceEachOther(ranges?: FourSlash.Range[]) {
this.state.verifyRangesReferenceEachOther(ranges);
}
@@ -3354,10 +3425,6 @@ namespace FourSlashInterface {
this.state.verifyDisplayPartsOfReferencedSymbol(expected);
}
public rangesWithSameTextReferenceEachOther() {
this.state.verifyRangesWithSameTextReferenceEachOther();
}
public currentParameterHelpArgumentNameIs(name: string) {
this.state.verifyCurrentParameterHelpName(name);
}
@@ -3660,10 +3727,6 @@ namespace FourSlashInterface {
this.state.printNavigationBar();
}
public printReferences() {
this.state.printReferences();
}
public printContext() {
this.state.printContext();
}
+2 -2
View File
@@ -5,7 +5,7 @@
namespace Harness.LanguageService {
export class ScriptInfo {
public version: number = 1;
public version = 1;
public editRanges: { length: number; textChangeRange: ts.TextChangeRange; }[] = [];
private lineMap: number[] = undefined;
@@ -594,7 +594,7 @@ namespace Harness.LanguageService {
class SessionServerHost implements ts.server.ServerHost, ts.server.Logger {
args: string[] = [];
newLine: string;
useCaseSensitiveFileNames: boolean = false;
useCaseSensitiveFileNames = false;
constructor(private host: NativeLanguageServiceHost) {
this.newLine = this.host.getNewLine();
+1 -1
View File
@@ -520,7 +520,7 @@ namespace ts.projectSystem {
const expectedEmittedFileName = "/a/b/f1.js";
assert.isTrue(host.fileExists(expectedEmittedFileName));
assert.equal(host.readFile(expectedEmittedFileName), `"use strict";\r\nfunction Foo() { return 10; }\r\nexports.Foo = Foo;\r\n`);
assert.equal(host.readFile(expectedEmittedFileName), `"use strict";\r\nexports.__esModule = true;\r\nfunction Foo() { return 10; }\r\nexports.Foo = Foo;\r\n`);
});
it("shoud not emit js files in external projects", () => {
+84 -1
View File
@@ -1589,6 +1589,41 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]);
});
it ("loading files with correct priority", () => {
const f1 = {
path: "/a/main.ts",
content: "let x = 1"
};
const f2 = {
path: "/a/main.js",
content: "var y = 1"
};
const config = {
path: "/a/tsconfig.json",
content: JSON.stringify({
compilerOptions: { allowJs: true }
})
};
const host = createServerHost([f1, f2, config]);
const projectService = createProjectService(host);
projectService.setHostConfiguration({
extraFileExtensions: [
{ extension: ".js", isMixedContent: false },
{ extension: ".html", isMixedContent: true }
]
});
projectService.openClientFile(f1.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [ f1.path ]);
projectService.closeClientFile(f1.path);
projectService.openClientFile(f2.path);
projectService.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [ f1.path ]);
checkProjectActualFiles(projectService.inferredProjects[0], [ f2.path ]);
});
it("tsconfig script block support", () => {
const file1 = {
path: "/a/b/f1.ts",
@@ -3031,6 +3066,54 @@ namespace ts.projectSystem {
});
});
describe("emit with outFile or out setting", () => {
function test(opts: CompilerOptions, expectedUsesOutFile: boolean) {
const f1 = {
path: "/a/a.ts",
content: "let x = 1"
};
const f2 = {
path: "/a/b.ts",
content: "let y = 1"
};
const config = {
path: "/a/tsconfig.json",
content: JSON.stringify({
compilerOptions: opts,
compileOnSave: true
})
};
const host = createServerHost([f1, f2, config]);
const session = createSession(host);
session.executeCommand(<protocol.OpenRequest>{
seq: 1,
type: "request",
command: "open",
arguments: { file: f1.path }
});
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 1 });
const { response } = session.executeCommand(<protocol.CompileOnSaveAffectedFileListRequest>{
seq: 2,
type: "request",
command: "compileOnSaveAffectedFileList",
arguments: { file: f1.path }
});
assert.equal((<protocol.CompileOnSaveAffectedFileListSingleProject[]>response).length, 1, "expected output for 1 project");
assert.equal((<protocol.CompileOnSaveAffectedFileListSingleProject[]>response)[0].fileNames.length, 2, "expected output for 1 project");
assert.equal((<protocol.CompileOnSaveAffectedFileListSingleProject[]>response)[0].projectUsesOutFile, expectedUsesOutFile, "usesOutFile");
}
it ("projectUsesOutFile should not be returned if not set", () => {
test({}, /*expectedUsesOutFile*/ false);
});
it ("projectUsesOutFile should be true if outFile is set", () => {
test({ outFile: "/a/out.js" }, /*expectedUsesOutFile*/ true);
});
it ("projectUsesOutFile should be true if out is set", () => {
test({ out: "/a/out.js" }, /*expectedUsesOutFile*/ true);
});
});
describe("import helpers", () => {
it("should not crash in tsserver", () => {
const f1 = {
@@ -3067,7 +3150,7 @@ namespace ts.projectSystem {
let options = project.getCompilerOptions();
assert.isTrue(options.maxNodeModuleJsDepth === 2);
// Assert the option sticks
// Assert the option sticks
projectService.setCompilerOptionsForInferredProjects({ target: ScriptTarget.ES2016 });
project = projectService.inferredProjects[0];
options = project.getCompilerOptions();
+39
View File
@@ -46,6 +46,45 @@ namespace ts.projectSystem {
import typingsName = server.typingsInstaller.typingsName;
describe("local module", () => {
it("should not be picked up", () => {
const f1 = {
path: "/a/app.js",
content: "const c = require('./config');"
};
const f2 = {
path: "/a/config.js",
content: "export let x = 1"
};
const typesCache = "/cache"
const typesConfig = {
path: typesCache + "/node_modules/@types/config/index.d.ts",
content: "export let y: number;"
};
const config = {
path: "/a/jsconfig.json",
content: JSON.stringify({
compilerOptions: { moduleResolution: "commonjs" },
typeAcquisition: { enable: true }
})
};
const host = createServerHost([f1, f2, config, typesConfig]);
const installer = new (class extends Installer {
constructor() {
super(host, { typesRegistry: createTypesRegistry("config"), globalTypingsCacheLocation: typesCache });
}
installWorker(_requestId: number, _args: string[], _cwd: string, _cb: server.typingsInstaller.RequestCompletedAction) {
assert(false, "should not be called")
}
})();
const service = createProjectService(host, { typingsInstaller: installer });
service.openClientFile(f1.path);
service.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(service.configuredProjects[0], [f1.path, f2.path]);
installer.installAll(0);
});
});
describe("typingsInstaller", () => {
it("configured projects (typings installed) 1", () => {
const file1 = {
@@ -1,7 +1,7 @@
/// <reference types="node" />
// TODO: extract services types
// TODO: extract services types
interface HostCancellationToken {
isCancellationRequested(): boolean;
}
+2 -2
View File
@@ -107,7 +107,7 @@ namespace ts.server {
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
hostInfo: string;
extraFileExtensions?: FileExtensionInfo[];
extraFileExtensions?: JsFileExtensionInfo[];
}
interface ConfigFileConversionResult {
@@ -132,7 +132,7 @@ namespace ts.server {
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T): ScriptKind;
hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[]): boolean;
hasMixedContent(f: T, extraFileExtensions: JsFileExtensionInfo[]): boolean;
}
const fileNamePropertyReader: FilePropertyReader<string> = {
+1 -1
View File
@@ -28,7 +28,7 @@ namespace ts.server {
: undefined;
const primaryResult = resolveModuleName(moduleName, containingFile, compilerOptions, host);
// return result immediately only if it is .ts, .tsx or .d.ts
if (!(primaryResult.resolvedModule && extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) {
if (moduleHasNonRelativeName(moduleName) && !(primaryResult.resolvedModule && extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) {
// otherwise try to load typings from @types
// create different collection of failed lookup locations for second pass
+7 -2
View File
@@ -1001,9 +1001,9 @@ namespace ts.server.protocol {
formatOptions?: FormatCodeSettings;
/**
* The host's additional supported file extensions
* The host's additional supported .js file extensions
*/
extraFileExtensions?: FileExtensionInfo[];
extraFileExtensions?: JsFileExtensionInfo[];
}
/**
@@ -1239,6 +1239,11 @@ namespace ts.server.protocol {
* List of files names that should be recompiled
*/
fileNames: string[];
/**
* true if project uses outFile or out compiler option
*/
projectUsesOutFile: boolean;
}
/**
+2 -1
View File
@@ -1040,7 +1040,8 @@ namespace ts.server {
if (project.compileOnSaveEnabled && project.languageServiceEnabled) {
result.push({
projectFileName: project.getProjectName(),
fileNames: project.getCompileOnSaveAffectedFileList(info)
fileNames: project.getCompileOnSaveAffectedFileList(info),
projectUsesOutFile: !!project.getCompilerOptions().outFile || !!project.getCompilerOptions().out
});
}
}
@@ -94,9 +94,9 @@ namespace ts.codefix {
return removeSingleItem(namedImports.elements, token);
}
// handle case where "import d, * as ns from './file'"
// handle case where "import d, * as ns from './file'"
// or "'import {a, b as ns} from './file'"
case SyntaxKind.ImportClause: // this covers both 'import |d|' and 'import |d,| *'
case SyntaxKind.ImportClause: // this covers both 'import |d|' and 'import |d,| *'
const importClause = <ImportClause>token.parent;
if (!importClause.namedBindings) { // |import d from './file'| or |import * as ns from './file'|
const importDecl = findImportDeclaration(importClause);
+5 -16
View File
@@ -5,6 +5,10 @@ namespace ts.FindAllReferences {
return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, isForRename);
}
export function convertReferences(referenceSymbols: ReferencedSymbol[]): ReferenceEntry[] {
return referenceSymbols && flatMap(referenceSymbols, r => r.references);
}
export function getReferencedSymbolsForNode(typeChecker: TypeChecker, cancellationToken: CancellationToken, node: Node, sourceFiles: SourceFile[], findInStrings?: boolean, findInComments?: boolean, isForRename?: boolean, implementations?: boolean): ReferencedSymbol[] | undefined {
if (!implementations) {
const special = getReferencedSymbolsSpecial(node, sourceFiles, typeChecker, cancellationToken);
@@ -277,7 +281,7 @@ namespace ts.FindAllReferences {
// if this symbol is visible from its parent container, e.g. exported, then bail out
// if symbol correspond to the union property - bail out
if (symbol.parent || (symbol.flags & SymbolFlags.SyntheticProperty)) {
if (symbol.parent || (symbol.flags & SymbolFlags.Transient && (<TransientSymbol>symbol).checkFlags & CheckFlags.SyntheticProperty)) {
return undefined;
}
@@ -411,7 +415,6 @@ namespace ts.FindAllReferences {
textSpan: createTextSpan(0, 1),
displayParts: [{ text: name, kind: ScriptElementKind.keyword }]
}
const references: ReferenceEntry[] = [];
for (const sourceFile of sourceFiles) {
cancellationToken.throwIfCancellationRequested();
@@ -1316,20 +1319,6 @@ namespace ts.FindAllReferences {
return meaning;
}
export function convertReferences(referenceSymbols: ReferencedSymbol[]): ReferenceEntry[] {
if (!referenceSymbols) {
return undefined;
}
const referenceEntries: ReferenceEntry[] = [];
for (const referenceSymbol of referenceSymbols) {
addRange(referenceEntries, referenceSymbol.references);
}
return referenceEntries;
}
function isImplementation(node: Node): boolean {
if (!node) {
return false;
+1 -6
View File
@@ -1415,7 +1415,6 @@ namespace ts {
function findReferences(fileName: string, position: number): ReferencedSymbol[] {
const referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false, /*isForRename*/false);
// Only include referenced symbols that have a valid definition.
return filter(referencedSymbols, rs => !!rs.definition);
}
@@ -2015,9 +2014,5 @@ namespace ts {
throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. ");
}
function initializeServices() {
objectAllocator = getServicesObjectAllocator();
}
initializeServices();
objectAllocator = getServicesObjectAllocator();
}
+1 -1
View File
@@ -51,7 +51,7 @@ namespace ts.SymbolDisplay {
if (flags & SymbolFlags.Constructor) return ScriptElementKind.constructorImplementationElement;
if (flags & SymbolFlags.Property) {
if (flags & SymbolFlags.SyntheticProperty) {
if (flags & SymbolFlags.Transient && (<TransientSymbol>symbol).checkFlags & CheckFlags.SyntheticProperty) {
// If union property is result of union of non method (property/accessors/variables), it is labeled as property
const unionPropertyKind = forEach(typeChecker.getRootSymbols(symbol), rootSymbol => {
const rootSymbolFlags = rootSymbol.getFlags();
@@ -41,6 +41,7 @@ compile(process.argv.slice(2), {
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
"use strict";
exports.__esModule = true;
var ts = require("typescript");
function compile(fileNames, options) {
var program = ts.createProgram(fileNames, options);
@@ -71,6 +71,7 @@ fileNames.forEach(fileName => {
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
"use strict";
exports.__esModule = true;
var ts = require("typescript");
function delint(sourceFile) {
delintNode(sourceFile);
@@ -43,6 +43,7 @@ export function createProgram(rootFiles: string[], compilerOptionsJson: string):
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
"use strict";
exports.__esModule = true;
var ts = require("typescript");
function printError(error) {
if (!error) {
@@ -23,6 +23,7 @@ console.log(JSON.stringify(result));
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
"use strict";
exports.__esModule = true;
var ts = require("typescript");
var source = "let x: string = 'string'";
var result = ts.transpile(source, { module: ts.ModuleKind.CommonJS });
@@ -116,6 +116,7 @@ watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS });
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
"use strict";
exports.__esModule = true;
var ts = require("typescript");
function watch(rootFileNames, options) {
var files = {};
@@ -31,6 +31,7 @@ export module A {
//// [part1.js]
"use strict";
exports.__esModule = true;
var A;
(function (A) {
var Utils;
@@ -44,6 +45,7 @@ var A;
})(A = exports.A || (exports.A = {}));
//// [part2.js]
"use strict";
exports.__esModule = true;
var A;
(function (A) {
// collision with 'Origin' var in other part of merged module
@@ -12,7 +12,7 @@ function f1(x: Color | string) {
if (typeof x === "number") {
>typeof x === "number" : boolean
>typeof x : string
>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"
>x : string | Color
>"number" : "number"
@@ -41,7 +41,7 @@ function f2(x: Color | string | string[]) {
if (typeof x === "object") {
>typeof x === "object" : boolean
>typeof x : string
>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"
>x : string | Color | string[]
>"object" : "object"
@@ -54,7 +54,7 @@ function f2(x: Color | string | string[]) {
}
if (typeof x === "number") {
>typeof x === "number" : boolean
>typeof x : string
>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"
>x : string | Color | string[]
>"number" : "number"
@@ -76,7 +76,7 @@ function f2(x: Color | string | string[]) {
}
if (typeof x === "string") {
>typeof x === "string" : boolean
>typeof x : string
>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"
>x : string | Color | string[]
>"string" : "string"
@@ -15,6 +15,7 @@ y = moduleA; // should be error
//// [aliasAssignments_moduleA.js]
"use strict";
exports.__esModule = true;
var someClass = (function () {
function someClass() {
}
@@ -23,6 +24,7 @@ var someClass = (function () {
exports.someClass = someClass;
//// [aliasAssignments_1.js]
"use strict";
exports.__esModule = true;
var moduleA = require("./aliasAssignments_moduleA");
var x = moduleA;
x = 1; // Should be error
@@ -24,6 +24,7 @@ var x: foo.A = foo.bar("hello"); // foo.A should be ok but foo.bar should be err
//// [aliasOnMergedModuleInterface_0.js]
//// [aliasOnMergedModuleInterface_1.js]
"use strict";
exports.__esModule = true;
var z;
z.bar("hello"); // This should be ok
var x = foo.bar("hello"); // foo.A should be ok but foo.bar should be error
@@ -29,6 +29,7 @@ class C2 {
//// [aliasUsage1_backbone.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Model = (function () {
function Model() {
}
@@ -47,6 +48,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Backbone = require("./aliasUsage1_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
@@ -58,6 +60,7 @@ var VisualizationModel = (function (_super) {
exports.VisualizationModel = VisualizationModel;
//// [aliasUsage1_main.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var moduleA = require("./aliasUsage1_moduleA");
var C2 = (function () {
function C2() {
@@ -23,6 +23,7 @@ var xs2: typeof moduleA[] = [moduleA];
//// [aliasUsageInArray_backbone.js]
"use strict";
exports.__esModule = true;
var Model = (function () {
function Model() {
}
@@ -41,6 +42,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var Backbone = require("./aliasUsageInArray_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
@@ -52,6 +54,7 @@ var VisualizationModel = (function (_super) {
exports.VisualizationModel = VisualizationModel;
//// [aliasUsageInArray_main.js]
"use strict";
exports.__esModule = true;
var moduleA = require("./aliasUsageInArray_moduleA");
var xs = [moduleA];
var xs2 = [moduleA];
@@ -22,6 +22,7 @@ f = (x) => moduleA;
//// [aliasUsageInFunctionExpression_backbone.js]
"use strict";
exports.__esModule = true;
var Model = (function () {
function Model() {
}
@@ -40,6 +41,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var Backbone = require("./aliasUsageInFunctionExpression_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
@@ -51,6 +53,7 @@ var VisualizationModel = (function (_super) {
exports.VisualizationModel = VisualizationModel;
//// [aliasUsageInFunctionExpression_main.js]
"use strict";
exports.__esModule = true;
var moduleA = require("./aliasUsageInFunctionExpression_moduleA");
var f = function (x) { return x; };
f = function (x) { return moduleA; };
@@ -26,6 +26,7 @@ var r2 = foo({ a: <IHasVisualizationModel>null });
//// [aliasUsageInGenericFunction_backbone.js]
"use strict";
exports.__esModule = true;
var Model = (function () {
function Model() {
}
@@ -44,6 +45,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var Backbone = require("./aliasUsageInGenericFunction_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
@@ -55,6 +57,7 @@ var VisualizationModel = (function (_super) {
exports.VisualizationModel = VisualizationModel;
//// [aliasUsageInGenericFunction_main.js]
"use strict";
exports.__esModule = true;
var moduleA = require("./aliasUsageInGenericFunction_moduleA");
function foo(x) {
return x;
@@ -28,6 +28,7 @@ class N2 {
//// [aliasUsageInIndexerOfClass_backbone.js]
"use strict";
exports.__esModule = true;
var Model = (function () {
function Model() {
}
@@ -46,6 +47,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var Backbone = require("./aliasUsageInIndexerOfClass_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
@@ -57,6 +59,7 @@ var VisualizationModel = (function (_super) {
exports.VisualizationModel = VisualizationModel;
//// [aliasUsageInIndexerOfClass_main.js]
"use strict";
exports.__esModule = true;
var moduleA = require("./aliasUsageInIndexerOfClass_moduleA");
var N = (function () {
function N() {
@@ -23,6 +23,7 @@ var c: { y: { z: IHasVisualizationModel } } = { y: { z: moduleA } };
//// [aliasUsageInObjectLiteral_backbone.js]
"use strict";
exports.__esModule = true;
var Model = (function () {
function Model() {
}
@@ -41,6 +42,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var Backbone = require("./aliasUsageInObjectLiteral_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
@@ -52,6 +54,7 @@ var VisualizationModel = (function (_super) {
exports.VisualizationModel = VisualizationModel;
//// [aliasUsageInObjectLiteral_main.js]
"use strict";
exports.__esModule = true;
var moduleA = require("./aliasUsageInObjectLiteral_moduleA");
var a = { x: moduleA };
var b = { x: moduleA };
@@ -26,6 +26,7 @@ var f: { x: IHasVisualizationModel } = <{ x: IHasVisualizationModel }>null ? { x
//// [aliasUsageInOrExpression_backbone.js]
"use strict";
exports.__esModule = true;
var Model = (function () {
function Model() {
}
@@ -44,6 +45,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var Backbone = require("./aliasUsageInOrExpression_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
@@ -55,6 +57,7 @@ var VisualizationModel = (function (_super) {
exports.VisualizationModel = VisualizationModel;
//// [aliasUsageInOrExpression_main.js]
"use strict";
exports.__esModule = true;
var moduleA = require("./aliasUsageInOrExpression_moduleA");
var i;
var d1 = i || moduleA;
@@ -26,6 +26,7 @@ class D extends C<IHasVisualizationModel> {
//// [aliasUsageInTypeArgumentOfExtendsClause_backbone.js]
"use strict";
exports.__esModule = true;
var Model = (function () {
function Model() {
}
@@ -44,6 +45,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var Backbone = require("./aliasUsageInTypeArgumentOfExtendsClause_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
@@ -65,6 +67,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var moduleA = require("./aliasUsageInTypeArgumentOfExtendsClause_moduleA");
var C = (function () {
function C() {
@@ -22,6 +22,7 @@ var m: typeof moduleA = i;
//// [aliasUsageInVarAssignment_backbone.js]
"use strict";
exports.__esModule = true;
var Model = (function () {
function Model() {
}
@@ -40,6 +41,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var Backbone = require("./aliasUsageInVarAssignment_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
@@ -51,5 +53,6 @@ var VisualizationModel = (function (_super) {
exports.VisualizationModel = VisualizationModel;
//// [aliasUsageInVarAssignment_main.js]
"use strict";
exports.__esModule = true;
var i;
var m = i;
@@ -20,12 +20,15 @@ export var a = function () {
//// [aliasUsedAsNameValue_0.js]
"use strict";
exports.__esModule = true;
//// [aliasUsedAsNameValue_1.js]
"use strict";
exports.__esModule = true;
function b(a) { return null; }
exports.b = b;
//// [aliasUsedAsNameValue_2.js]
"use strict";
exports.__esModule = true;
///<reference path='aliasUsedAsNameValue_0.ts' />
///<reference path='aliasUsedAsNameValue_1.ts' />
var mod = require("./aliasUsedAsNameValue_0");
@@ -12,6 +12,8 @@ var d = b.q3;
//// [aliasWithInterfaceExportAssignmentUsedInVarInitializer_0.js]
"use strict";
exports.__esModule = true;
//// [aliasWithInterfaceExportAssignmentUsedInVarInitializer_1.js]
"use strict";
exports.__esModule = true;
var d = b.q3;
@@ -12,6 +12,7 @@ export class Foo {
//// [b.js]
"use strict";
exports.__esModule = true;
var Foo = (function () {
function Foo() {
}
@@ -20,5 +21,6 @@ var Foo = (function () {
exports.Foo = Foo;
//// [a.js]
"use strict";
exports.__esModule = true;
var b_1 = require("./b");
exports.x = new b_1["default"].Foo();
@@ -12,6 +12,7 @@ Foo.default.default.foo();
//// [a.js]
"use strict";
exports.__esModule = true;
var Foo = require("./b");
Foo["default"].bar();
Foo["default"]["default"].foo();
@@ -13,5 +13,6 @@ export var x = new Foo();
//// [a.js]
"use strict";
exports.__esModule = true;
var b_1 = require("./b");
exports.x = new b_1["default"]();
@@ -12,6 +12,7 @@ Foo.foo();
//// [a.js]
"use strict";
exports.__esModule = true;
var b_1 = require("./b");
b_1["default"].bar();
b_1["default"].foo();
@@ -5,5 +5,6 @@ export const a = 1
//// [alwaysStrictModule4.js]
"use strict";
exports.__esModule = true;
// Module commonjs
exports.a = 1;
@@ -5,5 +5,6 @@ export const a = 1;
//// [alwaysStrictModule6.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Targeting ES5
exports.a = 1;
@@ -28,6 +28,7 @@ var n: number;
// Ambient external import declaration referencing ambient external module using top level module name
//// [consumer.js]
"use strict";
exports.__esModule = true;
// Ambient external module members are always exported with or without export keyword when module lacks export assignment
var imp3 = require("equ2");
var n = imp3.x;
@@ -34,6 +34,7 @@ foo(fileText);
//// [user.js]
"use strict";
exports.__esModule = true;
///<reference path="declarations.d.ts" />
var foobarbaz_1 = require("foobarbaz");
foobarbaz_1.foo(foobarbaz_1.baz);
@@ -4,4 +4,5 @@ export declare module "M" { }
//// [ambientExternalModuleInsideNonAmbientExternalModule.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
});
@@ -19,6 +19,7 @@ declare module "M" {
//// [ambientExternalModuleMerging_use.js]
define(["require", "exports", "M"], function (require, exports, M) {
"use strict";
exports.__esModule = true;
// Should be strings
var x = M.x;
var y = M.y;
@@ -22,5 +22,6 @@ var c = new A();
//// [ambientExternalModuleWithInternalImportDeclaration_1.js]
define(["require", "exports", "M"], function (require, exports, A) {
"use strict";
exports.__esModule = true;
var c = new A();
});
@@ -21,5 +21,6 @@ var c = new A();
//// [ambientExternalModuleWithoutInternalImportDeclaration_1.js]
define(["require", "exports", "M"], function (require, exports, A) {
"use strict";
exports.__esModule = true;
var c = new A();
});
@@ -8,4 +8,5 @@ export declare module M { }
//// [ambientInsideNonAmbientExternalModule.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
});
@@ -6,3 +6,4 @@ export declare namespace Foo {
//// [ambientNameRestrictions.js]
"use strict";
exports.__esModule = true;
@@ -15,6 +15,7 @@ foo(bar, baz, boom);
//// [user.js]
"use strict";
exports.__esModule = true;
///<reference path="declarations.d.ts"/>
var jquery_1 = require("jquery");
var baz = require("fs");
@@ -14,3 +14,4 @@ import foo from "foo";
//// [user.js]
"use strict";
exports.__esModule = true;
@@ -16,3 +16,4 @@ import foo, {bar} from "foo";
//// [user.js]
"use strict";
exports.__esModule = true;
@@ -18,6 +18,7 @@ x($);
//// [reExportX.js]
"use strict";
exports.__esModule = true;
var jquery_1 = require("jquery");
exports.x = jquery_1.x;
//// [reExportAll.js]
@@ -25,9 +26,11 @@ exports.x = jquery_1.x;
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
exports.__esModule = true;
__export(require("jquery"));
//// [reExportUser.js]
"use strict";
exports.__esModule = true;
var reExportX_1 = require("./reExportX");
var $ = require("./reExportAll");
// '$' is not callable, it is an object.
@@ -7,5 +7,6 @@ m1.f();
//// [amdDependencyComment1.js]
///<amd-dependency path='bar'/>
"use strict";
exports.__esModule = true;
var m1 = require("m2");
m1.f();
@@ -8,5 +8,6 @@ m1.f();
///<amd-dependency path='bar'/>
define(["require", "exports", "m2", "bar"], function (require, exports, m1) {
"use strict";
exports.__esModule = true;
m1.f();
});
@@ -7,5 +7,6 @@ m1.f();
//// [amdDependencyCommentName1.js]
///<amd-dependency path='bar' name='b'/>
"use strict";
exports.__esModule = true;
var m1 = require("m2");
m1.f();
@@ -8,5 +8,6 @@ m1.f();
///<amd-dependency path='bar' name='b'/>
define(["require", "exports", "bar", "m2"], function (require, exports, b, m1) {
"use strict";
exports.__esModule = true;
m1.f();
});
@@ -12,5 +12,6 @@ m1.f();
///<amd-dependency path='goo' name='c'/>
define(["require", "exports", "bar", "goo", "m2", "foo"], function (require, exports, b, c, m1) {
"use strict";
exports.__esModule = true;
m1.f();
});
@@ -27,6 +27,7 @@ import "unaliasedModule2";
///<amd-dependency path='unaliasedModule4'/>
define(["require", "exports", "aliasedModule5", "aliasedModule6", "aliasedModule1", "aliasedModule2", "aliasedModule3", "aliasedModule4", "unaliasedModule3", "unaliasedModule4", "unaliasedModule1", "unaliasedModule2"], function (require, exports, n1, n2, r1, aliasedModule2_1, aliasedModule3_1, ns) {
"use strict";
exports.__esModule = true;
r1;
aliasedModule2_1.p1;
aliasedModule3_1["default"];
@@ -15,6 +15,7 @@ if(foo.E1.A === 0){
//// [foo_0.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
var E1;
(function (E1) {
E1[E1["A"] = 0] = "A";
@@ -25,6 +26,8 @@ define(["require", "exports"], function (require, exports) {
//// [foo_1.js]
define(["require", "exports", "./foo_0"], function (require, exports, foo) {
"use strict";
exports.__esModule = true;
if (foo.E1.A === 0) {
// Should cause runtime import - interesting optimization possibility, as gets inlined to 0.
}
});
@@ -34,6 +34,7 @@ var e: number = <foo.E1>0;
//// [foo_0.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
var C1 = (function () {
function C1() {
this.m1 = 42;
@@ -52,6 +53,7 @@ define(["require", "exports"], function (require, exports) {
//// [foo_1.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
var i;
var x = {};
var y = false;
@@ -4,7 +4,7 @@ function f() {
return typeof class {} === "function";
>typeof class {} === "function" : boolean
>typeof class {} : string
>typeof class {} : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"
>class {} : typeof (Anonymous class)
>"function" : "function"
}
@@ -9,15 +9,15 @@ export default function() {}
//// [a.js]
define(["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class default_1 {
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
});
//// [b.js]
define(["require", "exports"], function (require, exports) {
"use strict";
function default_1() { }
Object.defineProperty(exports, "__esModule", { value: true });
function default_1() { }
exports.default = default_1;
});
@@ -8,12 +8,12 @@ export default function() {}
//// [a.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class default_1 {
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
//// [b.js]
"use strict";
function default_1() { }
Object.defineProperty(exports, "__esModule", { value: true });
function default_1() { }
exports.default = default_1;
@@ -17,9 +17,9 @@ export default function() {}
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class default_1 {
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
});
//// [b.js]
@@ -33,7 +33,7 @@ export default function() {}
}
})(function (require, exports) {
"use strict";
function default_1() { }
Object.defineProperty(exports, "__esModule", { value: true });
function default_1() { }
exports.default = default_1;
});
+1
View File
@@ -17,6 +17,7 @@ var C = (function () {
}
C.prototype.P = function (ii, j, k) {
for (var i = 0; i < arguments.length; i++) {
// WScript.Echo("param: " + arguments[i]);
}
};
return C;
@@ -83,7 +83,9 @@ f(// comment 1
// comment 2
function () {
// comment 4
});
}
// comment 5
);
// body is not a block
f(function (_) { return 1 +
2; });
+2
View File
@@ -14,10 +14,12 @@ import { foo } from './foo';
//// [foo.js]
"use strict";
exports.__esModule = true;
function foo() { }
exports.foo = foo;
//// [bar.js]
"use strict";
exports.__esModule = true;
var foo_1 = require("./foo");
// These should emit identically
foo_1.foo;
@@ -0,0 +1,21 @@
//// [assignmentNestedInLiterals.ts]
var target, x, y;
target = [x = 1, y = x];
var aegis, a, b;
aegis = { x: a = 1, y: b = a };
var kowloona, c, d;
for (kowloona of [c = 1, d = c]) {
}
//// [assignmentNestedInLiterals.js]
var target, x, y;
target = [x = 1, y = x];
var aegis, a, b;
aegis = { x: a = 1, y: b = a };
var kowloona, c, d;
for (var _i = 0, _a = [c = 1, d = c]; _i < _a.length; _i++) {
kowloona = _a[_i];
}
@@ -0,0 +1,37 @@
=== tests/cases/compiler/assignmentNestedInLiterals.ts ===
var target, x, y;
>target : Symbol(target, Decl(assignmentNestedInLiterals.ts, 0, 3))
>x : Symbol(x, Decl(assignmentNestedInLiterals.ts, 0, 11))
>y : Symbol(y, Decl(assignmentNestedInLiterals.ts, 0, 14))
target = [x = 1, y = x];
>target : Symbol(target, Decl(assignmentNestedInLiterals.ts, 0, 3))
>x : Symbol(x, Decl(assignmentNestedInLiterals.ts, 0, 11))
>y : Symbol(y, Decl(assignmentNestedInLiterals.ts, 0, 14))
>x : Symbol(x, Decl(assignmentNestedInLiterals.ts, 0, 11))
var aegis, a, b;
>aegis : Symbol(aegis, Decl(assignmentNestedInLiterals.ts, 3, 3))
>a : Symbol(a, Decl(assignmentNestedInLiterals.ts, 3, 10))
>b : Symbol(b, Decl(assignmentNestedInLiterals.ts, 3, 13))
aegis = { x: a = 1, y: b = a };
>aegis : Symbol(aegis, Decl(assignmentNestedInLiterals.ts, 3, 3))
>x : Symbol(x, Decl(assignmentNestedInLiterals.ts, 4, 9))
>a : Symbol(a, Decl(assignmentNestedInLiterals.ts, 3, 10))
>y : Symbol(y, Decl(assignmentNestedInLiterals.ts, 4, 19))
>b : Symbol(b, Decl(assignmentNestedInLiterals.ts, 3, 13))
>a : Symbol(a, Decl(assignmentNestedInLiterals.ts, 3, 10))
var kowloona, c, d;
>kowloona : Symbol(kowloona, Decl(assignmentNestedInLiterals.ts, 6, 3))
>c : Symbol(c, Decl(assignmentNestedInLiterals.ts, 6, 13))
>d : Symbol(d, Decl(assignmentNestedInLiterals.ts, 6, 16))
for (kowloona of [c = 1, d = c]) {
>kowloona : Symbol(kowloona, Decl(assignmentNestedInLiterals.ts, 6, 3))
>c : Symbol(c, Decl(assignmentNestedInLiterals.ts, 6, 13))
>d : Symbol(d, Decl(assignmentNestedInLiterals.ts, 6, 16))
>c : Symbol(c, Decl(assignmentNestedInLiterals.ts, 6, 13))
}
@@ -0,0 +1,51 @@
=== tests/cases/compiler/assignmentNestedInLiterals.ts ===
var target, x, y;
>target : any
>x : any
>y : any
target = [x = 1, y = x];
>target = [x = 1, y = x] : number[]
>target : any
>[x = 1, y = x] : number[]
>x = 1 : 1
>x : any
>1 : 1
>y = x : number
>y : any
>x : number
var aegis, a, b;
>aegis : any
>a : any
>b : any
aegis = { x: a = 1, y: b = a };
>aegis = { x: a = 1, y: b = a } : { x: number; y: number; }
>aegis : any
>{ x: a = 1, y: b = a } : { x: number; y: number; }
>x : number
>a = 1 : 1
>a : any
>1 : 1
>y : number
>b = a : number
>b : any
>a : number
var kowloona, c, d;
>kowloona : any
>c : any
>d : any
for (kowloona of [c = 1, d = c]) {
>kowloona : any
>[c = 1, d = c] : number[]
>c = 1 : 1
>c : any
>1 : 1
>d = c : number
>d : any
>c : number
}
@@ -77,6 +77,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
}
};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var missing_1 = require("missing");
function f0() {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
@@ -21,6 +21,7 @@ var __extends = (this && this.__extends) || (function () {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Task = (function (_super) {
__extends(Task, _super);
function Task() {
@@ -66,6 +67,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var task_1 = require("./task");
var Test = (function () {
function Test() {
@@ -11,6 +11,7 @@ class Test {
//// [task.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Task extends Promise {
}
exports.Task = Task;
@@ -24,6 +25,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
class Test {
example() {
return __awaiter(this, void 0, void 0, function* () { return; });
@@ -28,9 +28,11 @@ define(["require", "exports"], function (require, exports) {
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
});
//// [file3.js]
define(["require", "exports", "./file2"], function (require, exports) {
"use strict";
exports.__esModule = true;
var a; // should not work
});
@@ -25,9 +25,11 @@ let a: x.A; // should not work
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
});
//// [file3.js]
define(["require", "exports", "file2"], function (require, exports) {
"use strict";
exports.__esModule = true;
var a; // should not work
});
@@ -27,9 +27,11 @@ define(["require", "exports"], function (require, exports) {
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
});
//// [file3.js]
define(["require", "exports", "./file2"], function (require, exports) {
"use strict";
exports.__esModule = true;
var a; // should not work
});
@@ -25,9 +25,11 @@ let a: x.A; // should not work
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
});
//// [file3.js]
define(["require", "exports", "file2"], function (require, exports) {
"use strict";
exports.__esModule = true;
var a; // should not work
});
@@ -36,11 +36,13 @@ define(["require", "exports"], function (require, exports) {
//// [file2.js]
define(["require", "exports", "./file1"], function (require, exports, x) {
"use strict";
exports.__esModule = true;
x.b = 1;
});
//// [file3.js]
define(["require", "exports", "./file1", "./file2"], function (require, exports, x) {
"use strict";
exports.__esModule = true;
var a;
var b = x.b;
});
@@ -30,11 +30,13 @@ let b = x.b;
//// [file2.js]
define(["require", "exports", "file1"], function (require, exports, x) {
"use strict";
exports.__esModule = true;
x.b = 1;
});
//// [file3.js]
define(["require", "exports", "file1", "file2"], function (require, exports, x) {
"use strict";
exports.__esModule = true;
var a;
var b = x.b;
});
@@ -40,11 +40,13 @@ define(["require", "exports"], function (require, exports) {
//// [file2.js]
define(["require", "exports", "./file1"], function (require, exports, x) {
"use strict";
exports.__esModule = true;
x.b = 1;
});
//// [file3.js]
define(["require", "exports", "./file1", "./file2"], function (require, exports, x) {
"use strict";
exports.__esModule = true;
var a;
var b = x.b;
});
@@ -31,11 +31,13 @@ let b = x.b;
//// [file2.js]
define(["require", "exports", "file1"], function (require, exports, x) {
"use strict";
exports.__esModule = true;
x.b = 1;
});
//// [file3.js]
define(["require", "exports", "file1", "file2"], function (require, exports, x) {
"use strict";
exports.__esModule = true;
var a;
var b = x.b;
});
@@ -85,10 +85,12 @@ const y = x.id;
//// [augmentation.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
});
//// [consumer.js]
define(["require", "exports", "./augmentation"], function (require, exports) {
"use strict";
exports.__esModule = true;
var x;
var y = x.id;
});
@@ -52,11 +52,13 @@ define(["require", "exports"], function (require, exports) {
//// [file2.js]
define(["require", "exports", "./file1"], function (require, exports, x) {
"use strict";
exports.__esModule = true;
x.B.b = 1;
});
//// [file3.js]
define(["require", "exports", "./file1", "./file2"], function (require, exports, x) {
"use strict";
exports.__esModule = true;
var a;
var b = a.a;
var c = x.B.b;
@@ -29,10 +29,12 @@ let b = a.a;
//// [file2.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
});
//// [file3.js]
define(["require", "exports", "file2"], function (require, exports) {
"use strict";
exports.__esModule = true;
var a;
var b = a.a;
});
@@ -6,6 +6,7 @@ module c5 { } // should be ok everywhere
//// [augmentedTypesExternalModule1.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
exports.a = 1;
var c5 = (function () {
function c5() {
@@ -9,4 +9,5 @@ export declare var a: {
//// [badExternalModuleReference.js]
define(["require", "exports"], function (require, exports) {
"use strict";
exports.__esModule = true;
});

Some files were not shown because too many files have changed in this diff Show More