From 5b4e964ae8afebe71997da0e00a0723e590a6670 Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Wed, 25 May 2016 00:06:47 -0700 Subject: [PATCH 01/13] do not swallow test execution errors --- Jakefile.js | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/Jakefile.js b/Jakefile.js index 55113f986bc..7cf6e67bb06 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -726,24 +726,39 @@ function runConsoleTests(defaultReporter, defaultSubsets) { subsetRegexes = subsets.map(function (sub) { return "^" + sub + ".*$"; }); subsetRegexes.push("^(?!" + subsets.join("|") + ").*$"); } + var counter = subsetRegexes.length; + var errorStatus; subsetRegexes.forEach(function (subsetRegex, i) { tests = subsetRegex ? ' -g "' + subsetRegex + '"' : ''; var cmd = "mocha" + (debug ? " --debug-brk" : "") + " -R " + reporter + tests + colors + ' -t ' + testTimeout + ' ' + run; console.log(cmd); - function finish() { + function finish(status) { + counter--; + // save first error status + if (status !== undefined && errorStatus === undefined) { + errorStatus = status; + } + deleteTemporaryProjectOutput(); - complete(); + if (counter !== 0 || errorStatus === undefined) { + if (lintFlag) { + var lint = jake.Task['lint']; + lint.addListener('complete', function () { + complete(); + }); + lint.invoke(); + } + complete(); + } + else { + fail("Process exited with code " + status); + } } exec(cmd, function () { - if (lintFlag && i === 0) { - var lint = jake.Task['lint']; - lint.addListener('complete', function () { - complete(); - }); - lint.invoke(); - } finish(); - }, finish); + }, function(e, status) { + finish(status); + }); }); } From bd633c828f1c474ab2d928c5737365db92a859a4 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 25 May 2016 06:32:55 -0700 Subject: [PATCH 02/13] Lint all servicesSources --- Jakefile.js | 13 +- scripts/tslint/noIncrementDecrementRule.ts | 11 +- src/services/breakpoints.ts | 38 ++-- src/services/formatting/formatting.ts | 210 +++++++++--------- src/services/formatting/formattingContext.ts | 16 +- src/services/formatting/formattingScanner.ts | 35 ++- src/services/formatting/ruleOperation.ts | 5 +- .../formatting/ruleOperationContext.ts | 4 +- src/services/formatting/rules.ts | 24 +- src/services/formatting/rulesMap.ts | 31 +-- src/services/formatting/rulesProvider.ts | 5 +- src/services/formatting/smartIndenter.ts | 72 +++--- src/services/formatting/tokenRange.ts | 4 +- src/services/signatureHelp.ts | 148 ++++++------ src/services/utilities.ts | 92 ++++---- 15 files changed, 348 insertions(+), 360 deletions(-) diff --git a/Jakefile.js b/Jakefile.js index 55113f986bc..5bf30c824cd 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -962,24 +962,13 @@ function lintFileAsync(options, path, cb) { }); } -var servicesLintTargets = [ - "navigateTo.ts", - "navigationBar.ts", - "outliningElementsCollector.ts", - "patternMatcher.ts", - "services.ts", - "shims.ts", - "jsTyping.ts" -].map(function (s) { - return path.join(servicesDirectory, s); -}); var lintTargets = compilerSources .concat(harnessSources) // Other harness sources .concat(["instrumenter.ts"].map(function(f) { return path.join(harnessDirectory, f) })) .concat(serverCoreSources) .concat(tslintRulesFiles) - .concat(servicesLintTargets); + .concat(servicesSources); desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex"); diff --git a/scripts/tslint/noIncrementDecrementRule.ts b/scripts/tslint/noIncrementDecrementRule.ts index 75f4d2f5c08..f5c90abe893 100644 --- a/scripts/tslint/noIncrementDecrementRule.ts +++ b/scripts/tslint/noIncrementDecrementRule.ts @@ -28,8 +28,15 @@ class IncrementDecrementWalker extends Lint.RuleWalker { } visitIncrementDecrement(node: ts.UnaryExpression) { - if (node.parent && (node.parent.kind === ts.SyntaxKind.ExpressionStatement || - node.parent.kind === ts.SyntaxKind.ForStatement)) { + if (node.parent && ( + // Can be a statement + node.parent.kind === ts.SyntaxKind.ExpressionStatement || + // Can be directly in a for-statement + node.parent.kind === ts.SyntaxKind.ForStatement || + // Can be in a comma operator in a for statement (`for (let a = 0, b = 10; a < b; a++, b--)`) + node.parent.kind === ts.SyntaxKind.BinaryExpression && + (node.parent).operatorToken.kind === ts.SyntaxKind.CommaToken && + node.parent.parent.kind === ts.SyntaxKind.ForStatement)) { return; } this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.POSTFIX_FAILURE_STRING)); diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index 02456f5add1..12b127ffd2d 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -15,7 +15,7 @@ namespace ts.BreakpointResolver { } let tokenAtLocation = getTokenAtPosition(sourceFile, position); - let lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line // eg: let x =10; |--- cursor is here @@ -216,7 +216,7 @@ namespace ts.BreakpointResolver { return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile)); case SyntaxKind.CommaToken: - return spanInPreviousNode(node) + return spanInPreviousNode(node); case SyntaxKind.OpenBraceToken: return spanInOpenBraceToken(node); @@ -259,13 +259,13 @@ namespace ts.BreakpointResolver { if (isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } - + // Set breakpoint on identifier element of destructuring pattern // a or ...c or d: x from // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern if ((node.kind === SyntaxKind.Identifier || - node.kind == SyntaxKind.SpreadElementExpression || - node.kind === SyntaxKind.PropertyAssignment || + node.kind == SyntaxKind.SpreadElementExpression || + node.kind === SyntaxKind.PropertyAssignment || node.kind === SyntaxKind.ShorthandPropertyAssignment) && isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { return textSpan(node); @@ -325,14 +325,14 @@ namespace ts.BreakpointResolver { break; } } - + // If this is name of property assignment, set breakpoint in the initializer if (node.parent.kind === SyntaxKind.PropertyAssignment && - (node.parent).name === node && + (node.parent).name === node && !isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode((node.parent).initializer); } - + // Breakpoint in type assertion goes to its operand if (node.parent.kind === SyntaxKind.TypeAssertionExpression && (node.parent).type === node) { return spanInNextNode((node.parent).type); @@ -370,7 +370,7 @@ namespace ts.BreakpointResolver { } function textSpanFromVariableDeclaration(variableDeclaration: VariableDeclaration): TextSpan { - let declarations = variableDeclaration.parent.declarations; + const declarations = variableDeclaration.parent.declarations; if (declarations && declarations[0] === variableDeclaration) { // First declaration - include let keyword return textSpan(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); @@ -386,7 +386,7 @@ namespace ts.BreakpointResolver { if (variableDeclaration.parent.parent.kind === SyntaxKind.ForInStatement) { return spanInNode(variableDeclaration.parent.parent); } - + // If this is a destructuring pattern, set breakpoint in binding pattern if (isBindingPattern(variableDeclaration.name)) { return spanInBindingPattern(variableDeclaration.name); @@ -400,7 +400,7 @@ namespace ts.BreakpointResolver { return textSpanFromVariableDeclaration(variableDeclaration); } - let declarations = variableDeclaration.parent.declarations; + const declarations = variableDeclaration.parent.declarations; if (declarations && declarations[0] !== variableDeclaration) { // If we cannot set breakpoint on this declaration, set it on previous one // Because the variable declaration may be binding pattern and @@ -425,8 +425,8 @@ namespace ts.BreakpointResolver { return textSpan(parameter); } else { - let functionDeclaration = parameter.parent; - let indexOfParameter = indexOf(functionDeclaration.parameters, parameter); + const functionDeclaration = parameter.parent; + const indexOfParameter = indexOf(functionDeclaration.parameters, parameter); if (indexOfParameter) { // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); @@ -459,7 +459,7 @@ namespace ts.BreakpointResolver { } function spanInFunctionBlock(block: Block): TextSpan { - let nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); + const nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); if (canFunctionHaveSpanInWholeDeclaration(block.parent)) { return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock); } @@ -493,7 +493,7 @@ namespace ts.BreakpointResolver { function spanInInitializerOfForLike(forLikeStatement: ForStatement | ForOfStatement | ForInStatement): TextSpan { if (forLikeStatement.initializer.kind === SyntaxKind.VariableDeclarationList) { // Declaration list - set breakpoint in first declaration - let variableDeclarationList = forLikeStatement.initializer; + const variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); } @@ -519,7 +519,7 @@ namespace ts.BreakpointResolver { function spanInBindingPattern(bindingPattern: BindingPattern): TextSpan { // Set breakpoint in first binding element - let firstBindingElement = forEach(bindingPattern.elements, + const firstBindingElement = forEach(bindingPattern.elements, element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined); if (firstBindingElement) { @@ -616,7 +616,7 @@ namespace ts.BreakpointResolver { default: if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { // Breakpoint in last binding element or binding pattern if it contains no elements - let objectLiteral = node.parent; + const objectLiteral = node.parent; return textSpan(lastOrUndefined(objectLiteral.properties) || objectLiteral); } return spanInNode(node.parent); @@ -633,7 +633,7 @@ namespace ts.BreakpointResolver { default: if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { // Breakpoint in last binding element or binding pattern if it contains no elements - let arrayLiteral = node.parent; + const arrayLiteral = node.parent; return textSpan(lastOrUndefined(arrayLiteral.elements) || arrayLiteral); } @@ -686,7 +686,7 @@ namespace ts.BreakpointResolver { function spanInColonToken(node: Node): TextSpan { // Is this : specifying return annotation of the function declaration if (isFunctionLike(node.parent) || - node.parent.kind === SyntaxKind.PropertyAssignment || + node.parent.kind === SyntaxKind.PropertyAssignment || node.parent.kind === SyntaxKind.Parameter) { return spanInPreviousNode(node); } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 20b20356907..2f5f10752f4 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -26,8 +26,8 @@ namespace ts.formatting { * while(true) * { let x; * } - * Normally indentation is applied only to the first token in line so at glance 'var' should not be touched. - * However if some format rule adds new line between '}' and 'var' 'var' will become + * Normally indentation is applied only to the first token in line so at glance 'let' should not be touched. + * However if some format rule adds new line between '}' and 'let' 'let' will become * the first token in line so it should be indented */ interface DynamicIndentation { @@ -64,11 +64,11 @@ namespace ts.formatting { interface Indentation { indentation: number; - delta: number + delta: number; } export function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[] { - let line = sourceFile.getLineAndCharacterOfPosition(position).line; + const line = sourceFile.getLineAndCharacterOfPosition(position).line; if (line === 0) { return []; } @@ -81,12 +81,12 @@ namespace ts.formatting { while (isWhiteSpace(sourceFile.text.charCodeAt(endOfFormatSpan)) && !isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) { endOfFormatSpan--; } - let span = { + const span = { // get start position for the previous line pos: getStartPositionOfLine(line - 1, sourceFile), // end value is exclusive so add 1 to the result end: endOfFormatSpan + 1 - } + }; return formatSpan(span, sourceFile, options, rulesProvider, FormattingRequestKind.FormatOnEnter); } @@ -99,7 +99,7 @@ namespace ts.formatting { } export function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[] { - let span = { + const span = { pos: 0, end: sourceFile.text.length }; @@ -108,7 +108,7 @@ namespace ts.formatting { export function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[] { // format from the beginning of the line - let span = { + const span = { pos: getLineStartPositionForPosition(start, sourceFile), end: end }; @@ -116,11 +116,11 @@ namespace ts.formatting { } function formatOutermostParent(position: number, expectedLastToken: SyntaxKind, sourceFile: SourceFile, options: FormatCodeOptions, rulesProvider: RulesProvider, requestKind: FormattingRequestKind): TextChange[] { - let parent = findOutermostParent(position, expectedLastToken, sourceFile); + const parent = findOutermostParent(position, expectedLastToken, sourceFile); if (!parent) { return []; } - let span = { + const span = { pos: getLineStartPositionForPosition(parent.getStart(sourceFile), sourceFile), end: parent.end }; @@ -128,7 +128,7 @@ namespace ts.formatting { } function findOutermostParent(position: number, expectedTokenKind: SyntaxKind, sourceFile: SourceFile): Node { - let precedingToken = findPrecedingToken(position, sourceFile); + const precedingToken = findPrecedingToken(position, sourceFile); // when it is claimed that trigger character was typed at given position // we verify that there is a token with a matching kind whose end is equal to position (because the character was just typed). @@ -168,7 +168,7 @@ namespace ts.formatting { case SyntaxKind.InterfaceDeclaration: return rangeContainsRange((parent).members, node); case SyntaxKind.ModuleDeclaration: - let body = (parent).body; + const body = (parent).body; return body && body.kind === SyntaxKind.Block && rangeContainsRange((body).statements, node); case SyntaxKind.SourceFile: case SyntaxKind.Block: @@ -186,9 +186,9 @@ namespace ts.formatting { return find(sourceFile); function find(n: Node): Node { - let candidate = forEachChild(n, c => startEndContainsRange(c.getStart(sourceFile), c.end, range) && c); + const candidate = forEachChild(n, c => startEndContainsRange(c.getStart(sourceFile), c.end, range) && c); if (candidate) { - let result = find(candidate); + const result = find(candidate); if (result) { return result; } @@ -208,7 +208,7 @@ namespace ts.formatting { } // pick only errors that fall in range - let sorted = errors + const sorted = errors .filter(d => rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length)) .sort((e1, e2) => e1.start - e2.start); @@ -227,7 +227,7 @@ namespace ts.formatting { return false; } - let error = sorted[index]; + const error = sorted[index]; if (r.end <= error.start) { // specified range ends before the error refered by 'index' - no error in range return false; @@ -253,12 +253,12 @@ namespace ts.formatting { * and return its end as start position for the scanner. */ function getScanStartPosition(enclosingNode: Node, originalRange: TextRange, sourceFile: SourceFile): number { - let start = enclosingNode.getStart(sourceFile); + const start = enclosingNode.getStart(sourceFile); if (start === originalRange.pos && enclosingNode.end === originalRange.end) { return start; } - let precedingToken = findPrecedingToken(originalRange.pos, sourceFile); + const precedingToken = findPrecedingToken(originalRange.pos, sourceFile); if (!precedingToken) { // no preceding token found - start from the beginning of enclosing node return enclosingNode.pos; @@ -292,7 +292,7 @@ namespace ts.formatting { let previousLine = Constants.Unknown; let child: Node; while (n) { - let line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; + const line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; if (previousLine !== Constants.Unknown && line !== previousLine) { break; } @@ -314,17 +314,17 @@ namespace ts.formatting { rulesProvider: RulesProvider, requestKind: FormattingRequestKind): TextChange[] { - let rangeContainsError = prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange); + const rangeContainsError = prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange); // formatting context is used by rules provider - let formattingContext = new FormattingContext(sourceFile, requestKind); + const formattingContext = new FormattingContext(sourceFile, requestKind); // find the smallest node that fully wraps the range and compute the initial indentation for the node - let enclosingNode = findEnclosingNode(originalRange, sourceFile); + const enclosingNode = findEnclosingNode(originalRange, sourceFile); - let formattingScanner = getFormattingScanner(sourceFile, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end); + const formattingScanner = getFormattingScanner(sourceFile, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end); - let initialIndentation = SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options); + const initialIndentation = SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options); let previousRangeHasError: boolean; let previousRange: TextRangeWithKind; @@ -334,23 +334,23 @@ namespace ts.formatting { let lastIndentedLine: number; let indentationOnLastIndentedLine: number; - let edits: TextChange[] = []; + const edits: TextChange[] = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { - let startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; + const startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; let undecoratedStartLine = startLine; if (enclosingNode.decorators) { undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; } - let delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); + const delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } if (!formattingScanner.isOnToken()) { - let leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + const leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined); trimTrailingWhitespacesForRemainingRange(); @@ -384,11 +384,11 @@ namespace ts.formatting { } } else { - let startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; - let startLinePosition = getLineStartPositionForPosition(startPos, sourceFile); - let column = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); + const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; + const startLinePosition = getLineStartPositionForPosition(startPos, sourceFile); + const column = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); if (startLine !== parentStartLine || startPos === column) { - return column + return column; } } @@ -404,7 +404,7 @@ namespace ts.formatting { effectiveParentStartLine: number): Indentation { let indentation = inheritedIndentation; - var delta = SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; + let delta = SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent @@ -427,7 +427,7 @@ namespace ts.formatting { return { indentation, delta - } + }; } function getFirstNonDecoratorTokenOfNode(node: Node) { @@ -511,7 +511,7 @@ namespace ts.formatting { } } } - } + }; function getEffectiveDelta(delta: number, child: TextRangeWithKind) { // Delta value should be zero when the node explicitly prevents indentation of the child node @@ -524,7 +524,7 @@ namespace ts.formatting { return; } - let nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta); + const nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta); // a useful observations when tracking context node // / @@ -545,7 +545,7 @@ namespace ts.formatting { forEachChild( node, child => { - processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListElement*/ false) + processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, (nodes: NodeArray) => { processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); @@ -553,7 +553,7 @@ namespace ts.formatting { // proceed any tokens in the node that are located after child nodes while (formattingScanner.isOnToken()) { - let tokenInfo = formattingScanner.readTokenInfo(node); + const tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > node.end) { break; } @@ -570,9 +570,9 @@ namespace ts.formatting { isListItem: boolean, isFirstListItem?: boolean): number { - let childStartPos = child.getStart(sourceFile); + const childStartPos = child.getStart(sourceFile); - let childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; + const childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; let undecoratedChildStartLine = childStartLine; if (child.decorators) { @@ -599,7 +599,7 @@ namespace ts.formatting { while (formattingScanner.isOnToken()) { // proceed any parent tokens that are located prior to child.getStart() - let tokenInfo = formattingScanner.readTokenInfo(node); + const tokenInfo = formattingScanner.readTokenInfo(node); if (tokenInfo.token.end > childStartPos) { // stop when formatting scanner advances past the beginning of the child break; @@ -614,14 +614,14 @@ namespace ts.formatting { if (isToken(child)) { // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules - let tokenInfo = formattingScanner.readTokenInfo(child); + const tokenInfo = formattingScanner.readTokenInfo(child); Debug.assert(tokenInfo.token.end === child.end); consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - let effectiveParentStartLine = child.kind === SyntaxKind.Decorator ? childStartLine : undecoratedParentStartLine; - let childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); + const effectiveParentStartLine = child.kind === SyntaxKind.Decorator ? childStartLine : undecoratedParentStartLine; + const childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); @@ -639,8 +639,8 @@ namespace ts.formatting { parentStartLine: number, parentDynamicIndentation: DynamicIndentation): void { - let listStartToken = getOpenTokenForList(parent, nodes); - let listEndToken = getCloseTokenForOpenToken(listStartToken); + const listStartToken = getOpenTokenForList(parent, nodes); + const listEndToken = getCloseTokenForOpenToken(listStartToken); let listDynamicIndentation = parentDynamicIndentation; let startLine = parentStartLine; @@ -648,7 +648,7 @@ namespace ts.formatting { if (listStartToken !== SyntaxKind.Unknown) { // introduce a new indentation scope for lists (including list start and end tokens) while (formattingScanner.isOnToken()) { - let tokenInfo = formattingScanner.readTokenInfo(parent); + const tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.end > nodes.pos) { // stop when formatting scanner moves past the beginning of node list break; @@ -656,7 +656,7 @@ namespace ts.formatting { else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - let indentation = + const indentation = computeIndentation(tokenInfo.token, startLine, Constants.Unknown, parent, parentDynamicIndentation, parentStartLine); listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation.indentation, indentation.delta); @@ -672,12 +672,12 @@ namespace ts.formatting { let inheritedIndentation = Constants.Unknown; for (let i = 0; i < nodes.length; i++) { const child = nodes[i]; - inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true, /*isFirstListItem*/ i === 0); + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } if (listEndToken !== SyntaxKind.Unknown) { if (formattingScanner.isOnToken()) { - let tokenInfo = formattingScanner.readTokenInfo(parent); + const tokenInfo = formattingScanner.readTokenInfo(parent); // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- @@ -693,7 +693,7 @@ namespace ts.formatting { function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation, container?: Node): void { Debug.assert(rangeContainsRange(parent, currentTokenInfo.token)); - let lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); + const lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); let indentToken = false; if (currentTokenInfo.leadingTrivia) { @@ -701,13 +701,13 @@ namespace ts.formatting { } let lineAdded: boolean; - let isTokenInRange = rangeContainsRange(originalRange, currentTokenInfo.token); + const isTokenInRange = rangeContainsRange(originalRange, currentTokenInfo.token); - let tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); + const tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); if (isTokenInRange) { - let rangeHasError = rangeContainsError(currentTokenInfo.token); + const rangeHasError = rangeContainsError(currentTokenInfo.token); // save previousRange since processRange will overwrite this value with current one - let savePreviousRange = previousRange; + const savePreviousRange = previousRange; lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); if (rangeHasError) { // do not indent comments\token if token range overlaps with some error @@ -730,15 +730,15 @@ namespace ts.formatting { } if (indentToken) { - let tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? + const tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : Constants.Unknown; let indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { - let commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); + const commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); - for (let triviaItem of currentTokenInfo.leadingTrivia) { + for (const triviaItem of currentTokenInfo.leadingTrivia) { const triviaInRange = rangeContainsRange(originalRange, triviaItem); switch (triviaItem.kind) { case SyntaxKind.MultiLineCommentTrivia: @@ -776,9 +776,9 @@ namespace ts.formatting { } function processTrivia(trivia: TextRangeWithKind[], parent: Node, contextNode: Node, dynamicIndentation: DynamicIndentation): void { - for (let triviaItem of trivia) { + for (const triviaItem of trivia) { if (isComment(triviaItem.kind) && rangeContainsRange(originalRange, triviaItem)) { - let triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); + const triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); } } @@ -790,17 +790,17 @@ namespace ts.formatting { contextNode: Node, dynamicIndentation: DynamicIndentation): boolean { - let rangeHasError = rangeContainsError(range); + const rangeHasError = rangeContainsError(range); let lineAdded: boolean; if (!rangeHasError && !previousRangeHasError) { if (!previousRange) { // trim whitespaces starting from the beginning of the span up to the current line - let originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); + const originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); } else { lineAdded = - processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation) + processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); } } @@ -823,7 +823,7 @@ namespace ts.formatting { formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); - let rule = rulesProvider.getRulesMap().GetRule(formattingContext); + const rule = rulesProvider.getRulesMap().GetRule(formattingContext); let trimTrailingWhitespaces: boolean; let lineAdded: boolean; @@ -835,7 +835,7 @@ namespace ts.formatting { // Handle the case where the next line is moved to be the end of this line. // In this case we don't indent the next line in the next pass. if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAdded*/ false); + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); } } else if (rule.Operation.Action & RuleAction.NewLine && currentStartLine === previousStartLine) { @@ -844,7 +844,7 @@ namespace ts.formatting { // In this case we indent token2 in the next pass but we set // sameLineIndent flag to notify the indenter that the indentation is within the line. if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAdded*/ true); + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); } } @@ -864,15 +864,15 @@ namespace ts.formatting { } function insertIndentation(pos: number, indentation: number, lineAdded: boolean): void { - let indentationString = getIndentationString(indentation, options); + const indentationString = getIndentationString(indentation, options); if (lineAdded) { // new line is added before the token by the formatting rules // insert indentation string at the very beginning of the token recordReplace(pos, 0, indentationString); } else { - let tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); - let startLinePosition = getStartPositionOfLine(tokenStart.line, sourceFile); + const tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); + const startLinePosition = getStartPositionOfLine(tokenStart.line, sourceFile); if (indentation !== tokenStart.character || indentationIsDifferent(indentationString, startLinePosition)) { recordReplace(startLinePosition, tokenStart.character, indentationString); } @@ -886,7 +886,7 @@ namespace ts.formatting { function indentMultilineComment(commentRange: TextRange, indentation: number, firstLineIsIndented: boolean) { // split comment in lines let startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; - let endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; + const endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; let parts: TextRange[]; if (startLine === endLine) { if (!firstLineIsIndented) { @@ -898,8 +898,8 @@ namespace ts.formatting { else { parts = []; let startPos = commentRange.pos; - for (let line = startLine; line < endLine; ++line) { - let endOfLine = getEndLinePosition(line, sourceFile); + for (let line = startLine; line < endLine; line++) { + const endOfLine = getEndLinePosition(line, sourceFile); parts.push({ pos: startPos, end: endOfLine }); startPos = getStartPositionOfLine(line + 1, sourceFile); } @@ -907,9 +907,9 @@ namespace ts.formatting { parts.push({ pos: startPos, end: commentRange.end }); } - let startLinePos = getStartPositionOfLine(startLine, sourceFile); + const startLinePos = getStartPositionOfLine(startLine, sourceFile); - let nonWhitespaceColumnInFirstPart = + const nonWhitespaceColumnInFirstPart = SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); if (indentation === nonWhitespaceColumnInFirstPart.column) { @@ -923,17 +923,17 @@ namespace ts.formatting { } // shift all parts on the delta size - let delta = indentation - nonWhitespaceColumnInFirstPart.column; - for (let i = startIndex, len = parts.length; i < len; ++i, ++startLine) { - let startLinePos = getStartPositionOfLine(startLine, sourceFile); - let nonWhitespaceCharacterAndColumn = + const delta = indentation - nonWhitespaceColumnInFirstPart.column; + for (let i = startIndex, len = parts.length; i < len; i++, startLine++) { + const startLinePos = getStartPositionOfLine(startLine, sourceFile); + const nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart : SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); - let newIndentation = nonWhitespaceCharacterAndColumn.column + delta; + const newIndentation = nonWhitespaceCharacterAndColumn.column + delta; if (newIndentation > 0) { - let indentationString = getIndentationString(newIndentation, options); + const indentationString = getIndentationString(newIndentation, options); recordReplace(startLinePos, nonWhitespaceCharacterAndColumn.character, indentationString); } else { @@ -943,16 +943,16 @@ namespace ts.formatting { } function trimTrailingWhitespacesForLines(line1: number, line2: number, range?: TextRangeWithKind) { - for (let line = line1; line < line2; ++line) { - let lineStartPosition = getStartPositionOfLine(line, sourceFile); - let lineEndPosition = getEndLinePosition(line, sourceFile); + for (let line = line1; line < line2; line++) { + const lineStartPosition = getStartPositionOfLine(line, sourceFile); + const lineEndPosition = getEndLinePosition(line, sourceFile); // do not trim whitespaces in comments or template expression if (range && (isComment(range.kind) || isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { continue; } - let whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + const whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); if (whitespaceStart !== -1) { Debug.assert(whitespaceStart === lineStartPosition || !isWhiteSpace(sourceFile.text.charCodeAt(whitespaceStart - 1))); recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); @@ -979,16 +979,16 @@ namespace ts.formatting { * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - let startPosition = previousRange ? previousRange.end : originalRange.pos; + const startPosition = previousRange ? previousRange.end : originalRange.pos; - let startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; - let endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + const startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + const endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); } function newTextChange(start: number, len: number, newText: string): TextChange { - return { span: createTextSpan(start, len), newText } + return { span: createTextSpan(start, len), newText }; } function recordDelete(start: number, len: number) { @@ -1009,7 +1009,6 @@ namespace ts.formatting { currentRange: TextRangeWithKind, currentStartLine: number): void { - let between: TextRange; switch (rule.Operation.Action) { case RuleAction.Ignore: // no action required @@ -1029,7 +1028,7 @@ namespace ts.formatting { } // edit should not be applied only if we have one line feed between elements - let lineDelta = currentStartLine - previousStartLine; + const lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); } @@ -1040,7 +1039,7 @@ namespace ts.formatting { return; } - let posDelta = currentRange.pos - previousRange.end; + const posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== CharacterCodes.space) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); } @@ -1049,15 +1048,6 @@ namespace ts.formatting { } } - function isSomeBlock(kind: SyntaxKind): boolean { - switch (kind) { - case SyntaxKind.Block: - case SyntaxKind.ModuleBlock: - return true; - } - return false; - } - function getOpenTokenForList(node: Node, list: Node[]) { switch (node.kind) { case SyntaxKind.Constructor: @@ -1102,13 +1092,13 @@ namespace ts.formatting { return SyntaxKind.Unknown; } - var internedSizes: { tabSize: number; indentSize: number }; - var internedTabsIndentation: string[]; - var internedSpacesIndentation: string[]; + let internedSizes: { tabSize: number; indentSize: number }; + let internedTabsIndentation: string[]; + let internedSpacesIndentation: string[]; export function getIndentationString(indentation: number, options: FormatCodeOptions): string { // reset interned strings if FormatCodeOptions were changed - let resetInternedStrings = + const resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); if (resetInternedStrings) { @@ -1117,8 +1107,8 @@ namespace ts.formatting { } if (!options.ConvertTabsToSpaces) { - let tabs = Math.floor(indentation / options.TabSize); - let spaces = indentation - tabs * options.TabSize; + const tabs = Math.floor(indentation / options.TabSize); + const spaces = indentation - tabs * options.TabSize; let tabString: string; if (!internedTabsIndentation) { @@ -1126,7 +1116,7 @@ namespace ts.formatting { } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat('\t', tabs); + internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; @@ -1136,8 +1126,8 @@ namespace ts.formatting { } else { let spacesString: string; - let quotient = Math.floor(indentation / options.IndentSize); - let remainder = indentation % options.IndentSize; + const quotient = Math.floor(indentation / options.IndentSize); + const remainder = indentation % options.IndentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } @@ -1155,7 +1145,7 @@ namespace ts.formatting { function repeat(value: string, count: number): string { let s = ""; - for (let i = 0; i < count; ++i) { + for (let i = 0; i < count; i++) { s += value; } diff --git a/src/services/formatting/formattingContext.ts b/src/services/formatting/formattingContext.ts index ab182797a3c..bd5ca352476 100644 --- a/src/services/formatting/formattingContext.ts +++ b/src/services/formatting/formattingContext.ts @@ -57,8 +57,8 @@ namespace ts.formatting { public TokensAreOnSameLine(): boolean { if (this.tokensAreOnSameLine === undefined) { - let startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; - let endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; + const startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; + const endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; this.tokensAreOnSameLine = (startLine === endLine); } @@ -82,17 +82,17 @@ namespace ts.formatting { } private NodeIsOnOneLine(node: Node): boolean { - let startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; - let endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; + const startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; + const endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; return startLine === endLine; } private BlockIsOnOneLine(node: Node): boolean { - let openBrace = findChildOfKind(node, SyntaxKind.OpenBraceToken, this.sourceFile); - let closeBrace = findChildOfKind(node, SyntaxKind.CloseBraceToken, this.sourceFile); + const openBrace = findChildOfKind(node, SyntaxKind.OpenBraceToken, this.sourceFile); + const closeBrace = findChildOfKind(node, SyntaxKind.CloseBraceToken, this.sourceFile); if (openBrace && closeBrace) { - let startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; - let endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; + const startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; + const endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; return startLine === endLine; } return false; diff --git a/src/services/formatting/formattingScanner.ts b/src/services/formatting/formattingScanner.ts index 5b869f12096..ff003e08007 100644 --- a/src/services/formatting/formattingScanner.ts +++ b/src/services/formatting/formattingScanner.ts @@ -35,7 +35,7 @@ namespace ts.formatting { scanner.setText(sourceFile.text); scanner.setTextPos(startPos); - let wasNewLine: boolean = true; + let wasNewLine = true; let leadingTrivia: TextRangeWithKind[]; let trailingTrivia: TextRangeWithKind[]; @@ -56,13 +56,13 @@ namespace ts.formatting { scanner.setText(undefined); scanner = undefined; } - } + }; function advance(): void { Debug.assert(scanner !== undefined); lastTokenInfo = undefined; - let isStarted = scanner.getStartPos() !== startPos; + const isStarted = scanner.getStartPos() !== startPos; if (isStarted) { if (trailingTrivia) { @@ -81,23 +81,22 @@ namespace ts.formatting { scanner.scan(); } - let t: SyntaxKind; let pos = scanner.getStartPos(); // Read leading trivia and token while (pos < endPos) { - let t = scanner.getToken(); + const t = scanner.getToken(); if (!isTrivia(t)) { break; } // consume leading trivia scanner.scan(); - let item = { + const item = { pos: pos, end: scanner.getStartPos(), kind: t - } + }; pos = scanner.getStartPos(); @@ -166,16 +165,16 @@ namespace ts.formatting { // normally scanner returns the smallest available token // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. - let expectedScanAction = + const expectedScanAction = shouldRescanGreaterThanToken(n) ? ScanAction.RescanGreaterThanToken - : shouldRescanSlashToken(n) - ? ScanAction.RescanSlashToken + : shouldRescanSlashToken(n) + ? ScanAction.RescanSlashToken : shouldRescanTemplateToken(n) ? ScanAction.RescanTemplateToken : shouldRescanJsxIdentifier(n) - ? ScanAction.RescanJsxIdentifier - : ScanAction.Scan + ? ScanAction.RescanJsxIdentifier + : ScanAction.Scan; if (lastTokenInfo && expectedScanAction === lastScanAction) { // readTokenInfo was called before with the same expected scan action. @@ -218,11 +217,11 @@ namespace ts.formatting { lastScanAction = ScanAction.Scan; } - let token: TextRangeWithKind = { + const token: TextRangeWithKind = { pos: scanner.getStartPos(), end: scanner.getTextPos(), kind: currentToken - } + }; // consume trailing trivia if (trailingTrivia) { @@ -233,7 +232,7 @@ namespace ts.formatting { if (!isTrivia(currentToken)) { break; } - let trivia = { + const trivia = { pos: scanner.getStartPos(), end: scanner.getTextPos(), kind: currentToken @@ -256,7 +255,7 @@ namespace ts.formatting { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token - } + }; return fixTokenKind(lastTokenInfo, n); } @@ -264,8 +263,8 @@ namespace ts.formatting { function isOnToken(): boolean { Debug.assert(scanner !== undefined); - let current = (lastTokenInfo && lastTokenInfo.token.kind) || scanner.getToken(); - let startPos = (lastTokenInfo && lastTokenInfo.token.pos) || scanner.getStartPos(); + const current = (lastTokenInfo && lastTokenInfo.token.kind) || scanner.getToken(); + const startPos = (lastTokenInfo && lastTokenInfo.token.pos) || scanner.getStartPos(); return startPos < endPos && current !== SyntaxKind.EndOfFileToken && !isTrivia(current); } diff --git a/src/services/formatting/ruleOperation.ts b/src/services/formatting/ruleOperation.ts index e897513bd27..9c35b80bcfe 100644 --- a/src/services/formatting/ruleOperation.ts +++ b/src/services/formatting/ruleOperation.ts @@ -1,4 +1,5 @@ /// +/* tslint:disable:no-null-keyword */ /* @internal */ namespace ts.formatting { @@ -17,11 +18,11 @@ namespace ts.formatting { } static create1(action: RuleAction) { - return RuleOperation.create2(RuleOperationContext.Any, action) + return RuleOperation.create2(RuleOperationContext.Any, action); } static create2(context: RuleOperationContext, action: RuleAction) { - let result = new RuleOperation(); + const result = new RuleOperation(); result.Context = context; result.Action = action; return result; diff --git a/src/services/formatting/ruleOperationContext.ts b/src/services/formatting/ruleOperationContext.ts index 47330faa0dd..6c368dcc617 100644 --- a/src/services/formatting/ruleOperationContext.ts +++ b/src/services/formatting/ruleOperationContext.ts @@ -5,7 +5,7 @@ namespace ts.formatting { export class RuleOperationContext { private customContextChecks: { (context: FormattingContext): boolean; }[]; - + constructor(...funcs: { (context: FormattingContext): boolean; }[]) { this.customContextChecks = funcs; } @@ -22,7 +22,7 @@ namespace ts.formatting { return true; } - for (let check of this.customContextChecks) { + for (const check of this.customContextChecks) { if (!check(context)) { return false; } diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index afcaad28560..47a204a5b7e 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -4,8 +4,8 @@ namespace ts.formatting { export class Rules { public getRuleName(rule: Rule) { - let o: ts.Map = this; - for (let name in o) { + const o: ts.Map = this; + for (const name in o) { if (o[name] === rule) { return name; } @@ -166,7 +166,7 @@ namespace ts.formatting { public NoSpaceAfterKeywordInControl: Rule; // Open Brace braces after function - //TypeScript: Function can have return types, which can be made of tons of different token kinds + // TypeScript: Function can have return types, which can be made of tons of different token kinds public FunctionOpenBraceLeftTokenRange: Shared.TokenRange; public SpaceBeforeOpenBraceInFunction: Rule; public NewLineBeforeOpenBraceInFunction: Rule; @@ -313,7 +313,7 @@ namespace ts.formatting { this.SpaceAfterVoidOperator = new Rule(RuleDescriptor.create3(SyntaxKind.VoidKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), RuleAction.Space)); this.NoSpaceBetweenReturnAndSemicolon = new Rule(RuleDescriptor.create1(SyntaxKind.ReturnKeyword, SyntaxKind.SemicolonToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete)); - + // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] this.SpaceBetweenStatements = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.CloseParenToken, SyntaxKind.DoKeyword, SyntaxKind.ElseKeyword, SyntaxKind.CaseKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotForContext), RuleAction.Space)); @@ -458,7 +458,7 @@ namespace ts.formatting { this.NoSpaceAfterKeywordInControl = new Rule(RuleDescriptor.create2(Shared.TokenRange.Keywords, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsControlDeclContext), RuleAction.Delete)); // Open Brace braces after function - //TypeScript: Function can have return types, which can be made of tons of different token kinds + // TypeScript: Function can have return types, which can be made of tons of different token kinds this.NewLineBeforeOpenBraceInFunction = new Rule(RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, SyntaxKind.OpenBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), RuleAction.NewLine), RuleFlags.CanDeleteNewLines); // Open Brace braces after TypeScript module/class/interface @@ -616,17 +616,17 @@ namespace ts.formatting { case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - //case SyntaxKind.MemberFunctionDeclaration: + // case SyntaxKind.MemberFunctionDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - ///case SyntaxKind.MethodSignature: + // case SyntaxKind.MethodSignature: case SyntaxKind.CallSignature: case SyntaxKind.FunctionExpression: case SyntaxKind.Constructor: case SyntaxKind.ArrowFunction: - //case SyntaxKind.ConstructorDeclaration: - //case SyntaxKind.SimpleArrowFunctionExpression: - //case SyntaxKind.ParenthesizedArrowFunctionExpression: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: case SyntaxKind.InterfaceDeclaration: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } @@ -724,7 +724,7 @@ namespace ts.formatting { } static IsNotBeforeBlockInFunctionDeclarationContext(context: FormattingContext): boolean { - return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context) + return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); } static IsEndOfDecoratorContextOnSameLine(context: FormattingContext): boolean { @@ -755,7 +755,7 @@ namespace ts.formatting { } static IsObjectTypeContext(context: FormattingContext): boolean { - return context.contextNode.kind === SyntaxKind.TypeLiteral;// && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === SyntaxKind.TypeLiteral; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } static IsTypeArgumentOrParameterOrAssertion(token: TextRangeWithKind, parent: Node): boolean { diff --git a/src/services/formatting/rulesMap.ts b/src/services/formatting/rulesMap.ts index bffbb75c02e..74a1a33b7de 100644 --- a/src/services/formatting/rulesMap.ts +++ b/src/services/formatting/rulesMap.ts @@ -1,4 +1,5 @@ /// +/* tslint:disable:no-null-keyword */ /* @internal */ namespace ts.formatting { @@ -12,17 +13,17 @@ namespace ts.formatting { } static create(rules: Rule[]): RulesMap { - let result = new RulesMap(); + const result = new RulesMap(); result.Initialize(rules); return result; } public Initialize(rules: Rule[]) { this.mapRowLength = SyntaxKind.LastToken + 1; - this.map = new Array(this.mapRowLength * this.mapRowLength);//new Array(this.mapRowLength * this.mapRowLength); + this.map = new Array(this.mapRowLength * this.mapRowLength); // new Array(this.mapRowLength * this.mapRowLength); // This array is used only during construction of the rulesbucket in the map - let rulesBucketConstructionStateList: RulesBucketConstructionState[] = new Array(this.map.length);//new Array(this.map.length); + const rulesBucketConstructionStateList: RulesBucketConstructionState[] = new Array(this.map.length); // new Array(this.map.length); this.FillRules(rules, rulesBucketConstructionStateList); return this.map; @@ -35,18 +36,18 @@ namespace ts.formatting { } private GetRuleBucketIndex(row: number, column: number): number { - let rulesBucketIndex = (row * this.mapRowLength) + column; - //Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array."); + const rulesBucketIndex = (row * this.mapRowLength) + column; + // Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array."); return rulesBucketIndex; } private FillRule(rule: Rule, rulesBucketConstructionStateList: RulesBucketConstructionState[]): void { - let specificRule = rule.Descriptor.LeftTokenRange !== Shared.TokenRange.Any && + const specificRule = rule.Descriptor.LeftTokenRange !== Shared.TokenRange.Any && rule.Descriptor.RightTokenRange !== Shared.TokenRange.Any; rule.Descriptor.LeftTokenRange.GetTokens().forEach((left) => { rule.Descriptor.RightTokenRange.GetTokens().forEach((right) => { - let rulesBucketIndex = this.GetRuleBucketIndex(left, right); + const rulesBucketIndex = this.GetRuleBucketIndex(left, right); let rulesBucket = this.map[rulesBucketIndex]; if (rulesBucket === undefined) { @@ -54,15 +55,15 @@ namespace ts.formatting { } rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); - }) - }) + }); + }); } public GetRule(context: FormattingContext): Rule { - let bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); - let bucket = this.map[bucketIndex]; + const bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); + const bucket = this.map[bucketIndex]; if (bucket != null) { - for (let rule of bucket.Rules()) { + for (const rule of bucket.Rules()) { if (rule.Operation.Context.InContext(context)) { return rule; } @@ -72,8 +73,8 @@ namespace ts.formatting { } } - let MaskBitSize = 5; - let Mask = 0x1f; + const MaskBitSize = 5; + const Mask = 0x1f; export enum RulesPosition { IgnoreRulesSpecific = 0, @@ -167,7 +168,7 @@ namespace ts.formatting { if (state === undefined) { state = constructionState[rulesBucketIndex] = new RulesBucketConstructionState(); } - let index = state.GetInsertionIndex(position); + const index = state.GetInsertionIndex(position); this.rules.splice(index, 0, rule); state.IncreaseInsertionIndex(position); } diff --git a/src/services/formatting/rulesProvider.ts b/src/services/formatting/rulesProvider.ts index 48a783dd0c6..19581173f2d 100644 --- a/src/services/formatting/rulesProvider.ts +++ b/src/services/formatting/rulesProvider.ts @@ -1,4 +1,5 @@ /// +/* tslint:disable:no-null-keyword */ /* @internal */ namespace ts.formatting { @@ -27,8 +28,8 @@ namespace ts.formatting { public ensureUpToDate(options: ts.FormatCodeOptions) { // TODO: Should this be '==='? if (this.options == null || !ts.compareDataObjects(this.options, options)) { - let activeRules = this.createActiveRules(options); - let rulesMap = RulesMap.create(activeRules); + const activeRules = this.createActiveRules(options); + const rulesMap = RulesMap.create(activeRules); this.activeRules = activeRules; this.rulesMap = rulesMap; diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 8e0fef884e7..23a1d937869 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -2,7 +2,7 @@ /* @internal */ namespace ts.formatting { - export module SmartIndenter { + export namespace SmartIndenter { const enum Value { Unknown = -1 @@ -19,18 +19,18 @@ namespace ts.formatting { return 0; } - let precedingToken = findPrecedingToken(position, sourceFile); + const precedingToken = findPrecedingToken(position, sourceFile); if (!precedingToken) { return 0; } // no indentation in string \regex\template literals - let precedingTokenIsLiteral = isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); + const precedingTokenIsLiteral = isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { return 0; } - let lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + const lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not @@ -40,21 +40,21 @@ namespace ts.formatting { // move backwards until we find a line with a non-whitespace character, // then find the first non-whitespace character for that line. let current = position; - while (current > 0){ - let char = sourceFile.text.charCodeAt(current); + while (current > 0) { + const char = sourceFile.text.charCodeAt(current); if (!isWhiteSpace(char) && !isLineBreak(char)) { break; } current--; } - let lineStart = ts.getLineStartPositionForPosition(current, sourceFile); + const lineStart = ts.getLineStartPositionForPosition(current, sourceFile); return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options); } if (precedingToken.kind === SyntaxKind.CommaToken && precedingToken.parent.kind !== SyntaxKind.BinaryExpression) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it - let actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); + const actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== Value.Unknown) { return actualIndentation; } @@ -104,7 +104,7 @@ namespace ts.formatting { } export function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: FormatCodeOptions): number { - let start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + const start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); } @@ -124,19 +124,19 @@ namespace ts.formatting { while (parent) { let useActualIndentation = true; if (ignoreActualIndentationRange) { - let start = current.getStart(sourceFile); + const start = current.getStart(sourceFile); useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; } if (useActualIndentation) { // check if current node is a list item - if yes, take indentation from it - let actualIndentation = getActualIndentationForListItem(current, sourceFile, options); + const actualIndentation = getActualIndentationForListItem(current, sourceFile, options); if (actualIndentation !== Value.Unknown) { return actualIndentation + indentationDelta; } } parentStart = getParentStart(parent, current, sourceFile); - let parentAndChildShareLine = + const parentAndChildShareLine = parentStart.line === currentStart.line || childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); @@ -167,7 +167,7 @@ namespace ts.formatting { function getParentStart(parent: Node, child: Node, sourceFile: SourceFile): LineAndCharacter { - let containingList = getContainingList(child, sourceFile); + const containingList = getContainingList(child, sourceFile); if (containingList) { return sourceFile.getLineAndCharacterOfPosition(containingList.pos); } @@ -180,7 +180,7 @@ namespace ts.formatting { */ function getActualIndentationForListItemBeforeComma(commaToken: Node, sourceFile: SourceFile, options: EditorOptions): number { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it - let commaItemInfo = findListItemInfo(commaToken); + const commaItemInfo = findListItemInfo(commaToken); if (commaItemInfo && commaItemInfo.listItemIndex > 0) { return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options); } @@ -203,7 +203,7 @@ namespace ts.formatting { // actual indentation is used for statements\declarations if one of cases below is true: // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line - let useActualIndentation = + const useActualIndentation = (isDeclaration(current) || isStatement(current)) && (parent.kind === SyntaxKind.SourceFile || !parentAndChildShareLine); @@ -215,7 +215,7 @@ namespace ts.formatting { } function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken: Node, current: Node, lineAtPosition: number, sourceFile: SourceFile): boolean { - let nextToken = findNextToken(precedingToken, current); + const nextToken = findNextToken(precedingToken, current); if (!nextToken) { return false; } @@ -234,7 +234,7 @@ namespace ts.formatting { // class A { // $} - let nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; + const nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; return lineAtPosition === nextTokenStartLine; } @@ -247,10 +247,10 @@ namespace ts.formatting { export function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFile): boolean { if (parent.kind === SyntaxKind.IfStatement && (parent).elseStatement === child) { - let elseKeyword = findChildOfKind(parent, SyntaxKind.ElseKeyword, sourceFile); + const elseKeyword = findChildOfKind(parent, SyntaxKind.ElseKeyword, sourceFile); Debug.assert(elseKeyword !== undefined); - let elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; + const elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; return elseKeywordStartLine === childStartLine; } @@ -277,7 +277,7 @@ namespace ts.formatting { case SyntaxKind.MethodSignature: case SyntaxKind.CallSignature: case SyntaxKind.ConstructSignature: { - let start = node.getStart(sourceFile); + const start = node.getStart(sourceFile); if ((node.parent).typeParameters && rangeContainsStartEnd((node.parent).typeParameters, start, node.getEnd())) { return (node.parent).typeParameters; @@ -289,7 +289,7 @@ namespace ts.formatting { } case SyntaxKind.NewExpression: case SyntaxKind.CallExpression: { - let start = node.getStart(sourceFile); + const start = node.getStart(sourceFile); if ((node.parent).typeArguments && rangeContainsStartEnd((node.parent).typeArguments, start, node.getEnd())) { return (node.parent).typeArguments; @@ -306,11 +306,11 @@ namespace ts.formatting { } function getActualIndentationForListItem(node: Node, sourceFile: SourceFile, options: EditorOptions): number { - let containingList = getContainingList(node, sourceFile); + const containingList = getContainingList(node, sourceFile); return containingList ? getActualIndentationFromList(containingList) : Value.Unknown; function getActualIndentationFromList(list: Node[]): number { - let index = indexOf(list, node); + const index = indexOf(list, node); return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : Value.Unknown; } } @@ -327,15 +327,15 @@ namespace ts.formatting { node.parent.kind === SyntaxKind.NewExpression) && (node.parent).expression !== node) { - let fullCallOrNewExpression = (node.parent).expression; - let startingExpression = getStartingExpression(fullCallOrNewExpression); + const fullCallOrNewExpression = (node.parent).expression; + const startingExpression = getStartingExpression(fullCallOrNewExpression); if (fullCallOrNewExpression === startingExpression) { return Value.Unknown; } - let fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); - let startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); + const fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); + const startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { return Value.Unknown; @@ -365,17 +365,17 @@ namespace ts.formatting { function deriveActualIndentationFromList(list: Node[], index: number, sourceFile: SourceFile, options: EditorOptions): number { Debug.assert(index >= 0 && index < list.length); - let node = list[index]; + const node = list[index]; // walk toward the start of the list starting from current node and check if the line is the same for all items. // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] let lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); - for (let i = index - 1; i >= 0; --i) { + for (let i = index - 1; i >= 0; i--) { if (list[i].kind === SyntaxKind.CommaToken) { continue; } // skip list items that ends on the same line with the current list element - let prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; + const prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; if (prevEndLine !== lineAndCharacter.line) { return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); } @@ -386,7 +386,7 @@ namespace ts.formatting { } function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter: LineAndCharacter, sourceFile: SourceFile, options: EditorOptions): number { - let lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); + const lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); } @@ -400,8 +400,8 @@ namespace ts.formatting { export function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions) { let character = 0; let column = 0; - for (let pos = startPos; pos < endPos; ++pos) { - let ch = sourceFile.text.charCodeAt(pos); + for (let pos = startPos; pos < endPos; pos++) { + const ch = sourceFile.text.charCodeAt(pos); if (!isWhiteSpace(ch)) { break; } @@ -467,10 +467,10 @@ namespace ts.formatting { } return false; } - + /* @internal */ export function nodeWillIndentChild(parent: TextRangeWithKind, child: TextRangeWithKind, indentByDefault: boolean) { - let childKind = child ? child.kind : SyntaxKind.Unknown; + const childKind = child ? child.kind : SyntaxKind.Unknown; switch (parent.kind) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: @@ -497,7 +497,7 @@ namespace ts.formatting { Function returns true when the parent node should indent the given child by an explicit rule */ export function shouldIndentChildNode(parent: TextRangeWithKind, child?: TextRangeWithKind): boolean { - return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); + return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false); } } } diff --git a/src/services/formatting/tokenRange.ts b/src/services/formatting/tokenRange.ts index 1afde613618..0e4ec4d221c 100644 --- a/src/services/formatting/tokenRange.ts +++ b/src/services/formatting/tokenRange.ts @@ -2,7 +2,7 @@ /* @internal */ namespace ts.formatting { - export module Shared { + export namespace Shared { export interface ITokenAccess { GetTokens(): SyntaxKind[]; Contains(token: SyntaxKind): boolean; @@ -60,7 +60,7 @@ namespace ts.formatting { export class TokenAllAccess implements ITokenAccess { public GetTokens(): SyntaxKind[] { - let result: SyntaxKind[] = []; + const result: SyntaxKind[] = []; for (let token = SyntaxKind.FirstToken; token <= SyntaxKind.LastToken; token++) { result.push(token); } diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 9e8a2f14ed8..53fb7a474a7 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -7,7 +7,7 @@ namespace ts.SignatureHelp { // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it // will return the generic identifier that started the expression (e.g. "foo" in "foo[]; - let resolvedSignature = typeChecker.getResolvedSignature(call, candidates); + const call = argumentInfo.invocation; + const candidates = []; + const resolvedSignature = typeChecker.getResolvedSignature(call, candidates); cancellationToken.throwIfCancellationRequested(); if (!candidates.length) { @@ -219,9 +219,9 @@ namespace ts.SignatureHelp { } // See if we can find some symbol with the call expression name that has call signatures. - let callExpression = argumentInfo.invocation; - let expression = callExpression.expression; - let name = expression.kind === SyntaxKind.Identifier + const callExpression = argumentInfo.invocation; + const expression = callExpression.expression; + const name = expression.kind === SyntaxKind.Identifier ? expression : expression.kind === SyntaxKind.PropertyAccessExpression ? (expression).name @@ -231,18 +231,18 @@ namespace ts.SignatureHelp { return undefined; } - let typeChecker = program.getTypeChecker(); - for (let sourceFile of program.getSourceFiles()) { - let nameToDeclarations = sourceFile.getNamedDeclarations(); - let declarations = getProperty(nameToDeclarations, name.text); + const typeChecker = program.getTypeChecker(); + for (const sourceFile of program.getSourceFiles()) { + const nameToDeclarations = sourceFile.getNamedDeclarations(); + const declarations = getProperty(nameToDeclarations, name.text); if (declarations) { - for (let declaration of declarations) { - let symbol = declaration.symbol; + for (const declaration of declarations) { + const symbol = declaration.symbol; if (symbol) { - let type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); + const type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); if (type) { - let callSignatures = type.getCallSignatures(); + const callSignatures = type.getCallSignatures(); if (callSignatures && callSignatures.length) { return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo); } @@ -259,7 +259,7 @@ namespace ts.SignatureHelp { */ function getImmediatelyContainingArgumentInfo(node: Node): ArgumentListInfo { if (node.parent.kind === SyntaxKind.CallExpression || node.parent.kind === SyntaxKind.NewExpression) { - let callExpression = node.parent; + const callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session // 2. The token is either not associated with a list, or ends a list, so the session should end @@ -278,8 +278,8 @@ namespace ts.SignatureHelp { node.kind === SyntaxKind.OpenParenToken) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. - let list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); - let isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; + const list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); + const isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; Debug.assert(list !== undefined); return { kind: isTypeArgList ? ArgumentListKind.TypeArguments : ArgumentListKind.CallArguments, @@ -296,16 +296,16 @@ namespace ts.SignatureHelp { // - Between the type arguments and the arguments (greater than token) // - On the target of the call (parent.func) // - On the 'new' keyword in a 'new' expression - let listItemInfo = findListItemInfo(node); + const listItemInfo = findListItemInfo(node); if (listItemInfo) { - let list = listItemInfo.list; - let isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; + const list = listItemInfo.list; + const isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; - let argumentIndex = getArgumentIndex(list, node); - let argumentCount = getArgumentCount(list); + const argumentIndex = getArgumentIndex(list, node); + const argumentCount = getArgumentCount(list); Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, - `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`); + `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`); return { kind: isTypeArgList ? ArgumentListKind.TypeArguments : ArgumentListKind.CallArguments, @@ -324,18 +324,18 @@ namespace ts.SignatureHelp { } } else if (node.kind === SyntaxKind.TemplateHead && node.parent.parent.kind === SyntaxKind.TaggedTemplateExpression) { - let templateExpression = node.parent; - let tagExpression = templateExpression.parent; + const templateExpression = node.parent; + const tagExpression = templateExpression.parent; Debug.assert(templateExpression.kind === SyntaxKind.TemplateExpression); - let argumentIndex = isInsideTemplateLiteral(node, position) ? 0 : 1; + const argumentIndex = isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } else if (node.parent.kind === SyntaxKind.TemplateSpan && node.parent.parent.parent.kind === SyntaxKind.TaggedTemplateExpression) { - let templateSpan = node.parent; - let templateExpression = templateSpan.parent; - let tagExpression = templateExpression.parent; + const templateSpan = node.parent; + const templateExpression = templateSpan.parent; + const tagExpression = templateExpression.parent; Debug.assert(templateExpression.kind === SyntaxKind.TemplateExpression); // If we're just after a template tail, don't show signature help. @@ -343,12 +343,12 @@ namespace ts.SignatureHelp { return undefined; } - let spanIndex = templateExpression.templateSpans.indexOf(templateSpan); - let argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node); + const spanIndex = templateExpression.templateSpans.indexOf(templateSpan); + const argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node); return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - + return undefined; } @@ -365,8 +365,8 @@ namespace ts.SignatureHelp { // that trailing comma in the list, and we'll have generated the appropriate // arg index. let argumentIndex = 0; - let listChildren = argumentsList.getChildren(); - for (let child of listChildren) { + const listChildren = argumentsList.getChildren(); + for (const child of listChildren) { if (child === node) { break; } @@ -390,7 +390,7 @@ namespace ts.SignatureHelp { // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, givin us an // arg count of 3. - let listChildren = argumentsList.getChildren(); + const listChildren = argumentsList.getChildren(); let argumentCount = countWhere(listChildren, arg => arg.kind !== SyntaxKind.CommaToken); if (listChildren.length > 0 && lastOrUndefined(listChildren).kind === SyntaxKind.CommaToken) { @@ -426,11 +426,11 @@ namespace ts.SignatureHelp { function getArgumentListInfoForTemplate(tagExpression: TaggedTemplateExpression, argumentIndex: number): ArgumentListInfo { // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. - let argumentCount = tagExpression.template.kind === SyntaxKind.NoSubstitutionTemplateLiteral + const argumentCount = tagExpression.template.kind === SyntaxKind.NoSubstitutionTemplateLiteral ? 1 : (tagExpression.template).templateSpans.length + 1; - Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`); + Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`); return { kind: ArgumentListKind.TaggedTemplateArguments, @@ -450,14 +450,14 @@ namespace ts.SignatureHelp { // // The applicable span is from the first bar to the second bar (inclusive, // but not including parentheses) - let applicableSpanStart = argumentsList.getFullStart(); - let applicableSpanEnd = skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); + const applicableSpanStart = argumentsList.getFullStart(); + const applicableSpanEnd = skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getApplicableSpanForTaggedTemplate(taggedTemplate: TaggedTemplateExpression): TextSpan { - let template = taggedTemplate.template; - let applicableSpanStart = template.getStart(); + const template = taggedTemplate.template; + const applicableSpanStart = template.getStart(); let applicableSpanEnd = template.getEnd(); // We need to adjust the end position for the case where the template does not have a tail. @@ -470,7 +470,7 @@ namespace ts.SignatureHelp { // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === SyntaxKind.TemplateExpression) { - let lastSpan = lastOrUndefined((template).templateSpans); + const lastSpan = lastOrUndefined((template).templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); } @@ -491,7 +491,7 @@ namespace ts.SignatureHelp { Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind); } - let argumentInfo = getImmediatelyContainingArgumentInfo(n); + const argumentInfo = getImmediatelyContainingArgumentInfo(n); if (argumentInfo) { return argumentInfo; } @@ -503,8 +503,8 @@ namespace ts.SignatureHelp { } function getChildListThatStartsWithOpenerToken(parent: Node, openerToken: Node, sourceFile: SourceFile): Node { - let children = parent.getChildren(sourceFile); - let indexOfOpenerToken = children.indexOf(openerToken); + const children = parent.getChildren(sourceFile); + const indexOfOpenerToken = children.indexOf(openerToken); Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } @@ -521,7 +521,7 @@ namespace ts.SignatureHelp { let maxParamsSignatureIndex = -1; let maxParams = -1; for (let i = 0; i < candidates.length; i++) { - let candidate = candidates[i]; + const candidate = candidates[i]; if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) { return i; @@ -537,17 +537,17 @@ namespace ts.SignatureHelp { } function createSignatureHelpItems(candidates: Signature[], bestSignature: Signature, argumentListInfo: ArgumentListInfo): SignatureHelpItems { - let applicableSpan = argumentListInfo.argumentsSpan; - let isTypeParameterList = argumentListInfo.kind === ArgumentListKind.TypeArguments; + const applicableSpan = argumentListInfo.argumentsSpan; + const isTypeParameterList = argumentListInfo.kind === ArgumentListKind.TypeArguments; - let invocation = argumentListInfo.invocation; - let callTarget = getInvokedExpression(invocation) - let callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); - let callTargetDisplayParts = callTargetSymbol && symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); - let items: SignatureHelpItem[] = map(candidates, candidateSignature => { + const invocation = argumentListInfo.invocation; + const callTarget = getInvokedExpression(invocation); + const callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); + const callTargetDisplayParts = callTargetSymbol && symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); + const items: SignatureHelpItem[] = map(candidates, candidateSignature => { let signatureHelpParameters: SignatureHelpParameter[]; - let prefixDisplayParts: SymbolDisplayPart[] = []; - let suffixDisplayParts: SymbolDisplayPart[] = []; + const prefixDisplayParts: SymbolDisplayPart[] = []; + const suffixDisplayParts: SymbolDisplayPart[] = []; if (callTargetDisplayParts) { addRange(prefixDisplayParts, callTargetDisplayParts); @@ -555,28 +555,28 @@ namespace ts.SignatureHelp { if (isTypeParameterList) { prefixDisplayParts.push(punctuationPart(SyntaxKind.LessThanToken)); - let typeParameters = candidateSignature.typeParameters; + const typeParameters = candidateSignature.typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; suffixDisplayParts.push(punctuationPart(SyntaxKind.GreaterThanToken)); - let parameterParts = mapToDisplayParts(writer => + const parameterParts = mapToDisplayParts(writer => typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisType, candidateSignature.parameters, writer, invocation)); addRange(suffixDisplayParts, parameterParts); } else { - let typeParameterParts = mapToDisplayParts(writer => + const typeParameterParts = mapToDisplayParts(writer => typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation)); addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(punctuationPart(SyntaxKind.OpenParenToken)); - let parameters = candidateSignature.parameters; + const parameters = candidateSignature.parameters; signatureHelpParameters = parameters.length > 0 ? map(parameters, createSignatureHelpParameterForParameter) : emptyArray; suffixDisplayParts.push(punctuationPart(SyntaxKind.CloseParenToken)); } - let returnTypeParts = mapToDisplayParts(writer => + const returnTypeParts = mapToDisplayParts(writer => typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation)); addRange(suffixDisplayParts, returnTypeParts); - + return { isVariadic: candidateSignature.hasRestParameter, prefixDisplayParts, @@ -587,17 +587,17 @@ namespace ts.SignatureHelp { }; }); - let argumentIndex = argumentListInfo.argumentIndex; + const argumentIndex = argumentListInfo.argumentIndex; // argumentCount is the *apparent* number of arguments. - let argumentCount = argumentListInfo.argumentCount; + const argumentCount = argumentListInfo.argumentCount; let selectedItemIndex = candidates.indexOf(bestSignature); if (selectedItemIndex < 0) { selectedItemIndex = selectBestInvalidOverloadIndex(candidates, argumentCount); } - Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`); + Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`); return { items, @@ -608,7 +608,7 @@ namespace ts.SignatureHelp { }; function createSignatureHelpParameterForParameter(parameter: Symbol): SignatureHelpParameter { - let displayParts = mapToDisplayParts(writer => + const displayParts = mapToDisplayParts(writer => typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation)); return { @@ -620,7 +620,7 @@ namespace ts.SignatureHelp { } function createSignatureHelpParameterForTypeParameter(typeParameter: TypeParameter): SignatureHelpParameter { - let displayParts = mapToDisplayParts(writer => + const displayParts = mapToDisplayParts(writer => typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation)); return { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 404fdf92d4d..34ae39c02d4 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -7,8 +7,8 @@ namespace ts { } export function getLineStartPositionForPosition(position: number, sourceFile: SourceFile): number { - let lineStarts = sourceFile.getLineStarts(); - let line = sourceFile.getLineAndCharacterOfPosition(position).line; + const lineStarts = sourceFile.getLineStarts(); + const line = sourceFile.getLineAndCharacterOfPosition(position).line; return lineStarts[line]; } @@ -29,8 +29,8 @@ namespace ts { } export function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number) { - let start = Math.max(start1, start2); - let end = Math.min(end1, end2); + const start = Math.max(start1, start2); + const end = Math.min(end1, end2); return start < end; } @@ -131,7 +131,7 @@ namespace ts { return isCompletedNode((n).statement, sourceFile); case SyntaxKind.DoStatement: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; - let hasWhileKeyword = findChildOfKind(n, SyntaxKind.WhileKeyword, sourceFile); + const hasWhileKeyword = findChildOfKind(n, SyntaxKind.WhileKeyword, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile); } @@ -145,13 +145,13 @@ namespace ts { case SyntaxKind.VoidExpression: case SyntaxKind.YieldExpression: case SyntaxKind.SpreadElementExpression: - let unaryWordExpression = (n); + const unaryWordExpression = (n); return isCompletedNode(unaryWordExpression.expression, sourceFile); case SyntaxKind.TaggedTemplateExpression: return isCompletedNode((n).template, sourceFile); case SyntaxKind.TemplateExpression: - let lastSpan = lastOrUndefined((n).templateSpans); + const lastSpan = lastOrUndefined((n).templateSpans); return isCompletedNode(lastSpan, sourceFile); case SyntaxKind.TemplateSpan: return nodeIsPresent((n).literal); @@ -173,9 +173,9 @@ namespace ts { * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. */ function nodeEndsWith(n: Node, expectedLastToken: SyntaxKind, sourceFile: SourceFile): boolean { - let children = n.getChildren(sourceFile); + const children = n.getChildren(sourceFile); if (children.length) { - let last = lastOrUndefined(children); + const last = lastOrUndefined(children); if (last.kind === expectedLastToken) { return true; } @@ -187,7 +187,7 @@ namespace ts { } export function findListItemInfo(node: Node): ListItemInfo { - let list = findContainingList(node); + const list = findContainingList(node); // It is possible at this point for syntaxList to be undefined, either if // node.parent had no list child, or if none of its list children contained @@ -197,8 +197,8 @@ namespace ts { return undefined; } - let children = list.getChildren(); - let listItemIndex = indexOf(children, node); + const children = list.getChildren(); + const listItemIndex = indexOf(children, node); return { listItemIndex, @@ -219,7 +219,7 @@ namespace ts { // be parented by the container of the SyntaxList, not the SyntaxList itself. // In order to find the list item index, we first need to locate SyntaxList itself and then search // for the position of the relevant node (or comma). - let syntaxList = forEach(node.parent.getChildren(), c => { + const syntaxList = forEach(node.parent.getChildren(), c => { // find syntax list that covers the span of the node if (c.kind === SyntaxKind.SyntaxList && c.pos <= node.pos && c.end >= node.end) { return c; @@ -266,16 +266,16 @@ namespace ts { // find the child that contains 'position' for (let i = 0, n = current.getChildCount(sourceFile); i < n; i++) { - let child = current.getChildAt(i); - let start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile); + const child = current.getChildAt(i); + const start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile); if (start <= position) { - let end = child.getEnd(); + const end = child.getEnd(); if (position < end || (position === end && child.kind === SyntaxKind.EndOfFileToken)) { current = child; continue outer; } else if (includeItemAtEndPosition && end === position) { - let previousToken = findPrecedingToken(position, sourceFile, child); + const previousToken = findPrecedingToken(position, sourceFile, child); if (previousToken && includeItemAtEndPosition(previousToken)) { return previousToken; } @@ -297,7 +297,7 @@ namespace ts { export function findTokenOnLeftOfPosition(file: SourceFile, position: number): Node { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. - let tokenAtPosition = getTokenAtPosition(file, position); + const tokenAtPosition = getTokenAtPosition(file, position); if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -314,9 +314,9 @@ namespace ts { return n; } - let children = n.getChildren(); - for (let child of children) { - let shouldDiveInChildNode = + const children = n.getChildren(); + for (const child of children) { + const shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || // previous token ends exactly at the beginning of child @@ -339,8 +339,8 @@ namespace ts { return n; } - let children = n.getChildren(); - let candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + const children = n.getChildren(); + const candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); return candidate && findRightmostToken(candidate); } @@ -352,7 +352,7 @@ namespace ts { const children = n.getChildren(); for (let i = 0, len = children.length; i < len; i++) { - let child = children[i]; + const child = children[i]; // condition 'position < child.end' checks if child node end after the position // in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc' // aaaa___bbbb___$__ccc @@ -369,7 +369,7 @@ namespace ts { if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - let candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); + const candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); return candidate && findRightmostToken(candidate); } else { @@ -386,14 +386,14 @@ namespace ts { // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' if (children.length) { - let candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + const candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); return candidate && findRightmostToken(candidate); } } /// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition' function findRightmostChildNodeWithTokens(children: Node[], exclusiveStartPosition: number): Node { - for (let i = exclusiveStartPosition - 1; i >= 0; --i) { + for (let i = exclusiveStartPosition - 1; i >= 0; i--) { if (nodeHasTokens(children[i])) { return children[i]; } @@ -402,7 +402,7 @@ namespace ts { } export function isInString(sourceFile: SourceFile, position: number) { - let token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position); return token && (token.kind === SyntaxKind.StringLiteral || token.kind === SyntaxKind.StringLiteralType) && position > token.getStart(sourceFile); } @@ -414,7 +414,7 @@ namespace ts { * returns true if the position is in between the open and close elements of an JSX expression. */ export function isInsideJsxElementOrAttribute(sourceFile: SourceFile, position: number) { - let token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position); if (!token) { return false; @@ -446,7 +446,7 @@ namespace ts { } export function isInTemplateString(sourceFile: SourceFile, position: number) { - let token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position); return isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } @@ -455,10 +455,10 @@ namespace ts { * satisfies predicate, and false otherwise. */ export function isInCommentHelper(sourceFile: SourceFile, position: number, predicate?: (c: CommentRange) => boolean): boolean { - let token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position); if (token && position <= token.getStart(sourceFile)) { - let commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); + const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); // The end marker of a single-line comment does not include the newline character. // In the following case, we are inside a comment (^ denotes the cursor position): @@ -482,10 +482,10 @@ namespace ts { } export function hasDocComment(sourceFile: SourceFile, position: number) { - let token = getTokenAtPosition(sourceFile, position); + const token = getTokenAtPosition(sourceFile, position); // First, we have to see if this position actually landed in a comment. - let commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); + const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); return forEach(commentRanges, jsDocPrefix); @@ -515,9 +515,9 @@ namespace ts { } if (node) { - let jsDocComment = node.jsDocComment; + const jsDocComment = node.jsDocComment; if (jsDocComment) { - for (let tag of jsDocComment.tags) { + for (const tag of jsDocComment.tags) { if (tag.pos <= position && position <= tag.end) { return tag; } @@ -535,8 +535,8 @@ namespace ts { } export function getNodeModifiers(node: Node): string { - let flags = getCombinedNodeFlags(node); - let result: string[] = []; + const flags = getCombinedNodeFlags(node); + const result: string[] = []; if (flags & NodeFlags.Private) result.push(ScriptElementKindModifier.privateMemberModifier); if (flags & NodeFlags.Protected) result.push(ScriptElementKindModifier.protectedMemberModifier); @@ -608,7 +608,7 @@ namespace ts { } export function compareDataObjects(dst: any, src: any): boolean { - for (let e in dst) { + for (const e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { return false; @@ -661,7 +661,7 @@ namespace ts { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === SyntaxKind.Parameter; } - let displayPartWriter = getDisplayPartWriter(); + const displayPartWriter = getDisplayPartWriter(); function getDisplayPartWriter(): DisplayPartsSymbolWriter { let displayParts: SymbolDisplayPart[]; let lineStart: boolean; @@ -687,7 +687,7 @@ namespace ts { function writeIndent() { if (lineStart) { - let indentString = getIndentString(indent); + const indentString = getIndentString(indent); if (indentString) { displayParts.push(displayPart(indentString, SymbolDisplayPartKind.space)); } @@ -721,7 +721,7 @@ namespace ts { return displayPart(text, displayPartKind(symbol), symbol); function displayPartKind(symbol: Symbol): SymbolDisplayPartKind { - let flags = symbol.flags; + const flags = symbol.flags; if (flags & SymbolFlags.Variable) { return isFirstDeclarationOfSymbolParameter(symbol) ? SymbolDisplayPartKind.parameterName : SymbolDisplayPartKind.localName; @@ -792,7 +792,7 @@ namespace ts { export function mapToDisplayParts(writeDisplayParts: (writer: DisplayPartsSymbolWriter) => void): SymbolDisplayPart[] { writeDisplayParts(displayPartWriter); - let result = displayPartWriter.displayParts(); + const result = displayPartWriter.displayParts(); displayPartWriter.clear(); return result; } @@ -828,9 +828,9 @@ namespace ts { // Try to get the local symbol if we're dealing with an 'export default' // since that symbol has the "true" name. - let localExportDefaultSymbol = getLocalSymbolForExportDefault(symbol); + const localExportDefaultSymbol = getLocalSymbolForExportDefault(symbol); - let name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); + const name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); return name; } @@ -847,7 +847,7 @@ namespace ts { * @return non-quoted string */ export function stripQuotes(name: string) { - let length = name.length; + const length = name.length; if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && (name.charCodeAt(0) === CharacterCodes.doubleQuote || name.charCodeAt(0) === CharacterCodes.singleQuote)) { From dbd30542a6a7ecdb3b6a2594a353bb91d0bbcdd7 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 25 May 2016 07:16:23 -0700 Subject: [PATCH 03/13] Include classes as childItems in navigation bar --- src/services/navigationBar.ts | 3 +++ tests/cases/fourslash/navbar_contains-no-duplicates.ts | 4 ++-- .../navigationBarItemsBindingPatternsInConstructor.ts | 2 +- .../cases/fourslash/navigationBarItemsEmptyConstructors.ts | 2 +- .../navigationBarItemsInsideMethodsAndConstructors.ts | 2 +- tests/cases/fourslash/navigationBarItemsItems.ts | 4 ++-- .../fourslash/navigationBarItemsItemsExternalModules.ts | 4 ++-- .../fourslash/navigationBarItemsItemsExternalModules2.ts | 4 ++-- .../fourslash/navigationBarItemsItemsExternalModules3.ts | 4 ++-- tests/cases/fourslash/navigationBarItemsMissingName1.ts | 6 +++--- .../navigationBarItemsMultilineStringIdentifiers.ts | 4 ++-- .../navigationBarItemsPropertiesDefinedInConstructors.ts | 2 +- tests/cases/fourslash/navigationBarItemsSymbols1.ts | 5 +++-- tests/cases/fourslash/server/navbar01.ts | 4 ++-- 14 files changed, 27 insertions(+), 23 deletions(-) diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index cb81c398cb8..f05f3f3a6e6 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -330,6 +330,9 @@ namespace ts.NavigationBar { case SyntaxKind.PropertySignature: return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.memberVariableElement); + case SyntaxKind.ClassDeclaration: + return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.classElement); + case SyntaxKind.FunctionDeclaration: return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.functionElement); diff --git a/tests/cases/fourslash/navbar_contains-no-duplicates.ts b/tests/cases/fourslash/navbar_contains-no-duplicates.ts index ec86e4b2f20..a698e5b0f0e 100644 --- a/tests/cases/fourslash/navbar_contains-no-duplicates.ts +++ b/tests/cases/fourslash/navbar_contains-no-duplicates.ts @@ -2,7 +2,7 @@ //// {| "itemName": "Windows", "kind": "module", "parentName": "" |}declare module Windows { //// {| "itemName": "Foundation", "kind": "module", "parentName": "" |}export module Foundation { //// export var {| "itemName": "A", "kind": "var" |}A; -//// {| "itemName": "Test", "kind": "class" |}export class Test { +//// {| "itemName": "Test", "kind": "class", "parentName": "Foundation" |}export class Test { //// {| "itemName": "wow", "kind": "method" |}public wow(); //// } //// } @@ -38,4 +38,4 @@ test.markers().forEach(marker => { marker.position); } }); -verify.navigationBarCount(12); \ No newline at end of file +verify.navigationBarCount(15); \ No newline at end of file diff --git a/tests/cases/fourslash/navigationBarItemsBindingPatternsInConstructor.ts b/tests/cases/fourslash/navigationBarItemsBindingPatternsInConstructor.ts index 84c1d09efe7..24979e141e5 100644 --- a/tests/cases/fourslash/navigationBarItemsBindingPatternsInConstructor.ts +++ b/tests/cases/fourslash/navigationBarItemsBindingPatternsInConstructor.ts @@ -11,4 +11,4 @@ //// } ////} -verify.navigationBarCount(6); // 2x(class + field + constructor) +verify.navigationBarCount(9); // global + 2 children + 2x(class + field + constructor) diff --git a/tests/cases/fourslash/navigationBarItemsEmptyConstructors.ts b/tests/cases/fourslash/navigationBarItemsEmptyConstructors.ts index 2255d29e293..a80f4c596d4 100644 --- a/tests/cases/fourslash/navigationBarItemsEmptyConstructors.ts +++ b/tests/cases/fourslash/navigationBarItemsEmptyConstructors.ts @@ -9,4 +9,4 @@ verify.navigationBarContains("Test", "class"); verify.navigationBarContains("constructor", "constructor"); // no other items -verify.navigationBarCount(2); \ No newline at end of file +verify.navigationBarCount(4); // global + 1 child, Test + 1 child \ No newline at end of file diff --git a/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts b/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts index 89b05dc6b07..3d2c026d360 100644 --- a/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts +++ b/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts @@ -39,4 +39,4 @@ test.markers().forEach((marker) => { }); // no other items -verify.navigationBarCount(19); +verify.navigationBarCount(21); diff --git a/tests/cases/fourslash/navigationBarItemsItems.ts b/tests/cases/fourslash/navigationBarItemsItems.ts index 5cae68b1194..95fdecd369c 100644 --- a/tests/cases/fourslash/navigationBarItemsItems.ts +++ b/tests/cases/fourslash/navigationBarItemsItems.ts @@ -13,7 +13,7 @@ ////{| "itemName": "Shapes", "kind": "module", "parentName": "" |}module Shapes { //// //// // Class -//// {| "itemName": "Point", "kind": "class", "parentName": "" |}export class Point implements IPoint { +//// {| "itemName": "Point", "kind": "class", "parentName": "Shapes" |}export class Point implements IPoint { //// {| "itemName": "constructor", "kind": "constructor", "parentName": "Point" |}constructor (public x: number, public y: number) { } //// //// // Instance member @@ -49,4 +49,4 @@ test.markers().forEach((marker) => { } }); -verify.navigationBarCount(24); +verify.navigationBarCount(25); diff --git a/tests/cases/fourslash/navigationBarItemsItemsExternalModules.ts b/tests/cases/fourslash/navigationBarItemsItemsExternalModules.ts index 64a595cafb1..7b2e0def4bf 100644 --- a/tests/cases/fourslash/navigationBarItemsItemsExternalModules.ts +++ b/tests/cases/fourslash/navigationBarItemsItemsExternalModules.ts @@ -1,6 +1,6 @@ /// -////{| "itemName": "Bar", "kind": "class" |}export class Bar { +////{| "itemName": "Bar", "kind": "class", "parentName": "\"navigationBarItemsItemsExternalModules\"" |}export class Bar { //// {| "itemName": "s", "kind": "property", "parentName": "Bar" |}public s: string; ////} @@ -8,4 +8,4 @@ test.markers().forEach((marker) => { verify.navigationBarContains(marker.data.itemName, marker.data.kind, marker.fileName, marker.data.parentName); }); -verify.navigationBarCount(2); // external module node + class + property +verify.navigationBarCount(4); // external module node + class + property diff --git a/tests/cases/fourslash/navigationBarItemsItemsExternalModules2.ts b/tests/cases/fourslash/navigationBarItemsItemsExternalModules2.ts index 7c1c32cff76..9087493b298 100644 --- a/tests/cases/fourslash/navigationBarItemsItemsExternalModules2.ts +++ b/tests/cases/fourslash/navigationBarItemsItemsExternalModules2.ts @@ -1,7 +1,7 @@ /// // @Filename: test/file.ts -////{| "itemName": "Bar", "kind": "class" |}export class Bar { +////{| "itemName": "Bar", "kind": "class", "parentName": "\"file\"" |}export class Bar { //// {| "itemName": "s", "kind": "property", "parentName": "Bar" |}public s: string; ////} ////{| "itemName": "\"file\"", "kind": "module" |} @@ -12,4 +12,4 @@ test.markers().forEach((marker) => { verify.navigationBarContains(marker.data.itemName, marker.data.kind, marker.fileName, marker.data.parentName); }); -verify.navigationBarCount(4); // external module node + variable in module + class + property +verify.navigationBarCount(5); // external module node + variable in module + class + property diff --git a/tests/cases/fourslash/navigationBarItemsItemsExternalModules3.ts b/tests/cases/fourslash/navigationBarItemsItemsExternalModules3.ts index 6e6dc9871cc..a00b3a131dd 100644 --- a/tests/cases/fourslash/navigationBarItemsItemsExternalModules3.ts +++ b/tests/cases/fourslash/navigationBarItemsItemsExternalModules3.ts @@ -1,7 +1,7 @@ /// // @Filename: test/my fil"e.ts -////{| "itemName": "Bar", "kind": "class" |}export class Bar { +////{| "itemName": "Bar", "kind": "class", "parentName": "\"my fil\\\"e\"" |}export class Bar { //// {| "itemName": "s", "kind": "property", "parentName": "Bar" |}public s: string; ////} ////{| "itemName": "\"my fil\\\"e\"", "kind": "module" |} @@ -12,4 +12,4 @@ test.markers().forEach((marker) => { verify.navigationBarContains(marker.data.itemName, marker.data.kind, marker.fileName, marker.data.parentName); }); -verify.navigationBarCount(4); // external module node + variable in module + class + property +verify.navigationBarCount(5); // external module node + 2 children + class + property diff --git a/tests/cases/fourslash/navigationBarItemsMissingName1.ts b/tests/cases/fourslash/navigationBarItemsMissingName1.ts index 98321039c5a..59f2911f3aa 100644 --- a/tests/cases/fourslash/navigationBarItemsMissingName1.ts +++ b/tests/cases/fourslash/navigationBarItemsMissingName1.ts @@ -2,7 +2,7 @@ /////** //// * This is a class. //// */ -////{| "itemName": "C", "kind": "class" |} class C { +////{| "itemName": "C", "kind": "class", "parentName": "\"navigationBarItemsMissingName1\"" |} class C { //// {| "itemName": "foo", "kind": "method" |} foo() { //// } ////} @@ -12,5 +12,5 @@ test.markers().forEach((marker) => { verify.navigationBarContains(marker.data.itemName, marker.data.kind, marker.fileName, marker.data.parentName); }); -/// Only have two named elements. -verify.navigationBarCount(2); +/// Root + 1 child, class + 1 child +verify.navigationBarCount(4); diff --git a/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts b/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts index 8856c4c044a..54524436d40 100644 --- a/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts +++ b/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts @@ -20,7 +20,7 @@ //// b"(): Foo; ////} //// -////{| "itemName": "Bar", "kind": "class" |} +////{| "itemName": "Bar", "kind": "class", "parentName": "" |} ////class Bar implements Foo { //// {| "itemName": "'a1\\\\\\r\\nb'", "kind": "property", "parentName": "Bar" |} //// 'a1\\\r\nb': Foo; @@ -38,4 +38,4 @@ test.markers().forEach((marker) => { verify.navigationBarContains(marker.data.itemName, marker.data.kind, marker.fileName, marker.data.parentName); }); -verify.navigationBarCount(9); // interface w/ 2 properties, class w/ 2 properties, 3 modules \ No newline at end of file +verify.navigationBarCount(11); // global + 1 child, interface w/ 2 properties, class w/ 2 properties, 3 modules \ No newline at end of file diff --git a/tests/cases/fourslash/navigationBarItemsPropertiesDefinedInConstructors.ts b/tests/cases/fourslash/navigationBarItemsPropertiesDefinedInConstructors.ts index 9b3f4aacd9c..8e1981f6101 100644 --- a/tests/cases/fourslash/navigationBarItemsPropertiesDefinedInConstructors.ts +++ b/tests/cases/fourslash/navigationBarItemsPropertiesDefinedInConstructors.ts @@ -12,4 +12,4 @@ verify.navigationBarContains("a", "property"); verify.navigationBarContains("b", "property"); // no other items -verify.navigationBarCount(4); \ No newline at end of file +verify.navigationBarCount(6); \ No newline at end of file diff --git a/tests/cases/fourslash/navigationBarItemsSymbols1.ts b/tests/cases/fourslash/navigationBarItemsSymbols1.ts index c9df85b3ece..6d55812fa0e 100644 --- a/tests/cases/fourslash/navigationBarItemsSymbols1.ts +++ b/tests/cases/fourslash/navigationBarItemsSymbols1.ts @@ -1,6 +1,6 @@ /// -////{| "itemName": "C", "kind": "class", "parentName": "" |} +////{| "itemName": "C", "kind": "class", "parentName": "" |} ////class C { //// {| "itemName": "[Symbol.isRegExp]", "kind": "property", "parentName": "C" |} //// [Symbol.isRegExp] = 0; @@ -14,4 +14,5 @@ test.markers().forEach(marker => { verify.navigationBarContains(marker.data.itemName, marker.data.kind, marker.fileName, marker.data.parentName); }); -verify.navigationBarCount(test.markers().length); \ No newline at end of file +// 2 lack markers: and its child +verify.navigationBarCount(2 + test.markers().length); \ No newline at end of file diff --git a/tests/cases/fourslash/server/navbar01.ts b/tests/cases/fourslash/server/navbar01.ts index e4e2b699be5..ead4cafe0c8 100644 --- a/tests/cases/fourslash/server/navbar01.ts +++ b/tests/cases/fourslash/server/navbar01.ts @@ -13,7 +13,7 @@ ////{| "itemName": "Shapes", "kind": "module", "parentName": "" |}module Shapes { //// //// // Class -//// {| "itemName": "Point", "kind": "class", "parentName": "" |}export class Point implements IPoint { +//// {| "itemName": "Point", "kind": "class", "parentName": "Shapes" |}export class Point implements IPoint { //// {| "itemName": "constructor", "kind": "constructor", "parentName": "Point" |}constructor (public x: number, public y: number) { } //// //// // Instance member @@ -49,4 +49,4 @@ test.markers().forEach((marker) => { } }); -verify.navigationBarCount(24); +verify.navigationBarCount(25); From 91b473389b042e0e6e38763fbfce0b775f9cbb57 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 25 May 2016 07:34:35 -0700 Subject: [PATCH 04/13] Include interfaces as childItems in navigation bar --- src/services/navigationBar.ts | 3 +++ .../navigationBarItemsInsideMethodsAndConstructors.ts | 6 +++--- tests/cases/fourslash/navigationBarItemsItems.ts | 4 ++-- .../navigationBarItemsMultilineStringIdentifiers.ts | 4 ++-- tests/cases/fourslash/navigationBarItemsSymbols2.ts | 5 +++-- tests/cases/fourslash/server/navbar01.ts | 4 ++-- 6 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index cb81c398cb8..2896031eb96 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -320,6 +320,9 @@ namespace ts.NavigationBar { case SyntaxKind.EnumMember: return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.memberVariableElement); + case SyntaxKind.InterfaceDeclaration: + return createItem(node, getTextOfNode((node).name), ts.ScriptElementKind.interfaceElement); + case SyntaxKind.CallSignature: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); diff --git a/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts b/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts index 89b05dc6b07..d6fb0a91eb2 100644 --- a/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts +++ b/tests/cases/fourslash/navigationBarItemsInsideMethodsAndConstructors.ts @@ -6,7 +6,7 @@ //// //// } //// -//// {| "itemName": "LocalInterfaceInConstrcutor", "kind": "interface", "parentName": ""|}interface LocalInterfaceInConstrcutor { +//// {| "itemName": "LocalInterfaceInConstrcutor", "kind": "interface", "parentName": "constructor"|}interface LocalInterfaceInConstrcutor { //// } //// //// {| "itemName": "LocalEnumInConstructor", "kind": "enum", "parentName": "constructor"|}enum LocalEnumInConstructor { @@ -21,7 +21,7 @@ //// } //// } //// -//// {| "itemName": "LocalInterfaceInMethod", "kind": "interface", "parentName": ""|}interface LocalInterfaceInMethod { +//// {| "itemName": "LocalInterfaceInMethod", "kind": "interface", "parentName": "method"|}interface LocalInterfaceInMethod { //// } //// //// {| "itemName": "LocalEnumInMethod", "kind": "enum", "parentName": "method"|}enum LocalEnumInMethod { @@ -39,4 +39,4 @@ test.markers().forEach((marker) => { }); // no other items -verify.navigationBarCount(19); +verify.navigationBarCount(21); diff --git a/tests/cases/fourslash/navigationBarItemsItems.ts b/tests/cases/fourslash/navigationBarItemsItems.ts index 5cae68b1194..d9ae3d35dff 100644 --- a/tests/cases/fourslash/navigationBarItemsItems.ts +++ b/tests/cases/fourslash/navigationBarItemsItems.ts @@ -1,7 +1,7 @@ /// ////// Interface -////{| "itemName": "IPoint", "kind": "interface", "parentName": "" |}interface IPoint { +////{| "itemName": "IPoint", "kind": "interface", "parentName": "" |}interface IPoint { //// {| "itemName": "getDist", "kind": "method", "parentName": "IPoint" |}getDist(): number; //// {| "itemName": "new()", "kind": "construct", "parentName": "IPoint" |}new(): IPoint; //// {| "itemName": "()", "kind": "call", "parentName": "IPoint" |}(): any; @@ -49,4 +49,4 @@ test.markers().forEach((marker) => { } }); -verify.navigationBarCount(24); +verify.navigationBarCount(25); diff --git a/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts b/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts index 8856c4c044a..f779c7a0580 100644 --- a/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts +++ b/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts @@ -10,7 +10,7 @@ ////{| "itemName": "\"MultilineMadness\"", "kind": "module" |} ////declare module "MultilineMadness" {} //// -////{| "itemName": "Foo", "kind": "interface" |} +////{| "itemName": "Foo", "kind": "interface", "parentName": "" |} ////interface Foo { //// {| "itemName": "\"a1\\\\\\r\\nb\"", "kind": "property", "parentName": "Foo" |} //// "a1\\\r\nb"; @@ -38,4 +38,4 @@ test.markers().forEach((marker) => { verify.navigationBarContains(marker.data.itemName, marker.data.kind, marker.fileName, marker.data.parentName); }); -verify.navigationBarCount(9); // interface w/ 2 properties, class w/ 2 properties, 3 modules \ No newline at end of file +verify.navigationBarCount(11); // interface w/ 2 properties, class w/ 2 properties, 3 modules \ No newline at end of file diff --git a/tests/cases/fourslash/navigationBarItemsSymbols2.ts b/tests/cases/fourslash/navigationBarItemsSymbols2.ts index 579a6353c13..5c398f77bbd 100644 --- a/tests/cases/fourslash/navigationBarItemsSymbols2.ts +++ b/tests/cases/fourslash/navigationBarItemsSymbols2.ts @@ -1,6 +1,6 @@ /// -////{| "itemName": "I", "kind": "interface", "parentName": "" |} +////{| "itemName": "I", "kind": "interface", "parentName": "" |} ////interface I { //// {| "itemName": "[Symbol.isRegExp]", "kind": "property", "parentName": "I" |} //// [Symbol.isRegExp]: string; @@ -12,4 +12,5 @@ test.markers().forEach(marker => { verify.navigationBarContains(marker.data.itemName, marker.data.kind, marker.fileName, marker.data.parentName); }); -verify.navigationBarCount(test.markers().length); \ No newline at end of file +// 2 are not marked: and its child. +verify.navigationBarCount(2 + test.markers().length); \ No newline at end of file diff --git a/tests/cases/fourslash/server/navbar01.ts b/tests/cases/fourslash/server/navbar01.ts index e4e2b699be5..05e92c2835f 100644 --- a/tests/cases/fourslash/server/navbar01.ts +++ b/tests/cases/fourslash/server/navbar01.ts @@ -1,7 +1,7 @@ /// ////// Interface -////{| "itemName": "IPoint", "kind": "interface", "parentName": "" |}interface IPoint { +////{| "itemName": "IPoint", "kind": "interface", "parentName": "" |}interface IPoint { //// {| "itemName": "getDist", "kind": "method", "parentName": "IPoint" |}getDist(): number; //// {| "itemName": "new()", "kind": "construct", "parentName": "IPoint" |}new(): IPoint; //// {| "itemName": "()", "kind": "call", "parentName": "IPoint" |}(): any; @@ -49,4 +49,4 @@ test.markers().forEach((marker) => { } }); -verify.navigationBarCount(24); +verify.navigationBarCount(25); From c707e80463fa1bf7f39493c17c7731d29e53ee02 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 25 May 2016 07:59:26 -0700 Subject: [PATCH 05/13] Show indent and childItems when debugging the navigation bar --- src/harness/fourslash.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 7f2972e8125..4fd3161d1dc 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -1096,14 +1096,6 @@ namespace FourSlash { } addSpanInfoString(); return resultString; - - function repeatString(count: number, char: string) { - let result = ""; - for (let i = 0; i < count; i++) { - result += char; - } - return result; - } } public getBreakpointStatementLocation(pos: number) { @@ -2055,7 +2047,7 @@ namespace FourSlash { for (let i = 0; i < length; i++) { const item = items[i]; - Harness.IO.log(`name: ${item.text}, kind: ${item.kind}`); + Harness.IO.log(`${repeatString(item.indent, " ")}name: ${item.text}, kind: ${item.kind}, childItems: ${item.childItems.map(child => child.text)}`); } } @@ -2742,6 +2734,14 @@ ${code} fileName: fileName }; } + + function repeatString(count: number, char: string) { + let result = ""; + for (let i = 0; i < count; i++) { + result += char; + } + return result; + } } namespace FourSlashInterface { From c4b517ce450b72ee3bfcbe67dd46740079f689fe Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Wed, 25 May 2016 09:42:59 -0700 Subject: [PATCH 06/13] run linter once after last worker is finished in case if there are no errors --- Jakefile.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jakefile.js b/Jakefile.js index 7cf6e67bb06..59d9b690210 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -741,7 +741,8 @@ function runConsoleTests(defaultReporter, defaultSubsets) { deleteTemporaryProjectOutput(); if (counter !== 0 || errorStatus === undefined) { - if (lintFlag) { + // run linter when last worker is finished + if (lintFlag && counter === 0) { var lint = jake.Task['lint']; lint.addListener('complete', function () { complete(); From 34e85600700d0cc61e2500c524e007cd86574c91 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Wed, 25 May 2016 10:11:54 -0700 Subject: [PATCH 07/13] Fix broken baselines --- src/compiler/checker.ts | 22 ++++++++++--------- ...nterfaceMergeConflictingMembers.errors.txt | 16 +++++++------- ...ssibilityModifiersOnParameters2.errors.txt | 19 +++++++++++----- ...constructorParameterProperties2.errors.txt | 16 +++++++------- ...duplicateIdentifierComputedName.errors.txt | 4 ++-- ...ateIdentifierDifferentModifiers.errors.txt | 16 +++++++------- .../reference/numericClassMembers1.errors.txt | 8 +++---- .../numericNamedPropertyDuplicates.errors.txt | 4 ++-- ...cStringNamedPropertyEquivalence.errors.txt | 4 ++-- ...ypeWithDuplicateNumericProperty.errors.txt | 12 +++++----- .../optionalPropertiesSyntax.errors.txt | 8 +++---- ...parameterPropertyInConstructor2.errors.txt | 5 ++++- .../stringNamedPropertyDuplicates.errors.txt | 8 +++---- .../reference/symbolProperty44.errors.txt | 5 +---- 14 files changed, 79 insertions(+), 68 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3e8066865ac..eb6fa4240a4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12972,18 +12972,20 @@ namespace ts { const names = static ? staticNames : instanceNames; const memberName = member.name && getPropertyNameForPropertyNameNode(member.name); - switch (member.kind) { - case SyntaxKind.GetAccessor: - addName(names, member.name, memberName, getter); - break; + if (memberName) { + switch (member.kind) { + case SyntaxKind.GetAccessor: + addName(names, member.name, memberName, getter); + break; - case SyntaxKind.SetAccessor: - addName(names, member.name, memberName, setter); - break; + case SyntaxKind.SetAccessor: + addName(names, member.name, memberName, setter); + break; - case SyntaxKind.PropertyDeclaration: - addName(names, member.name, memberName, property); - break; + case SyntaxKind.PropertyDeclaration: + addName(names, member.name, memberName, property); + break; + } } } } diff --git a/tests/baselines/reference/classAndInterfaceMergeConflictingMembers.errors.txt b/tests/baselines/reference/classAndInterfaceMergeConflictingMembers.errors.txt index a28471a3f91..8b3fa5bba55 100644 --- a/tests/baselines/reference/classAndInterfaceMergeConflictingMembers.errors.txt +++ b/tests/baselines/reference/classAndInterfaceMergeConflictingMembers.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/classes/classDeclarations/classAndInterfaceMergeConflictingMembers.ts(10,15): error TS2686: All declarations of 'x' must have identical modifiers. -tests/cases/conformance/classes/classDeclarations/classAndInterfaceMergeConflictingMembers.ts(14,5): error TS2686: All declarations of 'x' must have identical modifiers. -tests/cases/conformance/classes/classDeclarations/classAndInterfaceMergeConflictingMembers.ts(18,13): error TS2686: All declarations of 'x' must have identical modifiers. -tests/cases/conformance/classes/classDeclarations/classAndInterfaceMergeConflictingMembers.ts(22,5): error TS2686: All declarations of 'x' must have identical modifiers. +tests/cases/conformance/classes/classDeclarations/classAndInterfaceMergeConflictingMembers.ts(10,15): error TS2687: All declarations of 'x' must have identical modifiers. +tests/cases/conformance/classes/classDeclarations/classAndInterfaceMergeConflictingMembers.ts(14,5): error TS2687: All declarations of 'x' must have identical modifiers. +tests/cases/conformance/classes/classDeclarations/classAndInterfaceMergeConflictingMembers.ts(18,13): error TS2687: All declarations of 'x' must have identical modifiers. +tests/cases/conformance/classes/classDeclarations/classAndInterfaceMergeConflictingMembers.ts(22,5): error TS2687: All declarations of 'x' must have identical modifiers. ==== tests/cases/conformance/classes/classDeclarations/classAndInterfaceMergeConflictingMembers.ts (4 errors) ==== @@ -16,23 +16,23 @@ tests/cases/conformance/classes/classDeclarations/classAndInterfaceMergeConflict declare class C2 { protected x : number; ~ -!!! error TS2686: All declarations of 'x' must have identical modifiers. +!!! error TS2687: All declarations of 'x' must have identical modifiers. } interface C2 { x : number; ~ -!!! error TS2686: All declarations of 'x' must have identical modifiers. +!!! error TS2687: All declarations of 'x' must have identical modifiers. } declare class C3 { private x : number; ~ -!!! error TS2686: All declarations of 'x' must have identical modifiers. +!!! error TS2687: All declarations of 'x' must have identical modifiers. } interface C3 { x : number; ~ -!!! error TS2686: All declarations of 'x' must have identical modifiers. +!!! error TS2687: All declarations of 'x' must have identical modifiers. } \ No newline at end of file diff --git a/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters2.errors.txt b/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters2.errors.txt index 1bc487189d3..78ef601af23 100644 --- a/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters2.errors.txt +++ b/tests/baselines/reference/constructSignatureWithAccessibilityModifiersOnParameters2.errors.txt @@ -1,8 +1,11 @@ tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(4,17): error TS2369: A parameter property is only allowed in a constructor implementation. tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(4,27): error TS2369: A parameter property is only allowed in a constructor implementation. +tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(5,24): error TS2300: Duplicate identifier 'x'. +tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(5,35): error TS2300: Duplicate identifier 'y'. tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(9,17): error TS2369: A parameter property is only allowed in a constructor implementation. -tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(9,25): error TS2686: All declarations of 'x' must have identical modifiers. -tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(10,24): error TS2686: All declarations of 'x' must have identical modifiers. +tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(9,25): error TS2687: All declarations of 'x' must have identical modifiers. +tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(10,24): error TS2300: Duplicate identifier 'x'. +tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(10,24): error TS2687: All declarations of 'x' must have identical modifiers. tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(14,17): error TS2369: A parameter property is only allowed in a constructor implementation. tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(19,10): error TS2369: A parameter property is only allowed in a constructor implementation. tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(20,10): error TS2369: A parameter property is only allowed in a constructor implementation. @@ -14,7 +17,7 @@ tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatur tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts(35,10): error TS2369: A parameter property is only allowed in a constructor implementation. -==== tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts (14 errors) ==== +==== tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatureWithAccessibilityModifiersOnParameters2.ts (17 errors) ==== // Parameter properties are not valid in overloads of constructors class C { @@ -24,6 +27,10 @@ tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatur ~~~~~~~~~ !!! error TS2369: A parameter property is only allowed in a constructor implementation. constructor(public x, private y) { } + ~ +!!! error TS2300: Duplicate identifier 'x'. + ~ +!!! error TS2300: Duplicate identifier 'y'. } class C2 { @@ -31,10 +38,12 @@ tests/cases/conformance/types/objectTypeLiteral/callSignatures/constructSignatur ~~~~~~~~~ !!! error TS2369: A parameter property is only allowed in a constructor implementation. ~ -!!! error TS2686: All declarations of 'x' must have identical modifiers. +!!! error TS2687: All declarations of 'x' must have identical modifiers. constructor(public x) { } ~ -!!! error TS2686: All declarations of 'x' must have identical modifiers. +!!! error TS2300: Duplicate identifier 'x'. + ~ +!!! error TS2687: All declarations of 'x' must have identical modifiers. } class C3 { diff --git a/tests/baselines/reference/constructorParameterProperties2.errors.txt b/tests/baselines/reference/constructorParameterProperties2.errors.txt index 409660c3133..7058b39bcca 100644 --- a/tests/baselines/reference/constructorParameterProperties2.errors.txt +++ b/tests/baselines/reference/constructorParameterProperties2.errors.txt @@ -1,10 +1,10 @@ tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(11,24): error TS2300: Duplicate identifier 'y'. -tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(18,5): error TS2686: All declarations of 'y' must have identical modifiers. +tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(18,5): error TS2687: All declarations of 'y' must have identical modifiers. tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(19,25): error TS2300: Duplicate identifier 'y'. -tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(19,25): error TS2686: All declarations of 'y' must have identical modifiers. -tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(26,5): error TS2686: All declarations of 'y' must have identical modifiers. +tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(19,25): error TS2687: All declarations of 'y' must have identical modifiers. +tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(26,5): error TS2687: All declarations of 'y' must have identical modifiers. tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(27,27): error TS2300: Duplicate identifier 'y'. -tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(27,27): error TS2686: All declarations of 'y' must have identical modifiers. +tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts(27,27): error TS2687: All declarations of 'y' must have identical modifiers. ==== tests/cases/conformance/classes/constructorDeclarations/constructorParameters/constructorParameterProperties2.ts (7 errors) ==== @@ -29,12 +29,12 @@ tests/cases/conformance/classes/constructorDeclarations/constructorParameters/co class E { y: number; ~ -!!! error TS2686: All declarations of 'y' must have identical modifiers. +!!! error TS2687: All declarations of 'y' must have identical modifiers. constructor(private y: number) { } // error ~ !!! error TS2300: Duplicate identifier 'y'. ~ -!!! error TS2686: All declarations of 'y' must have identical modifiers. +!!! error TS2687: All declarations of 'y' must have identical modifiers. } var e: E; @@ -43,12 +43,12 @@ tests/cases/conformance/classes/constructorDeclarations/constructorParameters/co class F { y: number; ~ -!!! error TS2686: All declarations of 'y' must have identical modifiers. +!!! error TS2687: All declarations of 'y' must have identical modifiers. constructor(protected y: number) { } // error ~ !!! error TS2300: Duplicate identifier 'y'. ~ -!!! error TS2686: All declarations of 'y' must have identical modifiers. +!!! error TS2687: All declarations of 'y' must have identical modifiers. } var f: F; diff --git a/tests/baselines/reference/duplicateIdentifierComputedName.errors.txt b/tests/baselines/reference/duplicateIdentifierComputedName.errors.txt index faef1106c41..12d70ca5458 100644 --- a/tests/baselines/reference/duplicateIdentifierComputedName.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierComputedName.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/duplicateIdentifierComputedName.ts(3,5): error TS2300: Duplicate identifier 'a'. +tests/cases/compiler/duplicateIdentifierComputedName.ts(3,5): error TS2300: Duplicate identifier '["a"]'. ==== tests/cases/compiler/duplicateIdentifierComputedName.ts (1 errors) ==== @@ -6,6 +6,6 @@ tests/cases/compiler/duplicateIdentifierComputedName.ts(3,5): error TS2300: Dupl ["a"]: string; ["a"]: string; ~~~~~ -!!! error TS2300: Duplicate identifier 'a'. +!!! error TS2300: Duplicate identifier '["a"]'. } \ No newline at end of file diff --git a/tests/baselines/reference/duplicateIdentifierDifferentModifiers.errors.txt b/tests/baselines/reference/duplicateIdentifierDifferentModifiers.errors.txt index c25609bfa42..efb10e3d399 100644 --- a/tests/baselines/reference/duplicateIdentifierDifferentModifiers.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierDifferentModifiers.errors.txt @@ -1,17 +1,17 @@ -tests/cases/compiler/duplicateIdentifierDifferentModifiers.ts(2,15): error TS2686: All declarations of 'x' must have identical modifiers. -tests/cases/compiler/duplicateIdentifierDifferentModifiers.ts(3,15): error TS2686: All declarations of 'x' must have identical modifiers. -tests/cases/compiler/duplicateIdentifierDifferentModifiers.ts(16,11): error TS2686: All declarations of 'y' must have identical modifiers. -tests/cases/compiler/duplicateIdentifierDifferentModifiers.ts(20,3): error TS2686: All declarations of 'y' must have identical modifiers. +tests/cases/compiler/duplicateIdentifierDifferentModifiers.ts(2,15): error TS2687: All declarations of 'x' must have identical modifiers. +tests/cases/compiler/duplicateIdentifierDifferentModifiers.ts(3,15): error TS2687: All declarations of 'x' must have identical modifiers. +tests/cases/compiler/duplicateIdentifierDifferentModifiers.ts(16,11): error TS2687: All declarations of 'y' must have identical modifiers. +tests/cases/compiler/duplicateIdentifierDifferentModifiers.ts(20,3): error TS2687: All declarations of 'y' must have identical modifiers. ==== tests/cases/compiler/duplicateIdentifierDifferentModifiers.ts (4 errors) ==== // Not OK interface B { x; } ~ -!!! error TS2686: All declarations of 'x' must have identical modifiers. +!!! error TS2687: All declarations of 'x' must have identical modifiers. interface B { x?; } ~ -!!! error TS2686: All declarations of 'x' must have identical modifiers. +!!! error TS2687: All declarations of 'x' must have identical modifiers. // OK class A { @@ -26,12 +26,12 @@ tests/cases/compiler/duplicateIdentifierDifferentModifiers.ts(20,3): error TS268 class C { private y: string; ~ -!!! error TS2686: All declarations of 'y' must have identical modifiers. +!!! error TS2687: All declarations of 'y' must have identical modifiers. } interface C { y: string; ~ -!!! error TS2686: All declarations of 'y' must have identical modifiers. +!!! error TS2687: All declarations of 'y' must have identical modifiers. } \ No newline at end of file diff --git a/tests/baselines/reference/numericClassMembers1.errors.txt b/tests/baselines/reference/numericClassMembers1.errors.txt index 7c99932e937..28c06a6fcf5 100644 --- a/tests/baselines/reference/numericClassMembers1.errors.txt +++ b/tests/baselines/reference/numericClassMembers1.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/numericClassMembers1.ts(3,3): error TS2300: Duplicate identifier '0'. -tests/cases/compiler/numericClassMembers1.ts(8,2): error TS2300: Duplicate identifier '0'. +tests/cases/compiler/numericClassMembers1.ts(3,3): error TS2300: Duplicate identifier '0.0'. +tests/cases/compiler/numericClassMembers1.ts(8,2): error TS2300: Duplicate identifier ''0''. ==== tests/cases/compiler/numericClassMembers1.ts (2 errors) ==== @@ -7,14 +7,14 @@ tests/cases/compiler/numericClassMembers1.ts(8,2): error TS2300: Duplicate ident 0 = 1; 0.0 = 2; ~~~ -!!! error TS2300: Duplicate identifier '0'. +!!! error TS2300: Duplicate identifier '0.0'. } class C235 { 0.0 = 1; '0' = 2; ~~~ -!!! error TS2300: Duplicate identifier '0'. +!!! error TS2300: Duplicate identifier ''0''. } class C236 { diff --git a/tests/baselines/reference/numericNamedPropertyDuplicates.errors.txt b/tests/baselines/reference/numericNamedPropertyDuplicates.errors.txt index 24801f2847a..5fb05297f11 100644 --- a/tests/baselines/reference/numericNamedPropertyDuplicates.errors.txt +++ b/tests/baselines/reference/numericNamedPropertyDuplicates.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericNamedPropertyDuplicates.ts(3,5): error TS2300: Duplicate identifier '1'. +tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericNamedPropertyDuplicates.ts(3,5): error TS2300: Duplicate identifier '1.0'. tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericNamedPropertyDuplicates.ts(5,12): error TS2300: Duplicate identifier '2'. tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericNamedPropertyDuplicates.ts(9,5): error TS2300: Duplicate identifier '2'. tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericNamedPropertyDuplicates.ts(10,5): error TS2300: Duplicate identifier '2'. @@ -12,7 +12,7 @@ tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericNamedP 1: number; 1.0: number; ~~~ -!!! error TS2300: Duplicate identifier '1'. +!!! error TS2300: Duplicate identifier '1.0'. static 2: number; static 2: number; ~ diff --git a/tests/baselines/reference/numericStringNamedPropertyEquivalence.errors.txt b/tests/baselines/reference/numericStringNamedPropertyEquivalence.errors.txt index 359a45ded51..102a6a07836 100644 --- a/tests/baselines/reference/numericStringNamedPropertyEquivalence.errors.txt +++ b/tests/baselines/reference/numericStringNamedPropertyEquivalence.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericStringNamedPropertyEquivalence.ts(6,5): error TS2300: Duplicate identifier '1'. +tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericStringNamedPropertyEquivalence.ts(6,5): error TS2300: Duplicate identifier '1.0'. tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericStringNamedPropertyEquivalence.ts(10,5): error TS2300: Duplicate identifier '1'. tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericStringNamedPropertyEquivalence.ts(12,5): error TS2300: Duplicate identifier '1'. tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericStringNamedPropertyEquivalence.ts(16,5): error TS2300: Duplicate identifier '1'. @@ -15,7 +15,7 @@ tests/cases/conformance/types/objectTypeLiteral/propertySignatures/numericString "1.0": number; // not a duplicate 1.0: number; ~~~ -!!! error TS2300: Duplicate identifier '1'. +!!! error TS2300: Duplicate identifier '1.0'. } interface I { diff --git a/tests/baselines/reference/objectTypeWithDuplicateNumericProperty.errors.txt b/tests/baselines/reference/objectTypeWithDuplicateNumericProperty.errors.txt index 0565bf884e0..80931650d0a 100644 --- a/tests/baselines/reference/objectTypeWithDuplicateNumericProperty.errors.txt +++ b/tests/baselines/reference/objectTypeWithDuplicateNumericProperty.errors.txt @@ -1,6 +1,6 @@ -tests/cases/conformance/types/members/objectTypeWithDuplicateNumericProperty.ts(6,5): error TS2300: Duplicate identifier '1'. -tests/cases/conformance/types/members/objectTypeWithDuplicateNumericProperty.ts(7,5): error TS2300: Duplicate identifier '1'. -tests/cases/conformance/types/members/objectTypeWithDuplicateNumericProperty.ts(8,5): error TS2300: Duplicate identifier '1'. +tests/cases/conformance/types/members/objectTypeWithDuplicateNumericProperty.ts(6,5): error TS2300: Duplicate identifier '1.0'. +tests/cases/conformance/types/members/objectTypeWithDuplicateNumericProperty.ts(7,5): error TS2300: Duplicate identifier '1.'. +tests/cases/conformance/types/members/objectTypeWithDuplicateNumericProperty.ts(8,5): error TS2300: Duplicate identifier '1.00'. tests/cases/conformance/types/members/objectTypeWithDuplicateNumericProperty.ts(12,5): error TS2300: Duplicate identifier '1'. tests/cases/conformance/types/members/objectTypeWithDuplicateNumericProperty.ts(13,5): error TS2300: Duplicate identifier '1'. tests/cases/conformance/types/members/objectTypeWithDuplicateNumericProperty.ts(14,5): error TS2300: Duplicate identifier '1'. @@ -22,13 +22,13 @@ tests/cases/conformance/types/members/objectTypeWithDuplicateNumericProperty.ts( 1; 1.0; ~~~ -!!! error TS2300: Duplicate identifier '1'. +!!! error TS2300: Duplicate identifier '1.0'. 1.; ~~ -!!! error TS2300: Duplicate identifier '1'. +!!! error TS2300: Duplicate identifier '1.'. 1.00; ~~~~ -!!! error TS2300: Duplicate identifier '1'. +!!! error TS2300: Duplicate identifier '1.00'. } interface I { diff --git a/tests/baselines/reference/optionalPropertiesSyntax.errors.txt b/tests/baselines/reference/optionalPropertiesSyntax.errors.txt index 51e49e048d5..e7cc8742127 100644 --- a/tests/baselines/reference/optionalPropertiesSyntax.errors.txt +++ b/tests/baselines/reference/optionalPropertiesSyntax.errors.txt @@ -5,9 +5,9 @@ tests/cases/compiler/optionalPropertiesSyntax.ts(12,5): error TS1131: Property o tests/cases/compiler/optionalPropertiesSyntax.ts(18,11): error TS1005: ';' expected. tests/cases/compiler/optionalPropertiesSyntax.ts(18,12): error TS1131: Property or signature expected. tests/cases/compiler/optionalPropertiesSyntax.ts(24,5): error TS2300: Duplicate identifier 'prop'. -tests/cases/compiler/optionalPropertiesSyntax.ts(24,5): error TS2686: All declarations of 'prop' must have identical modifiers. +tests/cases/compiler/optionalPropertiesSyntax.ts(24,5): error TS2687: All declarations of 'prop' must have identical modifiers. tests/cases/compiler/optionalPropertiesSyntax.ts(25,5): error TS2300: Duplicate identifier 'prop'. -tests/cases/compiler/optionalPropertiesSyntax.ts(25,5): error TS2686: All declarations of 'prop' must have identical modifiers. +tests/cases/compiler/optionalPropertiesSyntax.ts(25,5): error TS2687: All declarations of 'prop' must have identical modifiers. tests/cases/compiler/optionalPropertiesSyntax.ts(32,5): error TS2375: Duplicate number index signature. tests/cases/compiler/optionalPropertiesSyntax.ts(32,18): error TS1005: ';' expected. tests/cases/compiler/optionalPropertiesSyntax.ts(32,19): error TS1131: Property or signature expected. @@ -56,12 +56,12 @@ tests/cases/compiler/optionalPropertiesSyntax.ts(34,5): error TS2375: Duplicate ~~~~ !!! error TS2300: Duplicate identifier 'prop'. ~~~~ -!!! error TS2686: All declarations of 'prop' must have identical modifiers. +!!! error TS2687: All declarations of 'prop' must have identical modifiers. prop?: any; ~~~~ !!! error TS2300: Duplicate identifier 'prop'. ~~~~ -!!! error TS2686: All declarations of 'prop' must have identical modifiers. +!!! error TS2687: All declarations of 'prop' must have identical modifiers. prop2?: any; } diff --git a/tests/baselines/reference/parameterPropertyInConstructor2.errors.txt b/tests/baselines/reference/parameterPropertyInConstructor2.errors.txt index a99db2a39ad..d1a0513c1f6 100644 --- a/tests/baselines/reference/parameterPropertyInConstructor2.errors.txt +++ b/tests/baselines/reference/parameterPropertyInConstructor2.errors.txt @@ -1,8 +1,9 @@ tests/cases/compiler/parameterPropertyInConstructor2.ts(3,5): error TS2394: Overload signature is not compatible with function implementation. tests/cases/compiler/parameterPropertyInConstructor2.ts(3,17): error TS2369: A parameter property is only allowed in a constructor implementation. +tests/cases/compiler/parameterPropertyInConstructor2.ts(4,24): error TS2300: Duplicate identifier 'names'. -==== tests/cases/compiler/parameterPropertyInConstructor2.ts (2 errors) ==== +==== tests/cases/compiler/parameterPropertyInConstructor2.ts (3 errors) ==== module mod { class Customers { constructor(public names: string); @@ -11,6 +12,8 @@ tests/cases/compiler/parameterPropertyInConstructor2.ts(3,17): error TS2369: A p ~~~~~~~~~~~~~~~~~~~~ !!! error TS2369: A parameter property is only allowed in a constructor implementation. constructor(public names: string, public ages: number) { + ~~~~~ +!!! error TS2300: Duplicate identifier 'names'. } } } diff --git a/tests/baselines/reference/stringNamedPropertyDuplicates.errors.txt b/tests/baselines/reference/stringNamedPropertyDuplicates.errors.txt index f6ae46d9b28..5bd8a2771ba 100644 --- a/tests/baselines/reference/stringNamedPropertyDuplicates.errors.txt +++ b/tests/baselines/reference/stringNamedPropertyDuplicates.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/objectTypeLiteral/propertySignatures/stringNamedPropertyDuplicates.ts(3,5): error TS2300: Duplicate identifier 'a b'. -tests/cases/conformance/types/objectTypeLiteral/propertySignatures/stringNamedPropertyDuplicates.ts(5,12): error TS2300: Duplicate identifier 'c d'. +tests/cases/conformance/types/objectTypeLiteral/propertySignatures/stringNamedPropertyDuplicates.ts(3,5): error TS2300: Duplicate identifier '"a b"'. +tests/cases/conformance/types/objectTypeLiteral/propertySignatures/stringNamedPropertyDuplicates.ts(5,12): error TS2300: Duplicate identifier '"c d"'. tests/cases/conformance/types/objectTypeLiteral/propertySignatures/stringNamedPropertyDuplicates.ts(9,5): error TS2300: Duplicate identifier 'a b'. tests/cases/conformance/types/objectTypeLiteral/propertySignatures/stringNamedPropertyDuplicates.ts(10,5): error TS2300: Duplicate identifier 'a b'. tests/cases/conformance/types/objectTypeLiteral/propertySignatures/stringNamedPropertyDuplicates.ts(14,5): error TS2300: Duplicate identifier 'a b'. @@ -12,11 +12,11 @@ tests/cases/conformance/types/objectTypeLiteral/propertySignatures/stringNamedPr "a b": number; "a b": number; ~~~~~ -!!! error TS2300: Duplicate identifier 'a b'. +!!! error TS2300: Duplicate identifier '"a b"'. static "c d": number; static "c d": number; ~~~~~ -!!! error TS2300: Duplicate identifier 'c d'. +!!! error TS2300: Duplicate identifier '"c d"'. } interface I { diff --git a/tests/baselines/reference/symbolProperty44.errors.txt b/tests/baselines/reference/symbolProperty44.errors.txt index 984a20e9974..2cef480e736 100644 --- a/tests/baselines/reference/symbolProperty44.errors.txt +++ b/tests/baselines/reference/symbolProperty44.errors.txt @@ -1,9 +1,8 @@ tests/cases/conformance/es6/Symbols/symbolProperty44.ts(2,9): error TS2300: Duplicate identifier '[Symbol.hasInstance]'. tests/cases/conformance/es6/Symbols/symbolProperty44.ts(5,9): error TS2300: Duplicate identifier '[Symbol.hasInstance]'. -tests/cases/conformance/es6/Symbols/symbolProperty44.ts(5,9): error TS2300: Duplicate identifier '__@hasInstance'. -==== tests/cases/conformance/es6/Symbols/symbolProperty44.ts (3 errors) ==== +==== tests/cases/conformance/es6/Symbols/symbolProperty44.ts (2 errors) ==== class C { get [Symbol.hasInstance]() { ~~~~~~~~~~~~~~~~~~~~ @@ -13,8 +12,6 @@ tests/cases/conformance/es6/Symbols/symbolProperty44.ts(5,9): error TS2300: Dupl get [Symbol.hasInstance]() { ~~~~~~~~~~~~~~~~~~~~ !!! error TS2300: Duplicate identifier '[Symbol.hasInstance]'. - ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2300: Duplicate identifier '__@hasInstance'. return ""; } } \ No newline at end of file From a431a0b60bc8b55c674524da76e58253329d8c2f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 25 May 2016 11:16:33 -0700 Subject: [PATCH 08/13] Improve intersection type inference --- src/compiler/checker.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index eb6fa4240a4..5a7c6fa29e5 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7158,11 +7158,10 @@ namespace ts { inferFromTypes(source, t); } } - // Next, if target is a union type containing a single naked type parameter, make a - // secondary inference to that type parameter. We don't do this for intersection types - // because in a target type like Foo & T we don't know how which parts of the source type - // should be matched by Foo and which should be inferred to T. - if (target.flags & TypeFlags.Union && typeParameterCount === 1) { + // Next, if target containings a single naked type parameter, make a secondary inference to that type + // parameter. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). + if (typeParameterCount === 1) { inferiority++; inferFromTypes(source, typeParameter); inferiority--; From 6a27289b2ddc177589b4e44697a97126ca4e023b Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 25 May 2016 11:17:03 -0700 Subject: [PATCH 09/13] Add test --- .../reference/intersectionTypeInference1.js | 17 ++++++++ .../intersectionTypeInference1.symbols | 33 +++++++++++++++ .../intersectionTypeInference1.types | 41 +++++++++++++++++++ .../compiler/intersectionTypeInference1.ts | 7 ++++ 4 files changed, 98 insertions(+) create mode 100644 tests/baselines/reference/intersectionTypeInference1.js create mode 100644 tests/baselines/reference/intersectionTypeInference1.symbols create mode 100644 tests/baselines/reference/intersectionTypeInference1.types create mode 100644 tests/cases/compiler/intersectionTypeInference1.ts diff --git a/tests/baselines/reference/intersectionTypeInference1.js b/tests/baselines/reference/intersectionTypeInference1.js new file mode 100644 index 00000000000..f4ad4da608b --- /dev/null +++ b/tests/baselines/reference/intersectionTypeInference1.js @@ -0,0 +1,17 @@ +//// [intersectionTypeInference1.ts] +// Repro from #8801 + +function alert(s: string) {} + +const parameterFn = (props:{store:string}) => alert(props.store) +const brokenFunction = (f: (p: {dispatch: number} & OwnProps) => void) => (o: OwnProps) => o +export const Form3 = brokenFunction(parameterFn)({store: "hello"}) + + +//// [intersectionTypeInference1.js] +// Repro from #8801 +"use strict"; +function alert(s) { } +var parameterFn = function (props) { return alert(props.store); }; +var brokenFunction = function (f) { return function (o) { return o; }; }; +exports.Form3 = brokenFunction(parameterFn)({ store: "hello" }); diff --git a/tests/baselines/reference/intersectionTypeInference1.symbols b/tests/baselines/reference/intersectionTypeInference1.symbols new file mode 100644 index 00000000000..f45d4fbd5b8 --- /dev/null +++ b/tests/baselines/reference/intersectionTypeInference1.symbols @@ -0,0 +1,33 @@ +=== tests/cases/compiler/intersectionTypeInference1.ts === +// Repro from #8801 + +function alert(s: string) {} +>alert : Symbol(alert, Decl(intersectionTypeInference1.ts, 0, 0)) +>s : Symbol(s, Decl(intersectionTypeInference1.ts, 2, 15)) + +const parameterFn = (props:{store:string}) => alert(props.store) +>parameterFn : Symbol(parameterFn, Decl(intersectionTypeInference1.ts, 4, 5)) +>props : Symbol(props, Decl(intersectionTypeInference1.ts, 4, 21)) +>store : Symbol(store, Decl(intersectionTypeInference1.ts, 4, 28)) +>alert : Symbol(alert, Decl(intersectionTypeInference1.ts, 0, 0)) +>props.store : Symbol(store, Decl(intersectionTypeInference1.ts, 4, 28)) +>props : Symbol(props, Decl(intersectionTypeInference1.ts, 4, 21)) +>store : Symbol(store, Decl(intersectionTypeInference1.ts, 4, 28)) + +const brokenFunction = (f: (p: {dispatch: number} & OwnProps) => void) => (o: OwnProps) => o +>brokenFunction : Symbol(brokenFunction, Decl(intersectionTypeInference1.ts, 5, 5)) +>OwnProps : Symbol(OwnProps, Decl(intersectionTypeInference1.ts, 5, 24)) +>f : Symbol(f, Decl(intersectionTypeInference1.ts, 5, 34)) +>p : Symbol(p, Decl(intersectionTypeInference1.ts, 5, 38)) +>dispatch : Symbol(dispatch, Decl(intersectionTypeInference1.ts, 5, 42)) +>OwnProps : Symbol(OwnProps, Decl(intersectionTypeInference1.ts, 5, 24)) +>o : Symbol(o, Decl(intersectionTypeInference1.ts, 5, 85)) +>OwnProps : Symbol(OwnProps, Decl(intersectionTypeInference1.ts, 5, 24)) +>o : Symbol(o, Decl(intersectionTypeInference1.ts, 5, 85)) + +export const Form3 = brokenFunction(parameterFn)({store: "hello"}) +>Form3 : Symbol(Form3, Decl(intersectionTypeInference1.ts, 6, 12)) +>brokenFunction : Symbol(brokenFunction, Decl(intersectionTypeInference1.ts, 5, 5)) +>parameterFn : Symbol(parameterFn, Decl(intersectionTypeInference1.ts, 4, 5)) +>store : Symbol(store, Decl(intersectionTypeInference1.ts, 6, 50)) + diff --git a/tests/baselines/reference/intersectionTypeInference1.types b/tests/baselines/reference/intersectionTypeInference1.types new file mode 100644 index 00000000000..b74b2d2a453 --- /dev/null +++ b/tests/baselines/reference/intersectionTypeInference1.types @@ -0,0 +1,41 @@ +=== tests/cases/compiler/intersectionTypeInference1.ts === +// Repro from #8801 + +function alert(s: string) {} +>alert : (s: string) => void +>s : string + +const parameterFn = (props:{store:string}) => alert(props.store) +>parameterFn : (props: { store: string; }) => void +>(props:{store:string}) => alert(props.store) : (props: { store: string; }) => void +>props : { store: string; } +>store : string +>alert(props.store) : void +>alert : (s: string) => void +>props.store : string +>props : { store: string; } +>store : string + +const brokenFunction = (f: (p: {dispatch: number} & OwnProps) => void) => (o: OwnProps) => o +>brokenFunction : (f: (p: { dispatch: number; } & OwnProps) => void) => (o: OwnProps) => OwnProps +>(f: (p: {dispatch: number} & OwnProps) => void) => (o: OwnProps) => o : (f: (p: { dispatch: number; } & OwnProps) => void) => (o: OwnProps) => OwnProps +>OwnProps : OwnProps +>f : (p: { dispatch: number; } & OwnProps) => void +>p : { dispatch: number; } & OwnProps +>dispatch : number +>OwnProps : OwnProps +>(o: OwnProps) => o : (o: OwnProps) => OwnProps +>o : OwnProps +>OwnProps : OwnProps +>o : OwnProps + +export const Form3 = brokenFunction(parameterFn)({store: "hello"}) +>Form3 : { store: string; } +>brokenFunction(parameterFn)({store: "hello"}) : { store: string; } +>brokenFunction(parameterFn) : (o: { store: string; }) => { store: string; } +>brokenFunction : (f: (p: { dispatch: number; } & OwnProps) => void) => (o: OwnProps) => OwnProps +>parameterFn : (props: { store: string; }) => void +>{store: "hello"} : { store: string; } +>store : string +>"hello" : string + diff --git a/tests/cases/compiler/intersectionTypeInference1.ts b/tests/cases/compiler/intersectionTypeInference1.ts new file mode 100644 index 00000000000..c4d46800f0c --- /dev/null +++ b/tests/cases/compiler/intersectionTypeInference1.ts @@ -0,0 +1,7 @@ +// Repro from #8801 + +function alert(s: string) {} + +const parameterFn = (props:{store:string}) => alert(props.store) +const brokenFunction = (f: (p: {dispatch: number} & OwnProps) => void) => (o: OwnProps) => o +export const Form3 = brokenFunction(parameterFn)({store: "hello"}) From f7ff3eb562611f2fc5791a95ace04c107962cc84 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 25 May 2016 11:42:48 -0700 Subject: [PATCH 10/13] Remove uses of `null` in services --- src/services/formatting/ruleOperation.ts | 14 ++------------ src/services/formatting/rulesMap.ts | 5 ++--- src/services/formatting/rulesProvider.ts | 4 +--- 3 files changed, 5 insertions(+), 18 deletions(-) diff --git a/src/services/formatting/ruleOperation.ts b/src/services/formatting/ruleOperation.ts index 9c35b80bcfe..8ad83b11653 100644 --- a/src/services/formatting/ruleOperation.ts +++ b/src/services/formatting/ruleOperation.ts @@ -1,16 +1,9 @@ /// -/* tslint:disable:no-null-keyword */ /* @internal */ namespace ts.formatting { export class RuleOperation { - public Context: RuleOperationContext; - public Action: RuleAction; - - constructor() { - this.Context = null; - this.Action = null; - } + constructor(public Context: RuleOperationContext, public Action: RuleAction) {} public toString(): string { return "[context=" + this.Context + "," + @@ -22,10 +15,7 @@ namespace ts.formatting { } static create2(context: RuleOperationContext, action: RuleAction) { - const result = new RuleOperation(); - result.Context = context; - result.Action = action; - return result; + return new RuleOperation(context, action); } } } \ No newline at end of file diff --git a/src/services/formatting/rulesMap.ts b/src/services/formatting/rulesMap.ts index 74a1a33b7de..7f635ea07e3 100644 --- a/src/services/formatting/rulesMap.ts +++ b/src/services/formatting/rulesMap.ts @@ -1,5 +1,4 @@ /// -/* tslint:disable:no-null-keyword */ /* @internal */ namespace ts.formatting { @@ -62,14 +61,14 @@ namespace ts.formatting { public GetRule(context: FormattingContext): Rule { const bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); const bucket = this.map[bucketIndex]; - if (bucket != null) { + if (bucket) { for (const rule of bucket.Rules()) { if (rule.Operation.Context.InContext(context)) { return rule; } } } - return null; + return undefined; } } diff --git a/src/services/formatting/rulesProvider.ts b/src/services/formatting/rulesProvider.ts index 19581173f2d..d672a401d89 100644 --- a/src/services/formatting/rulesProvider.ts +++ b/src/services/formatting/rulesProvider.ts @@ -1,5 +1,4 @@ /// -/* tslint:disable:no-null-keyword */ /* @internal */ namespace ts.formatting { @@ -26,8 +25,7 @@ namespace ts.formatting { } public ensureUpToDate(options: ts.FormatCodeOptions) { - // TODO: Should this be '==='? - if (this.options == null || !ts.compareDataObjects(this.options, options)) { + if (!this.options || !ts.compareDataObjects(this.options, options)) { const activeRules = this.createActiveRules(options); const rulesMap = RulesMap.create(activeRules); From 58c8d345bc56b53a63f6b5f516484153fbbac5fe Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 25 May 2016 12:17:57 -0700 Subject: [PATCH 11/13] Update LKG --- lib/lib.d.ts | 24 +- lib/lib.es5.d.ts | 24 +- lib/lib.es6.d.ts | 24 +- lib/tsc.js | 365 ++++++++++++++++------- lib/tsserver.js | 431 ++++++++++++++++++--------- lib/tsserverlibrary.d.ts | 48 +++- lib/tsserverlibrary.js | 431 ++++++++++++++++++--------- lib/typescript.d.ts | 40 ++- lib/typescript.js | 560 ++++++++++++++++++++++++------------ lib/typescriptServices.d.ts | 40 ++- lib/typescriptServices.js | 560 ++++++++++++++++++++++++------------ 11 files changed, 1726 insertions(+), 821 deletions(-) diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 6bded7a1135..15745c5d533 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -965,38 +965,22 @@ interface JSON { * If a member contains nested objects, the nested objects are transformed before the parent object is. */ parse(text: string, reviver?: (key: any, value: any) => any): any; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - */ - stringify(value: any): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer A function that transforms the results. - */ - stringify(value: any, replacer: (key: string, value: any) => any): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer Array that transforms the results. - */ - stringify(value: any, replacer: any[]): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. * @param replacer A function that transforms the results. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */ - stringify(value: any, replacer: (key: string, value: any) => any, space: string | number): string; + stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer Array that transforms the results. + * @param replacer An array of strings and numbers that acts as a white list for selecting the object properties that will be stringified. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */ - stringify(value: any, replacer: any[], space: string | number): string; + stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; } + /** * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. */ diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 3a0f73f3cc7..e4e0334e0cb 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -965,38 +965,22 @@ interface JSON { * If a member contains nested objects, the nested objects are transformed before the parent object is. */ parse(text: string, reviver?: (key: any, value: any) => any): any; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - */ - stringify(value: any): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer A function that transforms the results. - */ - stringify(value: any, replacer: (key: string, value: any) => any): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer Array that transforms the results. - */ - stringify(value: any, replacer: any[]): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. * @param replacer A function that transforms the results. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */ - stringify(value: any, replacer: (key: string, value: any) => any, space: string | number): string; + stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer Array that transforms the results. + * @param replacer An array of strings and numbers that acts as a white list for selecting the object properties that will be stringified. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */ - stringify(value: any, replacer: any[], space: string | number): string; + stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; } + /** * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. */ diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 6ed743d739a..ae54e8e8570 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -965,38 +965,22 @@ interface JSON { * If a member contains nested objects, the nested objects are transformed before the parent object is. */ parse(text: string, reviver?: (key: any, value: any) => any): any; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - */ - stringify(value: any): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer A function that transforms the results. - */ - stringify(value: any, replacer: (key: string, value: any) => any): string; - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer Array that transforms the results. - */ - stringify(value: any, replacer: any[]): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. * @param replacer A function that transforms the results. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */ - stringify(value: any, replacer: (key: string, value: any) => any, space: string | number): string; + stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; /** * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer Array that transforms the results. + * @param replacer An array of strings and numbers that acts as a white list for selecting the object properties that will be stringified. * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. */ - stringify(value: any, replacer: any[], space: string | number): string; + stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; } + /** * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. */ diff --git a/lib/tsc.js b/lib/tsc.js index 8dba7a921dc..00c758c0446 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -913,6 +913,10 @@ var ts; } return result.sort(); } + function getDirectories(path) { + var folder = fso.GetFolder(path); + return getNames(folder.subfolders); + } function readDirectory(path, extension, exclude) { var result = []; exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); @@ -967,6 +971,7 @@ var ts; getCurrentDirectory: function () { return new ActiveXObject("WScript.Shell").CurrentDirectory; }, + getDirectories: getDirectories, readDirectory: readDirectory, exit: function (exitCode) { try { @@ -1114,6 +1119,9 @@ var ts; function directoryExists(path) { return fileSystemEntryExists(path, 1); } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); + } function readDirectory(path, extension, exclude) { var result = []; exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); @@ -1206,6 +1214,7 @@ var ts; getCurrentDirectory: function () { return process.cwd(); }, + getDirectories: getDirectories, readDirectory: readDirectory, getModifiedTime: function (path) { try { @@ -1256,6 +1265,7 @@ var ts; createDirectory: ChakraHost.createDirectory, getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, readDirectory: ChakraHost.readDirectory, exit: ChakraHost.quit, realpath: realpath @@ -1389,7 +1399,7 @@ var ts; or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting__1148", message: "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -1759,6 +1769,8 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, + Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1852,7 +1864,7 @@ var ts; Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character" }, Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character" }, - Substututions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substututions_for_pattern_0_should_be_an_array_5063", message: "Substututions for pattern '{0}' should be an array." }, + Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, @@ -1865,6 +1877,7 @@ var ts; Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, + Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -1966,6 +1979,7 @@ var ts; Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'" }, + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -5004,7 +5018,7 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 69 || name.kind === 9 || name.kind === 8) { + if (name.kind === 69 || name.kind === 9 || name.kind === 8 || name.kind === 142) { return name.text; } if (name.kind === 140) { @@ -12050,10 +12064,10 @@ var ts; case 145: case 144: case 266: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); case 253: case 254: - return bindPropertyOrMethodOrAccessor(node, 4, 107455); + return bindPropertyOrMethodOrAccessor(node, 4, 0); case 255: return bindPropertyOrMethodOrAccessor(node, 8, 107455); case 247: @@ -12065,7 +12079,7 @@ var ts; return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 147: case 146: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); case 220: return bindFunctionDeclaration(node); case 148: @@ -12108,7 +12122,7 @@ var ts; case 238: return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); case 228: - return bindGlobalModuleExportDeclaration(node); + return bindNamespaceExportDeclaration(node); case 231: return bindImportClause(node); case 236: @@ -12144,13 +12158,13 @@ var ts; bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } else if (boundExpression.kind === 69 && node.kind === 235) { - declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0 | 8388608); } else { - declareSymbol(container.symbol.exports, container.symbol, node, 4, 107455 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, 4, 0 | 8388608); } } - function bindGlobalModuleExportDeclaration(node) { + function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } @@ -12202,7 +12216,7 @@ var ts; function bindThisPropertyAssignment(node) { if (container.kind === 179 || container.kind === 220) { container.symbol.members = container.symbol.members || {}; - declareSymbol(container.symbol.members, container.symbol, node, 4, 107455 & ~4); + declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); } } function bindPrototypePropertyAssignment(node) { @@ -12219,7 +12233,7 @@ var ts; if (!funcSymbol.members) { funcSymbol.members = {}; } - declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 107455); + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } function bindCallExpression(node) { if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { @@ -12295,7 +12309,7 @@ var ts; } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 0); } } function bindFunctionDeclaration(node) { @@ -12595,7 +12609,7 @@ var ts; if (flags & 1) result |= 107454; if (flags & 4) - result |= 107455; + result |= 0; if (flags & 8) result |= 107455; if (flags & 16) @@ -12851,6 +12865,7 @@ var ts; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; + var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { @@ -12882,6 +12897,7 @@ var ts; case 256: if (!ts.isExternalOrCommonJsModule(location)) break; + isInExternalModule = true; case 225: var moduleExports = getSymbolOfNode(location).exports; if (location.kind === 256 || ts.isAmbientModule(location)) { @@ -13005,6 +13021,12 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } + if (result && isInExternalModule) { + var decls = result.declarations; + if (decls && decls.length === 1 && decls[0].kind === 228) { + error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + } + } } return result; } @@ -14480,7 +14502,7 @@ var ts; } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } function getTextOfPropertyName(name) { switch (name.kind) { @@ -14585,7 +14607,7 @@ var ts; function addOptionality(type, optional) { return strictNullChecks && optional ? addNullableKind(type, 32) : type; } - function getTypeForVariableLikeDeclaration(declaration) { + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 134217728) { var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { @@ -14602,7 +14624,7 @@ var ts; return getTypeForBindingElement(declaration); } if (declaration.type) { - return addOptionality(getTypeFromTypeNode(declaration.type), !!declaration.questionToken); + return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } if (declaration.kind === 142) { var func = declaration.parent; @@ -14621,11 +14643,11 @@ var ts; ? getContextuallyTypedThisType(func) : getContextuallyTypedParameterType(declaration); if (type) { - return addOptionality(type, !!declaration.questionToken); + return addOptionality(type, declaration.questionToken && includeOptionality); } } if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), !!declaration.questionToken); + return addOptionality(checkExpressionCached(declaration.initializer), declaration.questionToken && includeOptionality); } if (declaration.kind === 254) { return checkIdentifier(declaration.name); @@ -14693,7 +14715,7 @@ var ts; : getTypeFromArrayBindingPattern(pattern, includePatternInType); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration); + var type = getTypeForVariableLikeDeclaration(declaration, true); if (type) { if (reportErrors) { reportErrorsFromWidening(declaration, type); @@ -17010,7 +17032,7 @@ var ts; return isIdenticalTo(source, target); } if (!(target.flags & 134217728)) { - if (target.flags & 1) + if (target.flags & 1 || source.flags & 134217728) return -1; if (source.flags & 32) { if (!strictNullChecks || target.flags & (32 | 16) || source === emptyArrayElementType) @@ -17030,7 +17052,7 @@ var ts; if (source.flags & 256 && target === stringType) return -1; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & (1 | 134217728)) + if (source.flags & 1) return -1; if (source === numberType && target.flags & 128) return -1; @@ -17807,41 +17829,47 @@ var ts; getSignaturesOfType(type, 0).length === 0 && getSignaturesOfType(type, 1).length === 0; } + function createTransientSymbol(source, type) { + var symbol = createSymbol(source.flags | 67108864, source.name); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = {}; + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members[property.name] = updated === original ? property : createTransientSymbol(property, updated); + } + ; + return members; + } function getRegularTypeOfObjectLiteral(type) { - if (type.flags & 1048576) { - var regularType = type.regularType; - if (!regularType) { - regularType = createType(type.flags & ~1048576); - regularType.symbol = type.symbol; - regularType.members = type.members; - regularType.properties = type.properties; - regularType.callSignatures = type.callSignatures; - regularType.constructSignatures = type.constructSignatures; - regularType.stringIndexInfo = type.stringIndexInfo; - regularType.numberIndexInfo = type.numberIndexInfo; - type.regularType = regularType; - } + if (!(type.flags & 1048576)) { + return type; + } + var regularType = type.regularType; + if (regularType) { return regularType; } - return type; + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags & ~1048576; + type.regularType = regularNew; + return regularNew; } function getWidenedTypeOfObjectLiteral(type) { - var properties = getPropertiesOfObjectType(type); - var members = {}; - ts.forEach(properties, function (p) { - var propType = getTypeOfSymbol(p); - var widenedType = getWidenedType(propType); - if (propType !== widenedType) { - var symbol = createSymbol(p.flags | 67108864, p.name); - symbol.declarations = p.declarations; - symbol.parent = p.parent; - symbol.type = widenedType; - symbol.target = p; - if (p.valueDeclaration) - symbol.valueDeclaration = p.valueDeclaration; - p = symbol; - } - members[p.name] = p; + var members = transformTypeOfMembers(type, function (prop) { + var widened = getWidenedType(prop); + return prop === widened ? prop : widened; }); var stringIndexInfo = getIndexInfoOfType(type, 0); var numberIndexInfo = getIndexInfoOfType(type, 1); @@ -19134,7 +19162,7 @@ var ts; } return nodeCheckFlag === 512 ? getBaseConstructorTypeOfClass(classType) - : baseClassType; + : getTypeWithThisArgument(baseClassType, classType.thisType); function isLegalUsageOfSuperExpression(container) { if (!container) { return false; @@ -21182,7 +21210,7 @@ var ts; var types = void 0; var funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { - types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + types = checkAndAggregateYieldOperandTypes(func, contextualMapper); if (types.length === 0) { var iterableIteratorAny = createIterableIteratorType(anyType); if (compilerOptions.noImplicitAny) { @@ -21192,8 +21220,7 @@ var ts; } } else { - var hasImplicitReturn = !!(func.flags & 32768); - types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper, isAsync, hasImplicitReturn); + types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { return neverType; } @@ -21240,9 +21267,9 @@ var ts; return widenedType; } } - function checkAndAggregateYieldOperandTypes(body, contextualMapper) { + function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; - ts.forEachYieldExpression(body, function (yieldExpression) { + ts.forEachYieldExpression(func.body, function (yieldExpression) { var expr = yieldExpression.expression; if (expr) { var type = checkExpressionCached(expr, contextualMapper); @@ -21256,28 +21283,34 @@ var ts; }); return aggregatedTypes; } - function checkAndAggregateReturnExpressionTypes(body, contextualMapper, isAsync, hasImplicitReturn) { + function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { + var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasOmittedExpressions = false; - ts.forEachReturnStatement(body, function (returnStatement) { + var hasReturnWithNoExpression = !!(func.flags & 32768); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; if (expr) { var type = checkExpressionCached(expr, contextualMapper); if (isAsync) { - type = checkAwaitedType(type, body.parent, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type !== neverType && !ts.contains(aggregatedTypes, type)) { + if (type === neverType) { + hasReturnOfTypeNever = true; + } + else if (!ts.contains(aggregatedTypes, type)) { aggregatedTypes.push(type); } } else { - hasOmittedExpressions = true; + hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasOmittedExpressions && !hasImplicitReturn) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || + func.kind === 179 || func.kind === 180)) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && (hasOmittedExpressions || hasImplicitReturn)) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { if (!ts.contains(aggregatedTypes, undefinedType)) { aggregatedTypes.push(undefinedType); } @@ -21407,7 +21440,9 @@ var ts; (expr.kind === 172 || expr.kind === 173) && expr.expression.kind === 97) { var func = ts.getContainingFunction(expr); - return !(func && func.kind === 148 && func.parent === symbol.valueDeclaration.parent); + if (!(func && func.kind === 148)) + return true; + return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } @@ -22231,6 +22266,79 @@ var ts; } } } + function checkClassForDuplicateDeclarations(node) { + var getter = 1, setter = 2, property = getter | setter; + var instanceNames = {}; + var staticNames = {}; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param)) { + addName(instanceNames, param.name, param.name.text, property); + } + } + } + else { + var static = ts.forEach(member.modifiers, function (m) { return m.kind === 113; }); + var names = static ? staticNames : instanceNames; + var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); + if (memberName) { + switch (member.kind) { + case 149: + addName(names, member.name, memberName, getter); + break; + case 150: + addName(names, member.name, memberName, setter); + break; + case 145: + addName(names, member.name, memberName, property); + break; + } + } + } + } + function addName(names, location, name, meaning) { + if (ts.hasProperty(names, name)) { + var prev = names[name]; + if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names[name] = prev | meaning; + } + } + else { + names[name] = meaning; + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = {}; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind == 144) { + var memberName = void 0; + switch (member.name.kind) { + case 9: + case 8: + case 69: + memberName = member.name.text; + break; + default: + continue; + } + if (ts.hasProperty(names, memberName)) { + error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names[memberName] = true; + } + } + } + } function checkTypeForDuplicateIndexSignatures(node) { if (node.kind === 222) { var nodeSymbol = getSymbolOfNode(node); @@ -22449,6 +22557,7 @@ var ts; var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); } } function checkArrayType(node) { @@ -23208,6 +23317,10 @@ var ts; if (node.initializer) { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } } if (node.kind !== 145 && node.kind !== 144) { checkExportsOnMergedDeclarations(node); @@ -23220,6 +23333,18 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } + function areDeclarationFlagsIdentical(left, right) { + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 | + 16 | + 256 | + 128 | + 64 | + 32; + return (left.flags & interestingFlags) === (right.flags & interestingFlags); + } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); return checkVariableLikeDeclaration(node); @@ -23770,6 +23895,7 @@ var ts; var typeWithThis = getTypeWithThisArgument(type); var staticType = getTypeOfSymbol(symbol); checkTypeParameterListsIdentical(node, symbol); + checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { var baseTypes = getBaseTypes(type); @@ -23981,6 +24107,7 @@ var ts; checkIndexConstraints(type); } } + checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { @@ -24735,10 +24862,8 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1)) { - if (compilerOptions.skipDefaultLibCheck) { - if (node.hasNoDefaultLib) { - return; - } + if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + return; } checkGrammarSourceFile(node); potentialThisCollisions.length = 0; @@ -25107,7 +25232,7 @@ var ts; return symbol && getTypeOfSymbol(symbol); } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent); + return getTypeForVariableLikeDeclaration(node.parent, true); } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -25546,7 +25671,7 @@ var ts; if (file.moduleAugmentations.length) { (augmentations || (augmentations = [])).push(file.moduleAugmentations); } - if (file.wasReferenced && file.symbol && file.symbol.globalExports) { + if (file.symbol && file.symbol.globalExports) { mergeSymbolTable(globals, file.symbol.globalExports); } }); @@ -26116,7 +26241,6 @@ var ts; if (prop.kind === 193 || name_20.kind === 140) { checkGrammarComputedPropertyName(name_20); - return "continue"; } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; @@ -26146,17 +26270,21 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_20.text)) { - seen[name_20.text] = currentKind; + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_20); + if (effectiveName === undefined) { + return "continue"; + } + if (!ts.hasProperty(seen, effectiveName)) { + seen[effectiveName] = currentKind; } else { - var existingKind = seen[name_20.text]; + var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - return "continue"; + grammarErrorOnNode(name_20, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_20)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_20.text] = currentKind | existingKind; + seen[effectiveName] = currentKind | existingKind; } else { return { value: grammarErrorOnNode(name_20, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; @@ -34613,7 +34741,7 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : undefined); + var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); if (traceEnabled) { if (containingFile === undefined) { if (rootDir === undefined) { @@ -35116,12 +35244,25 @@ var ts; } } } + function getDefaultTypeDirectiveNames(rootPath) { + var localTypes = ts.combinePaths(rootPath, "types"); + var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); + var result = []; + if (ts.sys.directoryExists(localTypes)) { + result = result.concat(ts.sys.getDirectories(localTypes)); + } + if (ts.sys.directoryExists(npmTypes)) { + result = result.concat(ts.sys.getDirectories(npmTypes)); + } + return result; + } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { + getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -35189,6 +35330,19 @@ var ts; } return resolutions; } + function getDefaultTypeDirectiveNames(options, rootFiles, host) { + if (options.types) { + return options.types; + } + if (host && host.getDefaultTypeDirectiveNames) { + var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + if (commonRoot) { + return host.getDefaultTypeDirectiveNames(commonRoot); + } + } + return undefined; + } + ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -35224,13 +35378,14 @@ var ts; var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { - if (options.types && options.types.length) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(options.types, undefined); - for (var i = 0; i < options.types.length; i++) { - processTypeReferenceDirective(options.types[i], resolutions[i]); + ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + if (typeReferences) { + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, undefined); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); } } - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); if (!skipDefaultLib) { if (!options.lib) { processRootFile(host.getDefaultLibFileName(options), true); @@ -35807,9 +35962,6 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1) { - file_1.wasReferenced = file_1.wasReferenced || isReference; - } return file_1; } var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { @@ -35822,7 +35974,6 @@ var ts; }); filesByName.set(path, file); if (file) { - file.wasReferenced = file.wasReferenced || isReference; file.path = path; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(path); @@ -35923,17 +36074,7 @@ var ts; !options.noResolve && i < file.imports.length; if (shouldAddFile) { - var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); - if (importedFile && resolution.isExternalLibraryImport) { - if (!ts.isExternalModule(importedFile) && importedFile.statements.length) { - var start_5 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); - } - else if (importedFile.referencedFiles.length) { - var firstRef = importedFile.referencedFiles[0]; - fileProcessingDiagnostics.add(ts.createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, ts.Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); - } - } + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } } } @@ -36018,7 +36159,7 @@ var ts; } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substututions_for_pattern_0_should_be_an_array, key)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)); } } } @@ -36067,13 +36208,19 @@ var ts; } else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } - if (outFile && options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + if (outFile) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + } + else if (options.module === undefined && firstExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } } if (options.outDir || options.sourceRoot || @@ -36156,6 +36303,11 @@ var ts; type: "boolean", description: ts.Diagnostics.Print_this_message }, + { + name: "help", + shortName: "?", + type: "boolean" + }, { name: "init", type: "boolean", @@ -36258,6 +36410,11 @@ var ts; name: "skipDefaultLibCheck", type: "boolean" }, + { + name: "skipLibCheck", + type: "boolean", + description: ts.Diagnostics.Skip_type_checking_of_declaration_files + }, { name: "out", type: "string", diff --git a/lib/tsserver.js b/lib/tsserver.js index ecb7bfb5509..7eb744a77d3 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -918,6 +918,10 @@ var ts; } return result.sort(); } + function getDirectories(path) { + var folder = fso.GetFolder(path); + return getNames(folder.subfolders); + } function readDirectory(path, extension, exclude) { var result = []; exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); @@ -972,6 +976,7 @@ var ts; getCurrentDirectory: function () { return new ActiveXObject("WScript.Shell").CurrentDirectory; }, + getDirectories: getDirectories, readDirectory: readDirectory, exit: function (exitCode) { try { @@ -1119,6 +1124,9 @@ var ts; function directoryExists(path) { return fileSystemEntryExists(path, 1); } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); + } function readDirectory(path, extension, exclude) { var result = []; exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); @@ -1211,6 +1219,7 @@ var ts; getCurrentDirectory: function () { return process.cwd(); }, + getDirectories: getDirectories, readDirectory: readDirectory, getModifiedTime: function (path) { try { @@ -1261,6 +1270,7 @@ var ts; createDirectory: ChakraHost.createDirectory, getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, readDirectory: ChakraHost.readDirectory, exit: ChakraHost.quit, realpath: realpath @@ -1394,7 +1404,7 @@ var ts; or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting__1148", message: "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -1764,6 +1774,8 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, + Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1857,7 +1869,7 @@ var ts; Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character" }, Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character" }, - Substututions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substututions_for_pattern_0_should_be_an_array_5063", message: "Substututions for pattern '{0}' should be an array." }, + Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, @@ -1870,6 +1882,7 @@ var ts; Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, + Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -1971,6 +1984,7 @@ var ts; Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'" }, + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3537,6 +3551,11 @@ var ts; type: "boolean", description: ts.Diagnostics.Print_this_message }, + { + name: "help", + shortName: "?", + type: "boolean" + }, { name: "init", type: "boolean", @@ -3639,6 +3658,11 @@ var ts; name: "skipDefaultLibCheck", type: "boolean" }, + { + name: "skipLibCheck", + type: "boolean", + description: ts.Diagnostics.Skip_type_checking_of_declaration_files + }, { name: "out", type: "string", @@ -5758,7 +5782,7 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 69 || name.kind === 9 || name.kind === 8) { + if (name.kind === 69 || name.kind === 9 || name.kind === 8 || name.kind === 142) { return name.text; } if (name.kind === 140) { @@ -12804,10 +12828,10 @@ var ts; case 145: case 144: case 266: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); case 253: case 254: - return bindPropertyOrMethodOrAccessor(node, 4, 107455); + return bindPropertyOrMethodOrAccessor(node, 4, 0); case 255: return bindPropertyOrMethodOrAccessor(node, 8, 107455); case 247: @@ -12819,7 +12843,7 @@ var ts; return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 147: case 146: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); case 220: return bindFunctionDeclaration(node); case 148: @@ -12862,7 +12886,7 @@ var ts; case 238: return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); case 228: - return bindGlobalModuleExportDeclaration(node); + return bindNamespaceExportDeclaration(node); case 231: return bindImportClause(node); case 236: @@ -12898,13 +12922,13 @@ var ts; bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } else if (boundExpression.kind === 69 && node.kind === 235) { - declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0 | 8388608); } else { - declareSymbol(container.symbol.exports, container.symbol, node, 4, 107455 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, 4, 0 | 8388608); } } - function bindGlobalModuleExportDeclaration(node) { + function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } @@ -12956,7 +12980,7 @@ var ts; function bindThisPropertyAssignment(node) { if (container.kind === 179 || container.kind === 220) { container.symbol.members = container.symbol.members || {}; - declareSymbol(container.symbol.members, container.symbol, node, 4, 107455 & ~4); + declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); } } function bindPrototypePropertyAssignment(node) { @@ -12973,7 +12997,7 @@ var ts; if (!funcSymbol.members) { funcSymbol.members = {}; } - declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 107455); + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } function bindCallExpression(node) { if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { @@ -13049,7 +13073,7 @@ var ts; } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 0); } } function bindFunctionDeclaration(node) { @@ -13349,7 +13373,7 @@ var ts; if (flags & 1) result |= 107454; if (flags & 4) - result |= 107455; + result |= 0; if (flags & 8) result |= 107455; if (flags & 16) @@ -13605,6 +13629,7 @@ var ts; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; + var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { @@ -13636,6 +13661,7 @@ var ts; case 256: if (!ts.isExternalOrCommonJsModule(location)) break; + isInExternalModule = true; case 225: var moduleExports = getSymbolOfNode(location).exports; if (location.kind === 256 || ts.isAmbientModule(location)) { @@ -13759,6 +13785,12 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } + if (result && isInExternalModule) { + var decls = result.declarations; + if (decls && decls.length === 1 && decls[0].kind === 228) { + error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + } + } } return result; } @@ -15234,7 +15266,7 @@ var ts; } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } function getTextOfPropertyName(name) { switch (name.kind) { @@ -15339,7 +15371,7 @@ var ts; function addOptionality(type, optional) { return strictNullChecks && optional ? addNullableKind(type, 32) : type; } - function getTypeForVariableLikeDeclaration(declaration) { + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 134217728) { var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { @@ -15356,7 +15388,7 @@ var ts; return getTypeForBindingElement(declaration); } if (declaration.type) { - return addOptionality(getTypeFromTypeNode(declaration.type), !!declaration.questionToken); + return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } if (declaration.kind === 142) { var func = declaration.parent; @@ -15375,11 +15407,11 @@ var ts; ? getContextuallyTypedThisType(func) : getContextuallyTypedParameterType(declaration); if (type) { - return addOptionality(type, !!declaration.questionToken); + return addOptionality(type, declaration.questionToken && includeOptionality); } } if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), !!declaration.questionToken); + return addOptionality(checkExpressionCached(declaration.initializer), declaration.questionToken && includeOptionality); } if (declaration.kind === 254) { return checkIdentifier(declaration.name); @@ -15447,7 +15479,7 @@ var ts; : getTypeFromArrayBindingPattern(pattern, includePatternInType); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration); + var type = getTypeForVariableLikeDeclaration(declaration, true); if (type) { if (reportErrors) { reportErrorsFromWidening(declaration, type); @@ -17764,7 +17796,7 @@ var ts; return isIdenticalTo(source, target); } if (!(target.flags & 134217728)) { - if (target.flags & 1) + if (target.flags & 1 || source.flags & 134217728) return -1; if (source.flags & 32) { if (!strictNullChecks || target.flags & (32 | 16) || source === emptyArrayElementType) @@ -17784,7 +17816,7 @@ var ts; if (source.flags & 256 && target === stringType) return -1; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & (1 | 134217728)) + if (source.flags & 1) return -1; if (source === numberType && target.flags & 128) return -1; @@ -18561,41 +18593,47 @@ var ts; getSignaturesOfType(type, 0).length === 0 && getSignaturesOfType(type, 1).length === 0; } + function createTransientSymbol(source, type) { + var symbol = createSymbol(source.flags | 67108864, source.name); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = {}; + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members[property.name] = updated === original ? property : createTransientSymbol(property, updated); + } + ; + return members; + } function getRegularTypeOfObjectLiteral(type) { - if (type.flags & 1048576) { - var regularType = type.regularType; - if (!regularType) { - regularType = createType(type.flags & ~1048576); - regularType.symbol = type.symbol; - regularType.members = type.members; - regularType.properties = type.properties; - regularType.callSignatures = type.callSignatures; - regularType.constructSignatures = type.constructSignatures; - regularType.stringIndexInfo = type.stringIndexInfo; - regularType.numberIndexInfo = type.numberIndexInfo; - type.regularType = regularType; - } + if (!(type.flags & 1048576)) { + return type; + } + var regularType = type.regularType; + if (regularType) { return regularType; } - return type; + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags & ~1048576; + type.regularType = regularNew; + return regularNew; } function getWidenedTypeOfObjectLiteral(type) { - var properties = getPropertiesOfObjectType(type); - var members = {}; - ts.forEach(properties, function (p) { - var propType = getTypeOfSymbol(p); - var widenedType = getWidenedType(propType); - if (propType !== widenedType) { - var symbol = createSymbol(p.flags | 67108864, p.name); - symbol.declarations = p.declarations; - symbol.parent = p.parent; - symbol.type = widenedType; - symbol.target = p; - if (p.valueDeclaration) - symbol.valueDeclaration = p.valueDeclaration; - p = symbol; - } - members[p.name] = p; + var members = transformTypeOfMembers(type, function (prop) { + var widened = getWidenedType(prop); + return prop === widened ? prop : widened; }); var stringIndexInfo = getIndexInfoOfType(type, 0); var numberIndexInfo = getIndexInfoOfType(type, 1); @@ -19888,7 +19926,7 @@ var ts; } return nodeCheckFlag === 512 ? getBaseConstructorTypeOfClass(classType) - : baseClassType; + : getTypeWithThisArgument(baseClassType, classType.thisType); function isLegalUsageOfSuperExpression(container) { if (!container) { return false; @@ -21936,7 +21974,7 @@ var ts; var types = void 0; var funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { - types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + types = checkAndAggregateYieldOperandTypes(func, contextualMapper); if (types.length === 0) { var iterableIteratorAny = createIterableIteratorType(anyType); if (compilerOptions.noImplicitAny) { @@ -21946,8 +21984,7 @@ var ts; } } else { - var hasImplicitReturn = !!(func.flags & 32768); - types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper, isAsync, hasImplicitReturn); + types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { return neverType; } @@ -21994,9 +22031,9 @@ var ts; return widenedType; } } - function checkAndAggregateYieldOperandTypes(body, contextualMapper) { + function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; - ts.forEachYieldExpression(body, function (yieldExpression) { + ts.forEachYieldExpression(func.body, function (yieldExpression) { var expr = yieldExpression.expression; if (expr) { var type = checkExpressionCached(expr, contextualMapper); @@ -22010,28 +22047,34 @@ var ts; }); return aggregatedTypes; } - function checkAndAggregateReturnExpressionTypes(body, contextualMapper, isAsync, hasImplicitReturn) { + function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { + var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasOmittedExpressions = false; - ts.forEachReturnStatement(body, function (returnStatement) { + var hasReturnWithNoExpression = !!(func.flags & 32768); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; if (expr) { var type = checkExpressionCached(expr, contextualMapper); if (isAsync) { - type = checkAwaitedType(type, body.parent, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type !== neverType && !ts.contains(aggregatedTypes, type)) { + if (type === neverType) { + hasReturnOfTypeNever = true; + } + else if (!ts.contains(aggregatedTypes, type)) { aggregatedTypes.push(type); } } else { - hasOmittedExpressions = true; + hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasOmittedExpressions && !hasImplicitReturn) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || + func.kind === 179 || func.kind === 180)) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && (hasOmittedExpressions || hasImplicitReturn)) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { if (!ts.contains(aggregatedTypes, undefinedType)) { aggregatedTypes.push(undefinedType); } @@ -22161,7 +22204,9 @@ var ts; (expr.kind === 172 || expr.kind === 173) && expr.expression.kind === 97) { var func = ts.getContainingFunction(expr); - return !(func && func.kind === 148 && func.parent === symbol.valueDeclaration.parent); + if (!(func && func.kind === 148)) + return true; + return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } @@ -22985,6 +23030,79 @@ var ts; } } } + function checkClassForDuplicateDeclarations(node) { + var getter = 1, setter = 2, property = getter | setter; + var instanceNames = {}; + var staticNames = {}; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param)) { + addName(instanceNames, param.name, param.name.text, property); + } + } + } + else { + var static = ts.forEach(member.modifiers, function (m) { return m.kind === 113; }); + var names = static ? staticNames : instanceNames; + var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); + if (memberName) { + switch (member.kind) { + case 149: + addName(names, member.name, memberName, getter); + break; + case 150: + addName(names, member.name, memberName, setter); + break; + case 145: + addName(names, member.name, memberName, property); + break; + } + } + } + } + function addName(names, location, name, meaning) { + if (ts.hasProperty(names, name)) { + var prev = names[name]; + if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names[name] = prev | meaning; + } + } + else { + names[name] = meaning; + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = {}; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind == 144) { + var memberName = void 0; + switch (member.name.kind) { + case 9: + case 8: + case 69: + memberName = member.name.text; + break; + default: + continue; + } + if (ts.hasProperty(names, memberName)) { + error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names[memberName] = true; + } + } + } + } function checkTypeForDuplicateIndexSignatures(node) { if (node.kind === 222) { var nodeSymbol = getSymbolOfNode(node); @@ -23203,6 +23321,7 @@ var ts; var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); } } function checkArrayType(node) { @@ -23962,6 +24081,10 @@ var ts; if (node.initializer) { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } } if (node.kind !== 145 && node.kind !== 144) { checkExportsOnMergedDeclarations(node); @@ -23974,6 +24097,18 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } + function areDeclarationFlagsIdentical(left, right) { + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 | + 16 | + 256 | + 128 | + 64 | + 32; + return (left.flags & interestingFlags) === (right.flags & interestingFlags); + } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); return checkVariableLikeDeclaration(node); @@ -24524,6 +24659,7 @@ var ts; var typeWithThis = getTypeWithThisArgument(type); var staticType = getTypeOfSymbol(symbol); checkTypeParameterListsIdentical(node, symbol); + checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { var baseTypes = getBaseTypes(type); @@ -24735,6 +24871,7 @@ var ts; checkIndexConstraints(type); } } + checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { @@ -25489,10 +25626,8 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1)) { - if (compilerOptions.skipDefaultLibCheck) { - if (node.hasNoDefaultLib) { - return; - } + if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + return; } checkGrammarSourceFile(node); potentialThisCollisions.length = 0; @@ -25861,7 +25996,7 @@ var ts; return symbol && getTypeOfSymbol(symbol); } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent); + return getTypeForVariableLikeDeclaration(node.parent, true); } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -26300,7 +26435,7 @@ var ts; if (file.moduleAugmentations.length) { (augmentations || (augmentations = [])).push(file.moduleAugmentations); } - if (file.wasReferenced && file.symbol && file.symbol.globalExports) { + if (file.symbol && file.symbol.globalExports) { mergeSymbolTable(globals, file.symbol.globalExports); } }); @@ -26870,7 +27005,6 @@ var ts; if (prop.kind === 193 || name_20.kind === 140) { checkGrammarComputedPropertyName(name_20); - return "continue"; } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; @@ -26900,17 +27034,21 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_20.text)) { - seen[name_20.text] = currentKind; + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_20); + if (effectiveName === undefined) { + return "continue"; + } + if (!ts.hasProperty(seen, effectiveName)) { + seen[effectiveName] = currentKind; } else { - var existingKind = seen[name_20.text]; + var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - return "continue"; + grammarErrorOnNode(name_20, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_20)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_20.text] = currentKind | existingKind; + seen[effectiveName] = currentKind | existingKind; } else { return { value: grammarErrorOnNode(name_20, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; @@ -35367,7 +35505,7 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : undefined); + var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); if (traceEnabled) { if (containingFile === undefined) { if (rootDir === undefined) { @@ -35870,12 +36008,25 @@ var ts; } } } + function getDefaultTypeDirectiveNames(rootPath) { + var localTypes = ts.combinePaths(rootPath, "types"); + var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); + var result = []; + if (ts.sys.directoryExists(localTypes)) { + result = result.concat(ts.sys.getDirectories(localTypes)); + } + if (ts.sys.directoryExists(npmTypes)) { + result = result.concat(ts.sys.getDirectories(npmTypes)); + } + return result; + } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { + getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -35943,6 +36094,19 @@ var ts; } return resolutions; } + function getDefaultTypeDirectiveNames(options, rootFiles, host) { + if (options.types) { + return options.types; + } + if (host && host.getDefaultTypeDirectiveNames) { + var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + if (commonRoot) { + return host.getDefaultTypeDirectiveNames(commonRoot); + } + } + return undefined; + } + ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -35978,13 +36142,14 @@ var ts; var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { - if (options.types && options.types.length) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(options.types, undefined); - for (var i = 0; i < options.types.length; i++) { - processTypeReferenceDirective(options.types[i], resolutions[i]); + ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + if (typeReferences) { + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, undefined); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); } } - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); if (!skipDefaultLib) { if (!options.lib) { processRootFile(host.getDefaultLibFileName(options), true); @@ -36561,9 +36726,6 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1) { - file_1.wasReferenced = file_1.wasReferenced || isReference; - } return file_1; } var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { @@ -36576,7 +36738,6 @@ var ts; }); filesByName.set(path, file); if (file) { - file.wasReferenced = file.wasReferenced || isReference; file.path = path; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(path); @@ -36677,17 +36838,7 @@ var ts; !options.noResolve && i < file.imports.length; if (shouldAddFile) { - var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); - if (importedFile && resolution.isExternalLibraryImport) { - if (!ts.isExternalModule(importedFile) && importedFile.statements.length) { - var start_5 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); - } - else if (importedFile.referencedFiles.length) { - var firstRef = importedFile.referencedFiles[0]; - fileProcessingDiagnostics.add(ts.createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, ts.Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); - } - } + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } } } @@ -36772,7 +36923,7 @@ var ts; } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substututions_for_pattern_0_should_be_an_array, key)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)); } } } @@ -36821,13 +36972,19 @@ var ts; } else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } - if (outFile && options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + if (outFile) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + } + else if (options.module === undefined && firstExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } } if (options.outDir || options.sourceRoot || @@ -37517,7 +37674,7 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; var baseSensitivity = { sensitivity: "base" }; @@ -37550,6 +37707,17 @@ var ts; } } }); + rawItems = ts.filter(rawItems, function (item) { + var decl = item.declaration; + if (decl.kind === 231 || decl.kind === 234 || decl.kind === 229) { + var importer = checker.getSymbolAtLocation(decl.name); + var imported = checker.getAliasedSymbol(importer); + return importer.name !== imported.name; + } + else { + return true; + } + }); rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { rawItems = rawItems.slice(0, maxResultCount); @@ -37892,8 +38060,12 @@ var ts; return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); case 153: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); + case 224: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); case 255: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 222: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); case 151: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); case 152: @@ -39263,7 +39435,7 @@ var ts; } } function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { - for (var i = exclusiveStartPosition - 1; i >= 0; --i) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { if (nodeHasTokens(children[i])) { return children[i]; } @@ -39889,18 +40061,17 @@ var ts; if (!isStarted) { scanner.scan(); } - var t; var pos = scanner.getStartPos(); while (pos < endPos) { - var t_1 = scanner.getToken(); - if (!ts.isTrivia(t_1)) { + var t = scanner.getToken(); + if (!ts.isTrivia(t)) { break; } scanner.scan(); var item = { pos: pos, end: scanner.getStartPos(), - kind: t_1 + kind: t }; pos = scanner.getStartPos(); if (!leadingTrivia) { @@ -41550,7 +41721,7 @@ var ts; else { parts = []; var startPos = commentRange.pos; - for (var line = startLine; line < endLine; ++line) { + for (var line = startLine; line < endLine; line++) { var endOfLine = ts.getEndLinePosition(line, sourceFile); parts.push({ pos: startPos, end: endOfLine }); startPos = ts.getStartPositionOfLine(line + 1, sourceFile); @@ -41568,7 +41739,7 @@ var ts; startLine++; } var delta = indentation - nonWhitespaceColumnInFirstPart.column; - for (var i = startIndex, len = parts.length; i < len; ++i, ++startLine) { + for (var i = startIndex, len = parts.length; i < len; i++, startLine++) { var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart @@ -41584,7 +41755,7 @@ var ts; } } function trimTrailingWhitespacesForLines(line1, line2, range) { - for (var line = line1; line < line2; ++line) { + for (var line = line1; line < line2; line++) { var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var lineEndPosition = ts.getEndLinePosition(line, sourceFile); if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { @@ -41627,7 +41798,6 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { - var between; switch (rule.Operation.Action) { case 1: return; @@ -41657,14 +41827,6 @@ var ts; } } } - function isSomeBlock(kind) { - switch (kind) { - case 199: - case 226: - return true; - } - return false; - } function getOpenTokenForList(node, list) { switch (node.kind) { case 148: @@ -41722,7 +41884,7 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat('\t', tabs); + internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; @@ -41747,7 +41909,7 @@ var ts; } function repeat(value, count) { var s = ""; - for (var i = 0; i < count; ++i) { + for (var i = 0; i < count; i++) { s += value; } return s; @@ -42015,7 +42177,7 @@ var ts; ts.Debug.assert(index >= 0 && index < list.length); var node = list[index]; var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); - for (var i = index - 1; i >= 0; --i) { + for (var i = index - 1; i >= 0; i--) { if (list[i].kind === 24) { continue; } @@ -42034,7 +42196,7 @@ var ts; function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { var character = 0; var column = 0; - for (var pos = startPos; pos < endPos; ++pos) { + for (var pos = startPos; pos < endPos; pos++) { var ch = sourceFile.text.charCodeAt(pos); if (!ts.isWhiteSpace(ch)) { break; @@ -44005,9 +44167,9 @@ var ts; log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); var contextToken = previousToken; if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_6 = new Date().getTime(); + var start_5 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); } var node = currentToken; var isRightOfDot = false; @@ -44234,9 +44396,9 @@ var ts; || contextToken.kind === 166 || contextToken.kind === 10 || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_7 = contextToken.getStart(); + var start_6 = contextToken.getStart(); var end = contextToken.getEnd(); - if (start_7 < position && position < end) { + if (start_6 < position && position < end) { return true; } if (position === end) { @@ -45314,8 +45476,7 @@ var ts; } function getDocumentHighlights(fileName, position, filesToSearch) { synchronizeHostData(); - filesToSearch = ts.map(filesToSearch, ts.normalizeSlashes); - var sourceFilesToSearch = ts.filter(program.getSourceFiles(), function (f) { return ts.contains(filesToSearch, f.fileName); }); + var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingWord(sourceFile, position); if (!node) { @@ -46498,7 +46659,8 @@ var ts; } function getNavigateToItems(searchValue, maxResultCount) { synchronizeHostData(); - return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); + var checker = getProgram().getTypeChecker(); + return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); } function getEmitOutput(fileName) { synchronizeHostData(); @@ -51195,6 +51357,9 @@ var ts; LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () { return this.shimHost.getCurrentDirectory(); }; + LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { + return this.shimHost.getDirectories(path); + }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 0629ad983a3..76b66dda93b 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -247,7 +247,7 @@ declare namespace ts { ModuleDeclaration = 225, ModuleBlock = 226, CaseBlock = 227, - GlobalModuleExportDeclaration = 228, + NamespaceExportDeclaration = 228, ImportEqualsDeclaration = 229, ImportDeclaration = 230, ImportClause = 231, @@ -925,7 +925,7 @@ declare namespace ts { interface NamespaceImport extends Declaration { name: Identifier; } - interface GlobalModuleExportDeclaration extends DeclarationStatement { + interface NamespaceExportDeclaration extends DeclarationStatement { name: Identifier; moduleReference: LiteralLikeNode; } @@ -1087,7 +1087,6 @@ declare namespace ts { scriptKind: ScriptKind; externalModuleIndicator: Node; commonJsModuleIndicator: Node; - wasReferenced?: boolean; identifiers: Map; nodeCount: number; identifierCount: number; @@ -1381,7 +1380,7 @@ declare namespace ts { FunctionScopedVariableExcludes = 107454, BlockScopedVariableExcludes = 107455, ParameterExcludes = 107455, - PropertyExcludes = 107455, + PropertyExcludes = 0, EnumMemberExcludes = 107455, FunctionExcludes = 106927, ClassExcludes = 899519, @@ -1735,6 +1734,7 @@ declare namespace ts { allowJs?: boolean; noImplicitUseStrict?: boolean; strictNullChecks?: boolean; + skipLibCheck?: boolean; listEmittedFiles?: boolean; lib?: string[]; stripInternal?: boolean; @@ -1967,6 +1967,7 @@ declare namespace ts { trace?(s: string): void; directoryExists?(directoryName: string): boolean; realpath?(path: string): string; + getCurrentDirectory?(): string; } interface ResolvedModule { resolvedFileName: string; @@ -1990,6 +1991,7 @@ declare namespace ts { getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; + getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; getCanonicalFileName(fileName: string): string; @@ -2136,6 +2138,7 @@ declare namespace ts { createDirectory(path: string): void; getExecutingFilePath(): string; getCurrentDirectory(): string; + getDirectories(path: string): string[]; readDirectory(path: string, extension?: string, exclude?: string[]): string[]; getModifiedTime?(path: string): Date; createHash?(data: string): string; @@ -2820,7 +2823,7 @@ declare namespace ts { key: string; message: string; }; - Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: number; category: DiagnosticCategory; key: string; @@ -5040,6 +5043,18 @@ declare namespace ts { key: string; message: string; }; + Identifier_0_must_be_imported_from_a_module: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + All_declarations_of_0_must_have_identical_modifiers: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Import_declaration_0_is_using_private_name_1: { code: number; category: DiagnosticCategory; @@ -5598,7 +5613,7 @@ declare namespace ts { key: string; message: string; }; - Substututions_for_pattern_0_should_be_an_array: { + Substitutions_for_pattern_0_should_be_an_array: { code: number; category: DiagnosticCategory; key: string; @@ -5676,6 +5691,12 @@ declare namespace ts { key: string; message: string; }; + Skip_type_checking_of_declaration_files: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: number; category: DiagnosticCategory; @@ -6282,6 +6303,12 @@ declare namespace ts { key: string; message: string; }; + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Variable_0_implicitly_has_an_1_type: { code: number; category: DiagnosticCategory; @@ -7024,6 +7051,7 @@ declare namespace ts { function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function getDefaultTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts.BreakpointResolver { @@ -7033,7 +7061,7 @@ declare namespace ts.OutliningElementsCollector { function collectElements(sourceFile: SourceFile): OutliningSpan[]; } declare namespace ts.NavigateTo { - function getNavigateToItems(program: Program, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[]; + function getNavigateToItems(program: Program, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[]; } declare namespace ts.NavigationBar { function getNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): ts.NavigationBarItem[]; @@ -7431,7 +7459,7 @@ declare namespace ts.formatting { } } declare namespace ts.formatting { - module Shared { + namespace Shared { interface ITokenAccess { GetTokens(): SyntaxKind[]; Contains(token: SyntaxKind): boolean; @@ -7516,7 +7544,7 @@ declare namespace ts.formatting { function getIndentationString(indentation: number, options: FormatCodeOptions): string; } declare namespace ts.formatting { - module SmartIndenter { + namespace SmartIndenter { function getIndentation(position: number, sourceFile: SourceFile, options: EditorOptions): number; function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: FormatCodeOptions): number; function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFile): boolean; @@ -8487,6 +8515,7 @@ declare namespace ts { getLocalizedDiagnosticMessages(): string; getCancellationToken(): HostCancellationToken; getCurrentDirectory(): string; + getDirectories(path: string): string[]; getDefaultLibFileName(options: string): string; getNewLine?(): string; getProjectVersion?(): string; @@ -8582,6 +8611,7 @@ declare namespace ts { getLocalizedDiagnosticMessages(): any; getCancellationToken(): HostCancellationToken; getCurrentDirectory(): string; + getDirectories(path: string): string[]; getDefaultLibFileName(options: CompilerOptions): string; } class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResolutionHost { diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 050d9ca265d..902bfcf610e 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -918,6 +918,10 @@ var ts; } return result.sort(); } + function getDirectories(path) { + var folder = fso.GetFolder(path); + return getNames(folder.subfolders); + } function readDirectory(path, extension, exclude) { var result = []; exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); @@ -972,6 +976,7 @@ var ts; getCurrentDirectory: function () { return new ActiveXObject("WScript.Shell").CurrentDirectory; }, + getDirectories: getDirectories, readDirectory: readDirectory, exit: function (exitCode) { try { @@ -1119,6 +1124,9 @@ var ts; function directoryExists(path) { return fileSystemEntryExists(path, 1); } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); + } function readDirectory(path, extension, exclude) { var result = []; exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); @@ -1211,6 +1219,7 @@ var ts; getCurrentDirectory: function () { return process.cwd(); }, + getDirectories: getDirectories, readDirectory: readDirectory, getModifiedTime: function (path) { try { @@ -1261,6 +1270,7 @@ var ts; createDirectory: ChakraHost.createDirectory, getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, readDirectory: ChakraHost.readDirectory, exit: ChakraHost.quit, realpath: realpath @@ -1394,7 +1404,7 @@ var ts; or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting__1148", message: "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -1764,6 +1774,8 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, + Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1857,7 +1869,7 @@ var ts; Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character" }, Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character" }, - Substututions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substututions_for_pattern_0_should_be_an_array_5063", message: "Substututions for pattern '{0}' should be an array." }, + Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, @@ -1870,6 +1882,7 @@ var ts; Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, + Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -1971,6 +1984,7 @@ var ts; Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'" }, + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -3537,6 +3551,11 @@ var ts; type: "boolean", description: ts.Diagnostics.Print_this_message }, + { + name: "help", + shortName: "?", + type: "boolean" + }, { name: "init", type: "boolean", @@ -3639,6 +3658,11 @@ var ts; name: "skipDefaultLibCheck", type: "boolean" }, + { + name: "skipLibCheck", + type: "boolean", + description: ts.Diagnostics.Skip_type_checking_of_declaration_files + }, { name: "out", type: "string", @@ -5758,7 +5782,7 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 69 || name.kind === 9 || name.kind === 8) { + if (name.kind === 69 || name.kind === 9 || name.kind === 8 || name.kind === 142) { return name.text; } if (name.kind === 140) { @@ -12804,10 +12828,10 @@ var ts; case 145: case 144: case 266: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 107455); + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); case 253: case 254: - return bindPropertyOrMethodOrAccessor(node, 4, 107455); + return bindPropertyOrMethodOrAccessor(node, 4, 0); case 255: return bindPropertyOrMethodOrAccessor(node, 8, 107455); case 247: @@ -12819,7 +12843,7 @@ var ts; return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 147: case 146: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 107455 : 99263); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); case 220: return bindFunctionDeclaration(node); case 148: @@ -12862,7 +12886,7 @@ var ts; case 238: return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); case 228: - return bindGlobalModuleExportDeclaration(node); + return bindNamespaceExportDeclaration(node); case 231: return bindImportClause(node); case 236: @@ -12898,13 +12922,13 @@ var ts; bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); } else if (boundExpression.kind === 69 && node.kind === 235) { - declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 107455 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0 | 8388608); } else { - declareSymbol(container.symbol.exports, container.symbol, node, 4, 107455 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, 4, 0 | 8388608); } } - function bindGlobalModuleExportDeclaration(node) { + function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } @@ -12956,7 +12980,7 @@ var ts; function bindThisPropertyAssignment(node) { if (container.kind === 179 || container.kind === 220) { container.symbol.members = container.symbol.members || {}; - declareSymbol(container.symbol.members, container.symbol, node, 4, 107455 & ~4); + declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); } } function bindPrototypePropertyAssignment(node) { @@ -12973,7 +12997,7 @@ var ts; if (!funcSymbol.members) { funcSymbol.members = {}; } - declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 107455); + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4, 0); } function bindCallExpression(node) { if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { @@ -13049,7 +13073,7 @@ var ts; } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 107455); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4, 0); } } function bindFunctionDeclaration(node) { @@ -13349,7 +13373,7 @@ var ts; if (flags & 1) result |= 107454; if (flags & 4) - result |= 107455; + result |= 0; if (flags & 8) result |= 107455; if (flags & 16) @@ -13605,6 +13629,7 @@ var ts; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; + var isInExternalModule = false; loop: while (location) { if (location.locals && !isGlobalSourceFile(location)) { if (result = getSymbol(location.locals, name, meaning)) { @@ -13636,6 +13661,7 @@ var ts; case 256: if (!ts.isExternalOrCommonJsModule(location)) break; + isInExternalModule = true; case 225: var moduleExports = getSymbolOfNode(location).exports; if (location.kind === 256 || ts.isAmbientModule(location)) { @@ -13759,6 +13785,12 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } + if (result && isInExternalModule) { + var decls = result.declarations; + if (decls && decls.length === 1 && decls[0].kind === 228) { + error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + } + } } return result; } @@ -15234,7 +15266,7 @@ var ts; } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } function getTextOfPropertyName(name) { switch (name.kind) { @@ -15339,7 +15371,7 @@ var ts; function addOptionality(type, optional) { return strictNullChecks && optional ? addNullableKind(type, 32) : type; } - function getTypeForVariableLikeDeclaration(declaration) { + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 134217728) { var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { @@ -15356,7 +15388,7 @@ var ts; return getTypeForBindingElement(declaration); } if (declaration.type) { - return addOptionality(getTypeFromTypeNode(declaration.type), !!declaration.questionToken); + return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } if (declaration.kind === 142) { var func = declaration.parent; @@ -15375,11 +15407,11 @@ var ts; ? getContextuallyTypedThisType(func) : getContextuallyTypedParameterType(declaration); if (type) { - return addOptionality(type, !!declaration.questionToken); + return addOptionality(type, declaration.questionToken && includeOptionality); } } if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), !!declaration.questionToken); + return addOptionality(checkExpressionCached(declaration.initializer), declaration.questionToken && includeOptionality); } if (declaration.kind === 254) { return checkIdentifier(declaration.name); @@ -15447,7 +15479,7 @@ var ts; : getTypeFromArrayBindingPattern(pattern, includePatternInType); } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration); + var type = getTypeForVariableLikeDeclaration(declaration, true); if (type) { if (reportErrors) { reportErrorsFromWidening(declaration, type); @@ -17764,7 +17796,7 @@ var ts; return isIdenticalTo(source, target); } if (!(target.flags & 134217728)) { - if (target.flags & 1) + if (target.flags & 1 || source.flags & 134217728) return -1; if (source.flags & 32) { if (!strictNullChecks || target.flags & (32 | 16) || source === emptyArrayElementType) @@ -17784,7 +17816,7 @@ var ts; if (source.flags & 256 && target === stringType) return -1; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & (1 | 134217728)) + if (source.flags & 1) return -1; if (source === numberType && target.flags & 128) return -1; @@ -18561,41 +18593,47 @@ var ts; getSignaturesOfType(type, 0).length === 0 && getSignaturesOfType(type, 1).length === 0; } + function createTransientSymbol(source, type) { + var symbol = createSymbol(source.flags | 67108864, source.name); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = {}; + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members[property.name] = updated === original ? property : createTransientSymbol(property, updated); + } + ; + return members; + } function getRegularTypeOfObjectLiteral(type) { - if (type.flags & 1048576) { - var regularType = type.regularType; - if (!regularType) { - regularType = createType(type.flags & ~1048576); - regularType.symbol = type.symbol; - regularType.members = type.members; - regularType.properties = type.properties; - regularType.callSignatures = type.callSignatures; - regularType.constructSignatures = type.constructSignatures; - regularType.stringIndexInfo = type.stringIndexInfo; - regularType.numberIndexInfo = type.numberIndexInfo; - type.regularType = regularType; - } + if (!(type.flags & 1048576)) { + return type; + } + var regularType = type.regularType; + if (regularType) { return regularType; } - return type; + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags & ~1048576; + type.regularType = regularNew; + return regularNew; } function getWidenedTypeOfObjectLiteral(type) { - var properties = getPropertiesOfObjectType(type); - var members = {}; - ts.forEach(properties, function (p) { - var propType = getTypeOfSymbol(p); - var widenedType = getWidenedType(propType); - if (propType !== widenedType) { - var symbol = createSymbol(p.flags | 67108864, p.name); - symbol.declarations = p.declarations; - symbol.parent = p.parent; - symbol.type = widenedType; - symbol.target = p; - if (p.valueDeclaration) - symbol.valueDeclaration = p.valueDeclaration; - p = symbol; - } - members[p.name] = p; + var members = transformTypeOfMembers(type, function (prop) { + var widened = getWidenedType(prop); + return prop === widened ? prop : widened; }); var stringIndexInfo = getIndexInfoOfType(type, 0); var numberIndexInfo = getIndexInfoOfType(type, 1); @@ -19888,7 +19926,7 @@ var ts; } return nodeCheckFlag === 512 ? getBaseConstructorTypeOfClass(classType) - : baseClassType; + : getTypeWithThisArgument(baseClassType, classType.thisType); function isLegalUsageOfSuperExpression(container) { if (!container) { return false; @@ -21936,7 +21974,7 @@ var ts; var types = void 0; var funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { - types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + types = checkAndAggregateYieldOperandTypes(func, contextualMapper); if (types.length === 0) { var iterableIteratorAny = createIterableIteratorType(anyType); if (compilerOptions.noImplicitAny) { @@ -21946,8 +21984,7 @@ var ts; } } else { - var hasImplicitReturn = !!(func.flags & 32768); - types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper, isAsync, hasImplicitReturn); + types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { return neverType; } @@ -21994,9 +22031,9 @@ var ts; return widenedType; } } - function checkAndAggregateYieldOperandTypes(body, contextualMapper) { + function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; - ts.forEachYieldExpression(body, function (yieldExpression) { + ts.forEachYieldExpression(func.body, function (yieldExpression) { var expr = yieldExpression.expression; if (expr) { var type = checkExpressionCached(expr, contextualMapper); @@ -22010,28 +22047,34 @@ var ts; }); return aggregatedTypes; } - function checkAndAggregateReturnExpressionTypes(body, contextualMapper, isAsync, hasImplicitReturn) { + function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { + var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasOmittedExpressions = false; - ts.forEachReturnStatement(body, function (returnStatement) { + var hasReturnWithNoExpression = !!(func.flags & 32768); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; if (expr) { var type = checkExpressionCached(expr, contextualMapper); if (isAsync) { - type = checkAwaitedType(type, body.parent, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type !== neverType && !ts.contains(aggregatedTypes, type)) { + if (type === neverType) { + hasReturnOfTypeNever = true; + } + else if (!ts.contains(aggregatedTypes, type)) { aggregatedTypes.push(type); } } else { - hasOmittedExpressions = true; + hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasOmittedExpressions && !hasImplicitReturn) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || + func.kind === 179 || func.kind === 180)) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && (hasOmittedExpressions || hasImplicitReturn)) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { if (!ts.contains(aggregatedTypes, undefinedType)) { aggregatedTypes.push(undefinedType); } @@ -22161,7 +22204,9 @@ var ts; (expr.kind === 172 || expr.kind === 173) && expr.expression.kind === 97) { var func = ts.getContainingFunction(expr); - return !(func && func.kind === 148 && func.parent === symbol.valueDeclaration.parent); + if (!(func && func.kind === 148)) + return true; + return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } @@ -22985,6 +23030,79 @@ var ts; } } } + function checkClassForDuplicateDeclarations(node) { + var getter = 1, setter = 2, property = getter | setter; + var instanceNames = {}; + var staticNames = {}; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param)) { + addName(instanceNames, param.name, param.name.text, property); + } + } + } + else { + var static = ts.forEach(member.modifiers, function (m) { return m.kind === 113; }); + var names = static ? staticNames : instanceNames; + var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); + if (memberName) { + switch (member.kind) { + case 149: + addName(names, member.name, memberName, getter); + break; + case 150: + addName(names, member.name, memberName, setter); + break; + case 145: + addName(names, member.name, memberName, property); + break; + } + } + } + } + function addName(names, location, name, meaning) { + if (ts.hasProperty(names, name)) { + var prev = names[name]; + if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names[name] = prev | meaning; + } + } + else { + names[name] = meaning; + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = {}; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind == 144) { + var memberName = void 0; + switch (member.name.kind) { + case 9: + case 8: + case 69: + memberName = member.name.text; + break; + default: + continue; + } + if (ts.hasProperty(names, memberName)) { + error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names[memberName] = true; + } + } + } + } function checkTypeForDuplicateIndexSignatures(node) { if (node.kind === 222) { var nodeSymbol = getSymbolOfNode(node); @@ -23203,6 +23321,7 @@ var ts; var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); } } function checkArrayType(node) { @@ -23962,6 +24081,10 @@ var ts; if (node.initializer) { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } } if (node.kind !== 145 && node.kind !== 144) { checkExportsOnMergedDeclarations(node); @@ -23974,6 +24097,18 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } + function areDeclarationFlagsIdentical(left, right) { + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 | + 16 | + 256 | + 128 | + 64 | + 32; + return (left.flags & interestingFlags) === (right.flags & interestingFlags); + } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); return checkVariableLikeDeclaration(node); @@ -24524,6 +24659,7 @@ var ts; var typeWithThis = getTypeWithThisArgument(type); var staticType = getTypeOfSymbol(symbol); checkTypeParameterListsIdentical(node, symbol); + checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { var baseTypes = getBaseTypes(type); @@ -24735,6 +24871,7 @@ var ts; checkIndexConstraints(type); } } + checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { @@ -25489,10 +25626,8 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1)) { - if (compilerOptions.skipDefaultLibCheck) { - if (node.hasNoDefaultLib) { - return; - } + if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + return; } checkGrammarSourceFile(node); potentialThisCollisions.length = 0; @@ -25861,7 +25996,7 @@ var ts; return symbol && getTypeOfSymbol(symbol); } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent); + return getTypeForVariableLikeDeclaration(node.parent, true); } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -26300,7 +26435,7 @@ var ts; if (file.moduleAugmentations.length) { (augmentations || (augmentations = [])).push(file.moduleAugmentations); } - if (file.wasReferenced && file.symbol && file.symbol.globalExports) { + if (file.symbol && file.symbol.globalExports) { mergeSymbolTable(globals, file.symbol.globalExports); } }); @@ -26870,7 +27005,6 @@ var ts; if (prop.kind === 193 || name_20.kind === 140) { checkGrammarComputedPropertyName(name_20); - return "continue"; } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; @@ -26900,17 +27034,21 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_20.text)) { - seen[name_20.text] = currentKind; + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_20); + if (effectiveName === undefined) { + return "continue"; + } + if (!ts.hasProperty(seen, effectiveName)) { + seen[effectiveName] = currentKind; } else { - var existingKind = seen[name_20.text]; + var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - return "continue"; + grammarErrorOnNode(name_20, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_20)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_20.text] = currentKind | existingKind; + seen[effectiveName] = currentKind | existingKind; } else { return { value: grammarErrorOnNode(name_20, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; @@ -35367,7 +35505,7 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : undefined); + var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); if (traceEnabled) { if (containingFile === undefined) { if (rootDir === undefined) { @@ -35870,12 +36008,25 @@ var ts; } } } + function getDefaultTypeDirectiveNames(rootPath) { + var localTypes = ts.combinePaths(rootPath, "types"); + var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); + var result = []; + if (ts.sys.directoryExists(localTypes)) { + result = result.concat(ts.sys.getDirectories(localTypes)); + } + if (ts.sys.directoryExists(npmTypes)) { + result = result.concat(ts.sys.getDirectories(npmTypes)); + } + return result; + } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { + getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -35943,6 +36094,19 @@ var ts; } return resolutions; } + function getDefaultTypeDirectiveNames(options, rootFiles, host) { + if (options.types) { + return options.types; + } + if (host && host.getDefaultTypeDirectiveNames) { + var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + if (commonRoot) { + return host.getDefaultTypeDirectiveNames(commonRoot); + } + } + return undefined; + } + ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -35978,13 +36142,14 @@ var ts; var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { - if (options.types && options.types.length) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(options.types, undefined); - for (var i = 0; i < options.types.length; i++) { - processTypeReferenceDirective(options.types[i], resolutions[i]); + ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + if (typeReferences) { + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, undefined); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); } } - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); if (!skipDefaultLib) { if (!options.lib) { processRootFile(host.getDefaultLibFileName(options), true); @@ -36561,9 +36726,6 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1) { - file_1.wasReferenced = file_1.wasReferenced || isReference; - } return file_1; } var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { @@ -36576,7 +36738,6 @@ var ts; }); filesByName.set(path, file); if (file) { - file.wasReferenced = file.wasReferenced || isReference; file.path = path; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(path); @@ -36677,17 +36838,7 @@ var ts; !options.noResolve && i < file.imports.length; if (shouldAddFile) { - var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); - if (importedFile && resolution.isExternalLibraryImport) { - if (!ts.isExternalModule(importedFile) && importedFile.statements.length) { - var start_5 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); - } - else if (importedFile.referencedFiles.length) { - var firstRef = importedFile.referencedFiles[0]; - fileProcessingDiagnostics.add(ts.createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, ts.Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); - } - } + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } } } @@ -36772,7 +36923,7 @@ var ts; } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substututions_for_pattern_0_should_be_an_array, key)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)); } } } @@ -36821,13 +36972,19 @@ var ts; } else if (firstExternalModuleSourceFile && languageVersion < 2 && options.module === ts.ModuleKind.None) { var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } - if (outFile && options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + if (outFile) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + } + else if (options.module === undefined && firstExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } } if (options.outDir || options.sourceRoot || @@ -37517,7 +37674,7 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; var baseSensitivity = { sensitivity: "base" }; @@ -37550,6 +37707,17 @@ var ts; } } }); + rawItems = ts.filter(rawItems, function (item) { + var decl = item.declaration; + if (decl.kind === 231 || decl.kind === 234 || decl.kind === 229) { + var importer = checker.getSymbolAtLocation(decl.name); + var imported = checker.getAliasedSymbol(importer); + return importer.name !== imported.name; + } + else { + return true; + } + }); rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { rawItems = rawItems.slice(0, maxResultCount); @@ -37892,8 +38060,12 @@ var ts; return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); case 153: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); + case 224: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); case 255: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 222: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); case 151: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); case 152: @@ -39263,7 +39435,7 @@ var ts; } } function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { - for (var i = exclusiveStartPosition - 1; i >= 0; --i) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { if (nodeHasTokens(children[i])) { return children[i]; } @@ -39889,18 +40061,17 @@ var ts; if (!isStarted) { scanner.scan(); } - var t; var pos = scanner.getStartPos(); while (pos < endPos) { - var t_1 = scanner.getToken(); - if (!ts.isTrivia(t_1)) { + var t = scanner.getToken(); + if (!ts.isTrivia(t)) { break; } scanner.scan(); var item = { pos: pos, end: scanner.getStartPos(), - kind: t_1 + kind: t }; pos = scanner.getStartPos(); if (!leadingTrivia) { @@ -41550,7 +41721,7 @@ var ts; else { parts = []; var startPos = commentRange.pos; - for (var line = startLine; line < endLine; ++line) { + for (var line = startLine; line < endLine; line++) { var endOfLine = ts.getEndLinePosition(line, sourceFile); parts.push({ pos: startPos, end: endOfLine }); startPos = ts.getStartPositionOfLine(line + 1, sourceFile); @@ -41568,7 +41739,7 @@ var ts; startLine++; } var delta = indentation - nonWhitespaceColumnInFirstPart.column; - for (var i = startIndex, len = parts.length; i < len; ++i, ++startLine) { + for (var i = startIndex, len = parts.length; i < len; i++, startLine++) { var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart @@ -41584,7 +41755,7 @@ var ts; } } function trimTrailingWhitespacesForLines(line1, line2, range) { - for (var line = line1; line < line2; ++line) { + for (var line = line1; line < line2; line++) { var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var lineEndPosition = ts.getEndLinePosition(line, sourceFile); if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { @@ -41627,7 +41798,6 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { - var between; switch (rule.Operation.Action) { case 1: return; @@ -41657,14 +41827,6 @@ var ts; } } } - function isSomeBlock(kind) { - switch (kind) { - case 199: - case 226: - return true; - } - return false; - } function getOpenTokenForList(node, list) { switch (node.kind) { case 148: @@ -41722,7 +41884,7 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat('\t', tabs); + internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; @@ -41747,7 +41909,7 @@ var ts; } function repeat(value, count) { var s = ""; - for (var i = 0; i < count; ++i) { + for (var i = 0; i < count; i++) { s += value; } return s; @@ -42015,7 +42177,7 @@ var ts; ts.Debug.assert(index >= 0 && index < list.length); var node = list[index]; var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); - for (var i = index - 1; i >= 0; --i) { + for (var i = index - 1; i >= 0; i--) { if (list[i].kind === 24) { continue; } @@ -42034,7 +42196,7 @@ var ts; function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { var character = 0; var column = 0; - for (var pos = startPos; pos < endPos; ++pos) { + for (var pos = startPos; pos < endPos; pos++) { var ch = sourceFile.text.charCodeAt(pos); if (!ts.isWhiteSpace(ch)) { break; @@ -44005,9 +44167,9 @@ var ts; log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); var contextToken = previousToken; if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_6 = new Date().getTime(); + var start_5 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); } var node = currentToken; var isRightOfDot = false; @@ -44234,9 +44396,9 @@ var ts; || contextToken.kind === 166 || contextToken.kind === 10 || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_7 = contextToken.getStart(); + var start_6 = contextToken.getStart(); var end = contextToken.getEnd(); - if (start_7 < position && position < end) { + if (start_6 < position && position < end) { return true; } if (position === end) { @@ -45314,8 +45476,7 @@ var ts; } function getDocumentHighlights(fileName, position, filesToSearch) { synchronizeHostData(); - filesToSearch = ts.map(filesToSearch, ts.normalizeSlashes); - var sourceFilesToSearch = ts.filter(program.getSourceFiles(), function (f) { return ts.contains(filesToSearch, f.fileName); }); + var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingWord(sourceFile, position); if (!node) { @@ -46498,7 +46659,8 @@ var ts; } function getNavigateToItems(searchValue, maxResultCount) { synchronizeHostData(); - return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); + var checker = getProgram().getTypeChecker(); + return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); } function getEmitOutput(fileName) { synchronizeHostData(); @@ -50961,6 +51123,9 @@ var ts; LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () { return this.shimHost.getCurrentDirectory(); }; + LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { + return this.shimHost.getDirectories(path); + }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 84a06001d14..1ac624055d7 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -261,7 +261,7 @@ declare namespace ts { ModuleDeclaration = 225, ModuleBlock = 226, CaseBlock = 227, - GlobalModuleExportDeclaration = 228, + NamespaceExportDeclaration = 228, ImportEqualsDeclaration = 229, ImportDeclaration = 230, ImportClause = 231, @@ -934,7 +934,7 @@ declare namespace ts { interface NamespaceImport extends Declaration { name: Identifier; } - interface GlobalModuleExportDeclaration extends DeclarationStatement { + interface NamespaceExportDeclaration extends DeclarationStatement { name: Identifier; moduleReference: LiteralLikeNode; } @@ -1329,7 +1329,7 @@ declare namespace ts { FunctionScopedVariableExcludes = 107454, BlockScopedVariableExcludes = 107455, ParameterExcludes = 107455, - PropertyExcludes = 107455, + PropertyExcludes = 0, EnumMemberExcludes = 107455, FunctionExcludes = 106927, ClassExcludes = 899519, @@ -1554,6 +1554,7 @@ declare namespace ts { allowJs?: boolean; noImplicitUseStrict?: boolean; strictNullChecks?: boolean; + skipLibCheck?: boolean; listEmittedFiles?: boolean; lib?: string[]; types?: string[]; @@ -1627,6 +1628,7 @@ declare namespace ts { trace?(s: string): void; directoryExists?(directoryName: string): boolean; realpath?(path: string): string; + getCurrentDirectory?(): string; } interface ResolvedModule { resolvedFileName: string; @@ -1650,6 +1652,7 @@ declare namespace ts { getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; + getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; getCanonicalFileName(fileName: string): string; @@ -1693,6 +1696,7 @@ declare namespace ts { createDirectory(path: string): void; getExecutingFilePath(): string; getCurrentDirectory(): string; + getDirectories(path: string): string[]; readDirectory(path: string, extension?: string, exclude?: string[]): string[]; getModifiedTime?(path: string): Date; createHash?(data: string): string; @@ -1812,6 +1816,7 @@ declare namespace ts { function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function getDefaultTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -2345,26 +2350,55 @@ declare namespace ts { namespace ScriptElementKind { const unknown: string; const warning: string; + /** predefined type (void) or keyword (class) */ const keyword: string; + /** top level script node */ const scriptElement: string; + /** module foo {} */ const moduleElement: string; + /** class X {} */ const classElement: string; + /** var x = class X {} */ const localClassElement: string; + /** interface Y {} */ const interfaceElement: string; + /** type T = ... */ const typeElement: string; + /** enum E */ const enumElement: string; + /** + * Inside module and script only + * const v = .. + */ const variableElement: string; + /** Inside function */ const localVariableElement: string; + /** + * Inside module and script only + * function f() { } + */ const functionElement: string; + /** Inside function */ const localFunctionElement: string; + /** class X { [public|private]* foo() {} } */ const memberFunctionElement: string; + /** class X { [public|private]* [get|set] foo:number; } */ const memberGetAccessorElement: string; const memberSetAccessorElement: string; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ const memberVariableElement: string; + /** class X { constructor() { } } */ const constructorImplementationElement: string; + /** interface Y { ():number; } */ const callSignatureElement: string; + /** interface Y { []:number; } */ const indexSignatureElement: string; + /** interface Y { new():Y; } */ const constructSignatureElement: string; + /** function foo(*Y*: string) */ const parameterElement: string; const typeParameterElement: string; const primitiveType: string; diff --git a/lib/typescript.js b/lib/typescript.js index e78eda7b0bb..19fffd35501 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -271,7 +271,7 @@ var ts; SyntaxKind[SyntaxKind["ModuleDeclaration"] = 225] = "ModuleDeclaration"; SyntaxKind[SyntaxKind["ModuleBlock"] = 226] = "ModuleBlock"; SyntaxKind[SyntaxKind["CaseBlock"] = 227] = "CaseBlock"; - SyntaxKind[SyntaxKind["GlobalModuleExportDeclaration"] = 228] = "GlobalModuleExportDeclaration"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 228] = "NamespaceExportDeclaration"; SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 229] = "ImportEqualsDeclaration"; SyntaxKind[SyntaxKind["ImportDeclaration"] = 230] = "ImportDeclaration"; SyntaxKind[SyntaxKind["ImportClause"] = 231] = "ImportClause"; @@ -561,7 +561,7 @@ var ts; // they can not merge with anything in the value space SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; - SymbolFlags[SymbolFlags["PropertyExcludes"] = 107455] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 107455] = "EnumMemberExcludes"; SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; @@ -1841,6 +1841,10 @@ var ts; } return result.sort(); } + function getDirectories(path) { + var folder = fso.GetFolder(path); + return getNames(folder.subfolders); + } function readDirectory(path, extension, exclude) { var result = []; exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); @@ -1895,6 +1899,7 @@ var ts; getCurrentDirectory: function () { return new ActiveXObject("WScript.Shell").CurrentDirectory; }, + getDirectories: getDirectories, readDirectory: readDirectory, exit: function (exitCode) { try { @@ -2057,6 +2062,9 @@ var ts; function directoryExists(path) { return fileSystemEntryExists(path, 1 /* Directory */); } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); }); + } function readDirectory(path, extension, exclude) { var result = []; exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); @@ -2157,6 +2165,7 @@ var ts; getCurrentDirectory: function () { return process.cwd(); }, + getDirectories: getDirectories, readDirectory: readDirectory, getModifiedTime: function (path) { try { @@ -2209,6 +2218,7 @@ var ts; createDirectory: ChakraHost.createDirectory, getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, readDirectory: ChakraHost.readDirectory, exit: ChakraHost.quit, realpath: realpath @@ -2347,7 +2357,7 @@ var ts; or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting__1148", message: "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -2717,6 +2727,8 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, + Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2810,7 +2822,7 @@ var ts; Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character" }, Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character" }, - Substututions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substututions_for_pattern_0_should_be_an_array_5063", message: "Substututions for pattern '{0}' should be an array." }, + Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, @@ -2823,6 +2835,7 @@ var ts; Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, + Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -2924,6 +2937,7 @@ var ts; Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'" }, + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -6172,7 +6186,7 @@ var ts; // export default ... function isAliasSymbolDeclaration(node) { return node.kind === 229 /* ImportEqualsDeclaration */ || - node.kind === 228 /* GlobalModuleExportDeclaration */ || + node.kind === 228 /* NamespaceExportDeclaration */ || node.kind === 231 /* ImportClause */ && !!node.name || node.kind === 232 /* NamespaceImport */ || node.kind === 234 /* ImportSpecifier */ || @@ -6301,7 +6315,7 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 69 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { + if (name.kind === 69 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name.kind === 142 /* Parameter */) { return name.text; } if (name.kind === 140 /* ComputedPropertyName */) { @@ -7773,7 +7787,7 @@ var ts; case 231 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 228 /* GlobalModuleExportDeclaration */: + case 228 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); case 232 /* NamespaceImport */: return visitNode(cbNode, node.name); @@ -12182,7 +12196,7 @@ var ts; return nextToken() === 39 /* SlashToken */; } function parseGlobalModuleExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(228 /* GlobalModuleExportDeclaration */, fullStart); + var exportDeclaration = createNode(228 /* NamespaceExportDeclaration */, fullStart); exportDeclaration.decorators = decorators; exportDeclaration.modifiers = modifiers; parseExpected(116 /* AsKeyword */); @@ -15018,10 +15032,10 @@ var ts; case 145 /* PropertyDeclaration */: case 144 /* PropertySignature */: case 266 /* JSDocRecordMember */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); case 253 /* PropertyAssignment */: case 254 /* ShorthandPropertyAssignment */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); case 255 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); case 247 /* JsxSpreadAttribute */: @@ -15037,7 +15051,7 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); case 220 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 148 /* Constructor */: @@ -15081,8 +15095,8 @@ var ts; case 234 /* ImportSpecifier */: case 238 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - case 228 /* GlobalModuleExportDeclaration */: - return bindGlobalModuleExportDeclaration(node); + case 228 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); case 231 /* ImportClause */: return bindImportClause(node); case 236 /* ExportDeclaration */: @@ -15120,14 +15134,14 @@ var ts; } else if (boundExpression.kind === 69 /* Identifier */ && node.kind === 235 /* ExportAssignment */) { // An export default clause with an identifier exports all meanings of that identifier - declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); } else { // An export default clause with an expression exports a value - declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); } } - function bindGlobalModuleExportDeclaration(node) { + function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } @@ -15186,7 +15200,7 @@ var ts; if (container.kind === 179 /* FunctionExpression */ || container.kind === 220 /* FunctionDeclaration */) { container.symbol.members = container.symbol.members || {}; // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ & ~4 /* Property */); + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } } function bindPrototypePropertyAssignment(node) { @@ -15209,7 +15223,7 @@ var ts; funcSymbol.members = {}; } // Declare the method/property - declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 107455 /* PropertyExcludes */); + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 0 /* PropertyExcludes */); } function bindCallExpression(node) { // We're only inspecting call expressions to detect CommonJS modules, so we can skip @@ -15310,7 +15324,7 @@ var ts; // containing class. if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */); } } function bindFunctionDeclaration(node) { @@ -15696,7 +15710,7 @@ var ts; if (flags & 1 /* FunctionScopedVariable */) result |= 107454 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) - result |= 107455 /* PropertyExcludes */; + result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 107455 /* EnumMemberExcludes */; if (flags & 16 /* Function */) @@ -15982,6 +15996,7 @@ var ts; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; + var isInExternalModule = false; loop: while (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { @@ -16024,6 +16039,7 @@ var ts; case 256 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; + isInExternalModule = true; case 225 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; if (location.kind === 256 /* SourceFile */ || ts.isAmbientModule(location)) { @@ -16207,6 +16223,13 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } + // If we're in an external module, we can't reference symbols created from UMD export declarations + if (result && isInExternalModule) { + var decls = result.declarations; + if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { + error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + } + } } return result; } @@ -16409,7 +16432,7 @@ var ts; return getTargetOfExportSpecifier(node); case 235 /* ExportAssignment */: return getTargetOfExportAssignment(node); - case 228 /* GlobalModuleExportDeclaration */: + case 228 /* NamespaceExportDeclaration */: return getTargetOfGlobalModuleExportDeclaration(node); } } @@ -17883,7 +17906,7 @@ var ts; // assigned by contextual typing. function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function getTextOfPropertyName(name) { switch (name.kind) { @@ -18009,7 +18032,7 @@ var ts; return strictNullChecks && optional ? addNullableKind(type, 32 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration - function getTypeForVariableLikeDeclaration(declaration) { + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 134217728 /* 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 @@ -18035,7 +18058,7 @@ var ts; } // Use type from type annotation if one is present if (declaration.type) { - return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ !!declaration.questionToken); + return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); } if (declaration.kind === 142 /* Parameter */) { var func = declaration.parent; @@ -18056,12 +18079,12 @@ var ts; ? getContextuallyTypedThisType(func) : getContextuallyTypedParameterType(declaration); if (type) { - return addOptionality(type, /*optional*/ !!declaration.questionToken); + return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } } // Use the type of the initializer expression if one is present if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), /*optional*/ !!declaration.questionToken); + return addOptionality(checkExpressionCached(declaration.initializer), /*optional*/ declaration.questionToken && includeOptionality); } // If it is a short-hand property assignment, use the type of the identifier if (declaration.kind === 254 /* ShorthandPropertyAssignment */) { @@ -18155,7 +18178,7 @@ var ts; // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration); + var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); if (type) { if (reportErrors) { reportErrorsFromWidening(declaration, type); @@ -20719,7 +20742,7 @@ var ts; return isIdenticalTo(source, target); } if (!(target.flags & 134217728 /* Never */)) { - if (target.flags & 1 /* Any */) + if (target.flags & 1 /* Any */ || source.flags & 134217728 /* Never */) return -1 /* True */; if (source.flags & 32 /* Undefined */) { if (!strictNullChecks || target.flags & (32 /* Undefined */ | 16 /* Void */) || source === emptyArrayElementType) @@ -20739,7 +20762,7 @@ var ts; if (source.flags & 256 /* StringLiteral */ && target === stringType) return -1 /* True */; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & (1 /* Any */ | 134217728 /* Never */)) + if (source.flags & 1 /* Any */) return -1 /* True */; if (source === numberType && target.flags & 128 /* Enum */) return -1 /* True */; @@ -21634,41 +21657,52 @@ var ts; getSignaturesOfType(type, 0 /* Call */).length === 0 && getSignaturesOfType(type, 1 /* Construct */).length === 0; } + function createTransientSymbol(source, type) { + var symbol = createSymbol(source.flags | 67108864 /* Transient */, source.name); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = {}; + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members[property.name] = updated === original ? property : createTransientSymbol(property, updated); + } + ; + return members; + } + /** + * If the the provided object literal is subject to the excess properties check, + * create a new that is exempt. Recursively mark object literal members as exempt. + * Leave signatures alone since they are not subject to the check. + */ function getRegularTypeOfObjectLiteral(type) { - if (type.flags & 1048576 /* FreshObjectLiteral */) { - var regularType = type.regularType; - if (!regularType) { - regularType = createType(type.flags & ~1048576 /* FreshObjectLiteral */); - regularType.symbol = type.symbol; - regularType.members = type.members; - regularType.properties = type.properties; - regularType.callSignatures = type.callSignatures; - regularType.constructSignatures = type.constructSignatures; - regularType.stringIndexInfo = type.stringIndexInfo; - regularType.numberIndexInfo = type.numberIndexInfo; - type.regularType = regularType; - } + if (!(type.flags & 1048576 /* FreshObjectLiteral */)) { + return type; + } + var regularType = type.regularType; + if (regularType) { return regularType; } - return type; + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags & ~1048576 /* FreshObjectLiteral */; + type.regularType = regularNew; + return regularNew; } function getWidenedTypeOfObjectLiteral(type) { - var properties = getPropertiesOfObjectType(type); - var members = {}; - ts.forEach(properties, function (p) { - var propType = getTypeOfSymbol(p); - var widenedType = getWidenedType(propType); - if (propType !== widenedType) { - var symbol = createSymbol(p.flags | 67108864 /* Transient */, p.name); - symbol.declarations = p.declarations; - symbol.parent = p.parent; - symbol.type = widenedType; - symbol.target = p; - if (p.valueDeclaration) - symbol.valueDeclaration = p.valueDeclaration; - p = symbol; - } - members[p.name] = p; + var members = transformTypeOfMembers(type, function (prop) { + var widened = getWidenedType(prop); + return prop === widened ? prop : widened; }); var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); @@ -23224,7 +23258,7 @@ var ts; } return nodeCheckFlag === 512 /* SuperStatic */ ? getBaseConstructorTypeOfClass(classType) - : baseClassType; + : getTypeWithThisArgument(baseClassType, classType.thisType); function isLegalUsageOfSuperExpression(container) { if (!container) { return false; @@ -25936,7 +25970,7 @@ var ts; var types = void 0; var funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { - types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + types = checkAndAggregateYieldOperandTypes(func, contextualMapper); if (types.length === 0) { var iterableIteratorAny = createIterableIteratorType(anyType); if (compilerOptions.noImplicitAny) { @@ -25946,8 +25980,7 @@ var ts; } } else { - var hasImplicitReturn = !!(func.flags & 32768 /* HasImplicitReturn */); - types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper, isAsync, hasImplicitReturn); + types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { return neverType; } @@ -26001,9 +26034,9 @@ var ts; return widenedType; } } - function checkAndAggregateYieldOperandTypes(body, contextualMapper) { + function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; - ts.forEachYieldExpression(body, function (yieldExpression) { + ts.forEachYieldExpression(func.body, function (yieldExpression) { var expr = yieldExpression.expression; if (expr) { var type = checkExpressionCached(expr, contextualMapper); @@ -26018,10 +26051,12 @@ var ts; }); return aggregatedTypes; } - function checkAndAggregateReturnExpressionTypes(body, contextualMapper, isAsync, hasImplicitReturn) { + function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { + var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasOmittedExpressions = false; - ts.forEachReturnStatement(body, function (returnStatement) { + var hasReturnWithNoExpression = !!(func.flags & 32768 /* HasImplicitReturn */); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; if (expr) { var type = checkExpressionCached(expr, contextualMapper); @@ -26030,20 +26065,24 @@ var ts; // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body should be unwrapped to its awaited type, which should be wrapped in // the native Promise type by the caller. - type = checkAwaitedType(type, body.parent, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type !== neverType && !ts.contains(aggregatedTypes, type)) { + if (type === neverType) { + hasReturnOfTypeNever = true; + } + else if (!ts.contains(aggregatedTypes, type)) { aggregatedTypes.push(type); } } else { - hasOmittedExpressions = true; + hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasOmittedExpressions && !hasImplicitReturn) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || + func.kind === 179 /* FunctionExpression */ || func.kind === 180 /* ArrowFunction */)) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && (hasOmittedExpressions || hasImplicitReturn)) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { if (!ts.contains(aggregatedTypes, undefinedType)) { aggregatedTypes.push(undefinedType); } @@ -26215,8 +26254,14 @@ var ts; if (symbol.flags & 4 /* Property */ && (expr.kind === 172 /* PropertyAccessExpression */ || expr.kind === 173 /* ElementAccessExpression */) && expr.expression.kind === 97 /* ThisKeyword */) { + // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - return !(func && func.kind === 148 /* Constructor */ && func.parent === symbol.valueDeclaration.parent); + if (!(func && func.kind === 148 /* Constructor */)) + return true; + // If func.parent is a class and symbol is a (readonly) property of that class, or + // if func is a constructor and symbol is a (readonly) parameter property declared in it, + // then symbol is writeable here. + return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } @@ -27148,6 +27193,79 @@ var ts; } } } + function checkClassForDuplicateDeclarations(node) { + var getter = 1, setter = 2, property = getter | setter; + var instanceNames = {}; + var staticNames = {}; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param)) { + addName(instanceNames, param.name, param.name.text, property); + } + } + } + else { + var static = ts.forEach(member.modifiers, function (m) { return m.kind === 113 /* StaticKeyword */; }); + var names = static ? staticNames : instanceNames; + var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); + if (memberName) { + switch (member.kind) { + case 149 /* GetAccessor */: + addName(names, member.name, memberName, getter); + break; + case 150 /* SetAccessor */: + addName(names, member.name, memberName, setter); + break; + case 145 /* PropertyDeclaration */: + addName(names, member.name, memberName, property); + break; + } + } + } + } + function addName(names, location, name, meaning) { + if (ts.hasProperty(names, name)) { + var prev = names[name]; + if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names[name] = prev | meaning; + } + } + else { + names[name] = meaning; + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = {}; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind == 144 /* PropertySignature */) { + var memberName = void 0; + switch (member.name.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 69 /* Identifier */: + memberName = member.name.text; + break; + default: + continue; + } + if (ts.hasProperty(names, memberName)) { + error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names[memberName] = true; + } + } + } + } function checkTypeForDuplicateIndexSignatures(node) { if (node.kind === 222 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); @@ -27399,6 +27517,7 @@ var ts; var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); } } function checkArrayType(node) { @@ -28444,6 +28563,10 @@ var ts; if (node.initializer) { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } } if (node.kind !== 145 /* PropertyDeclaration */ && node.kind !== 144 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here @@ -28457,6 +28580,18 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } + function areDeclarationFlagsIdentical(left, right) { + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 /* Private */ | + 16 /* Protected */ | + 256 /* Async */ | + 128 /* Abstract */ | + 64 /* Readonly */ | + 32 /* Static */; + return (left.flags & interestingFlags) === (right.flags & interestingFlags); + } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); return checkVariableLikeDeclaration(node); @@ -29150,6 +29285,7 @@ var ts; var typeWithThis = getTypeWithThisArgument(type); var staticType = getTypeOfSymbol(symbol); checkTypeParameterListsIdentical(node, symbol); + checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { var baseTypes = getBaseTypes(type); @@ -29398,6 +29534,7 @@ var ts; checkIndexConstraints(type); } } + checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { @@ -30241,14 +30378,11 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1 /* TypeChecked */)) { - // Check whether the file has declared it is the default lib, - // and whether the user has specifically chosen to avoid checking it. - if (compilerOptions.skipDefaultLibCheck) { - // If the user specified '--noLib' and a file has a '/// ', - // then we should treat that file as a default lib. - if (node.hasNoDefaultLib) { - return; - } + // If skipLibCheck is enabled, skip type checking if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip type checking if file contains a + // '/// ' directive. + if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + return; } // Grammar checking checkGrammarSourceFile(node); @@ -30665,7 +30799,7 @@ var ts; return symbol && getTypeOfSymbol(symbol); } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -31204,7 +31338,7 @@ var ts; if (file.moduleAugmentations.length) { (augmentations || (augmentations = [])).push(file.moduleAugmentations); } - if (file.wasReferenced && file.symbol && file.symbol.globalExports) { + if (file.symbol && file.symbol.globalExports) { mergeSymbolTable(globals, file.symbol.globalExports); } }); @@ -31787,7 +31921,6 @@ var ts; name_20.kind === 140 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name_20); - return "continue"; } if (prop.kind === 254 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern @@ -31829,17 +31962,21 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_20.text)) { - seen[name_20.text] = currentKind; + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_20); + if (effectiveName === undefined) { + return "continue"; + } + if (!ts.hasProperty(seen, effectiveName)) { + seen[effectiveName] = currentKind; } else { - var existingKind = seen[name_20.text]; + var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - return "continue"; + grammarErrorOnNode(name_20, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_20)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_20.text] = currentKind | existingKind; + seen[effectiveName] = currentKind | existingKind; } else { return { value: grammarErrorOnNode(name_20, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; @@ -41638,8 +41775,8 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - // use typesRoot and fallback to directory that contains tsconfig if typesRoot is not set - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : undefined); + // use typesRoot and fallback to directory that contains tsconfig or current directory if typesRoot is not set + var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); if (traceEnabled) { if (containingFile === undefined) { if (rootDir === undefined) { @@ -42229,12 +42366,25 @@ var ts; } } } + function getDefaultTypeDirectiveNames(rootPath) { + var localTypes = ts.combinePaths(rootPath, "types"); + var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); + var result = []; + if (ts.sys.directoryExists(localTypes)) { + result = result.concat(ts.sys.getDirectories(localTypes)); + } + if (ts.sys.directoryExists(npmTypes)) { + result = result.concat(ts.sys.getDirectories(npmTypes)); + } + return result; + } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { + getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -42302,6 +42452,21 @@ var ts; } return resolutions; } + function getDefaultTypeDirectiveNames(options, rootFiles, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // or load all types from the automatic type import fields + if (host && host.getDefaultTypeDirectiveNames) { + var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + if (commonRoot) { + return host.getDefaultTypeDirectiveNames(commonRoot); + } + } + return undefined; + } + ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -42340,14 +42505,15 @@ var ts; // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument - if (options.types && options.types.length) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(options.types, /*containingFile*/ undefined); - for (var i = 0; i < options.types.length; i++) { - processTypeReferenceDirective(options.types[i], resolutions[i]); + var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + if (typeReferences) { + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, /*containingFile*/ undefined); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); } } - ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // Do not process the default library if: // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in @@ -42999,9 +43165,6 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1) { - file_1.wasReferenced = file_1.wasReferenced || isReference; - } return file_1; } // We haven't looked for this file, do so now and cache result @@ -43015,7 +43178,6 @@ var ts; }); filesByName.set(path, file); if (file) { - file.wasReferenced = file.wasReferenced || isReference; file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -43129,19 +43291,7 @@ var ts; !options.noResolve && i < file.imports.length; if (shouldAddFile) { - var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); - if (importedFile && resolution.isExternalLibraryImport) { - // Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files, - // this check is ok. Otherwise this would be never true for javascript file - if (!ts.isExternalModule(importedFile) && importedFile.statements.length) { - var start_5 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); - } - else if (importedFile.referencedFiles.length) { - var firstRef = importedFile.referencedFiles[0]; - fileProcessingDiagnostics.add(ts.createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, ts.Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); - } - } + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } } } @@ -43227,7 +43377,7 @@ var ts; } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substututions_for_pattern_0_should_be_an_array, key)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)); } } } @@ -43278,15 +43428,21 @@ var ts; else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen target of es6 when below es6 if (options.module === ts.ModuleKind.ES6 && languageVersion < 2 /* ES6 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile && options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + if (outFile) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + } + else if (options.module === undefined && firstExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted @@ -43384,6 +43540,11 @@ var ts; type: "boolean", description: ts.Diagnostics.Print_this_message }, + { + name: "help", + shortName: "?", + type: "boolean" + }, { name: "init", type: "boolean", @@ -43486,6 +43647,11 @@ var ts; name: "skipDefaultLibCheck", type: "boolean" }, + { + name: "skipLibCheck", + type: "boolean", + description: ts.Diagnostics.Skip_type_checking_of_declaration_files + }, { name: "out", type: "string", @@ -44315,7 +44481,7 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; // This means "compare in a case insensitive manner." @@ -44354,6 +44520,18 @@ var ts; } } }); + // Remove imports when the imported declaration is already in the list and has the same name. + rawItems = ts.filter(rawItems, function (item) { + var decl = item.declaration; + if (decl.kind === 231 /* ImportClause */ || decl.kind === 234 /* ImportSpecifier */ || decl.kind === 229 /* ImportEqualsDeclaration */) { + var importer = checker.getSymbolAtLocation(decl.name); + var imported = checker.getAliasedSymbol(importer); + return importer.name !== imported.name; + } + else { + return true; + } + }); rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { rawItems = rawItems.slice(0, maxResultCount); @@ -44752,8 +44930,12 @@ var ts; return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); case 153 /* IndexSignature */: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); + case 224 /* EnumDeclaration */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); case 255 /* EnumMember */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 222 /* InterfaceDeclaration */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); case 151 /* CallSignature */: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); case 152 /* ConstructSignature */: @@ -45714,7 +45896,7 @@ var ts; // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it // will return the generic identifier that started the expression (e.g. "foo" in "foo= 0; --i) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { if (nodeHasTokens(children[i])) { return children[i]; } @@ -47337,12 +47519,11 @@ var ts; if (!isStarted) { scanner.scan(); } - var t; var pos = scanner.getStartPos(); // Read leading trivia and token while (pos < endPos) { - var t_1 = scanner.getToken(); - if (!ts.isTrivia(t_1)) { + var t = scanner.getToken(); + if (!ts.isTrivia(t)) { break; } // consume leading trivia @@ -47350,7 +47531,7 @@ var ts; var item = { pos: pos, end: scanner.getStartPos(), - kind: t_1 + kind: t }; pos = scanner.getStartPos(); if (!leadingTrivia) { @@ -47690,6 +47871,7 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// +/* tslint:disable:no-null-keyword */ /* @internal */ var ts; (function (ts) { @@ -47951,7 +48133,7 @@ var ts; this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2 /* Space */)); this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8 /* Delete */)); // Open Brace braces after function - //TypeScript: Function can have return types, which can be made of tons of different token kinds + // TypeScript: Function can have return types, which can be made of tons of different token kinds this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Open Brace braces after TypeScript module/class/interface this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); @@ -48092,17 +48274,17 @@ var ts; case 220 /* FunctionDeclaration */: case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - //case SyntaxKind.MemberFunctionDeclaration: + // case SyntaxKind.MemberFunctionDeclaration: case 149 /* GetAccessor */: case 150 /* SetAccessor */: - ///case SyntaxKind.MethodSignature: + // case SyntaxKind.MethodSignature: case 151 /* CallSignature */: case 179 /* FunctionExpression */: case 148 /* Constructor */: case 180 /* ArrowFunction */: - //case SyntaxKind.ConstructorDeclaration: - //case SyntaxKind.SimpleArrowFunctionExpression: - //case SyntaxKind.ParenthesizedArrowFunctionExpression: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: case 222 /* InterfaceDeclaration */: return true; } @@ -48254,6 +48436,7 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// +/* tslint:disable:no-null-keyword */ /* @internal */ var ts; (function (ts) { @@ -48271,9 +48454,9 @@ var ts; }; RulesMap.prototype.Initialize = function (rules) { this.mapRowLength = 138 /* LastToken */ + 1; - this.map = new Array(this.mapRowLength * this.mapRowLength); //new Array(this.mapRowLength * this.mapRowLength); + this.map = new Array(this.mapRowLength * this.mapRowLength); // new Array(this.mapRowLength * this.mapRowLength); // This array is used only during construction of the rulesbucket in the map - var rulesBucketConstructionStateList = new Array(this.map.length); //new Array(this.map.length); + var rulesBucketConstructionStateList = new Array(this.map.length); // new Array(this.map.length); this.FillRules(rules, rulesBucketConstructionStateList); return this.map; }; @@ -48285,7 +48468,7 @@ var ts; }; RulesMap.prototype.GetRuleBucketIndex = function (row, column) { var rulesBucketIndex = (row * this.mapRowLength) + column; - //Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array."); + // Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array."); return rulesBucketIndex; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { @@ -48537,6 +48720,7 @@ var ts; /// /// /// +/* tslint:disable:no-null-keyword */ /* @internal */ var ts; (function (ts) { @@ -49058,7 +49242,7 @@ var ts; // if there are any tokens that logically belong to node and interleave child nodes // such tokens will be consumed in processChildNode for for the child that follows them ts.forEachChild(node, function (child) { - processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListElement*/ false); + processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, function (nodes) { processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); }); @@ -49149,7 +49333,7 @@ var ts; var inheritedIndentation = -1 /* Unknown */; for (var i = 0; i < nodes.length; i++) { var child = nodes[i]; - inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true, /*isFirstListItem*/ i === 0); + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } if (listEndToken !== 0 /* Unknown */) { if (formattingScanner.isOnToken()) { @@ -49279,7 +49463,7 @@ var ts; // Handle the case where the next line is moved to be the end of this line. // In this case we don't indent the next line in the next pass. if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAdded*/ false); + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); } } else if (rule.Operation.Action & 4 /* NewLine */ && currentStartLine === previousStartLine) { @@ -49288,7 +49472,7 @@ var ts; // In this case we indent token2 in the next pass but we set // sameLineIndent flag to notify the indenter that the indentation is within the line. if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAdded*/ true); + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line @@ -49336,7 +49520,7 @@ var ts; else { parts = []; var startPos = commentRange.pos; - for (var line = startLine; line < endLine; ++line) { + for (var line = startLine; line < endLine; line++) { var endOfLine = ts.getEndLinePosition(line, sourceFile); parts.push({ pos: startPos, end: endOfLine }); startPos = ts.getStartPositionOfLine(line + 1, sourceFile); @@ -49355,7 +49539,7 @@ var ts; } // shift all parts on the delta size var delta = indentation - nonWhitespaceColumnInFirstPart.column; - for (var i = startIndex, len = parts.length; i < len; ++i, ++startLine) { + for (var i = startIndex, len = parts.length; i < len; i++, startLine++) { var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart @@ -49371,7 +49555,7 @@ var ts; } } function trimTrailingWhitespacesForLines(line1, line2, range) { - for (var line = line1; line < line2; ++line) { + for (var line = line1; line < line2; line++) { var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var lineEndPosition = ts.getEndLinePosition(line, sourceFile); // do not trim whitespaces in comments or template expression @@ -49422,7 +49606,6 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { - var between; switch (rule.Operation.Action) { case 1 /* Ignore */: // no action required @@ -49459,14 +49642,6 @@ var ts; } } } - function isSomeBlock(kind) { - switch (kind) { - case 199 /* Block */: - case 226 /* ModuleBlock */: - return true; - } - return false; - } function getOpenTokenForList(node, list) { switch (node.kind) { case 148 /* Constructor */: @@ -49525,7 +49700,7 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat('\t', tabs); + internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; @@ -49550,7 +49725,7 @@ var ts; } function repeat(value, count) { var s = ""; - for (var i = 0; i < count; ++i) { + for (var i = 0; i < count; i++) { s += value; } return s; @@ -49866,7 +50041,7 @@ var ts; // walk toward the start of the list starting from current node and check if the line is the same for all items. // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); - for (var i = index - 1; i >= 0; --i) { + for (var i = index - 1; i >= 0; i--) { if (list[i].kind === 24 /* CommaToken */) { continue; } @@ -49893,7 +50068,7 @@ var ts; function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { var character = 0; var column = 0; - for (var pos = startPos; pos < endPos; ++pos) { + for (var pos = startPos; pos < endPos; pos++) { var ch = sourceFile.text.charCodeAt(pos); if (!ts.isWhiteSpace(ch)) { break; @@ -49987,7 +50162,7 @@ var ts; Function returns true when the parent node should indent the given child by an explicit rule */ function shouldIndentChildNode(parent, child) { - return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); + return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); @@ -50809,49 +50984,55 @@ var ts; (function (ScriptElementKind) { ScriptElementKind.unknown = ""; ScriptElementKind.warning = "warning"; - // predefined type (void) or keyword (class) + /** predefined type (void) or keyword (class) */ ScriptElementKind.keyword = "keyword"; - // top level script node + /** top level script node */ ScriptElementKind.scriptElement = "script"; - // module foo {} + /** module foo {} */ ScriptElementKind.moduleElement = "module"; - // class X {} + /** class X {} */ ScriptElementKind.classElement = "class"; - // var x = class X {} + /** var x = class X {} */ ScriptElementKind.localClassElement = "local class"; - // interface Y {} + /** interface Y {} */ ScriptElementKind.interfaceElement = "interface"; - // type T = ... + /** type T = ... */ ScriptElementKind.typeElement = "type"; - // enum E + /** enum E */ ScriptElementKind.enumElement = "enum"; - // Inside module and script only - // const v = .. + /** + * Inside module and script only + * const v = .. + */ ScriptElementKind.variableElement = "var"; - // Inside function + /** Inside function */ ScriptElementKind.localVariableElement = "local var"; - // Inside module and script only - // function f() { } + /** + * Inside module and script only + * function f() { } + */ ScriptElementKind.functionElement = "function"; - // Inside function + /** Inside function */ ScriptElementKind.localFunctionElement = "local function"; - // class X { [public|private]* foo() {} } + /** class X { [public|private]* foo() {} } */ ScriptElementKind.memberFunctionElement = "method"; - // class X { [public|private]* [get|set] foo:number; } + /** class X { [public|private]* [get|set] foo:number; } */ ScriptElementKind.memberGetAccessorElement = "getter"; ScriptElementKind.memberSetAccessorElement = "setter"; - // class X { [public|private]* foo:number; } - // interface Y { foo:number; } + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ ScriptElementKind.memberVariableElement = "property"; - // class X { constructor() { } } + /** class X { constructor() { } } */ ScriptElementKind.constructorImplementationElement = "constructor"; - // interface Y { ():number; } + /** interface Y { ():number; } */ ScriptElementKind.callSignatureElement = "call"; - // interface Y { []:number; } + /** interface Y { []:number; } */ ScriptElementKind.indexSignatureElement = "index"; - // interface Y { new():Y; } + /** interface Y { new():Y; } */ ScriptElementKind.constructSignatureElement = "construct"; - // function foo(*Y*: string) + /** function foo(*Y*: string) */ ScriptElementKind.parameterElement = "parameter"; ScriptElementKind.typeParameterElement = "type parameter"; ScriptElementKind.primitiveType = "primitive type"; @@ -52236,9 +52417,9 @@ var ts; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_6 = new Date().getTime(); + var start_5 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -52518,13 +52699,13 @@ var ts; || contextToken.kind === 166 /* StringLiteralType */ || contextToken.kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_7 = contextToken.getStart(); + var start_6 = contextToken.getStart(); var end = contextToken.getEnd(); // To be "in" one of these literals, the position has to be: // 1. entirely within the token text. // 2. at the end position of an unterminated token. // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). - if (start_7 < position && position < end) { + if (start_6 < position && position < end) { return true; } if (position === end) { @@ -53759,8 +53940,7 @@ var ts; } function getDocumentHighlights(fileName, position, filesToSearch) { synchronizeHostData(); - filesToSearch = ts.map(filesToSearch, ts.normalizeSlashes); - var sourceFilesToSearch = ts.filter(program.getSourceFiles(), function (f) { return ts.contains(filesToSearch, f.fileName); }); + var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingWord(sourceFile, position); if (!node) { @@ -55150,7 +55330,8 @@ var ts; /// NavigateTo function getNavigateToItems(searchValue, maxResultCount) { synchronizeHostData(); - return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); + var checker = getProgram().getTypeChecker(); + return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); } function getEmitOutput(fileName) { synchronizeHostData(); @@ -57559,6 +57740,9 @@ var ts; LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () { return this.shimHost.getCurrentDirectory(); }; + LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { + return this.shimHost.getDirectories(path); + }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index cd459201d8b..67530e211bc 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -261,7 +261,7 @@ declare namespace ts { ModuleDeclaration = 225, ModuleBlock = 226, CaseBlock = 227, - GlobalModuleExportDeclaration = 228, + NamespaceExportDeclaration = 228, ImportEqualsDeclaration = 229, ImportDeclaration = 230, ImportClause = 231, @@ -934,7 +934,7 @@ declare namespace ts { interface NamespaceImport extends Declaration { name: Identifier; } - interface GlobalModuleExportDeclaration extends DeclarationStatement { + interface NamespaceExportDeclaration extends DeclarationStatement { name: Identifier; moduleReference: LiteralLikeNode; } @@ -1329,7 +1329,7 @@ declare namespace ts { FunctionScopedVariableExcludes = 107454, BlockScopedVariableExcludes = 107455, ParameterExcludes = 107455, - PropertyExcludes = 107455, + PropertyExcludes = 0, EnumMemberExcludes = 107455, FunctionExcludes = 106927, ClassExcludes = 899519, @@ -1554,6 +1554,7 @@ declare namespace ts { allowJs?: boolean; noImplicitUseStrict?: boolean; strictNullChecks?: boolean; + skipLibCheck?: boolean; listEmittedFiles?: boolean; lib?: string[]; types?: string[]; @@ -1627,6 +1628,7 @@ declare namespace ts { trace?(s: string): void; directoryExists?(directoryName: string): boolean; realpath?(path: string): string; + getCurrentDirectory?(): string; } interface ResolvedModule { resolvedFileName: string; @@ -1650,6 +1652,7 @@ declare namespace ts { getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; + getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; getCanonicalFileName(fileName: string): string; @@ -1693,6 +1696,7 @@ declare namespace ts { createDirectory(path: string): void; getExecutingFilePath(): string; getCurrentDirectory(): string; + getDirectories(path: string): string[]; readDirectory(path: string, extension?: string, exclude?: string[]): string[]; getModifiedTime?(path: string): Date; createHash?(data: string): string; @@ -1812,6 +1816,7 @@ declare namespace ts { function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function getDefaultTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -2345,26 +2350,55 @@ declare namespace ts { namespace ScriptElementKind { const unknown: string; const warning: string; + /** predefined type (void) or keyword (class) */ const keyword: string; + /** top level script node */ const scriptElement: string; + /** module foo {} */ const moduleElement: string; + /** class X {} */ const classElement: string; + /** var x = class X {} */ const localClassElement: string; + /** interface Y {} */ const interfaceElement: string; + /** type T = ... */ const typeElement: string; + /** enum E */ const enumElement: string; + /** + * Inside module and script only + * const v = .. + */ const variableElement: string; + /** Inside function */ const localVariableElement: string; + /** + * Inside module and script only + * function f() { } + */ const functionElement: string; + /** Inside function */ const localFunctionElement: string; + /** class X { [public|private]* foo() {} } */ const memberFunctionElement: string; + /** class X { [public|private]* [get|set] foo:number; } */ const memberGetAccessorElement: string; const memberSetAccessorElement: string; + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ const memberVariableElement: string; + /** class X { constructor() { } } */ const constructorImplementationElement: string; + /** interface Y { ():number; } */ const callSignatureElement: string; + /** interface Y { []:number; } */ const indexSignatureElement: string; + /** interface Y { new():Y; } */ const constructSignatureElement: string; + /** function foo(*Y*: string) */ const parameterElement: string; const typeParameterElement: string; const primitiveType: string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index e78eda7b0bb..19fffd35501 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -271,7 +271,7 @@ var ts; SyntaxKind[SyntaxKind["ModuleDeclaration"] = 225] = "ModuleDeclaration"; SyntaxKind[SyntaxKind["ModuleBlock"] = 226] = "ModuleBlock"; SyntaxKind[SyntaxKind["CaseBlock"] = 227] = "CaseBlock"; - SyntaxKind[SyntaxKind["GlobalModuleExportDeclaration"] = 228] = "GlobalModuleExportDeclaration"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 228] = "NamespaceExportDeclaration"; SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 229] = "ImportEqualsDeclaration"; SyntaxKind[SyntaxKind["ImportDeclaration"] = 230] = "ImportDeclaration"; SyntaxKind[SyntaxKind["ImportClause"] = 231] = "ImportClause"; @@ -561,7 +561,7 @@ var ts; // they can not merge with anything in the value space SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; - SymbolFlags[SymbolFlags["PropertyExcludes"] = 107455] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 107455] = "EnumMemberExcludes"; SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; @@ -1841,6 +1841,10 @@ var ts; } return result.sort(); } + function getDirectories(path) { + var folder = fso.GetFolder(path); + return getNames(folder.subfolders); + } function readDirectory(path, extension, exclude) { var result = []; exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); @@ -1895,6 +1899,7 @@ var ts; getCurrentDirectory: function () { return new ActiveXObject("WScript.Shell").CurrentDirectory; }, + getDirectories: getDirectories, readDirectory: readDirectory, exit: function (exitCode) { try { @@ -2057,6 +2062,9 @@ var ts; function directoryExists(path) { return fileSystemEntryExists(path, 1 /* Directory */); } + function getDirectories(path) { + return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); }); + } function readDirectory(path, extension, exclude) { var result = []; exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); @@ -2157,6 +2165,7 @@ var ts; getCurrentDirectory: function () { return process.cwd(); }, + getDirectories: getDirectories, readDirectory: readDirectory, getModifiedTime: function (path) { try { @@ -2209,6 +2218,7 @@ var ts; createDirectory: ChakraHost.createDirectory, getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + getDirectories: ChakraHost.getDirectories, readDirectory: ChakraHost.readDirectory, exit: ChakraHost.quit, realpath: realpath @@ -2347,7 +2357,7 @@ var ts; or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting__1148", message: "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" }, new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" }, @@ -2717,6 +2727,8 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, + Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2810,7 +2822,7 @@ var ts; Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character" }, Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character" }, - Substututions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substututions_for_pattern_0_should_be_an_array_5063", message: "Substututions for pattern '{0}' should be an array." }, + Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, @@ -2823,6 +2835,7 @@ var ts; Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, + Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" }, Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, @@ -2924,6 +2937,7 @@ var ts; Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'" }, + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -6172,7 +6186,7 @@ var ts; // export default ... function isAliasSymbolDeclaration(node) { return node.kind === 229 /* ImportEqualsDeclaration */ || - node.kind === 228 /* GlobalModuleExportDeclaration */ || + node.kind === 228 /* NamespaceExportDeclaration */ || node.kind === 231 /* ImportClause */ && !!node.name || node.kind === 232 /* NamespaceImport */ || node.kind === 234 /* ImportSpecifier */ || @@ -6301,7 +6315,7 @@ var ts; } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 69 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { + if (name.kind === 69 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name.kind === 142 /* Parameter */) { return name.text; } if (name.kind === 140 /* ComputedPropertyName */) { @@ -7773,7 +7787,7 @@ var ts; case 231 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 228 /* GlobalModuleExportDeclaration */: + case 228 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); case 232 /* NamespaceImport */: return visitNode(cbNode, node.name); @@ -12182,7 +12196,7 @@ var ts; return nextToken() === 39 /* SlashToken */; } function parseGlobalModuleExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(228 /* GlobalModuleExportDeclaration */, fullStart); + var exportDeclaration = createNode(228 /* NamespaceExportDeclaration */, fullStart); exportDeclaration.decorators = decorators; exportDeclaration.modifiers = modifiers; parseExpected(116 /* AsKeyword */); @@ -15018,10 +15032,10 @@ var ts; case 145 /* PropertyDeclaration */: case 144 /* PropertySignature */: case 266 /* JSDocRecordMember */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); case 253 /* PropertyAssignment */: case 254 /* ShorthandPropertyAssignment */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); case 255 /* EnumMember */: return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); case 247 /* JsxSpreadAttribute */: @@ -15037,7 +15051,7 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); case 220 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 148 /* Constructor */: @@ -15081,8 +15095,8 @@ var ts; case 234 /* ImportSpecifier */: case 238 /* ExportSpecifier */: return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - case 228 /* GlobalModuleExportDeclaration */: - return bindGlobalModuleExportDeclaration(node); + case 228 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); case 231 /* ImportClause */: return bindImportClause(node); case 236 /* ExportDeclaration */: @@ -15120,14 +15134,14 @@ var ts; } else if (boundExpression.kind === 69 /* Identifier */ && node.kind === 235 /* ExportAssignment */) { // An export default clause with an identifier exports all meanings of that identifier - declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); } else { // An export default clause with an expression exports a value - declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); } } - function bindGlobalModuleExportDeclaration(node) { + function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } @@ -15186,7 +15200,7 @@ var ts; if (container.kind === 179 /* FunctionExpression */ || container.kind === 220 /* FunctionDeclaration */) { container.symbol.members = container.symbol.members || {}; // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ & ~4 /* Property */); + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); } } function bindPrototypePropertyAssignment(node) { @@ -15209,7 +15223,7 @@ var ts; funcSymbol.members = {}; } // Declare the method/property - declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 107455 /* PropertyExcludes */); + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 0 /* PropertyExcludes */); } function bindCallExpression(node) { // We're only inspecting call expressions to detect CommonJS modules, so we can skip @@ -15310,7 +15324,7 @@ var ts; // containing class. if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */); } } function bindFunctionDeclaration(node) { @@ -15696,7 +15710,7 @@ var ts; if (flags & 1 /* FunctionScopedVariable */) result |= 107454 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) - result |= 107455 /* PropertyExcludes */; + result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 107455 /* EnumMemberExcludes */; if (flags & 16 /* Function */) @@ -15982,6 +15996,7 @@ var ts; var propertyWithInvalidInitializer; var errorLocation = location; var grandparent; + var isInExternalModule = false; loop: while (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { @@ -16024,6 +16039,7 @@ var ts; case 256 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; + isInExternalModule = true; case 225 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; if (location.kind === 256 /* SourceFile */ || ts.isAmbientModule(location)) { @@ -16207,6 +16223,13 @@ var ts; checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } + // If we're in an external module, we can't reference symbols created from UMD export declarations + if (result && isInExternalModule) { + var decls = result.declarations; + if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { + error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + } + } } return result; } @@ -16409,7 +16432,7 @@ var ts; return getTargetOfExportSpecifier(node); case 235 /* ExportAssignment */: return getTargetOfExportAssignment(node); - case 228 /* GlobalModuleExportDeclaration */: + case 228 /* NamespaceExportDeclaration */: return getTargetOfGlobalModuleExportDeclaration(node); } } @@ -17883,7 +17906,7 @@ var ts; // assigned by contextual typing. function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function getTextOfPropertyName(name) { switch (name.kind) { @@ -18009,7 +18032,7 @@ var ts; return strictNullChecks && optional ? addNullableKind(type, 32 /* Undefined */) : type; } // Return the inferred type for a variable, parameter, or property declaration - function getTypeForVariableLikeDeclaration(declaration) { + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 134217728 /* 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 @@ -18035,7 +18058,7 @@ var ts; } // Use type from type annotation if one is present if (declaration.type) { - return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ !!declaration.questionToken); + return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); } if (declaration.kind === 142 /* Parameter */) { var func = declaration.parent; @@ -18056,12 +18079,12 @@ var ts; ? getContextuallyTypedThisType(func) : getContextuallyTypedParameterType(declaration); if (type) { - return addOptionality(type, /*optional*/ !!declaration.questionToken); + return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); } } // Use the type of the initializer expression if one is present if (declaration.initializer) { - return addOptionality(checkExpressionCached(declaration.initializer), /*optional*/ !!declaration.questionToken); + return addOptionality(checkExpressionCached(declaration.initializer), /*optional*/ declaration.questionToken && includeOptionality); } // If it is a short-hand property assignment, use the type of the identifier if (declaration.kind === 254 /* ShorthandPropertyAssignment */) { @@ -18155,7 +18178,7 @@ var ts; // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration); + var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); if (type) { if (reportErrors) { reportErrorsFromWidening(declaration, type); @@ -20719,7 +20742,7 @@ var ts; return isIdenticalTo(source, target); } if (!(target.flags & 134217728 /* Never */)) { - if (target.flags & 1 /* Any */) + if (target.flags & 1 /* Any */ || source.flags & 134217728 /* Never */) return -1 /* True */; if (source.flags & 32 /* Undefined */) { if (!strictNullChecks || target.flags & (32 /* Undefined */ | 16 /* Void */) || source === emptyArrayElementType) @@ -20739,7 +20762,7 @@ var ts; if (source.flags & 256 /* StringLiteral */ && target === stringType) return -1 /* True */; if (relation === assignableRelation || relation === comparableRelation) { - if (source.flags & (1 /* Any */ | 134217728 /* Never */)) + if (source.flags & 1 /* Any */) return -1 /* True */; if (source === numberType && target.flags & 128 /* Enum */) return -1 /* True */; @@ -21634,41 +21657,52 @@ var ts; getSignaturesOfType(type, 0 /* Call */).length === 0 && getSignaturesOfType(type, 1 /* Construct */).length === 0; } + function createTransientSymbol(source, type) { + var symbol = createSymbol(source.flags | 67108864 /* Transient */, source.name); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = {}; + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members[property.name] = updated === original ? property : createTransientSymbol(property, updated); + } + ; + return members; + } + /** + * If the the provided object literal is subject to the excess properties check, + * create a new that is exempt. Recursively mark object literal members as exempt. + * Leave signatures alone since they are not subject to the check. + */ function getRegularTypeOfObjectLiteral(type) { - if (type.flags & 1048576 /* FreshObjectLiteral */) { - var regularType = type.regularType; - if (!regularType) { - regularType = createType(type.flags & ~1048576 /* FreshObjectLiteral */); - regularType.symbol = type.symbol; - regularType.members = type.members; - regularType.properties = type.properties; - regularType.callSignatures = type.callSignatures; - regularType.constructSignatures = type.constructSignatures; - regularType.stringIndexInfo = type.stringIndexInfo; - regularType.numberIndexInfo = type.numberIndexInfo; - type.regularType = regularType; - } + if (!(type.flags & 1048576 /* FreshObjectLiteral */)) { + return type; + } + var regularType = type.regularType; + if (regularType) { return regularType; } - return type; + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags & ~1048576 /* FreshObjectLiteral */; + type.regularType = regularNew; + return regularNew; } function getWidenedTypeOfObjectLiteral(type) { - var properties = getPropertiesOfObjectType(type); - var members = {}; - ts.forEach(properties, function (p) { - var propType = getTypeOfSymbol(p); - var widenedType = getWidenedType(propType); - if (propType !== widenedType) { - var symbol = createSymbol(p.flags | 67108864 /* Transient */, p.name); - symbol.declarations = p.declarations; - symbol.parent = p.parent; - symbol.type = widenedType; - symbol.target = p; - if (p.valueDeclaration) - symbol.valueDeclaration = p.valueDeclaration; - p = symbol; - } - members[p.name] = p; + var members = transformTypeOfMembers(type, function (prop) { + var widened = getWidenedType(prop); + return prop === widened ? prop : widened; }); var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); @@ -23224,7 +23258,7 @@ var ts; } return nodeCheckFlag === 512 /* SuperStatic */ ? getBaseConstructorTypeOfClass(classType) - : baseClassType; + : getTypeWithThisArgument(baseClassType, classType.thisType); function isLegalUsageOfSuperExpression(container) { if (!container) { return false; @@ -25936,7 +25970,7 @@ var ts; var types = void 0; var funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { - types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + types = checkAndAggregateYieldOperandTypes(func, contextualMapper); if (types.length === 0) { var iterableIteratorAny = createIterableIteratorType(anyType); if (compilerOptions.noImplicitAny) { @@ -25946,8 +25980,7 @@ var ts; } } else { - var hasImplicitReturn = !!(func.flags & 32768 /* HasImplicitReturn */); - types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper, isAsync, hasImplicitReturn); + types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { return neverType; } @@ -26001,9 +26034,9 @@ var ts; return widenedType; } } - function checkAndAggregateYieldOperandTypes(body, contextualMapper) { + function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; - ts.forEachYieldExpression(body, function (yieldExpression) { + ts.forEachYieldExpression(func.body, function (yieldExpression) { var expr = yieldExpression.expression; if (expr) { var type = checkExpressionCached(expr, contextualMapper); @@ -26018,10 +26051,12 @@ var ts; }); return aggregatedTypes; } - function checkAndAggregateReturnExpressionTypes(body, contextualMapper, isAsync, hasImplicitReturn) { + function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { + var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasOmittedExpressions = false; - ts.forEachReturnStatement(body, function (returnStatement) { + var hasReturnWithNoExpression = !!(func.flags & 32768 /* HasImplicitReturn */); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; if (expr) { var type = checkExpressionCached(expr, contextualMapper); @@ -26030,20 +26065,24 @@ var ts; // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body should be unwrapped to its awaited type, which should be wrapped in // the native Promise type by the caller. - type = checkAwaitedType(type, body.parent, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } - if (type !== neverType && !ts.contains(aggregatedTypes, type)) { + if (type === neverType) { + hasReturnOfTypeNever = true; + } + else if (!ts.contains(aggregatedTypes, type)) { aggregatedTypes.push(type); } } else { - hasOmittedExpressions = true; + hasReturnWithNoExpression = true; } }); - if (aggregatedTypes.length === 0 && !hasOmittedExpressions && !hasImplicitReturn) { + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || + func.kind === 179 /* FunctionExpression */ || func.kind === 180 /* ArrowFunction */)) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && (hasOmittedExpressions || hasImplicitReturn)) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { if (!ts.contains(aggregatedTypes, undefinedType)) { aggregatedTypes.push(undefinedType); } @@ -26215,8 +26254,14 @@ var ts; if (symbol.flags & 4 /* Property */ && (expr.kind === 172 /* PropertyAccessExpression */ || expr.kind === 173 /* ElementAccessExpression */) && expr.expression.kind === 97 /* ThisKeyword */) { + // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - return !(func && func.kind === 148 /* Constructor */ && func.parent === symbol.valueDeclaration.parent); + if (!(func && func.kind === 148 /* Constructor */)) + return true; + // If func.parent is a class and symbol is a (readonly) property of that class, or + // if func is a constructor and symbol is a (readonly) parameter property declared in it, + // then symbol is writeable here. + return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); } return true; } @@ -27148,6 +27193,79 @@ var ts; } } } + function checkClassForDuplicateDeclarations(node) { + var getter = 1, setter = 2, property = getter | setter; + var instanceNames = {}; + var staticNames = {}; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param)) { + addName(instanceNames, param.name, param.name.text, property); + } + } + } + else { + var static = ts.forEach(member.modifiers, function (m) { return m.kind === 113 /* StaticKeyword */; }); + var names = static ? staticNames : instanceNames; + var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); + if (memberName) { + switch (member.kind) { + case 149 /* GetAccessor */: + addName(names, member.name, memberName, getter); + break; + case 150 /* SetAccessor */: + addName(names, member.name, memberName, setter); + break; + case 145 /* PropertyDeclaration */: + addName(names, member.name, memberName, property); + break; + } + } + } + } + function addName(names, location, name, meaning) { + if (ts.hasProperty(names, name)) { + var prev = names[name]; + if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names[name] = prev | meaning; + } + } + else { + names[name] = meaning; + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = {}; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind == 144 /* PropertySignature */) { + var memberName = void 0; + switch (member.name.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 69 /* Identifier */: + memberName = member.name.text; + break; + default: + continue; + } + if (ts.hasProperty(names, memberName)) { + error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names[memberName] = true; + } + } + } + } function checkTypeForDuplicateIndexSignatures(node) { if (node.kind === 222 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); @@ -27399,6 +27517,7 @@ var ts; var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); } } function checkArrayType(node) { @@ -28444,6 +28563,10 @@ var ts; if (node.initializer) { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + } } if (node.kind !== 145 /* PropertyDeclaration */ && node.kind !== 144 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here @@ -28457,6 +28580,18 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } + function areDeclarationFlagsIdentical(left, right) { + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 /* Private */ | + 16 /* Protected */ | + 256 /* Async */ | + 128 /* Abstract */ | + 64 /* Readonly */ | + 32 /* Static */; + return (left.flags & interestingFlags) === (right.flags & interestingFlags); + } function checkVariableDeclaration(node) { checkGrammarVariableDeclaration(node); return checkVariableLikeDeclaration(node); @@ -29150,6 +29285,7 @@ var ts; var typeWithThis = getTypeWithThisArgument(type); var staticType = getTypeOfSymbol(symbol); checkTypeParameterListsIdentical(node, symbol); + checkClassForDuplicateDeclarations(node); var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { var baseTypes = getBaseTypes(type); @@ -29398,6 +29534,7 @@ var ts; checkIndexConstraints(type); } } + checkObjectTypeForDuplicateDeclarations(node); } ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { @@ -30241,14 +30378,11 @@ var ts; function checkSourceFileWorker(node) { var links = getNodeLinks(node); if (!(links.flags & 1 /* TypeChecked */)) { - // Check whether the file has declared it is the default lib, - // and whether the user has specifically chosen to avoid checking it. - if (compilerOptions.skipDefaultLibCheck) { - // If the user specified '--noLib' and a file has a '/// ', - // then we should treat that file as a default lib. - if (node.hasNoDefaultLib) { - return; - } + // If skipLibCheck is enabled, skip type checking if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip type checking if file contains a + // '/// ' directive. + if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + return; } // Grammar checking checkGrammarSourceFile(node); @@ -30665,7 +30799,7 @@ var ts; return symbol && getTypeOfSymbol(symbol); } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -31204,7 +31338,7 @@ var ts; if (file.moduleAugmentations.length) { (augmentations || (augmentations = [])).push(file.moduleAugmentations); } - if (file.wasReferenced && file.symbol && file.symbol.globalExports) { + if (file.symbol && file.symbol.globalExports) { mergeSymbolTable(globals, file.symbol.globalExports); } }); @@ -31787,7 +31921,6 @@ var ts; name_20.kind === 140 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name_20); - return "continue"; } if (prop.kind === 254 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern @@ -31829,17 +31962,21 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_20.text)) { - seen[name_20.text] = currentKind; + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_20); + if (effectiveName === undefined) { + return "continue"; + } + if (!ts.hasProperty(seen, effectiveName)) { + seen[effectiveName] = currentKind; } else { - var existingKind = seen[name_20.text]; + var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - return "continue"; + grammarErrorOnNode(name_20, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_20)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_20.text] = currentKind | existingKind; + seen[effectiveName] = currentKind | existingKind; } else { return { value: grammarErrorOnNode(name_20, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; @@ -41638,8 +41775,8 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - // use typesRoot and fallback to directory that contains tsconfig if typesRoot is not set - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : undefined); + // use typesRoot and fallback to directory that contains tsconfig or current directory if typesRoot is not set + var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); if (traceEnabled) { if (containingFile === undefined) { if (rootDir === undefined) { @@ -42229,12 +42366,25 @@ var ts; } } } + function getDefaultTypeDirectiveNames(rootPath) { + var localTypes = ts.combinePaths(rootPath, "types"); + var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); + var result = []; + if (ts.sys.directoryExists(localTypes)) { + result = result.concat(ts.sys.getDirectories(localTypes)); + } + if (ts.sys.directoryExists(npmTypes)) { + result = result.concat(ts.sys.getDirectories(npmTypes)); + } + return result; + } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { + getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -42302,6 +42452,21 @@ var ts; } return resolutions; } + function getDefaultTypeDirectiveNames(options, rootFiles, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // or load all types from the automatic type import fields + if (host && host.getDefaultTypeDirectiveNames) { + var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + if (commonRoot) { + return host.getDefaultTypeDirectiveNames(commonRoot); + } + } + return undefined; + } + ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -42340,14 +42505,15 @@ var ts; // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument - if (options.types && options.types.length) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(options.types, /*containingFile*/ undefined); - for (var i = 0; i < options.types.length; i++) { - processTypeReferenceDirective(options.types[i], resolutions[i]); + var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + if (typeReferences) { + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, /*containingFile*/ undefined); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); } } - ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // Do not process the default library if: // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in @@ -42999,9 +43165,6 @@ var ts; if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); } - if (file_1) { - file_1.wasReferenced = file_1.wasReferenced || isReference; - } return file_1; } // We haven't looked for this file, do so now and cache result @@ -43015,7 +43178,6 @@ var ts; }); filesByName.set(path, file); if (file) { - file.wasReferenced = file.wasReferenced || isReference; file.path = path; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -43129,19 +43291,7 @@ var ts; !options.noResolve && i < file.imports.length; if (shouldAddFile) { - var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); - if (importedFile && resolution.isExternalLibraryImport) { - // Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files, - // this check is ok. Otherwise this would be never true for javascript file - if (!ts.isExternalModule(importedFile) && importedFile.statements.length) { - var start_5 = ts.getTokenPosOfNode(file.imports[i], file); - fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); - } - else if (importedFile.referencedFiles.length) { - var firstRef = importedFile.referencedFiles[0]; - fileProcessingDiagnostics.add(ts.createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, ts.Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); - } - } + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } } } @@ -43227,7 +43377,7 @@ var ts; } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substututions_for_pattern_0_should_be_an_array, key)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)); } } } @@ -43278,15 +43428,21 @@ var ts; else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === ts.ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen target of es6 when below es6 if (options.module === ts.ModuleKind.ES6 && languageVersion < 2 /* ES6 */) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile && options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + if (outFile) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + } + else if (options.module === undefined && firstExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } } // there has to be common source directory if user specified --outdir || --sourceRoot // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted @@ -43384,6 +43540,11 @@ var ts; type: "boolean", description: ts.Diagnostics.Print_this_message }, + { + name: "help", + shortName: "?", + type: "boolean" + }, { name: "init", type: "boolean", @@ -43486,6 +43647,11 @@ var ts; name: "skipDefaultLibCheck", type: "boolean" }, + { + name: "skipLibCheck", + type: "boolean", + description: ts.Diagnostics.Skip_type_checking_of_declaration_files + }, { name: "out", type: "string", @@ -44315,7 +44481,7 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(program, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; // This means "compare in a case insensitive manner." @@ -44354,6 +44520,18 @@ var ts; } } }); + // Remove imports when the imported declaration is already in the list and has the same name. + rawItems = ts.filter(rawItems, function (item) { + var decl = item.declaration; + if (decl.kind === 231 /* ImportClause */ || decl.kind === 234 /* ImportSpecifier */ || decl.kind === 229 /* ImportEqualsDeclaration */) { + var importer = checker.getSymbolAtLocation(decl.name); + var imported = checker.getAliasedSymbol(importer); + return importer.name !== imported.name; + } + else { + return true; + } + }); rawItems.sort(compareNavigateToItems); if (maxResultCount !== undefined) { rawItems = rawItems.slice(0, maxResultCount); @@ -44752,8 +44930,12 @@ var ts; return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); case 153 /* IndexSignature */: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); + case 224 /* EnumDeclaration */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); case 255 /* EnumMember */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 222 /* InterfaceDeclaration */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); case 151 /* CallSignature */: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); case 152 /* ConstructSignature */: @@ -45714,7 +45896,7 @@ var ts; // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it // will return the generic identifier that started the expression (e.g. "foo" in "foo= 0; --i) { + for (var i = exclusiveStartPosition - 1; i >= 0; i--) { if (nodeHasTokens(children[i])) { return children[i]; } @@ -47337,12 +47519,11 @@ var ts; if (!isStarted) { scanner.scan(); } - var t; var pos = scanner.getStartPos(); // Read leading trivia and token while (pos < endPos) { - var t_1 = scanner.getToken(); - if (!ts.isTrivia(t_1)) { + var t = scanner.getToken(); + if (!ts.isTrivia(t)) { break; } // consume leading trivia @@ -47350,7 +47531,7 @@ var ts; var item = { pos: pos, end: scanner.getStartPos(), - kind: t_1 + kind: t }; pos = scanner.getStartPos(); if (!leadingTrivia) { @@ -47690,6 +47871,7 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// +/* tslint:disable:no-null-keyword */ /* @internal */ var ts; (function (ts) { @@ -47951,7 +48133,7 @@ var ts; this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2 /* Space */)); this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8 /* Delete */)); // Open Brace braces after function - //TypeScript: Function can have return types, which can be made of tons of different token kinds + // TypeScript: Function can have return types, which can be made of tons of different token kinds this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); // Open Brace braces after TypeScript module/class/interface this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); @@ -48092,17 +48274,17 @@ var ts; case 220 /* FunctionDeclaration */: case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - //case SyntaxKind.MemberFunctionDeclaration: + // case SyntaxKind.MemberFunctionDeclaration: case 149 /* GetAccessor */: case 150 /* SetAccessor */: - ///case SyntaxKind.MethodSignature: + // case SyntaxKind.MethodSignature: case 151 /* CallSignature */: case 179 /* FunctionExpression */: case 148 /* Constructor */: case 180 /* ArrowFunction */: - //case SyntaxKind.ConstructorDeclaration: - //case SyntaxKind.SimpleArrowFunctionExpression: - //case SyntaxKind.ParenthesizedArrowFunctionExpression: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: case 222 /* InterfaceDeclaration */: return true; } @@ -48254,6 +48436,7 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// +/* tslint:disable:no-null-keyword */ /* @internal */ var ts; (function (ts) { @@ -48271,9 +48454,9 @@ var ts; }; RulesMap.prototype.Initialize = function (rules) { this.mapRowLength = 138 /* LastToken */ + 1; - this.map = new Array(this.mapRowLength * this.mapRowLength); //new Array(this.mapRowLength * this.mapRowLength); + this.map = new Array(this.mapRowLength * this.mapRowLength); // new Array(this.mapRowLength * this.mapRowLength); // This array is used only during construction of the rulesbucket in the map - var rulesBucketConstructionStateList = new Array(this.map.length); //new Array(this.map.length); + var rulesBucketConstructionStateList = new Array(this.map.length); // new Array(this.map.length); this.FillRules(rules, rulesBucketConstructionStateList); return this.map; }; @@ -48285,7 +48468,7 @@ var ts; }; RulesMap.prototype.GetRuleBucketIndex = function (row, column) { var rulesBucketIndex = (row * this.mapRowLength) + column; - //Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array."); + // Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array."); return rulesBucketIndex; }; RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { @@ -48537,6 +48720,7 @@ var ts; /// /// /// +/* tslint:disable:no-null-keyword */ /* @internal */ var ts; (function (ts) { @@ -49058,7 +49242,7 @@ var ts; // if there are any tokens that logically belong to node and interleave child nodes // such tokens will be consumed in processChildNode for for the child that follows them ts.forEachChild(node, function (child) { - processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListElement*/ false); + processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, function (nodes) { processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); }); @@ -49149,7 +49333,7 @@ var ts; var inheritedIndentation = -1 /* Unknown */; for (var i = 0; i < nodes.length; i++) { var child = nodes[i]; - inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true, /*isFirstListItem*/ i === 0); + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } if (listEndToken !== 0 /* Unknown */) { if (formattingScanner.isOnToken()) { @@ -49279,7 +49463,7 @@ var ts; // Handle the case where the next line is moved to be the end of this line. // In this case we don't indent the next line in the next pass. if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAdded*/ false); + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); } } else if (rule.Operation.Action & 4 /* NewLine */ && currentStartLine === previousStartLine) { @@ -49288,7 +49472,7 @@ var ts; // In this case we indent token2 in the next pass but we set // sameLineIndent flag to notify the indenter that the indentation is within the line. if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAdded*/ true); + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line @@ -49336,7 +49520,7 @@ var ts; else { parts = []; var startPos = commentRange.pos; - for (var line = startLine; line < endLine; ++line) { + for (var line = startLine; line < endLine; line++) { var endOfLine = ts.getEndLinePosition(line, sourceFile); parts.push({ pos: startPos, end: endOfLine }); startPos = ts.getStartPositionOfLine(line + 1, sourceFile); @@ -49355,7 +49539,7 @@ var ts; } // shift all parts on the delta size var delta = indentation - nonWhitespaceColumnInFirstPart.column; - for (var i = startIndex, len = parts.length; i < len; ++i, ++startLine) { + for (var i = startIndex, len = parts.length; i < len; i++, startLine++) { var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceCharacterAndColumn = i === 0 ? nonWhitespaceColumnInFirstPart @@ -49371,7 +49555,7 @@ var ts; } } function trimTrailingWhitespacesForLines(line1, line2, range) { - for (var line = line1; line < line2; ++line) { + for (var line = line1; line < line2; line++) { var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var lineEndPosition = ts.getEndLinePosition(line, sourceFile); // do not trim whitespaces in comments or template expression @@ -49422,7 +49606,6 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { - var between; switch (rule.Operation.Action) { case 1 /* Ignore */: // no action required @@ -49459,14 +49642,6 @@ var ts; } } } - function isSomeBlock(kind) { - switch (kind) { - case 199 /* Block */: - case 226 /* ModuleBlock */: - return true; - } - return false; - } function getOpenTokenForList(node, list) { switch (node.kind) { case 148 /* Constructor */: @@ -49525,7 +49700,7 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat('\t', tabs); + internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; @@ -49550,7 +49725,7 @@ var ts; } function repeat(value, count) { var s = ""; - for (var i = 0; i < count; ++i) { + for (var i = 0; i < count; i++) { s += value; } return s; @@ -49866,7 +50041,7 @@ var ts; // walk toward the start of the list starting from current node and check if the line is the same for all items. // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); - for (var i = index - 1; i >= 0; --i) { + for (var i = index - 1; i >= 0; i--) { if (list[i].kind === 24 /* CommaToken */) { continue; } @@ -49893,7 +50068,7 @@ var ts; function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { var character = 0; var column = 0; - for (var pos = startPos; pos < endPos; ++pos) { + for (var pos = startPos; pos < endPos; pos++) { var ch = sourceFile.text.charCodeAt(pos); if (!ts.isWhiteSpace(ch)) { break; @@ -49987,7 +50162,7 @@ var ts; Function returns true when the parent node should indent the given child by an explicit rule */ function shouldIndentChildNode(parent, child) { - return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false); + return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); @@ -50809,49 +50984,55 @@ var ts; (function (ScriptElementKind) { ScriptElementKind.unknown = ""; ScriptElementKind.warning = "warning"; - // predefined type (void) or keyword (class) + /** predefined type (void) or keyword (class) */ ScriptElementKind.keyword = "keyword"; - // top level script node + /** top level script node */ ScriptElementKind.scriptElement = "script"; - // module foo {} + /** module foo {} */ ScriptElementKind.moduleElement = "module"; - // class X {} + /** class X {} */ ScriptElementKind.classElement = "class"; - // var x = class X {} + /** var x = class X {} */ ScriptElementKind.localClassElement = "local class"; - // interface Y {} + /** interface Y {} */ ScriptElementKind.interfaceElement = "interface"; - // type T = ... + /** type T = ... */ ScriptElementKind.typeElement = "type"; - // enum E + /** enum E */ ScriptElementKind.enumElement = "enum"; - // Inside module and script only - // const v = .. + /** + * Inside module and script only + * const v = .. + */ ScriptElementKind.variableElement = "var"; - // Inside function + /** Inside function */ ScriptElementKind.localVariableElement = "local var"; - // Inside module and script only - // function f() { } + /** + * Inside module and script only + * function f() { } + */ ScriptElementKind.functionElement = "function"; - // Inside function + /** Inside function */ ScriptElementKind.localFunctionElement = "local function"; - // class X { [public|private]* foo() {} } + /** class X { [public|private]* foo() {} } */ ScriptElementKind.memberFunctionElement = "method"; - // class X { [public|private]* [get|set] foo:number; } + /** class X { [public|private]* [get|set] foo:number; } */ ScriptElementKind.memberGetAccessorElement = "getter"; ScriptElementKind.memberSetAccessorElement = "setter"; - // class X { [public|private]* foo:number; } - // interface Y { foo:number; } + /** + * class X { [public|private]* foo:number; } + * interface Y { foo:number; } + */ ScriptElementKind.memberVariableElement = "property"; - // class X { constructor() { } } + /** class X { constructor() { } } */ ScriptElementKind.constructorImplementationElement = "constructor"; - // interface Y { ():number; } + /** interface Y { ():number; } */ ScriptElementKind.callSignatureElement = "call"; - // interface Y { []:number; } + /** interface Y { []:number; } */ ScriptElementKind.indexSignatureElement = "index"; - // interface Y { new():Y; } + /** interface Y { new():Y; } */ ScriptElementKind.constructSignatureElement = "construct"; - // function foo(*Y*: string) + /** function foo(*Y*: string) */ ScriptElementKind.parameterElement = "parameter"; ScriptElementKind.typeParameterElement = "type parameter"; ScriptElementKind.primitiveType = "primitive type"; @@ -52236,9 +52417,9 @@ var ts; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_6 = new Date().getTime(); + var start_5 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_5)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -52518,13 +52699,13 @@ var ts; || contextToken.kind === 166 /* StringLiteralType */ || contextToken.kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_7 = contextToken.getStart(); + var start_6 = contextToken.getStart(); var end = contextToken.getEnd(); // To be "in" one of these literals, the position has to be: // 1. entirely within the token text. // 2. at the end position of an unterminated token. // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). - if (start_7 < position && position < end) { + if (start_6 < position && position < end) { return true; } if (position === end) { @@ -53759,8 +53940,7 @@ var ts; } function getDocumentHighlights(fileName, position, filesToSearch) { synchronizeHostData(); - filesToSearch = ts.map(filesToSearch, ts.normalizeSlashes); - var sourceFilesToSearch = ts.filter(program.getSourceFiles(), function (f) { return ts.contains(filesToSearch, f.fileName); }); + var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return program.getSourceFile(f); }); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingWord(sourceFile, position); if (!node) { @@ -55150,7 +55330,8 @@ var ts; /// NavigateTo function getNavigateToItems(searchValue, maxResultCount) { synchronizeHostData(); - return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); + var checker = getProgram().getTypeChecker(); + return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount); } function getEmitOutput(fileName) { synchronizeHostData(); @@ -57559,6 +57740,9 @@ var ts; LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () { return this.shimHost.getCurrentDirectory(); }; + LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) { + return this.shimHost.getDirectories(path); + }; LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; From 1e41af30fee7fbdb1b7e2bb1130ae183abd0a7ab Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 25 May 2016 12:27:29 -0700 Subject: [PATCH 12/13] Update LKG --- lib/tsc.js | 2 +- lib/tsserver.js | 2 +- lib/tsserverlibrary.js | 2 +- lib/typescript.js | 9 ++++----- lib/typescriptServices.js | 9 ++++----- 5 files changed, 11 insertions(+), 13 deletions(-) diff --git a/lib/tsc.js b/lib/tsc.js index 00c758c0446..ca303c49f7b 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -18090,7 +18090,7 @@ var ts; inferFromTypes(source, t); } } - if (target.flags & 16384 && typeParameterCount === 1) { + if (typeParameterCount === 1) { inferiority++; inferFromTypes(source, typeParameter); inferiority--; diff --git a/lib/tsserver.js b/lib/tsserver.js index 7eb744a77d3..dcf76693225 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -18854,7 +18854,7 @@ var ts; inferFromTypes(source, t); } } - if (target.flags & 16384 && typeParameterCount === 1) { + if (typeParameterCount === 1) { inferiority++; inferFromTypes(source, typeParameter); inferiority--; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 902bfcf610e..f16d02e472c 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -18854,7 +18854,7 @@ var ts; inferFromTypes(source, t); } } - if (target.flags & 16384 && typeParameterCount === 1) { + if (typeParameterCount === 1) { inferiority++; inferFromTypes(source, typeParameter); inferiority--; diff --git a/lib/typescript.js b/lib/typescript.js index 19fffd35501..cf982a3ede9 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -21958,11 +21958,10 @@ var ts; inferFromTypes(source, t); } } - // Next, if target is a union type containing a single naked type parameter, make a - // secondary inference to that type parameter. We don't do this for intersection types - // because in a target type like Foo & T we don't know how which parts of the source type - // should be matched by Foo and which should be inferred to T. - if (target.flags & 16384 /* Union */ && typeParameterCount === 1) { + // Next, if target containings a single naked type parameter, make a secondary inference to that type + // parameter. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). + if (typeParameterCount === 1) { inferiority++; inferFromTypes(source, typeParameter); inferiority--; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 19fffd35501..cf982a3ede9 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -21958,11 +21958,10 @@ var ts; inferFromTypes(source, t); } } - // Next, if target is a union type containing a single naked type parameter, make a - // secondary inference to that type parameter. We don't do this for intersection types - // because in a target type like Foo & T we don't know how which parts of the source type - // should be matched by Foo and which should be inferred to T. - if (target.flags & 16384 /* Union */ && typeParameterCount === 1) { + // Next, if target containings a single naked type parameter, make a secondary inference to that type + // parameter. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). + if (typeParameterCount === 1) { inferiority++; inferFromTypes(source, typeParameter); inferiority--; From 5c23b3bc20ea043e2022487a211364bfa7d320c2 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 26 May 2016 06:04:42 -0700 Subject: [PATCH 13/13] Fix more tests --- tests/cases/fourslash/getNavigationBarItems.ts | 2 +- .../fourslash/navigationBarItemsMultilineStringIdentifiers.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/cases/fourslash/getNavigationBarItems.ts b/tests/cases/fourslash/getNavigationBarItems.ts index 8e9b8de5b05..cd09f61011e 100644 --- a/tests/cases/fourslash/getNavigationBarItems.ts +++ b/tests/cases/fourslash/getNavigationBarItems.ts @@ -5,7 +5,7 @@ //// ["bar"]: string; ////} -verify.navigationBarCount(3); +verify.navigationBarCount(5); verify.navigationBarContains("C", "class"); verify.navigationBarChildItem("C", "[\"bar\"]", "property"); verify.navigationBarChildItem("C", "foo", "property"); diff --git a/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts b/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts index 681039d174a..4e7c715e6cd 100644 --- a/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts +++ b/tests/cases/fourslash/navigationBarItemsMultilineStringIdentifiers.ts @@ -38,4 +38,4 @@ test.markers().forEach((marker) => { verify.navigationBarContains(marker.data.itemName, marker.data.kind, marker.fileName, marker.data.parentName); }); -verify.navigationBarCount(11); // global + 1 child, interface w/ 2 properties, class w/ 2 properties, 3 modules +verify.navigationBarCount(12); // global + 1 child, interface w/ 2 properties, class w/ 2 properties, 3 modules