Merge branch 'master' into error-node-static-index-signatures

This commit is contained in:
Wesley Wigham
2021-05-24 13:38:34 -07:00
256 changed files with 10678 additions and 4204 deletions
+1
View File
@@ -34,6 +34,7 @@
],
"@typescript-eslint/consistent-type-definitions": ["error", "interface"],
"@typescript-eslint/consistent-type-assertions": ["error", { "assertionStyle": "as" }],
"no-duplicate-imports": "off",
"@typescript-eslint/no-duplicate-imports": "error",
-5
View File
@@ -20,11 +20,6 @@ jobs:
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
+21
View File
@@ -0,0 +1,21 @@
name: Sync Two Wiki Repos
on: [gollum]
jobs:
sync:
runs-on: ubuntu-latest
steps:
- name: Get repo name
run: R=${GITHUB_REPOSITORY%?wiki}; echo "BASENAME=${R##*/}" >> $GITHUB_ENV
- name: Checkout ${{ env.BASENAME }}-wiki
uses: actions/checkout@v2
with:
repository: "${{ GITHUB.repository_owner }}/${{ env.BASENAME }}-wiki"
token: ${{ secrets.TS_BOT_GITHUB_TOKEN }}
fetch-depth: 0
- name: Run sync
run: ./.github/workflows/sync
env:
PUSHER: typescript-bot <bot@typescriptlang.org>
AUTH: ${{ secrets.TS_BOT_GITHUB_TOKEN }}
+131 -26
View File
@@ -314,9 +314,9 @@
}
},
"@octokit/graphql": {
"version": "4.6.1",
"resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.6.1.tgz",
"integrity": "sha512-2lYlvf4YTDgZCTXTW4+OX+9WTLFtEUc6hGm4qM1nlZjzxj+arizM4aHWzBVBCxY9glh7GIs0WEuiSgbVzv8cmA==",
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.6.2.tgz",
"integrity": "sha512-WmsIR1OzOr/3IqfG9JIczI8gMJUMzzyx5j0XXQ4YihHtKlQc+u35VpVoOXhlKAlaBntvry1WpAzPl/a+s3n89Q==",
"dev": true,
"requires": {
"@octokit/request": "^5.3.0",
@@ -325,9 +325,9 @@
}
},
"@octokit/openapi-types": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-7.0.0.tgz",
"integrity": "sha512-gV/8DJhAL/04zjTI95a7FhQwS6jlEE0W/7xeYAzuArD0KVAVWDLP2f3vi98hs3HLTczxXdRK/mF0tRoQPpolEw==",
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-7.2.1.tgz",
"integrity": "sha512-IHQJpLciwzwDvciLxiFj3IEV5VYn7lSVcj5cu0jbTwMfK4IG6/g8SPrVp3Le1VRzIiYSRcBzm1dA7vgWelYP3Q==",
"dev": true
},
"@octokit/plugin-paginate-rest": {
@@ -401,12 +401,12 @@
}
},
"@octokit/types": {
"version": "6.14.2",
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.14.2.tgz",
"integrity": "sha512-wiQtW9ZSy4OvgQ09iQOdyXYNN60GqjCL/UdMsepDr1Gr0QzpW6irIKbH3REuAHXAhxkEk9/F2a3Gcs1P6kW5jA==",
"version": "6.16.0",
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.16.0.tgz",
"integrity": "sha512-EktqSNq8EKXE82a7Vw33ozOEhFXIRik+rZHJTHAgVZRm/p2K5r5ecn5fVpRkLCm3CAVFwchRvt3yvtmfbt2LCQ==",
"dev": true,
"requires": {
"@octokit/openapi-types": "^7.0.0"
"@octokit/openapi-types": "^7.2.0"
}
},
"@types/browserify": {
@@ -583,9 +583,9 @@
"dev": true
},
"@types/node": {
"version": "15.3.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-15.3.0.tgz",
"integrity": "sha512-8/bnjSZD86ZfpBsDlCIkNXIvm+h6wi9g7IqL+kmFkQ+Wvu3JrasgLElfiPgoo8V8vVfnEi0QVS12gbl94h9YsQ==",
"version": "15.6.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-15.6.0.tgz",
"integrity": "sha512-gCYSfQpy+LYhOFTKAeE8BkyGqaxmlFxe+n4DKM6DR0wzw/HISUE/hAmkC/KT8Sw5PCJblqg062b3z9gucv3k0A==",
"dev": true
},
"@types/node-fetch": {
@@ -1052,12 +1052,6 @@
"integrity": "sha1-p5SvDAWrF1KEbudTofIRoFugxE8=",
"dev": true
},
"array-filter": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/array-filter/-/array-filter-1.0.0.tgz",
"integrity": "sha1-uveeYubvTCpMC4MSMtr/7CUfnYM=",
"dev": true
},
"array-includes": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.1.tgz",
@@ -1141,6 +1135,111 @@
"integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=",
"dev": true
},
"array.prototype.filter": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/array.prototype.filter/-/array.prototype.filter-1.0.0.tgz",
"integrity": "sha512-TfO1gz+tLm+Bswq0FBOXPqAchtCr2Rn48T8dLJoRFl8NoEosjZmzptmuo1X8aZBzZcqsR1W8U761tjACJtngTQ==",
"dev": true,
"requires": {
"call-bind": "^1.0.2",
"define-properties": "^1.1.3",
"es-abstract": "^1.18.0",
"es-array-method-boxes-properly": "^1.0.0",
"is-string": "^1.0.5"
},
"dependencies": {
"es-abstract": {
"version": "1.18.0",
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.0.tgz",
"integrity": "sha512-LJzK7MrQa8TS0ja2w3YNLzUgJCGPdPOV1yVvezjNnS89D+VR08+Szt2mz3YB2Dck/+w5tfIq/RoUAFqJJGM2yw==",
"dev": true,
"requires": {
"call-bind": "^1.0.2",
"es-to-primitive": "^1.2.1",
"function-bind": "^1.1.1",
"get-intrinsic": "^1.1.1",
"has": "^1.0.3",
"has-symbols": "^1.0.2",
"is-callable": "^1.2.3",
"is-negative-zero": "^2.0.1",
"is-regex": "^1.1.2",
"is-string": "^1.0.5",
"object-inspect": "^1.9.0",
"object-keys": "^1.1.1",
"object.assign": "^4.1.2",
"string.prototype.trimend": "^1.0.4",
"string.prototype.trimstart": "^1.0.4",
"unbox-primitive": "^1.0.0"
}
},
"has-symbols": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz",
"integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==",
"dev": true
},
"is-callable": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.3.tgz",
"integrity": "sha512-J1DcMe8UYTBSrKezuIUTUwjXsho29693unXM2YhJUTR2txK/eG47bvNa/wipPFmZFgr/N6f1GA66dv0mEyTIyQ==",
"dev": true
},
"is-negative-zero": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz",
"integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==",
"dev": true
},
"is-regex": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.3.tgz",
"integrity": "sha512-qSVXFz28HM7y+IWX6vLCsexdlvzT1PJNFSBuaQLQ5o0IEw8UDYW6/2+eCMVyIsbM8CNLX2a/QWmSpyxYEHY7CQ==",
"dev": true,
"requires": {
"call-bind": "^1.0.2",
"has-symbols": "^1.0.2"
}
},
"object-inspect": {
"version": "1.10.3",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.10.3.tgz",
"integrity": "sha512-e5mCJlSH7poANfC8z8S9s9S2IN5/4Zb3aZ33f5s8YqoazCFzNLloLU8r5VCG+G7WoqLvAAZoVMcy3tp/3X0Plw==",
"dev": true
},
"object.assign": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz",
"integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==",
"dev": true,
"requires": {
"call-bind": "^1.0.0",
"define-properties": "^1.1.3",
"has-symbols": "^1.0.1",
"object-keys": "^1.1.1"
}
},
"string.prototype.trimend": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz",
"integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==",
"dev": true,
"requires": {
"call-bind": "^1.0.2",
"define-properties": "^1.1.3"
}
},
"string.prototype.trimstart": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz",
"integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==",
"dev": true,
"requires": {
"call-bind": "^1.0.2",
"define-properties": "^1.1.3"
}
}
}
},
"array.prototype.flat": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz",
@@ -1268,12 +1367,12 @@
"dev": true
},
"available-typed-arrays": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.2.tgz",
"integrity": "sha512-XWX3OX8Onv97LMk/ftVyBibpGwY5a8SmuxZPzeOxqmuEqUCOM9ZE+uIaD1VNJ5QnvU2UQusvmKbuM1FR8QWGfQ==",
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.3.tgz",
"integrity": "sha512-CuPhFULixV/d89POo1UG4GqGbR7dmrefY2ZdmsYakeR4gOSJXoF7tfeaiqMHGOMrlTiJoeEs87fpLsBYmE2BMw==",
"dev": true,
"requires": {
"array-filter": "^1.0.0"
"array.prototype.filter": "^1.0.0"
}
},
"azure-devops-node-api": {
@@ -2674,6 +2773,12 @@
}
}
},
"es-array-method-boxes-properly": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/es-array-method-boxes-properly/-/es-array-method-boxes-properly-1.0.0.tgz",
"integrity": "sha512-wd6JXUmyHmt8T5a2xreUwKcGPq6f1f+WwIJkijUqiGcJz1qqnZgP6XIK+QyIWU5lT7imeNxUll48bziG+TSYcA==",
"dev": true
},
"es-to-primitive": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz",
@@ -7960,9 +8065,9 @@
"dev": true
},
"uglify-js": {
"version": "3.13.6",
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.13.6.tgz",
"integrity": "sha512-rRprLwl8RVaS+Qvx3Wh5hPfPBn9++G6xkGlUupya0s5aDmNjI7z3lnRLB3u7sN4OmbB0pWgzhM9BEJyiWAwtAA==",
"version": "3.13.7",
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.13.7.tgz",
"integrity": "sha512-1Psi2MmnZJbnEsgJJIlfnd7tFlJfitusmR7zDI8lXlFI0ACD4/Rm/xdrU8bh6zF0i74aiVoBtkRiFulkrmh3AA==",
"dev": true,
"optional": true
},
+5 -5
View File
@@ -47,7 +47,7 @@ class DeclarationsWalker {
}
if (s.name === "Array" || s.name === "ReadOnlyArray") {
// we should process type argument instead
return this.processType((<any>type).typeArguments[0]);
return this.processType((type as any).typeArguments[0]);
}
else {
const declarations = s.getDeclarations();
@@ -84,12 +84,12 @@ class DeclarationsWalker {
case ts.SyntaxKind.PropertySignature:
case ts.SyntaxKind.Parameter:
case ts.SyntaxKind.IndexSignature:
if (((<ts.VariableDeclaration | ts.MethodDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration | ts.PropertySignature | ts.MethodSignature | ts.IndexSignatureDeclaration>node.parent).type) === node) {
if (((node.parent as ts.VariableDeclaration | ts.MethodDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration | ts.PropertySignature | ts.MethodSignature | ts.IndexSignatureDeclaration).type) === node) {
this.processTypeOfNode(node);
}
break;
case ts.SyntaxKind.InterfaceDeclaration:
const heritageClauses = (<ts.InterfaceDeclaration>node.parent).heritageClauses;
const heritageClauses = (node.parent as ts.InterfaceDeclaration).heritageClauses;
if (heritageClauses) {
if (heritageClauses[0].token !== ts.SyntaxKind.ExtendsKeyword) {
throw new Error(`Unexpected kind of heritage clause: ${ts.SyntaxKind[heritageClauses[0].kind]}`);
@@ -106,7 +106,7 @@ class DeclarationsWalker {
private processTypeOfNode(node: ts.Node): void {
if (node.kind === ts.SyntaxKind.UnionType) {
for (const t of (<ts.UnionTypeNode>node).types) {
for (const t of (node as ts.UnionTypeNode).types) {
this.processTypeOfNode(t);
}
}
@@ -120,7 +120,7 @@ class DeclarationsWalker {
}
function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptServicesDts: string) {
const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: false, types: <string[]>[], stripInternal: true };
const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: false, types: [] as string[], stripInternal: true };
/**
* 1st pass - generate a program from protocol.ts and typescriptservices.d.ts and emit core version of protocol.d.ts with all internal members stripped
+108 -108
View File
@@ -100,7 +100,7 @@ namespace ts {
case SyntaxKind.Identifier:
// Only jsdoc typedef definition can exist in jsdoc namespace, and it should
// be considered the same as type alias
if ((<Identifier>node).isInJSDocNamespace) {
if ((node as Identifier).isInJSDocNamespace) {
return ModuleInstanceState.NonInstantiated;
}
}
@@ -327,14 +327,14 @@ namespace ts {
// unless it is a well known Symbol.
function getDeclarationName(node: Declaration): __String | undefined {
if (node.kind === SyntaxKind.ExportAssignment) {
return (<ExportAssignment>node).isExportEquals ? InternalSymbolName.ExportEquals : InternalSymbolName.Default;
return (node as ExportAssignment).isExportEquals ? InternalSymbolName.ExportEquals : InternalSymbolName.Default;
}
const name = getNameOfDeclaration(node);
if (name) {
if (isAmbientModule(node)) {
const moduleName = getTextOfIdentifierOrLiteral(name as Identifier | StringLiteral);
return (isGlobalScopeAugmentation(<ModuleDeclaration>node) ? "__global" : `"${moduleName}"`) as __String;
return (isGlobalScopeAugmentation(node as ModuleDeclaration) ? "__global" : `"${moduleName}"`) as __String;
}
if (name.kind === SyntaxKind.ComputedPropertyName) {
const nameExpression = name.expression;
@@ -392,7 +392,7 @@ namespace ts {
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
Debug.assert(node.parent.kind === SyntaxKind.JSDocFunctionType, "Impossible parameter parent kind", () => `parent is: ${(ts as any).SyntaxKind ? (ts as any).SyntaxKind[node.parent.kind] : node.parent.kind}, expected JSDocFunctionType`);
const functionType = <JSDocFunctionType>node.parent;
const functionType = node.parent as JSDocFunctionType;
const index = functionType.parameters.indexOf(node as ParameterDeclaration);
return "arg" + index as __String;
}
@@ -499,7 +499,7 @@ namespace ts {
// 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
// 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
if (symbol.declarations && symbol.declarations.length &&
(node.kind === SyntaxKind.ExportAssignment && !(<ExportAssignment>node).isExportEquals)) {
(node.kind === SyntaxKind.ExportAssignment && !(node as ExportAssignment).isExportEquals)) {
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
messageNeedsName = false;
multipleDefaultExports = true;
@@ -656,13 +656,13 @@ namespace ts {
const saveActiveLabelList = activeLabelList;
const saveHasExplicitReturn = hasExplicitReturn;
const isIIFE = containerFlags & ContainerFlags.IsFunctionExpression && !hasSyntacticModifier(node, ModifierFlags.Async) &&
!(<FunctionLikeDeclaration>node).asteriskToken && !!getImmediatelyInvokedFunctionExpression(node);
!(node as FunctionLikeDeclaration).asteriskToken && !!getImmediatelyInvokedFunctionExpression(node);
// A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
// similarly to break statements that exit to a label just past the statement body.
if (!isIIFE) {
currentFlow = initFlowNode({ flags: FlowFlags.Start });
if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) {
currentFlow.node = <FunctionExpression | ArrowFunction | MethodDeclaration>node;
currentFlow.node = node as FunctionExpression | ArrowFunction | MethodDeclaration;
}
}
// We create a return control flow graph for IIFEs and constructors. For constructors
@@ -676,10 +676,10 @@ namespace ts {
bindChildren(node);
// Reset all reachability check related flags on node (for incremental scenarios)
node.flags &= ~NodeFlags.ReachabilityAndEmitFlags;
if (!(currentFlow.flags & FlowFlags.Unreachable) && containerFlags & ContainerFlags.IsFunctionLike && nodeIsPresent((<FunctionLikeDeclaration>node).body)) {
if (!(currentFlow.flags & FlowFlags.Unreachable) && containerFlags & ContainerFlags.IsFunctionLike && nodeIsPresent((node as FunctionLikeDeclaration).body)) {
node.flags |= NodeFlags.HasImplicitReturn;
if (hasExplicitReturn) node.flags |= NodeFlags.HasExplicitReturn;
(<FunctionLikeDeclaration>node).endFlowNode = currentFlow;
(node as FunctionLikeDeclaration).endFlowNode = currentFlow;
}
if (node.kind === SyntaxKind.SourceFile) {
node.flags |= emitFlags;
@@ -690,7 +690,7 @@ namespace ts {
addAntecedent(currentReturnTarget, currentFlow);
currentFlow = finishFlowLabel(currentReturnTarget);
if (node.kind === SyntaxKind.Constructor || (isInJSFile(node) && (node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.FunctionExpression))) {
(<FunctionLikeDeclaration>node).returnFlowNode = currentFlow;
(node as FunctionLikeDeclaration).returnFlowNode = currentFlow;
}
}
if (!isIIFE) {
@@ -750,52 +750,52 @@ namespace ts {
}
switch (node.kind) {
case SyntaxKind.WhileStatement:
bindWhileStatement(<WhileStatement>node);
bindWhileStatement(node as WhileStatement);
break;
case SyntaxKind.DoStatement:
bindDoStatement(<DoStatement>node);
bindDoStatement(node as DoStatement);
break;
case SyntaxKind.ForStatement:
bindForStatement(<ForStatement>node);
bindForStatement(node as ForStatement);
break;
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
bindForInOrForOfStatement(<ForInOrOfStatement>node);
bindForInOrForOfStatement(node as ForInOrOfStatement);
break;
case SyntaxKind.IfStatement:
bindIfStatement(<IfStatement>node);
bindIfStatement(node as IfStatement);
break;
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
bindReturnOrThrow(<ReturnStatement | ThrowStatement>node);
bindReturnOrThrow(node as ReturnStatement | ThrowStatement);
break;
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
bindBreakOrContinueStatement(<BreakOrContinueStatement>node);
bindBreakOrContinueStatement(node as BreakOrContinueStatement);
break;
case SyntaxKind.TryStatement:
bindTryStatement(<TryStatement>node);
bindTryStatement(node as TryStatement);
break;
case SyntaxKind.SwitchStatement:
bindSwitchStatement(<SwitchStatement>node);
bindSwitchStatement(node as SwitchStatement);
break;
case SyntaxKind.CaseBlock:
bindCaseBlock(<CaseBlock>node);
bindCaseBlock(node as CaseBlock);
break;
case SyntaxKind.CaseClause:
bindCaseClause(<CaseClause>node);
bindCaseClause(node as CaseClause);
break;
case SyntaxKind.ExpressionStatement:
bindExpressionStatement(<ExpressionStatement>node);
bindExpressionStatement(node as ExpressionStatement);
break;
case SyntaxKind.LabeledStatement:
bindLabeledStatement(<LabeledStatement>node);
bindLabeledStatement(node as LabeledStatement);
break;
case SyntaxKind.PrefixUnaryExpression:
bindPrefixUnaryExpressionFlow(<PrefixUnaryExpression>node);
bindPrefixUnaryExpressionFlow(node as PrefixUnaryExpression);
break;
case SyntaxKind.PostfixUnaryExpression:
bindPostfixUnaryExpressionFlow(<PostfixUnaryExpression>node);
bindPostfixUnaryExpressionFlow(node as PostfixUnaryExpression);
break;
case SyntaxKind.BinaryExpression:
if (isDestructuringAssignment(node)) {
@@ -805,26 +805,26 @@ namespace ts {
bindDestructuringAssignmentFlow(node);
return;
}
bindBinaryExpressionFlow(<BinaryExpression>node);
bindBinaryExpressionFlow(node as BinaryExpression);
break;
case SyntaxKind.DeleteExpression:
bindDeleteExpressionFlow(<DeleteExpression>node);
bindDeleteExpressionFlow(node as DeleteExpression);
break;
case SyntaxKind.ConditionalExpression:
bindConditionalExpressionFlow(<ConditionalExpression>node);
bindConditionalExpressionFlow(node as ConditionalExpression);
break;
case SyntaxKind.VariableDeclaration:
bindVariableDeclarationFlow(<VariableDeclaration>node);
bindVariableDeclarationFlow(node as VariableDeclaration);
break;
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.ElementAccessExpression:
bindAccessExpressionFlow(<AccessExpression>node);
bindAccessExpressionFlow(node as AccessExpression);
break;
case SyntaxKind.CallExpression:
bindCallExpressionFlow(<CallExpression>node);
bindCallExpressionFlow(node as CallExpression);
break;
case SyntaxKind.NonNullExpression:
bindNonNullExpressionFlow(<NonNullExpression>node);
bindNonNullExpressionFlow(node as NonNullExpression);
break;
case SyntaxKind.JSDocTypedefTag:
case SyntaxKind.JSDocCallbackTag:
@@ -842,7 +842,7 @@ namespace ts {
bindEachFunctionsFirst((node as Block).statements);
break;
case SyntaxKind.BindingElement:
bindBindingElementFlow(<BindingElement>node);
bindBindingElementFlow(node as BindingElement);
break;
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.ArrayLiteralExpression:
@@ -869,16 +869,16 @@ namespace ts {
case SyntaxKind.ElementAccessExpression:
return containsNarrowableReference(expr);
case SyntaxKind.CallExpression:
return hasNarrowableArgument(<CallExpression>expr);
return hasNarrowableArgument(expr as CallExpression);
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.NonNullExpression:
return isNarrowingExpression((<ParenthesizedExpression | NonNullExpression>expr).expression);
return isNarrowingExpression((expr as ParenthesizedExpression | NonNullExpression).expression);
case SyntaxKind.BinaryExpression:
return isNarrowingBinaryExpression(<BinaryExpression>expr);
return isNarrowingBinaryExpression(expr as BinaryExpression);
case SyntaxKind.PrefixUnaryExpression:
return (<PrefixUnaryExpression>expr).operator === SyntaxKind.ExclamationToken && isNarrowingExpression((<PrefixUnaryExpression>expr).operand);
return (expr as PrefixUnaryExpression).operator === SyntaxKind.ExclamationToken && isNarrowingExpression((expr as PrefixUnaryExpression).operand);
case SyntaxKind.TypeOfExpression:
return isNarrowingExpression((<TypeOfExpression>expr).expression);
return isNarrowingExpression((expr as TypeOfExpression).expression);
}
return false;
}
@@ -904,7 +904,7 @@ namespace ts {
}
}
if (expr.expression.kind === SyntaxKind.PropertyAccessExpression &&
containsNarrowableReference((<PropertyAccessExpression>expr.expression).expression)) {
containsNarrowableReference((expr.expression as PropertyAccessExpression).expression)) {
return true;
}
return false;
@@ -944,13 +944,13 @@ namespace ts {
function isNarrowableOperand(expr: Expression): boolean {
switch (expr.kind) {
case SyntaxKind.ParenthesizedExpression:
return isNarrowableOperand((<ParenthesizedExpression>expr).expression);
return isNarrowableOperand((expr as ParenthesizedExpression).expression);
case SyntaxKind.BinaryExpression:
switch ((<BinaryExpression>expr).operatorToken.kind) {
switch ((expr as BinaryExpression).operatorToken.kind) {
case SyntaxKind.EqualsToken:
return isNarrowableOperand((<BinaryExpression>expr).left);
return isNarrowableOperand((expr as BinaryExpression).left);
case SyntaxKind.CommaToken:
return isNarrowableOperand((<BinaryExpression>expr).right);
return isNarrowableOperand((expr as BinaryExpression).right);
}
}
return containsNarrowableReference(expr);
@@ -1035,10 +1035,10 @@ namespace ts {
case SyntaxKind.IfStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
return (<IfStatement | WhileStatement | DoStatement>parent).expression === node;
return (parent as IfStatement | WhileStatement | DoStatement).expression === node;
case SyntaxKind.ForStatement:
case SyntaxKind.ConditionalExpression:
return (<ForStatement | ConditionalExpression>parent).condition === node;
return (parent as ForStatement | ConditionalExpression).condition === node;
}
return false;
}
@@ -1046,16 +1046,16 @@ namespace ts {
function isLogicalExpression(node: Node) {
while (true) {
if (node.kind === SyntaxKind.ParenthesizedExpression) {
node = (<ParenthesizedExpression>node).expression;
node = (node as ParenthesizedExpression).expression;
}
else if (node.kind === SyntaxKind.PrefixUnaryExpression && (<PrefixUnaryExpression>node).operator === SyntaxKind.ExclamationToken) {
node = (<PrefixUnaryExpression>node).operand;
else if (node.kind === SyntaxKind.PrefixUnaryExpression && (node as PrefixUnaryExpression).operator === SyntaxKind.ExclamationToken) {
node = (node as PrefixUnaryExpression).operand;
}
else {
return node.kind === SyntaxKind.BinaryExpression && (
(<BinaryExpression>node).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken ||
(<BinaryExpression>node).operatorToken.kind === SyntaxKind.BarBarToken ||
(<BinaryExpression>node).operatorToken.kind === SyntaxKind.QuestionQuestionToken);
(node as BinaryExpression).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken ||
(node as BinaryExpression).operatorToken.kind === SyntaxKind.BarBarToken ||
(node as BinaryExpression).operatorToken.kind === SyntaxKind.QuestionQuestionToken);
}
}
}
@@ -1370,7 +1370,7 @@ namespace ts {
// A top level or LHS of comma expression call expression with a dotted function name and at least one argument
// is potentially an assertion and is therefore included in the control flow.
if (node.kind === SyntaxKind.CallExpression) {
const call = <CallExpression>node;
const call = node as CallExpression;
if (call.expression.kind !== SyntaxKind.SuperKeyword && isDottedName(call.expression)) {
currentFlow = createFlowCall(currentFlow, call);
}
@@ -1397,8 +1397,8 @@ namespace ts {
}
function bindDestructuringTargetFlow(node: Expression) {
if (node.kind === SyntaxKind.BinaryExpression && (<BinaryExpression>node).operatorToken.kind === SyntaxKind.EqualsToken) {
bindAssignmentTargetFlow((<BinaryExpression>node).left);
if (node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) {
bindAssignmentTargetFlow((node as BinaryExpression).left);
}
else {
bindAssignmentTargetFlow(node);
@@ -1410,9 +1410,9 @@ namespace ts {
currentFlow = createFlowMutation(FlowFlags.Assignment, currentFlow, node);
}
else if (node.kind === SyntaxKind.ArrayLiteralExpression) {
for (const e of (<ArrayLiteralExpression>node).elements) {
for (const e of (node as ArrayLiteralExpression).elements) {
if (e.kind === SyntaxKind.SpreadElement) {
bindAssignmentTargetFlow((<SpreadElement>e).expression);
bindAssignmentTargetFlow((e as SpreadElement).expression);
}
else {
bindDestructuringTargetFlow(e);
@@ -1420,7 +1420,7 @@ namespace ts {
}
}
else if (node.kind === SyntaxKind.ObjectLiteralExpression) {
for (const p of (<ObjectLiteralExpression>node).properties) {
for (const p of (node as ObjectLiteralExpression).properties) {
if (p.kind === SyntaxKind.PropertyAssignment) {
bindDestructuringTargetFlow(p.initializer);
}
@@ -1579,7 +1579,7 @@ namespace ts {
if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) {
bindAssignmentTargetFlow(node.left);
if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) {
const elementAccess = <ElementAccessExpression>node.left;
const elementAccess = node.left as ElementAccessExpression;
if (isNarrowableOperand(elementAccess.expression)) {
currentFlow = createFlowMutation(FlowFlags.ArrayMutation, currentFlow, node);
}
@@ -1784,7 +1784,7 @@ namespace ts {
}
}
if (node.expression.kind === SyntaxKind.PropertyAccessExpression) {
const propertyAccess = <PropertyAccessExpression>node.expression;
const propertyAccess = node.expression as PropertyAccessExpression;
if (isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) {
currentFlow = createFlowMutation(FlowFlags.ArrayMutation, currentFlow, node);
}
@@ -1839,7 +1839,7 @@ namespace ts {
case SyntaxKind.ModuleBlock:
return ContainerFlags.IsControlFlowContainer;
case SyntaxKind.PropertyDeclaration:
return (<PropertyDeclaration>node).initializer ? ContainerFlags.IsControlFlowContainer : 0;
return (node as PropertyDeclaration).initializer ? ContainerFlags.IsControlFlowContainer : 0;
case SyntaxKind.CatchClause:
case SyntaxKind.ForStatement:
@@ -2099,7 +2099,7 @@ namespace ts {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
case SyntaxKind.SourceFile:
if (isExternalOrCommonJsModule(<SourceFile>container)) {
if (isExternalOrCommonJsModule(container as SourceFile)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
}
@@ -2249,7 +2249,7 @@ namespace ts {
if (inStrictMode && isLeftHandSideExpression(node.left) && isAssignmentOperator(node.operatorToken.kind)) {
// ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
// Assignment operator(11.13) or of a PostfixExpression(11.3)
checkStrictModeEvalOrArguments(node, <Identifier>node.left);
checkStrictModeEvalOrArguments(node, node.left as Identifier);
}
}
@@ -2277,7 +2277,7 @@ namespace ts {
function checkStrictModeEvalOrArguments(contextNode: Node, name: Node | undefined) {
if (name && name.kind === SyntaxKind.Identifier) {
const identifier = <Identifier>name;
const identifier = name as Identifier;
if (isEvalOrArgumentsIdentifier(identifier)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
// otherwise report generic error message.
@@ -2350,7 +2350,7 @@ namespace ts {
// Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
// operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
if (inStrictMode) {
checkStrictModeEvalOrArguments(node, <Identifier>node.operand);
checkStrictModeEvalOrArguments(node, node.operand as Identifier);
}
}
@@ -2358,7 +2358,7 @@ namespace ts {
// Grammar checking
if (inStrictMode) {
if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) {
checkStrictModeEvalOrArguments(node, <Identifier>node.operand);
checkStrictModeEvalOrArguments(node, node.operand as Identifier);
}
}
}
@@ -2479,7 +2479,7 @@ namespace ts {
return;
}
if (isUseStrictPrologueDirective(<ExpressionStatement>statement)) {
if (isUseStrictPrologueDirective(statement as ExpressionStatement)) {
inStrictMode = true;
return;
}
@@ -2503,7 +2503,7 @@ namespace ts {
// for typedef type names with namespaces, bind the new jsdoc type symbol here
// because it requires all containing namespaces to be in effect, namely the
// current "blockScopeContainer" needs to be set to its immediate namespace parent.
if ((<Identifier>node).isInJSDocNamespace) {
if ((node as Identifier).isInJSDocNamespace) {
let parentNode = node.parent;
while (parentNode && !isJSDocTypeAlias(parentNode)) {
parentNode = parentNode.parent;
@@ -2516,9 +2516,9 @@ namespace ts {
if (currentFlow && (isExpression(node) || parent.kind === SyntaxKind.ShorthandPropertyAssignment)) {
node.flowNode = currentFlow;
}
return checkContextualIdentifier(<Identifier>node);
return checkContextualIdentifier(node as Identifier);
case SyntaxKind.QualifiedName:
if (currentFlow && parent.kind === SyntaxKind.TypeQuery) {
if (currentFlow && isPartOfTypeQuery(node)) {
node.flowNode = currentFlow;
}
break;
@@ -2580,21 +2580,21 @@ namespace ts {
default:
Debug.fail("Unknown binary expression special property assignment kind");
}
return checkStrictModeBinaryExpression(<BinaryExpression>node);
return checkStrictModeBinaryExpression(node as BinaryExpression);
case SyntaxKind.CatchClause:
return checkStrictModeCatchClause(<CatchClause>node);
return checkStrictModeCatchClause(node as CatchClause);
case SyntaxKind.DeleteExpression:
return checkStrictModeDeleteExpression(<DeleteExpression>node);
return checkStrictModeDeleteExpression(node as DeleteExpression);
case SyntaxKind.NumericLiteral:
return checkStrictModeNumericLiteral(<NumericLiteral>node);
return checkStrictModeNumericLiteral(node as NumericLiteral);
case SyntaxKind.PostfixUnaryExpression:
return checkStrictModePostfixUnaryExpression(<PostfixUnaryExpression>node);
return checkStrictModePostfixUnaryExpression(node as PostfixUnaryExpression);
case SyntaxKind.PrefixUnaryExpression:
return checkStrictModePrefixUnaryExpression(<PrefixUnaryExpression>node);
return checkStrictModePrefixUnaryExpression(node as PrefixUnaryExpression);
case SyntaxKind.WithStatement:
return checkStrictModeWithStatement(<WithStatement>node);
return checkStrictModeWithStatement(node as WithStatement);
case SyntaxKind.LabeledStatement:
return checkStrictModeLabeledStatement(<LabeledStatement>node);
return checkStrictModeLabeledStatement(node as LabeledStatement);
case SyntaxKind.ThisType:
seenThisKeyword = true;
return;
@@ -2603,46 +2603,46 @@ namespace ts {
case SyntaxKind.TypeParameter:
return bindTypeParameter(node as TypeParameterDeclaration);
case SyntaxKind.Parameter:
return bindParameter(<ParameterDeclaration>node);
return bindParameter(node as ParameterDeclaration);
case SyntaxKind.VariableDeclaration:
return bindVariableDeclarationOrBindingElement(<VariableDeclaration>node);
return bindVariableDeclarationOrBindingElement(node as VariableDeclaration);
case SyntaxKind.BindingElement:
node.flowNode = currentFlow;
return bindVariableDeclarationOrBindingElement(<BindingElement>node);
return bindVariableDeclarationOrBindingElement(node as BindingElement);
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
return bindPropertyWorker(node as PropertyDeclaration | PropertySignature);
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
case SyntaxKind.EnumMember:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes);
return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes);
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Signature, SymbolFlags.None);
return declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Signature, SymbolFlags.None);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
// If this is an ObjectLiteralExpression method, then it sits in the same space
// 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(<Declaration>node, SymbolFlags.Method | ((<MethodDeclaration>node).questionToken ? SymbolFlags.Optional : SymbolFlags.None),
return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.Method | ((node as MethodDeclaration).questionToken ? SymbolFlags.Optional : SymbolFlags.None),
isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes);
case SyntaxKind.FunctionDeclaration:
return bindFunctionDeclaration(<FunctionDeclaration>node);
return bindFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.Constructor:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None);
return declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None);
case SyntaxKind.GetAccessor:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes);
return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes);
case SyntaxKind.SetAccessor:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes);
return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes);
case SyntaxKind.FunctionType:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.JSDocSignature:
case SyntaxKind.ConstructorType:
return bindFunctionOrConstructorType(<SignatureDeclaration | JSDocSignature>node);
return bindFunctionOrConstructorType(node as SignatureDeclaration | JSDocSignature);
case SyntaxKind.TypeLiteral:
case SyntaxKind.JSDocTypeLiteral:
case SyntaxKind.MappedType:
@@ -2650,10 +2650,10 @@ namespace ts {
case SyntaxKind.JSDocClassTag:
return bindJSDocClassTag(node as JSDocClassTag);
case SyntaxKind.ObjectLiteralExpression:
return bindObjectLiteralExpression(<ObjectLiteralExpression>node);
return bindObjectLiteralExpression(node as ObjectLiteralExpression);
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
return bindFunctionExpression(<FunctionExpression>node);
return bindFunctionExpression(node as FunctionExpression);
case SyntaxKind.CallExpression:
const assignmentKind = getAssignmentDeclarationKind(node as CallExpression);
@@ -2670,7 +2670,7 @@ namespace ts {
return Debug.fail("Unknown call expression assignment declaration kind");
}
if (isInJSFile(node)) {
bindCallExpression(<CallExpression>node);
bindCallExpression(node as CallExpression);
}
break;
@@ -2679,37 +2679,37 @@ namespace ts {
case SyntaxKind.ClassDeclaration:
// All classes are automatically in strict mode in ES6.
inStrictMode = true;
return bindClassLikeDeclaration(<ClassLikeDeclaration>node);
return bindClassLikeDeclaration(node as ClassLikeDeclaration);
case SyntaxKind.InterfaceDeclaration:
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes);
return bindBlockScopedDeclaration(node as Declaration, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes);
case SyntaxKind.TypeAliasDeclaration:
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
return bindBlockScopedDeclaration(node as Declaration, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
case SyntaxKind.EnumDeclaration:
return bindEnumDeclaration(<EnumDeclaration>node);
return bindEnumDeclaration(node as EnumDeclaration);
case SyntaxKind.ModuleDeclaration:
return bindModuleDeclaration(<ModuleDeclaration>node);
return bindModuleDeclaration(node as ModuleDeclaration);
// Jsx-attributes
case SyntaxKind.JsxAttributes:
return bindJsxAttributes(<JsxAttributes>node);
return bindJsxAttributes(node as JsxAttributes);
case SyntaxKind.JsxAttribute:
return bindJsxAttribute(<JsxAttribute>node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
return bindJsxAttribute(node as JsxAttribute, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
// Imports and exports
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.NamespaceImport:
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
return declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
case SyntaxKind.NamespaceExportDeclaration:
return bindNamespaceExportDeclaration(<NamespaceExportDeclaration>node);
return bindNamespaceExportDeclaration(node as NamespaceExportDeclaration);
case SyntaxKind.ImportClause:
return bindImportClause(<ImportClause>node);
return bindImportClause(node as ImportClause);
case SyntaxKind.ExportDeclaration:
return bindExportDeclaration(<ExportDeclaration>node);
return bindExportDeclaration(node as ExportDeclaration);
case SyntaxKind.ExportAssignment:
return bindExportAssignment(<ExportAssignment>node);
return bindExportAssignment(node as ExportAssignment);
case SyntaxKind.SourceFile:
updateStrictModeStatementList((<SourceFile>node).statements);
updateStrictModeStatementList((node as SourceFile).statements);
return bindSourceFileIfExternalModule();
case SyntaxKind.Block:
if (!isFunctionLike(node.parent)) {
@@ -2717,7 +2717,7 @@ namespace ts {
}
// falls through
case SyntaxKind.ModuleBlock:
return updateStrictModeStatementList((<Block | ModuleBlock>node).statements);
return updateStrictModeStatementList((node as Block | ModuleBlock).statements);
case SyntaxKind.JSDocParameterTag:
if (node.parent.kind === SyntaxKind.JSDocSignature) {
@@ -2745,7 +2745,7 @@ namespace ts {
}
function bindAnonymousTypeWorker(node: TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral) {
return bindAnonymousDeclaration(<Declaration>node, SymbolFlags.TypeLiteral, InternalSymbolName.Type);
return bindAnonymousDeclaration(node as Declaration, SymbolFlags.TypeLiteral, InternalSymbolName.Type);
}
function bindSourceFileIfExternalModule() {
@@ -3432,7 +3432,7 @@ namespace ts {
// report error on class declarations
node.kind === SyntaxKind.ClassDeclaration ||
// report error on instantiated modules or const-enums only modules if preserveConstEnums is set
(node.kind === SyntaxKind.ModuleDeclaration && shouldReportErrorOnModuleDeclaration(<ModuleDeclaration>node));
(node.kind === SyntaxKind.ModuleDeclaration && shouldReportErrorOnModuleDeclaration(node as ModuleDeclaration));
if (reportError) {
currentFlow = reportedUnreachableFlow;
+1144 -1138
View File
File diff suppressed because it is too large Load Diff
+19 -19
View File
@@ -1287,7 +1287,7 @@ namespace ts {
case "string":
return mapDefined(values, v => validateJsonOptionValue(opt.element, v || "", errors));
default:
return mapDefined(values, v => parseCustomTypeOption(<CommandLineOptionOfCustomType>opt.element, v, errors));
return mapDefined(values, v => parseCustomTypeOption(opt.element as CommandLineOptionOfCustomType, v, errors));
}
}
@@ -1466,7 +1466,7 @@ namespace ts {
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
options[opt.name] = parseCustomTypeOption(<CommandLineOptionOfCustomType>opt, args[i], errors);
options[opt.name] = parseCustomTypeOption(opt as CommandLineOptionOfCustomType, args[i], errors);
i++;
break;
}
@@ -1570,7 +1570,7 @@ namespace ts {
/* @internal */
export function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string {
const diagnostic = createCompilerDiagnostic.apply(undefined, arguments);
return <string>diagnostic.messageText;
return diagnostic.messageText as string;
}
export type DiagnosticReporter = (diagnostic: Diagnostic) => void;
@@ -1654,7 +1654,7 @@ namespace ts {
*/
export function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile {
const textOrDiagnostic = tryReadFile(fileName, readFile);
return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : <TsConfigSourceFile>{ fileName, parseDiagnostics: [textOrDiagnostic] };
return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { fileName, parseDiagnostics: [textOrDiagnostic] } as TsConfigSourceFile;
}
/*@internal*/
@@ -1961,9 +1961,9 @@ namespace ts {
errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.String_literal_with_double_quotes_expected));
}
reportInvalidOptionValue(option && (isString(option.type) && option.type !== "string"));
const text = (<StringLiteral>valueExpression).text;
const text = (valueExpression as StringLiteral).text;
if (option && !isString(option.type)) {
const customOption = <CommandLineOptionOfCustomType>option;
const customOption = option as CommandLineOptionOfCustomType;
// Validate custom option type
if (!customOption.type.has(text.toLowerCase())) {
errors.push(
@@ -1979,18 +1979,18 @@ namespace ts {
case SyntaxKind.NumericLiteral:
reportInvalidOptionValue(option && option.type !== "number");
return validateValue(Number((<NumericLiteral>valueExpression).text));
return validateValue(Number((valueExpression as NumericLiteral).text));
case SyntaxKind.PrefixUnaryExpression:
if ((<PrefixUnaryExpression>valueExpression).operator !== SyntaxKind.MinusToken || (<PrefixUnaryExpression>valueExpression).operand.kind !== SyntaxKind.NumericLiteral) {
if ((valueExpression as PrefixUnaryExpression).operator !== SyntaxKind.MinusToken || (valueExpression as PrefixUnaryExpression).operand.kind !== SyntaxKind.NumericLiteral) {
break; // not valid JSON syntax
}
reportInvalidOptionValue(option && option.type !== "number");
return validateValue(-Number((<NumericLiteral>(<PrefixUnaryExpression>valueExpression).operand).text));
return validateValue(-Number(((valueExpression as PrefixUnaryExpression).operand as NumericLiteral).text));
case SyntaxKind.ObjectLiteralExpression:
reportInvalidOptionValue(option && option.type !== "object");
const objectLiteralExpression = <ObjectLiteralExpression>valueExpression;
const objectLiteralExpression = valueExpression as ObjectLiteralExpression;
// Currently having element option declaration in the tsconfig with type "object"
// determines if it needs onSetValidOptionKeyValueInParent callback or not
@@ -1999,7 +1999,7 @@ namespace ts {
// vs what we set in the json
// If need arises, we can modify this interface and callbacks as needed
if (option) {
const { elementOptions, extraKeyDiagnostics, name: optionName } = <TsConfigOnlyOption>option;
const { elementOptions, extraKeyDiagnostics, name: optionName } = option as TsConfigOnlyOption;
return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression,
elementOptions, extraKeyDiagnostics, optionName));
}
@@ -2012,8 +2012,8 @@ namespace ts {
case SyntaxKind.ArrayLiteralExpression:
reportInvalidOptionValue(option && option.type !== "list");
return validateValue(convertArrayLiteralExpressionToJson(
(<ArrayLiteralExpression>valueExpression).elements,
option && (<CommandLineOptionOfListType>option).element));
(valueExpression as ArrayLiteralExpression).elements,
option && (option as CommandLineOptionOfListType).element));
}
// Not in expected format
@@ -2172,7 +2172,7 @@ namespace ts {
return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
}
else {
return (<CommandLineOptionOfCustomType>optionDefinition).type;
return (optionDefinition as CommandLineOptionOfCustomType).type;
}
}
@@ -2211,7 +2211,7 @@ namespace ts {
if (optionsNameMap.has(name) && optionsNameMap.get(name)!.category === Diagnostics.Command_line_Options) {
continue;
}
const value = <CompilerOptionsValue>options[name];
const value = options[name] as CompilerOptionsValue;
const optionDefinition = optionsNameMap.get(name.toLowerCase());
if (optionDefinition) {
const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
@@ -2782,7 +2782,7 @@ namespace ts {
case "extends":
const newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
extendedConfigPath = getExtendsConfigPath(
<string>value,
value as string,
host,
newBase,
errors,
@@ -2972,10 +2972,10 @@ namespace ts {
if (isCompilerOptionsValue(opt, value)) {
const optType = opt.type;
if (optType === "list" && isArray(value)) {
return convertJsonOptionOfListType(<CommandLineOptionOfListType>opt, value, basePath, errors);
return convertJsonOptionOfListType(opt as CommandLineOptionOfListType, value, basePath, errors);
}
else if (!isString(optType)) {
return convertJsonOptionOfCustomType(<CommandLineOptionOfCustomType>opt, <string>value, errors);
return convertJsonOptionOfCustomType(opt as CommandLineOptionOfCustomType, value as string, errors);
}
const validatedValue = validateJsonOptionValue(opt, value, errors);
return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue);
@@ -2990,7 +2990,7 @@ namespace ts {
if (option.type === "list") {
const listOption = option;
if (listOption.element.isFilePath || !isString(listOption.element.type)) {
return <CompilerOptionsValue>filter(map(value, v => normalizeOptionValue(listOption.element, basePath, v)), v => !!v);
return filter(map(value, v => normalizeOptionValue(listOption.element, basePath, v)), v => !!v) as CompilerOptionsValue;
}
return value;
}
+2 -2
View File
@@ -1429,7 +1429,7 @@ namespace ts {
const result: any = {};
for (const id in object) {
if (hasOwnProperty.call(object, id)) {
result[id] = (<any>object)[id];
result[id] = (object as any)[id];
}
}
return result;
@@ -1441,7 +1441,7 @@ namespace ts {
* NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
*/
export function extend<T1, T2>(first: T1, second: T2): T1 & T2 {
const result: T1 & T2 = <any>{};
const result: T1 & T2 = {} as any;
for (const id in second) {
if (hasOwnProperty.call(second, id)) {
(result as any)[id] = (second as any)[id];
+14 -14
View File
@@ -112,8 +112,8 @@ namespace ts {
export function fail(message?: string, stackCrawlMark?: AnyFunction): never {
debugger;
const e = new Error(message ? `Debug Failure. ${message}` : "Debug Failure.");
if ((<any>Error).captureStackTrace) {
(<any>Error).captureStackTrace(e, stackCrawlMark || fail);
if ((Error as any).captureStackTrace) {
(Error as any).captureStackTrace(e, stackCrawlMark || fail);
}
throw e;
}
@@ -288,7 +288,7 @@ namespace ts {
return "";
}
else if (func.hasOwnProperty("name")) {
return (<any>func).name;
return (func as any).name;
}
else {
const text = Function.prototype.toString.call(func);
@@ -348,43 +348,43 @@ namespace ts {
}
export function formatSyntaxKind(kind: SyntaxKind | undefined): string {
return formatEnum(kind, (<any>ts).SyntaxKind, /*isFlags*/ false);
return formatEnum(kind, (ts as any).SyntaxKind, /*isFlags*/ false);
}
export function formatNodeFlags(flags: NodeFlags | undefined): string {
return formatEnum(flags, (<any>ts).NodeFlags, /*isFlags*/ true);
return formatEnum(flags, (ts as any).NodeFlags, /*isFlags*/ true);
}
export function formatModifierFlags(flags: ModifierFlags | undefined): string {
return formatEnum(flags, (<any>ts).ModifierFlags, /*isFlags*/ true);
return formatEnum(flags, (ts as any).ModifierFlags, /*isFlags*/ true);
}
export function formatTransformFlags(flags: TransformFlags | undefined): string {
return formatEnum(flags, (<any>ts).TransformFlags, /*isFlags*/ true);
return formatEnum(flags, (ts as any).TransformFlags, /*isFlags*/ true);
}
export function formatEmitFlags(flags: EmitFlags | undefined): string {
return formatEnum(flags, (<any>ts).EmitFlags, /*isFlags*/ true);
return formatEnum(flags, (ts as any).EmitFlags, /*isFlags*/ true);
}
export function formatSymbolFlags(flags: SymbolFlags | undefined): string {
return formatEnum(flags, (<any>ts).SymbolFlags, /*isFlags*/ true);
return formatEnum(flags, (ts as any).SymbolFlags, /*isFlags*/ true);
}
export function formatTypeFlags(flags: TypeFlags | undefined): string {
return formatEnum(flags, (<any>ts).TypeFlags, /*isFlags*/ true);
return formatEnum(flags, (ts as any).TypeFlags, /*isFlags*/ true);
}
export function formatSignatureFlags(flags: SignatureFlags | undefined): string {
return formatEnum(flags, (<any>ts).SignatureFlags, /*isFlags*/ true);
return formatEnum(flags, (ts as any).SignatureFlags, /*isFlags*/ true);
}
export function formatObjectFlags(flags: ObjectFlags | undefined): string {
return formatEnum(flags, (<any>ts).ObjectFlags, /*isFlags*/ true);
return formatEnum(flags, (ts as any).ObjectFlags, /*isFlags*/ true);
}
export function formatFlowFlags(flags: FlowFlags | undefined): string {
return formatEnum(flags, (<any>ts).FlowFlags, /*isFlags*/ true);
return formatEnum(flags, (ts as any).FlowFlags, /*isFlags*/ true);
}
let isDebugInfoEnabled = false;
@@ -570,7 +570,7 @@ namespace ts {
}
},
__debugFlags: { get(this: Type) { return formatTypeFlags(this.flags); } },
__debugObjectFlags: { get(this: Type) { return this.flags & TypeFlags.Object ? formatObjectFlags((<ObjectType>this).objectFlags) : ""; } },
__debugObjectFlags: { get(this: Type) { return this.flags & TypeFlags.Object ? formatObjectFlags((this as ObjectType).objectFlags) : ""; } },
__debugTypeToString: {
value(this: Type) {
// avoid recomputing
+9 -1
View File
@@ -15,7 +15,7 @@
"category": "Error",
"code": 1006
},
"The parser expected to find a '{1}' to match the '{0}' token here.": {
"The parser expected to find a '}' to match the '{' token here.": {
"category": "Error",
"code": 1007
},
@@ -887,6 +887,10 @@
"category": "Error",
"code": 1266
},
"Property '{0}' cannot have an initializer because it is marked abstract.": {
"category": "Error",
"code": 1267
},
"'with' statements are not allowed in an async function block.": {
"category": "Error",
@@ -6393,6 +6397,10 @@
"category": "Message",
"code": 95163
},
"Can only convert named export": {
"category": "Message",
"code": 95164
},
"No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": {
"category": "Error",
+181 -181
View File
@@ -959,9 +959,9 @@ namespace ts {
break;
}
switch (node.kind) {
case SyntaxKind.SourceFile: return printFile(<SourceFile>node);
case SyntaxKind.Bundle: return printBundle(<Bundle>node);
case SyntaxKind.UnparsedSource: return printUnparsedSource(<UnparsedSource>node);
case SyntaxKind.SourceFile: return printFile(node as SourceFile);
case SyntaxKind.Bundle: return printBundle(node as Bundle);
case SyntaxKind.UnparsedSource: return printUnparsedSource(node as UnparsedSource);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -1317,11 +1317,11 @@ namespace ts {
case SyntaxKind.TemplateHead:
case SyntaxKind.TemplateMiddle:
case SyntaxKind.TemplateTail:
return emitLiteral(<LiteralExpression>node, /*jsxAttributeEscape*/ false);
return emitLiteral(node as LiteralExpression, /*jsxAttributeEscape*/ false);
// Identifiers
case SyntaxKind.Identifier:
return emitIdentifier(<Identifier>node);
return emitIdentifier(node as Identifier);
// PrivateIdentifiers
case SyntaxKind.PrivateIdentifier:
@@ -1330,251 +1330,251 @@ namespace ts {
// Parse tree nodes
// Names
case SyntaxKind.QualifiedName:
return emitQualifiedName(<QualifiedName>node);
return emitQualifiedName(node as QualifiedName);
case SyntaxKind.ComputedPropertyName:
return emitComputedPropertyName(<ComputedPropertyName>node);
return emitComputedPropertyName(node as ComputedPropertyName);
// Signature elements
case SyntaxKind.TypeParameter:
return emitTypeParameter(<TypeParameterDeclaration>node);
return emitTypeParameter(node as TypeParameterDeclaration);
case SyntaxKind.Parameter:
return emitParameter(<ParameterDeclaration>node);
return emitParameter(node as ParameterDeclaration);
case SyntaxKind.Decorator:
return emitDecorator(<Decorator>node);
return emitDecorator(node as Decorator);
// Type members
case SyntaxKind.PropertySignature:
return emitPropertySignature(<PropertySignature>node);
return emitPropertySignature(node as PropertySignature);
case SyntaxKind.PropertyDeclaration:
return emitPropertyDeclaration(<PropertyDeclaration>node);
return emitPropertyDeclaration(node as PropertyDeclaration);
case SyntaxKind.MethodSignature:
return emitMethodSignature(<MethodSignature>node);
return emitMethodSignature(node as MethodSignature);
case SyntaxKind.MethodDeclaration:
return emitMethodDeclaration(<MethodDeclaration>node);
return emitMethodDeclaration(node as MethodDeclaration);
case SyntaxKind.Constructor:
return emitConstructor(<ConstructorDeclaration>node);
return emitConstructor(node as ConstructorDeclaration);
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return emitAccessorDeclaration(<AccessorDeclaration>node);
return emitAccessorDeclaration(node as AccessorDeclaration);
case SyntaxKind.CallSignature:
return emitCallSignature(<CallSignatureDeclaration>node);
return emitCallSignature(node as CallSignatureDeclaration);
case SyntaxKind.ConstructSignature:
return emitConstructSignature(<ConstructSignatureDeclaration>node);
return emitConstructSignature(node as ConstructSignatureDeclaration);
case SyntaxKind.IndexSignature:
return emitIndexSignature(<IndexSignatureDeclaration>node);
return emitIndexSignature(node as IndexSignatureDeclaration);
// Types
case SyntaxKind.TypePredicate:
return emitTypePredicate(<TypePredicateNode>node);
return emitTypePredicate(node as TypePredicateNode);
case SyntaxKind.TypeReference:
return emitTypeReference(<TypeReferenceNode>node);
return emitTypeReference(node as TypeReferenceNode);
case SyntaxKind.FunctionType:
return emitFunctionType(<FunctionTypeNode>node);
return emitFunctionType(node as FunctionTypeNode);
case SyntaxKind.ConstructorType:
return emitConstructorType(<ConstructorTypeNode>node);
return emitConstructorType(node as ConstructorTypeNode);
case SyntaxKind.TypeQuery:
return emitTypeQuery(<TypeQueryNode>node);
return emitTypeQuery(node as TypeQueryNode);
case SyntaxKind.TypeLiteral:
return emitTypeLiteral(<TypeLiteralNode>node);
return emitTypeLiteral(node as TypeLiteralNode);
case SyntaxKind.ArrayType:
return emitArrayType(<ArrayTypeNode>node);
return emitArrayType(node as ArrayTypeNode);
case SyntaxKind.TupleType:
return emitTupleType(<TupleTypeNode>node);
return emitTupleType(node as TupleTypeNode);
case SyntaxKind.OptionalType:
return emitOptionalType(<OptionalTypeNode>node);
return emitOptionalType(node as OptionalTypeNode);
// SyntaxKind.RestType is handled below
case SyntaxKind.UnionType:
return emitUnionType(<UnionTypeNode>node);
return emitUnionType(node as UnionTypeNode);
case SyntaxKind.IntersectionType:
return emitIntersectionType(<IntersectionTypeNode>node);
return emitIntersectionType(node as IntersectionTypeNode);
case SyntaxKind.ConditionalType:
return emitConditionalType(<ConditionalTypeNode>node);
return emitConditionalType(node as ConditionalTypeNode);
case SyntaxKind.InferType:
return emitInferType(<InferTypeNode>node);
return emitInferType(node as InferTypeNode);
case SyntaxKind.ParenthesizedType:
return emitParenthesizedType(<ParenthesizedTypeNode>node);
return emitParenthesizedType(node as ParenthesizedTypeNode);
case SyntaxKind.ExpressionWithTypeArguments:
return emitExpressionWithTypeArguments(<ExpressionWithTypeArguments>node);
return emitExpressionWithTypeArguments(node as ExpressionWithTypeArguments);
case SyntaxKind.ThisType:
return emitThisType();
case SyntaxKind.TypeOperator:
return emitTypeOperator(<TypeOperatorNode>node);
return emitTypeOperator(node as TypeOperatorNode);
case SyntaxKind.IndexedAccessType:
return emitIndexedAccessType(<IndexedAccessTypeNode>node);
return emitIndexedAccessType(node as IndexedAccessTypeNode);
case SyntaxKind.MappedType:
return emitMappedType(<MappedTypeNode>node);
return emitMappedType(node as MappedTypeNode);
case SyntaxKind.LiteralType:
return emitLiteralType(<LiteralTypeNode>node);
return emitLiteralType(node as LiteralTypeNode);
case SyntaxKind.NamedTupleMember:
return emitNamedTupleMember(node as NamedTupleMember);
case SyntaxKind.TemplateLiteralType:
return emitTemplateType(<TemplateLiteralTypeNode>node);
return emitTemplateType(node as TemplateLiteralTypeNode);
case SyntaxKind.TemplateLiteralTypeSpan:
return emitTemplateTypeSpan(<TemplateLiteralTypeSpan>node);
return emitTemplateTypeSpan(node as TemplateLiteralTypeSpan);
case SyntaxKind.ImportType:
return emitImportTypeNode(<ImportTypeNode>node);
return emitImportTypeNode(node as ImportTypeNode);
// Binding patterns
case SyntaxKind.ObjectBindingPattern:
return emitObjectBindingPattern(<ObjectBindingPattern>node);
return emitObjectBindingPattern(node as ObjectBindingPattern);
case SyntaxKind.ArrayBindingPattern:
return emitArrayBindingPattern(<ArrayBindingPattern>node);
return emitArrayBindingPattern(node as ArrayBindingPattern);
case SyntaxKind.BindingElement:
return emitBindingElement(<BindingElement>node);
return emitBindingElement(node as BindingElement);
// Misc
case SyntaxKind.TemplateSpan:
return emitTemplateSpan(<TemplateSpan>node);
return emitTemplateSpan(node as TemplateSpan);
case SyntaxKind.SemicolonClassElement:
return emitSemicolonClassElement();
// Statements
case SyntaxKind.Block:
return emitBlock(<Block>node);
return emitBlock(node as Block);
case SyntaxKind.VariableStatement:
return emitVariableStatement(<VariableStatement>node);
return emitVariableStatement(node as VariableStatement);
case SyntaxKind.EmptyStatement:
return emitEmptyStatement(/*isEmbeddedStatement*/ false);
case SyntaxKind.ExpressionStatement:
return emitExpressionStatement(<ExpressionStatement>node);
return emitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.IfStatement:
return emitIfStatement(<IfStatement>node);
return emitIfStatement(node as IfStatement);
case SyntaxKind.DoStatement:
return emitDoStatement(<DoStatement>node);
return emitDoStatement(node as DoStatement);
case SyntaxKind.WhileStatement:
return emitWhileStatement(<WhileStatement>node);
return emitWhileStatement(node as WhileStatement);
case SyntaxKind.ForStatement:
return emitForStatement(<ForStatement>node);
return emitForStatement(node as ForStatement);
case SyntaxKind.ForInStatement:
return emitForInStatement(<ForInStatement>node);
return emitForInStatement(node as ForInStatement);
case SyntaxKind.ForOfStatement:
return emitForOfStatement(<ForOfStatement>node);
return emitForOfStatement(node as ForOfStatement);
case SyntaxKind.ContinueStatement:
return emitContinueStatement(<ContinueStatement>node);
return emitContinueStatement(node as ContinueStatement);
case SyntaxKind.BreakStatement:
return emitBreakStatement(<BreakStatement>node);
return emitBreakStatement(node as BreakStatement);
case SyntaxKind.ReturnStatement:
return emitReturnStatement(<ReturnStatement>node);
return emitReturnStatement(node as ReturnStatement);
case SyntaxKind.WithStatement:
return emitWithStatement(<WithStatement>node);
return emitWithStatement(node as WithStatement);
case SyntaxKind.SwitchStatement:
return emitSwitchStatement(<SwitchStatement>node);
return emitSwitchStatement(node as SwitchStatement);
case SyntaxKind.LabeledStatement:
return emitLabeledStatement(<LabeledStatement>node);
return emitLabeledStatement(node as LabeledStatement);
case SyntaxKind.ThrowStatement:
return emitThrowStatement(<ThrowStatement>node);
return emitThrowStatement(node as ThrowStatement);
case SyntaxKind.TryStatement:
return emitTryStatement(<TryStatement>node);
return emitTryStatement(node as TryStatement);
case SyntaxKind.DebuggerStatement:
return emitDebuggerStatement(<DebuggerStatement>node);
return emitDebuggerStatement(node as DebuggerStatement);
// Declarations
case SyntaxKind.VariableDeclaration:
return emitVariableDeclaration(<VariableDeclaration>node);
return emitVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.VariableDeclarationList:
return emitVariableDeclarationList(<VariableDeclarationList>node);
return emitVariableDeclarationList(node as VariableDeclarationList);
case SyntaxKind.FunctionDeclaration:
return emitFunctionDeclaration(<FunctionDeclaration>node);
return emitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.ClassDeclaration:
return emitClassDeclaration(<ClassDeclaration>node);
return emitClassDeclaration(node as ClassDeclaration);
case SyntaxKind.InterfaceDeclaration:
return emitInterfaceDeclaration(<InterfaceDeclaration>node);
return emitInterfaceDeclaration(node as InterfaceDeclaration);
case SyntaxKind.TypeAliasDeclaration:
return emitTypeAliasDeclaration(<TypeAliasDeclaration>node);
return emitTypeAliasDeclaration(node as TypeAliasDeclaration);
case SyntaxKind.EnumDeclaration:
return emitEnumDeclaration(<EnumDeclaration>node);
return emitEnumDeclaration(node as EnumDeclaration);
case SyntaxKind.ModuleDeclaration:
return emitModuleDeclaration(<ModuleDeclaration>node);
return emitModuleDeclaration(node as ModuleDeclaration);
case SyntaxKind.ModuleBlock:
return emitModuleBlock(<ModuleBlock>node);
return emitModuleBlock(node as ModuleBlock);
case SyntaxKind.CaseBlock:
return emitCaseBlock(<CaseBlock>node);
return emitCaseBlock(node as CaseBlock);
case SyntaxKind.NamespaceExportDeclaration:
return emitNamespaceExportDeclaration(<NamespaceExportDeclaration>node);
return emitNamespaceExportDeclaration(node as NamespaceExportDeclaration);
case SyntaxKind.ImportEqualsDeclaration:
return emitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
return emitImportEqualsDeclaration(node as ImportEqualsDeclaration);
case SyntaxKind.ImportDeclaration:
return emitImportDeclaration(<ImportDeclaration>node);
return emitImportDeclaration(node as ImportDeclaration);
case SyntaxKind.ImportClause:
return emitImportClause(<ImportClause>node);
return emitImportClause(node as ImportClause);
case SyntaxKind.NamespaceImport:
return emitNamespaceImport(<NamespaceImport>node);
return emitNamespaceImport(node as NamespaceImport);
case SyntaxKind.NamespaceExport:
return emitNamespaceExport(<NamespaceExport>node);
return emitNamespaceExport(node as NamespaceExport);
case SyntaxKind.NamedImports:
return emitNamedImports(<NamedImports>node);
return emitNamedImports(node as NamedImports);
case SyntaxKind.ImportSpecifier:
return emitImportSpecifier(<ImportSpecifier>node);
return emitImportSpecifier(node as ImportSpecifier);
case SyntaxKind.ExportAssignment:
return emitExportAssignment(<ExportAssignment>node);
return emitExportAssignment(node as ExportAssignment);
case SyntaxKind.ExportDeclaration:
return emitExportDeclaration(<ExportDeclaration>node);
return emitExportDeclaration(node as ExportDeclaration);
case SyntaxKind.NamedExports:
return emitNamedExports(<NamedExports>node);
return emitNamedExports(node as NamedExports);
case SyntaxKind.ExportSpecifier:
return emitExportSpecifier(<ExportSpecifier>node);
return emitExportSpecifier(node as ExportSpecifier);
case SyntaxKind.MissingDeclaration:
return;
// Module references
case SyntaxKind.ExternalModuleReference:
return emitExternalModuleReference(<ExternalModuleReference>node);
return emitExternalModuleReference(node as ExternalModuleReference);
// JSX (non-expression)
case SyntaxKind.JsxText:
return emitJsxText(<JsxText>node);
return emitJsxText(node as JsxText);
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.JsxOpeningFragment:
return emitJsxOpeningElementOrFragment(<JsxOpeningElement>node);
return emitJsxOpeningElementOrFragment(node as JsxOpeningElement);
case SyntaxKind.JsxClosingElement:
case SyntaxKind.JsxClosingFragment:
return emitJsxClosingElementOrFragment(<JsxClosingElement>node);
return emitJsxClosingElementOrFragment(node as JsxClosingElement);
case SyntaxKind.JsxAttribute:
return emitJsxAttribute(<JsxAttribute>node);
return emitJsxAttribute(node as JsxAttribute);
case SyntaxKind.JsxAttributes:
return emitJsxAttributes(<JsxAttributes>node);
return emitJsxAttributes(node as JsxAttributes);
case SyntaxKind.JsxSpreadAttribute:
return emitJsxSpreadAttribute(<JsxSpreadAttribute>node);
return emitJsxSpreadAttribute(node as JsxSpreadAttribute);
case SyntaxKind.JsxExpression:
return emitJsxExpression(<JsxExpression>node);
return emitJsxExpression(node as JsxExpression);
// Clauses
case SyntaxKind.CaseClause:
return emitCaseClause(<CaseClause>node);
return emitCaseClause(node as CaseClause);
case SyntaxKind.DefaultClause:
return emitDefaultClause(<DefaultClause>node);
return emitDefaultClause(node as DefaultClause);
case SyntaxKind.HeritageClause:
return emitHeritageClause(<HeritageClause>node);
return emitHeritageClause(node as HeritageClause);
case SyntaxKind.CatchClause:
return emitCatchClause(<CatchClause>node);
return emitCatchClause(node as CatchClause);
// Property assignments
case SyntaxKind.PropertyAssignment:
return emitPropertyAssignment(<PropertyAssignment>node);
return emitPropertyAssignment(node as PropertyAssignment);
case SyntaxKind.ShorthandPropertyAssignment:
return emitShorthandPropertyAssignment(<ShorthandPropertyAssignment>node);
return emitShorthandPropertyAssignment(node as ShorthandPropertyAssignment);
case SyntaxKind.SpreadAssignment:
return emitSpreadAssignment(node as SpreadAssignment);
// Enum
case SyntaxKind.EnumMember:
return emitEnumMember(<EnumMember>node);
return emitEnumMember(node as EnumMember);
// Unparsed
case SyntaxKind.UnparsedPrologue:
return writeUnparsedNode(<UnparsedNode>node);
return writeUnparsedNode(node as UnparsedNode);
case SyntaxKind.UnparsedSource:
case SyntaxKind.UnparsedPrepend:
return emitUnparsedSourceOrPrepend(<UnparsedSource>node);
return emitUnparsedSourceOrPrepend(node as UnparsedSource);
case SyntaxKind.UnparsedText:
case SyntaxKind.UnparsedInternalText:
return emitUnparsedTextLike(<UnparsedTextLike>node);
return emitUnparsedTextLike(node as UnparsedTextLike);
case SyntaxKind.UnparsedSyntheticReference:
return emitUnparsedSyntheticReference(<UnparsedSyntheticReference>node);
return emitUnparsedSyntheticReference(node as UnparsedSyntheticReference);
// Top-level nodes
case SyntaxKind.SourceFile:
return emitSourceFile(<SourceFile>node);
return emitSourceFile(node as SourceFile);
case SyntaxKind.Bundle:
return Debug.fail("Bundles should be printed using printBundle");
// SyntaxKind.UnparsedSource (handled above)
@@ -1668,82 +1668,82 @@ namespace ts {
// Literals
case SyntaxKind.NumericLiteral:
case SyntaxKind.BigIntLiteral:
return emitNumericOrBigIntLiteral(<NumericLiteral | BigIntLiteral>node);
return emitNumericOrBigIntLiteral(node as NumericLiteral | BigIntLiteral);
case SyntaxKind.StringLiteral:
case SyntaxKind.RegularExpressionLiteral:
case SyntaxKind.NoSubstitutionTemplateLiteral:
return emitLiteral(<LiteralExpression>node, /*jsxAttributeEscape*/ false);
return emitLiteral(node as LiteralExpression, /*jsxAttributeEscape*/ false);
// Identifiers
case SyntaxKind.Identifier:
return emitIdentifier(<Identifier>node);
return emitIdentifier(node as Identifier);
// Expressions
case SyntaxKind.ArrayLiteralExpression:
return emitArrayLiteralExpression(<ArrayLiteralExpression>node);
return emitArrayLiteralExpression(node as ArrayLiteralExpression);
case SyntaxKind.ObjectLiteralExpression:
return emitObjectLiteralExpression(<ObjectLiteralExpression>node);
return emitObjectLiteralExpression(node as ObjectLiteralExpression);
case SyntaxKind.PropertyAccessExpression:
return emitPropertyAccessExpression(<PropertyAccessExpression>node);
return emitPropertyAccessExpression(node as PropertyAccessExpression);
case SyntaxKind.ElementAccessExpression:
return emitElementAccessExpression(<ElementAccessExpression>node);
return emitElementAccessExpression(node as ElementAccessExpression);
case SyntaxKind.CallExpression:
return emitCallExpression(<CallExpression>node);
return emitCallExpression(node as CallExpression);
case SyntaxKind.NewExpression:
return emitNewExpression(<NewExpression>node);
return emitNewExpression(node as NewExpression);
case SyntaxKind.TaggedTemplateExpression:
return emitTaggedTemplateExpression(<TaggedTemplateExpression>node);
return emitTaggedTemplateExpression(node as TaggedTemplateExpression);
case SyntaxKind.TypeAssertionExpression:
return emitTypeAssertionExpression(<TypeAssertion>node);
return emitTypeAssertionExpression(node as TypeAssertion);
case SyntaxKind.ParenthesizedExpression:
return emitParenthesizedExpression(<ParenthesizedExpression>node);
return emitParenthesizedExpression(node as ParenthesizedExpression);
case SyntaxKind.FunctionExpression:
return emitFunctionExpression(<FunctionExpression>node);
return emitFunctionExpression(node as FunctionExpression);
case SyntaxKind.ArrowFunction:
return emitArrowFunction(<ArrowFunction>node);
return emitArrowFunction(node as ArrowFunction);
case SyntaxKind.DeleteExpression:
return emitDeleteExpression(<DeleteExpression>node);
return emitDeleteExpression(node as DeleteExpression);
case SyntaxKind.TypeOfExpression:
return emitTypeOfExpression(<TypeOfExpression>node);
return emitTypeOfExpression(node as TypeOfExpression);
case SyntaxKind.VoidExpression:
return emitVoidExpression(<VoidExpression>node);
return emitVoidExpression(node as VoidExpression);
case SyntaxKind.AwaitExpression:
return emitAwaitExpression(<AwaitExpression>node);
return emitAwaitExpression(node as AwaitExpression);
case SyntaxKind.PrefixUnaryExpression:
return emitPrefixUnaryExpression(<PrefixUnaryExpression>node);
return emitPrefixUnaryExpression(node as PrefixUnaryExpression);
case SyntaxKind.PostfixUnaryExpression:
return emitPostfixUnaryExpression(<PostfixUnaryExpression>node);
return emitPostfixUnaryExpression(node as PostfixUnaryExpression);
case SyntaxKind.BinaryExpression:
return emitBinaryExpression(<BinaryExpression>node);
return emitBinaryExpression(node as BinaryExpression);
case SyntaxKind.ConditionalExpression:
return emitConditionalExpression(<ConditionalExpression>node);
return emitConditionalExpression(node as ConditionalExpression);
case SyntaxKind.TemplateExpression:
return emitTemplateExpression(<TemplateExpression>node);
return emitTemplateExpression(node as TemplateExpression);
case SyntaxKind.YieldExpression:
return emitYieldExpression(<YieldExpression>node);
return emitYieldExpression(node as YieldExpression);
case SyntaxKind.SpreadElement:
return emitSpreadElement(<SpreadElement>node);
return emitSpreadElement(node as SpreadElement);
case SyntaxKind.ClassExpression:
return emitClassExpression(<ClassExpression>node);
return emitClassExpression(node as ClassExpression);
case SyntaxKind.OmittedExpression:
return;
case SyntaxKind.AsExpression:
return emitAsExpression(<AsExpression>node);
return emitAsExpression(node as AsExpression);
case SyntaxKind.NonNullExpression:
return emitNonNullExpression(<NonNullExpression>node);
return emitNonNullExpression(node as NonNullExpression);
case SyntaxKind.MetaProperty:
return emitMetaProperty(<MetaProperty>node);
return emitMetaProperty(node as MetaProperty);
case SyntaxKind.SyntheticExpression:
return Debug.fail("SyntheticExpression should never be printed.");
// JSX
case SyntaxKind.JsxElement:
return emitJsxElement(<JsxElement>node);
return emitJsxElement(node as JsxElement);
case SyntaxKind.JsxSelfClosingElement:
return emitJsxSelfClosingElement(<JsxSelfClosingElement>node);
return emitJsxSelfClosingElement(node as JsxSelfClosingElement);
case SyntaxKind.JsxFragment:
return emitJsxFragment(<JsxFragment>node);
return emitJsxFragment(node as JsxFragment);
// Synthesized list
case SyntaxKind.SyntaxList:
@@ -1753,9 +1753,9 @@ namespace ts {
case SyntaxKind.NotEmittedStatement:
return;
case SyntaxKind.PartiallyEmittedExpression:
return emitPartiallyEmittedExpression(<PartiallyEmittedExpression>node);
return emitPartiallyEmittedExpression(node as PartiallyEmittedExpression);
case SyntaxKind.CommaListExpression:
return emitCommaList(<CommaListExpression>node);
return emitCommaList(node as CommaListExpression);
case SyntaxKind.MergeDeclarationMarker:
case SyntaxKind.EndOfDeclarationMarker:
return;
@@ -1807,7 +1807,7 @@ namespace ts {
function emitHelpers(node: Node) {
let helpersEmitted = false;
const bundle = node.kind === SyntaxKind.Bundle ? <Bundle>node : undefined;
const bundle = node.kind === SyntaxKind.Bundle ? node as Bundle : undefined;
if (bundle && moduleKind === ModuleKind.None) {
return;
}
@@ -2450,7 +2450,7 @@ namespace ts {
expression = skipPartiallyEmittedExpressions(expression);
if (isNumericLiteral(expression)) {
// check if numeric literal is a decimal literal that was originally written with a dot
const text = getLiteralTextOfNode(<LiteralExpression>expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
const text = getLiteralTextOfNode(expression as LiteralExpression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
// If he number will be printed verbatim and it doesn't already contain a dot, add one
// if the expression doesn't have any comments that will be emitted.
return !expression.numericLiteralFlags && !stringContains(text, tokenToString(SyntaxKind.DotToken)!);
@@ -2576,8 +2576,8 @@ namespace ts {
// The same is true of minus of course.
const operand = node.operand;
return operand.kind === SyntaxKind.PrefixUnaryExpression
&& ((node.operator === SyntaxKind.PlusToken && ((<PrefixUnaryExpression>operand).operator === SyntaxKind.PlusToken || (<PrefixUnaryExpression>operand).operator === SyntaxKind.PlusPlusToken))
|| (node.operator === SyntaxKind.MinusToken && ((<PrefixUnaryExpression>operand).operator === SyntaxKind.MinusToken || (<PrefixUnaryExpression>operand).operator === SyntaxKind.MinusMinusToken)));
&& ((node.operator === SyntaxKind.PlusToken && ((operand as PrefixUnaryExpression).operator === SyntaxKind.PlusToken || (operand as PrefixUnaryExpression).operator === SyntaxKind.PlusPlusToken))
|| (node.operator === SyntaxKind.MinusToken && ((operand as PrefixUnaryExpression).operator === SyntaxKind.MinusToken || (operand as PrefixUnaryExpression).operator === SyntaxKind.MinusMinusToken)));
}
function emitPostfixUnaryExpression(node: PostfixUnaryExpression) {
@@ -3785,7 +3785,7 @@ namespace ts {
emit(tagName);
}
function emitJSDocComment(comment: string | NodeArray<JSDocText | JSDocLink> | undefined) {
function emitJSDocComment(comment: string | NodeArray<JSDocComment> | undefined) {
const text = getTextOfJSDocComment(comment);
if (text) {
writeSpace();
@@ -4705,7 +4705,7 @@ namespace ts {
function skipSynthesizedParentheses(node: Node) {
while (node.kind === SyntaxKind.ParenthesizedExpression && nodeIsSynthesized(node)) {
node = (<ParenthesizedExpression>node).expression;
node = (node as ParenthesizedExpression).expression;
}
return node;
@@ -4718,8 +4718,8 @@ namespace ts {
else if ((isIdentifier(node) || isPrivateIdentifier(node)) && (nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && getSourceFileOfNode(node) !== getOriginalNode(currentSourceFile)))) {
return idText(node);
}
else if (node.kind === SyntaxKind.StringLiteral && (<StringLiteral>node).textSourceNode) {
return getTextOfNode((<StringLiteral>node).textSourceNode!, includeTrivia);
else if (node.kind === SyntaxKind.StringLiteral && (node as StringLiteral).textSourceNode) {
return getTextOfNode((node as StringLiteral).textSourceNode!, includeTrivia);
}
else if (isLiteralExpression(node) && (nodeIsSynthesized(node) || !node.parent)) {
return node.text;
@@ -4729,8 +4729,8 @@ namespace ts {
}
function getLiteralTextOfNode(node: LiteralLikeNode, neverAsciiEscape: boolean | undefined, jsxAttributeEscape: boolean): string {
if (node.kind === SyntaxKind.StringLiteral && (<StringLiteral>node).textSourceNode) {
const textSourceNode = (<StringLiteral>node).textSourceNode!;
if (node.kind === SyntaxKind.StringLiteral && (node as StringLiteral).textSourceNode) {
const textSourceNode = (node as StringLiteral).textSourceNode!;
if (isIdentifier(textSourceNode) || isNumericLiteral(textSourceNode)) {
const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode);
return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` :
@@ -4784,84 +4784,84 @@ namespace ts {
if (!node) return;
switch (node.kind) {
case SyntaxKind.Block:
forEach((<Block>node).statements, generateNames);
forEach((node as Block).statements, generateNames);
break;
case SyntaxKind.LabeledStatement:
case SyntaxKind.WithStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
generateNames((<LabeledStatement | WithStatement | DoStatement | WhileStatement>node).statement);
generateNames((node as LabeledStatement | WithStatement | DoStatement | WhileStatement).statement);
break;
case SyntaxKind.IfStatement:
generateNames((<IfStatement>node).thenStatement);
generateNames((<IfStatement>node).elseStatement);
generateNames((node as IfStatement).thenStatement);
generateNames((node as IfStatement).elseStatement);
break;
case SyntaxKind.ForStatement:
case SyntaxKind.ForOfStatement:
case SyntaxKind.ForInStatement:
generateNames((<ForStatement | ForInOrOfStatement>node).initializer);
generateNames((<ForStatement | ForInOrOfStatement>node).statement);
generateNames((node as ForStatement | ForInOrOfStatement).initializer);
generateNames((node as ForStatement | ForInOrOfStatement).statement);
break;
case SyntaxKind.SwitchStatement:
generateNames((<SwitchStatement>node).caseBlock);
generateNames((node as SwitchStatement).caseBlock);
break;
case SyntaxKind.CaseBlock:
forEach((<CaseBlock>node).clauses, generateNames);
forEach((node as CaseBlock).clauses, generateNames);
break;
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
forEach((<CaseOrDefaultClause>node).statements, generateNames);
forEach((node as CaseOrDefaultClause).statements, generateNames);
break;
case SyntaxKind.TryStatement:
generateNames((<TryStatement>node).tryBlock);
generateNames((<TryStatement>node).catchClause);
generateNames((<TryStatement>node).finallyBlock);
generateNames((node as TryStatement).tryBlock);
generateNames((node as TryStatement).catchClause);
generateNames((node as TryStatement).finallyBlock);
break;
case SyntaxKind.CatchClause:
generateNames((<CatchClause>node).variableDeclaration);
generateNames((<CatchClause>node).block);
generateNames((node as CatchClause).variableDeclaration);
generateNames((node as CatchClause).block);
break;
case SyntaxKind.VariableStatement:
generateNames((<VariableStatement>node).declarationList);
generateNames((node as VariableStatement).declarationList);
break;
case SyntaxKind.VariableDeclarationList:
forEach((<VariableDeclarationList>node).declarations, generateNames);
forEach((node as VariableDeclarationList).declarations, generateNames);
break;
case SyntaxKind.VariableDeclaration:
case SyntaxKind.Parameter:
case SyntaxKind.BindingElement:
case SyntaxKind.ClassDeclaration:
generateNameIfNeeded((<NamedDeclaration>node).name);
generateNameIfNeeded((node as NamedDeclaration).name);
break;
case SyntaxKind.FunctionDeclaration:
generateNameIfNeeded((<FunctionDeclaration>node).name);
generateNameIfNeeded((node as FunctionDeclaration).name);
if (getEmitFlags(node) & EmitFlags.ReuseTempVariableScope) {
forEach((<FunctionDeclaration>node).parameters, generateNames);
generateNames((<FunctionDeclaration>node).body);
forEach((node as FunctionDeclaration).parameters, generateNames);
generateNames((node as FunctionDeclaration).body);
}
break;
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
forEach((<BindingPattern>node).elements, generateNames);
forEach((node as BindingPattern).elements, generateNames);
break;
case SyntaxKind.ImportDeclaration:
generateNames((<ImportDeclaration>node).importClause);
generateNames((node as ImportDeclaration).importClause);
break;
case SyntaxKind.ImportClause:
generateNameIfNeeded((<ImportClause>node).name);
generateNames((<ImportClause>node).namedBindings);
generateNameIfNeeded((node as ImportClause).name);
generateNames((node as ImportClause).namedBindings);
break;
case SyntaxKind.NamespaceImport:
generateNameIfNeeded((<NamespaceImport>node).name);
generateNameIfNeeded((node as NamespaceImport).name);
break;
case SyntaxKind.NamespaceExport:
generateNameIfNeeded((<NamespaceExport>node).name);
generateNameIfNeeded((node as NamespaceExport).name);
break;
case SyntaxKind.NamedImports:
forEach((<NamedImports>node).elements, generateNames);
forEach((node as NamedImports).elements, generateNames);
break;
case SyntaxKind.ImportSpecifier:
generateNameIfNeeded((<ImportSpecifier>node).propertyName || (<ImportSpecifier>node).name);
generateNameIfNeeded((node as ImportSpecifier).propertyName || (node as ImportSpecifier).name);
break;
}
}
@@ -4875,7 +4875,7 @@ namespace ts {
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
generateNameIfNeeded((<NamedDeclaration>node).name);
generateNameIfNeeded((node as NamedDeclaration).name);
break;
}
}
@@ -5077,10 +5077,10 @@ namespace ts {
);
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.EnumDeclaration:
return generateNameForModuleOrEnum(<ModuleDeclaration | EnumDeclaration>node);
return generateNameForModuleOrEnum(node as ModuleDeclaration | EnumDeclaration);
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ExportDeclaration:
return generateNameForImportOrExportDeclaration(<ImportDeclaration | ExportDeclaration>node);
return generateNameForImportOrExportDeclaration(node as ImportDeclaration | ExportDeclaration);
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ExportAssignment:
@@ -5090,7 +5090,7 @@ namespace ts {
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return generateNameForMethodOrAccessor(<MethodDeclaration | AccessorDeclaration>node);
return generateNameForMethodOrAccessor(node as MethodDeclaration | AccessorDeclaration);
case SyntaxKind.ComputedPropertyName:
return makeTempVariableName(TempFlags.Auto, /*reserveInNestedScopes*/ true);
default:
+100 -45
View File
@@ -34,10 +34,10 @@ namespace ts {
const getJSDocPrimaryTypeCreateFunction = memoizeOne(<T extends JSDocType>(kind: T["kind"]) => () => createJSDocPrimaryTypeWorker(kind));
const getJSDocUnaryTypeCreateFunction = memoizeOne(<T extends JSDocType & { readonly type: TypeNode | undefined; }>(kind: T["kind"]) => (type: T["type"]) => createJSDocUnaryTypeWorker<T>(kind, type));
const getJSDocUnaryTypeUpdateFunction = memoizeOne(<T extends JSDocType & { readonly type: TypeNode | undefined; }>(kind: T["kind"]) => (node: T, type: T["type"]) => updateJSDocUnaryTypeWorker<T>(kind, node, type));
const getJSDocSimpleTagCreateFunction = memoizeOne(<T extends JSDocTag>(kind: T["kind"]) => (tagName: Identifier | undefined, comment?: NodeArray<JSDocText | JSDocLink>) => createJSDocSimpleTagWorker(kind, tagName, comment));
const getJSDocSimpleTagUpdateFunction = memoizeOne(<T extends JSDocTag>(kind: T["kind"]) => (node: T, tagName: Identifier | undefined, comment?: NodeArray<JSDocText | JSDocLink>) => updateJSDocSimpleTagWorker(kind, node, tagName, comment));
const getJSDocTypeLikeTagCreateFunction = memoizeOne(<T extends JSDocTag & { typeExpression?: JSDocTypeExpression }>(kind: T["kind"]) => (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray<JSDocText | JSDocLink>) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment));
const getJSDocTypeLikeTagUpdateFunction = memoizeOne(<T extends JSDocTag & { typeExpression?: JSDocTypeExpression }>(kind: T["kind"]) => (node: T, tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray<JSDocText | JSDocLink>) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment));
const getJSDocSimpleTagCreateFunction = memoizeOne(<T extends JSDocTag>(kind: T["kind"]) => (tagName: Identifier | undefined, comment?: NodeArray<JSDocComment>) => createJSDocSimpleTagWorker(kind, tagName, comment));
const getJSDocSimpleTagUpdateFunction = memoizeOne(<T extends JSDocTag>(kind: T["kind"]) => (node: T, tagName: Identifier | undefined, comment?: NodeArray<JSDocComment>) => updateJSDocSimpleTagWorker(kind, node, tagName, comment));
const getJSDocTypeLikeTagCreateFunction = memoizeOne(<T extends JSDocTag & { typeExpression?: JSDocTypeExpression }>(kind: T["kind"]) => (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray<JSDocComment>) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment));
const getJSDocTypeLikeTagUpdateFunction = memoizeOne(<T extends JSDocTag & { typeExpression?: JSDocTypeExpression }>(kind: T["kind"]) => (node: T, tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray<JSDocComment>) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment));
const factory: NodeFactory = {
get parenthesizer() { return parenthesizerRules(); },
@@ -345,8 +345,14 @@ namespace ts {
updateJSDocSeeTag,
createJSDocNameReference,
updateJSDocNameReference,
createJSDocMemberName,
updateJSDocMemberName,
createJSDocLink,
updateJSDocLink,
createJSDocLinkCode,
updateJSDocLinkCode,
createJSDocLinkPlain,
updateJSDocLinkPlain,
// lazily load factory members for JSDoc tags with similar structure
get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction<JSDocTypeTag>(SyntaxKind.JSDocTypeTag); },
get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction<JSDocTypeTag>(SyntaxKind.JSDocTypeTag); },
@@ -531,7 +537,7 @@ namespace ts {
// repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
// small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
const length = elements.length;
const array = <MutableNodeArray<T>>(length >= 1 && length <= 4 ? elements.slice() : elements);
const array = (length >= 1 && length <= 4 ? elements.slice() : elements) as MutableNodeArray<T>;
setTextRangePosEnd(array, -1, -1);
array.hasTrailingComma = !!hasTrailingComma;
aggregateChildrenFlags(array);
@@ -1896,13 +1902,13 @@ namespace ts {
function updateUnionOrIntersectionTypeNode<T extends UnionOrIntersectionTypeNode>(node: T, types: NodeArray<TypeNode>): T {
return node.types !== types
? update(<T>createUnionOrIntersectionTypeNode(node.kind, types), node)
? update(createUnionOrIntersectionTypeNode(node.kind, types) as T, node)
: node;
}
// @api
function createUnionTypeNode(types: readonly TypeNode[]): UnionTypeNode {
return <UnionTypeNode>createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, types);
return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, types) as UnionTypeNode;
}
// @api
@@ -1912,7 +1918,7 @@ namespace ts {
// @api
function createIntersectionTypeNode(types: readonly TypeNode[]): IntersectionTypeNode {
return <IntersectionTypeNode>createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, types);
return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, types) as IntersectionTypeNode;
}
// @api
@@ -2849,22 +2855,22 @@ namespace ts {
// @api
function createTemplateHead(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) {
return <TemplateHead>createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateHead, text, rawText, templateFlags);
return createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateHead, text, rawText, templateFlags) as TemplateHead;
}
// @api
function createTemplateMiddle(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) {
return <TemplateMiddle>createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateMiddle, text, rawText, templateFlags);
return createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateMiddle, text, rawText, templateFlags) as TemplateMiddle;
}
// @api
function createTemplateTail(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) {
return <TemplateTail>createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateTail, text, rawText, templateFlags);
return createTemplateLiteralLikeNodeChecked(SyntaxKind.TemplateTail, text, rawText, templateFlags) as TemplateTail;
}
// @api
function createNoSubstitutionTemplateLiteral(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) {
return <NoSubstitutionTemplateLiteral>createTemplateLiteralLikeNodeChecked(SyntaxKind.NoSubstitutionTemplateLiteral, text, rawText, templateFlags);
return createTemplateLiteralLikeNodeChecked(SyntaxKind.NoSubstitutionTemplateLiteral, text, rawText, templateFlags) as NoSubstitutionTemplateLiteral;
}
// @api
@@ -4244,7 +4250,7 @@ namespace ts {
}
// @api
function createBaseJSDocTag<T extends JSDocTag>(kind: T["kind"], tagName: Identifier, comment: string | NodeArray<JSDocText | JSDocLink> | undefined) {
function createBaseJSDocTag<T extends JSDocTag>(kind: T["kind"], tagName: Identifier, comment: string | NodeArray<JSDocComment> | undefined) {
const node = createBaseNode<T>(kind);
node.tagName = tagName;
node.comment = comment;
@@ -4252,7 +4258,7 @@ namespace ts {
}
// @api
function createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocTemplateTag {
function createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray<JSDocComment>): JSDocTemplateTag {
const node = createBaseJSDocTag<JSDocTemplateTag>(SyntaxKind.JSDocTemplateTag, tagName ?? createIdentifier("template"), comment);
node.constraint = constraint;
node.typeParameters = createNodeArray(typeParameters);
@@ -4260,7 +4266,7 @@ namespace ts {
}
// @api
function updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier = getDefaultTagName(node), constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocTemplateTag {
function updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier = getDefaultTagName(node), constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray<JSDocComment> | undefined): JSDocTemplateTag {
return node.tagName !== tagName
|| node.constraint !== constraint
|| node.typeParameters !== typeParameters
@@ -4270,7 +4276,7 @@ namespace ts {
}
// @api
function createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocTypedefTag {
function createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray<JSDocComment>): JSDocTypedefTag {
const node = createBaseJSDocTag<JSDocTypedefTag>(SyntaxKind.JSDocTypedefTag, tagName ?? createIdentifier("typedef"), comment);
node.typeExpression = typeExpression;
node.fullName = fullName;
@@ -4279,7 +4285,7 @@ namespace ts {
}
// @api
function updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocTypedefTag {
function updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocTypedefTag {
return node.tagName !== tagName
|| node.typeExpression !== typeExpression
|| node.fullName !== fullName
@@ -4289,7 +4295,7 @@ namespace ts {
}
// @api
function createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocParameterTag {
function createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray<JSDocComment>): JSDocParameterTag {
const node = createBaseJSDocTag<JSDocParameterTag>(SyntaxKind.JSDocParameterTag, tagName ?? createIdentifier("param"), comment);
node.typeExpression = typeExpression;
node.name = name;
@@ -4299,7 +4305,7 @@ namespace ts {
}
// @api
function updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocParameterTag {
function updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray<JSDocComment> | undefined): JSDocParameterTag {
return node.tagName !== tagName
|| node.name !== name
|| node.isBracketed !== isBracketed
@@ -4311,7 +4317,7 @@ namespace ts {
}
// @api
function createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocPropertyTag {
function createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray<JSDocComment>): JSDocPropertyTag {
const node = createBaseJSDocTag<JSDocPropertyTag>(SyntaxKind.JSDocPropertyTag, tagName ?? createIdentifier("prop"), comment);
node.typeExpression = typeExpression;
node.name = name;
@@ -4321,7 +4327,7 @@ namespace ts {
}
// @api
function updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocPropertyTag {
function updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray<JSDocComment> | undefined): JSDocPropertyTag {
return node.tagName !== tagName
|| node.name !== name
|| node.isBracketed !== isBracketed
@@ -4333,7 +4339,7 @@ namespace ts {
}
// @api
function createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocCallbackTag {
function createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray<JSDocComment>): JSDocCallbackTag {
const node = createBaseJSDocTag<JSDocCallbackTag>(SyntaxKind.JSDocCallbackTag, tagName ?? createIdentifier("callback"), comment);
node.typeExpression = typeExpression;
node.fullName = fullName;
@@ -4342,7 +4348,7 @@ namespace ts {
}
// @api
function updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocCallbackTag {
function updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocCallbackTag {
return node.tagName !== tagName
|| node.typeExpression !== typeExpression
|| node.fullName !== fullName
@@ -4352,14 +4358,14 @@ namespace ts {
}
// @api
function createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocAugmentsTag {
function createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray<JSDocComment>): JSDocAugmentsTag {
const node = createBaseJSDocTag<JSDocAugmentsTag>(SyntaxKind.JSDocAugmentsTag, tagName ?? createIdentifier("augments"), comment);
node.class = className;
return node;
}
// @api
function updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocAugmentsTag["class"], comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocAugmentsTag {
function updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocAugmentsTag["class"], comment: string | NodeArray<JSDocComment> | undefined): JSDocAugmentsTag {
return node.tagName !== tagName
|| node.class !== className
|| node.comment !== comment
@@ -4368,21 +4374,21 @@ namespace ts {
}
// @api
function createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocImplementsTag {
function createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray<JSDocComment>): JSDocImplementsTag {
const node = createBaseJSDocTag<JSDocImplementsTag>(SyntaxKind.JSDocImplementsTag, tagName ?? createIdentifier("implements"), comment);
node.class = className;
return node;
}
// @api
function createJSDocSeeTag(tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocSeeTag {
function createJSDocSeeTag(tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray<JSDocComment>): JSDocSeeTag {
const node = createBaseJSDocTag<JSDocSeeTag>(SyntaxKind.JSDocSeeTag, tagName ?? createIdentifier("see"), comment);
node.name = name;
return node;
}
// @api
function updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocSeeTag {
function updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray<JSDocComment>): JSDocSeeTag {
return node.tagName !== tagName
|| node.name !== name
|| node.comment !== comment
@@ -4391,21 +4397,40 @@ namespace ts {
}
// @api
function createJSDocNameReference(name: EntityName): JSDocNameReference {
function createJSDocNameReference(name: EntityName | JSDocMemberName): JSDocNameReference {
const node = createBaseNode<JSDocNameReference>(SyntaxKind.JSDocNameReference);
node.name = name;
return node;
}
// @api
function updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference {
function updateJSDocNameReference(node: JSDocNameReference, name: EntityName | JSDocMemberName): JSDocNameReference {
return node.name !== name
? update(createJSDocNameReference(name), node)
: node;
}
// @api
function createJSDocLink(name: EntityName | undefined, text: string): JSDocLink {
function createJSDocMemberName(left: EntityName | JSDocMemberName, right: Identifier) {
const node = createBaseNode<JSDocMemberName>(SyntaxKind.JSDocMemberName);
node.left = left;
node.right = right;
node.transformFlags |=
propagateChildFlags(node.left) |
propagateChildFlags(node.right);
return node;
}
// @api
function updateJSDocMemberName(node: JSDocMemberName, left: EntityName | JSDocMemberName, right: Identifier) {
return node.left !== left
|| node.right !== right
? update(createJSDocMemberName(left, right), node)
: node;
}
// @api
function createJSDocLink(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink {
const node = createBaseNode<JSDocLink>(SyntaxKind.JSDocLink);
node.name = name;
node.text = text;
@@ -4413,14 +4438,44 @@ namespace ts {
}
// @api
function updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink {
function updateJSDocLink(node: JSDocLink, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink {
return node.name !== name
? update(createJSDocLink(name, text), node)
: node;
}
// @api
function updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocImplementsTag["class"], comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocImplementsTag {
function createJSDocLinkCode(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode {
const node = createBaseNode<JSDocLinkCode>(SyntaxKind.JSDocLinkCode);
node.name = name;
node.text = text;
return node;
}
// @api
function updateJSDocLinkCode(node: JSDocLinkCode, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode {
return node.name !== name
? update(createJSDocLinkCode(name, text), node)
: node;
}
// @api
function createJSDocLinkPlain(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain {
const node = createBaseNode<JSDocLinkPlain>(SyntaxKind.JSDocLinkPlain);
node.name = name;
node.text = text;
return node;
}
// @api
function updateJSDocLinkPlain(node: JSDocLinkPlain, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain {
return node.name !== name
? update(createJSDocLinkPlain(name, text), node)
: node;
}
// @api
function updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocImplementsTag["class"], comment: string | NodeArray<JSDocComment> | undefined): JSDocImplementsTag {
return node.tagName !== tagName
|| node.class !== className
|| node.comment !== comment
@@ -4436,7 +4491,7 @@ namespace ts {
// createJSDocProtectedTag
// createJSDocReadonlyTag
// createJSDocDeprecatedTag
function createJSDocSimpleTagWorker<T extends JSDocTag>(kind: T["kind"], tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>) {
function createJSDocSimpleTagWorker<T extends JSDocTag>(kind: T["kind"], tagName: Identifier | undefined, comment?: string | NodeArray<JSDocComment>) {
const node = createBaseJSDocTag<T>(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment);
return node;
}
@@ -4449,7 +4504,7 @@ namespace ts {
// updateJSDocProtectedTag
// updateJSDocReadonlyTag
// updateJSDocDeprecatedTag
function updateJSDocSimpleTagWorker<T extends JSDocTag>(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), comment: string | NodeArray<JSDocText | JSDocLink> | undefined) {
function updateJSDocSimpleTagWorker<T extends JSDocTag>(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), comment: string | NodeArray<JSDocComment> | undefined) {
return node.tagName !== tagName
|| node.comment !== comment
? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) :
@@ -4461,7 +4516,7 @@ namespace ts {
// createJSDocReturnTag
// createJSDocThisTag
// createJSDocEnumTag
function createJSDocTypeLikeTagWorker<T extends JSDocTag & { typeExpression?: JSDocTypeExpression }>(kind: T["kind"], tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray<JSDocText | JSDocLink>) {
function createJSDocTypeLikeTagWorker<T extends JSDocTag & { typeExpression?: JSDocTypeExpression }>(kind: T["kind"], tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray<JSDocComment>) {
const node = createBaseJSDocTag<T>(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment);
node.typeExpression = typeExpression;
return node;
@@ -4472,7 +4527,7 @@ namespace ts {
// updateJSDocReturnTag
// updateJSDocThisTag
// updateJSDocEnumTag
function updateJSDocTypeLikeTagWorker<T extends JSDocTag & { typeExpression?: JSDocTypeExpression }>(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined) {
function updateJSDocTypeLikeTagWorker<T extends JSDocTag & { typeExpression?: JSDocTypeExpression }>(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray<JSDocComment> | undefined) {
return node.tagName !== tagName
|| node.typeExpression !== typeExpression
|| node.comment !== comment
@@ -4481,13 +4536,13 @@ namespace ts {
}
// @api
function createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocUnknownTag {
function createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray<JSDocComment>): JSDocUnknownTag {
const node = createBaseJSDocTag<JSDocUnknownTag>(SyntaxKind.JSDocTag, tagName, comment);
return node;
}
// @api
function updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocUnknownTag {
function updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray<JSDocComment> | undefined): JSDocUnknownTag {
return node.tagName !== tagName
|| node.comment !== comment
? update(createJSDocUnknownTag(tagName, comment), node)
@@ -4509,7 +4564,7 @@ namespace ts {
}
// @api
function createJSDocComment(comment?: string | NodeArray<JSDocText | JSDocLink> | undefined, tags?: readonly JSDocTag[] | undefined) {
function createJSDocComment(comment?: string | NodeArray<JSDocComment> | undefined, tags?: readonly JSDocTag[] | undefined) {
const node = createBaseNode<JSDoc>(SyntaxKind.JSDocComment);
node.comment = comment;
node.tags = asNodeArray(tags);
@@ -4517,7 +4572,7 @@ namespace ts {
}
// @api
function updateJSDocComment(node: JSDoc, comment: string | NodeArray<JSDocText | JSDocLink> | undefined, tags: readonly JSDocTag[] | undefined) {
function updateJSDocComment(node: JSDoc, comment: string | NodeArray<JSDocComment> | undefined, tags: readonly JSDocTag[] | undefined) {
return node.comment !== comment
|| node.tags !== tags
? update(createJSDocComment(comment, tags), node)
@@ -5457,13 +5512,13 @@ namespace ts {
case SyntaxKind.StringLiteral:
return false;
case SyntaxKind.ArrayLiteralExpression:
const elements = (<ArrayLiteralExpression>target).elements;
const elements = (target as ArrayLiteralExpression).elements;
if (elements.length === 0) {
return false;
}
return true;
case SyntaxKind.ObjectLiteralExpression:
return (<ObjectLiteralExpression>target).properties.length > 0;
return (target as ObjectLiteralExpression).properties.length > 0;
default:
return true;
}
@@ -5481,7 +5536,7 @@ namespace ts {
thisArg = createThis();
target = languageVersion !== undefined && languageVersion < ScriptTarget.ES2015
? setTextRange(createIdentifier("_super"), callee)
: <PrimaryExpression>callee;
: callee as PrimaryExpression;
}
else if (getEmitFlags(callee) & EmitFlags.HelperName) {
thisArg = createVoidZero();
@@ -5746,7 +5801,7 @@ namespace ts {
*/
function liftToBlock(nodes: readonly Node[]): Statement {
Debug.assert(every(nodes, isStatementOrBlock), "Cannot lift nodes to a Block.");
return <Statement>singleOrUndefined(nodes) || createBlock(<readonly Statement[]>nodes);
return singleOrUndefined(nodes) as Statement || createBlock(nodes as readonly Statement[]);
}
function findSpanEnd<T>(array: readonly T[], test: (value: T) => boolean, start: number) {
+12
View File
@@ -770,10 +770,22 @@ namespace ts {
return node.kind === SyntaxKind.JSDocNameReference;
}
export function isJSDocMemberName(node: Node): node is JSDocMemberName {
return node.kind === SyntaxKind.JSDocMemberName;
}
export function isJSDocLink(node: Node): node is JSDocLink {
return node.kind === SyntaxKind.JSDocLink;
}
export function isJSDocLinkCode(node: Node): node is JSDocLinkCode {
return node.kind === SyntaxKind.JSDocLinkCode;
}
export function isJSDocLinkPlain(node: Node): node is JSDocLinkPlain {
return node.kind === SyntaxKind.JSDocLinkPlain;
}
export function isJSDocAllType(node: Node): node is JSDocAllType {
return node.kind === SyntaxKind.JSDocAllType;
}
+7 -7
View File
@@ -190,18 +190,18 @@ namespace ts {
return node.kind;
}
if (node.kind === SyntaxKind.BinaryExpression && (<BinaryExpression>node).operatorToken.kind === SyntaxKind.PlusToken) {
if ((<BinaryPlusExpression>node).cachedLiteralKind !== undefined) {
return (<BinaryPlusExpression>node).cachedLiteralKind;
if (node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.PlusToken) {
if ((node as BinaryPlusExpression).cachedLiteralKind !== undefined) {
return (node as BinaryPlusExpression).cachedLiteralKind;
}
const leftKind = getLiteralKindOfBinaryPlusOperand((<BinaryExpression>node).left);
const leftKind = getLiteralKindOfBinaryPlusOperand((node as BinaryExpression).left);
const literalKind = isLiteralKind(leftKind)
&& leftKind === getLiteralKindOfBinaryPlusOperand((<BinaryExpression>node).right)
&& leftKind === getLiteralKindOfBinaryPlusOperand((node as BinaryExpression).right)
? leftKind
: SyntaxKind.Unknown;
(<BinaryPlusExpression>node).cachedLiteralKind = literalKind;
(node as BinaryPlusExpression).cachedLiteralKind = literalKind;
return literalKind;
}
@@ -319,7 +319,7 @@ namespace ts {
//
const emittedExpression = skipPartiallyEmittedExpressions(expression);
if (isLeftHandSideExpression(emittedExpression)
&& (emittedExpression.kind !== SyntaxKind.NewExpression || (<NewExpression>emittedExpression).arguments)) {
&& (emittedExpression.kind !== SyntaxKind.NewExpression || (emittedExpression as NewExpression).arguments)) {
// TODO(rbuckton): Verify whether this assertion holds.
return expression as LeftHandSideExpression;
}
+8 -8
View File
@@ -351,7 +351,7 @@ namespace ts {
}
export function isCommaSequence(node: Expression): node is BinaryExpression & {operatorToken: Token<SyntaxKind.CommaToken>} | CommaListExpression {
return node.kind === SyntaxKind.BinaryExpression && (<BinaryExpression>node).operatorToken.kind === SyntaxKind.CommaToken ||
return node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken ||
node.kind === SyntaxKind.CommaListExpression;
}
@@ -594,7 +594,7 @@ namespace ts {
if (isSpreadElement(bindingElement)) {
// Recovery consistent with existing emit.
return getInitializerOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.expression);
return getInitializerOfBindingOrAssignmentElement(bindingElement.expression as BindingOrAssignmentElement);
}
}
@@ -635,7 +635,7 @@ namespace ts {
// `b.c` in `({ a: b.c = 1 } = ...)`
// `b[0]` in `({ a: b[0] } = ...)`
// `b[0]` in `({ a: b[0] = 1 } = ...)`
return getTargetOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.initializer);
return getTargetOfBindingOrAssignmentElement(bindingElement.initializer as BindingOrAssignmentElement);
case SyntaxKind.ShorthandPropertyAssignment:
// `a` in `({ a } = ...)`
@@ -644,7 +644,7 @@ namespace ts {
case SyntaxKind.SpreadAssignment:
// `a` in `({ ...a } = ...)`
return getTargetOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.expression);
return getTargetOfBindingOrAssignmentElement(bindingElement.expression as BindingOrAssignmentElement);
}
// no target
@@ -657,12 +657,12 @@ namespace ts {
// `[a]` in `[[a] = 1] = ...`
// `a.b` in `[a.b = 1] = ...`
// `a[0]` in `[a[0] = 1] = ...`
return getTargetOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.left);
return getTargetOfBindingOrAssignmentElement(bindingElement.left as BindingOrAssignmentElement);
}
if (isSpreadElement(bindingElement)) {
// `a` in `[...a] = ...`
return getTargetOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.expression);
return getTargetOfBindingOrAssignmentElement(bindingElement.expression as BindingOrAssignmentElement);
}
// `a` in `[a] = ...`
@@ -767,11 +767,11 @@ namespace ts {
case SyntaxKind.ArrayLiteralExpression:
// `a` in `{a}`
// `a` in `[a]`
return <readonly BindingOrAssignmentElement[]>name.elements;
return name.elements as readonly BindingOrAssignmentElement[];
case SyntaxKind.ObjectLiteralExpression:
// `a` in `{a}`
return <readonly BindingOrAssignmentElement[]>name.properties;
return name.properties as readonly BindingOrAssignmentElement[];
}
}
+431 -363
View File
File diff suppressed because it is too large Load Diff
+20 -2
View File
@@ -452,6 +452,11 @@ namespace ts {
* Normalize path separators, converting `\` into `/`.
*/
export function normalizeSlashes(path: string): string {
const index = path.indexOf("\\");
if (index === -1) {
return path;
}
backslashRegExp.lastIndex = index; // prime regex with known position
return path.replace(backslashRegExp, directorySeparator);
}
@@ -547,6 +552,19 @@ namespace ts {
export function normalizePath(path: string): string {
path = normalizeSlashes(path);
// Most paths don't require normalization
if (!relativePathSegmentRegExp.test(path)) {
return path;
}
// Some paths only require cleanup of `/./` or leading `./`
const simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, "");
if (simplified !== path) {
path = simplified;
if (!relativePathSegmentRegExp.test(path)) {
return path;
}
}
// Other paths require full normalization
const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
}
@@ -564,7 +582,7 @@ namespace ts {
const nonCanonicalizedPath = isRootedDiskPath(fileName)
? normalizePath(fileName)
: getNormalizedAbsolutePath(fileName, basePath);
return <Path>getCanonicalFileName(nonCanonicalizedPath);
return getCanonicalFileName(nonCanonicalizedPath) as Path;
}
export function normalizePathAndParts(path: string): { path: string, parts: string[] } {
@@ -658,7 +676,7 @@ namespace ts {
//// Path Comparisons
// check path for these segments: '', '.'. '..'
const relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
const relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/;
function comparePathsWorker(a: string, b: string, componentComparer: (a: string, b: string) => Comparison) {
if (a === b) return Comparison.EqualTo;
+11 -11
View File
@@ -1281,7 +1281,7 @@ namespace ts {
let result: ResolvedModuleFull[] | undefined;
let reusedNames: string[] | undefined;
/** A transient placeholder used to mark predicted resolution in the result list. */
const predictedToResolveToAmbientModuleMarker: ResolvedModuleFull = <any>{};
const predictedToResolveToAmbientModuleMarker: ResolvedModuleFull = {} as any;
for (let i = 0; i < moduleNames.length; i++) {
const moduleName = moduleNames[i];
@@ -2005,7 +2005,7 @@ namespace ts {
case SyntaxKind.Parameter:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.MethodDeclaration:
if ((<ParameterDeclaration | PropertyDeclaration | MethodDeclaration>parent).questionToken === node) {
if ((parent as ParameterDeclaration | PropertyDeclaration | MethodDeclaration).questionToken === node) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
return "skip";
}
@@ -2019,7 +2019,7 @@ namespace ts {
case SyntaxKind.ArrowFunction:
case SyntaxKind.VariableDeclaration:
// type annotation
if ((<FunctionLikeDeclaration | VariableDeclaration | ParameterDeclaration | PropertyDeclaration>parent).type === node) {
if ((parent as FunctionLikeDeclaration | VariableDeclaration | ParameterDeclaration | PropertyDeclaration).type === node) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
return "skip";
}
@@ -2042,13 +2042,13 @@ namespace ts {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_TypeScript_files));
return "skip";
case SyntaxKind.ExportAssignment:
if ((<ExportAssignment>node).isExportEquals) {
if ((node as ExportAssignment).isExportEquals) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_TypeScript_files));
return "skip";
}
break;
case SyntaxKind.HeritageClause:
const heritageClause = <HeritageClause>node;
const heritageClause = node as HeritageClause;
if (heritageClause.token === SyntaxKind.ImplementsKeyword) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
return "skip";
@@ -2098,7 +2098,7 @@ namespace ts {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
// Check type parameters
if (nodes === (<DeclarationWithTypeParameterChildren>parent).typeParameters) {
if (nodes === (parent as DeclarationWithTypeParameterChildren).typeParameters) {
diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
return "skip";
}
@@ -2113,8 +2113,8 @@ namespace ts {
break;
case SyntaxKind.PropertyDeclaration:
// Check modifiers of property declaration
if (nodes === (<PropertyDeclaration>parent).modifiers) {
for (const modifier of <NodeArray<Modifier>>nodes) {
if (nodes === (parent as PropertyDeclaration).modifiers) {
for (const modifier of nodes as NodeArray<Modifier>) {
if (modifier.kind !== SyntaxKind.StaticKeyword) {
diagnostics.push(createDiagnosticForNode(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind)));
}
@@ -2124,7 +2124,7 @@ namespace ts {
break;
case SyntaxKind.Parameter:
// Check modifiers of parameter declaration
if (nodes === (<ParameterDeclaration>parent).modifiers) {
if (nodes === (parent as ParameterDeclaration).modifiers) {
diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
return "skip";
}
@@ -2136,7 +2136,7 @@ namespace ts {
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.TaggedTemplateExpression:
// Check type arguments
if (nodes === (<NodeWithTypeArguments>parent).typeArguments) {
if (nodes === (parent as NodeWithTypeArguments).typeArguments) {
diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
return "skip";
}
@@ -2348,7 +2348,7 @@ namespace ts {
// Relative external module names are not permitted
// NOTE: body of ambient module is always a module block, if it exists
const body = <ModuleBlock>(<ModuleDeclaration>node).body;
const body = (node as ModuleDeclaration).body as ModuleBlock;
if (body) {
for (const statement of body.statements) {
collectModuleReferences(statement, /*inAmbientModule*/ true);
+16 -14
View File
@@ -42,6 +42,7 @@ namespace ts {
reScanJsxAttributeValue(): SyntaxKind;
reScanJsxToken(allowMultilineJsxText?: boolean): JsxTokenSyntaxKind;
reScanLessThanToken(): SyntaxKind;
reScanHashToken(): SyntaxKind;
reScanQuestionToken(): SyntaxKind;
reScanInvalidIdentifier(): SyntaxKind;
scanJsxToken(): JsxTokenSyntaxKind;
@@ -220,7 +221,8 @@ namespace ts {
"&&=": SyntaxKind.AmpersandAmpersandEqualsToken,
"??=": SyntaxKind.QuestionQuestionEqualsToken,
"@": SyntaxKind.AtToken,
"`": SyntaxKind.BacktickToken
"#": SyntaxKind.HashToken,
"`": SyntaxKind.BacktickToken,
}));
/*
@@ -981,6 +983,7 @@ namespace ts {
reScanJsxAttributeValue,
reScanJsxToken,
reScanLessThanToken,
reScanHashToken,
reScanQuestionToken,
reScanInvalidIdentifier,
scanJsxToken,
@@ -1610,7 +1613,7 @@ namespace ts {
if (pos >= end) {
return token = SyntaxKind.EndOfFileToken;
}
let ch = codePointAt(text, pos);
const ch = codePointAt(text, pos);
// Special handling for shebang
if (ch === CharacterCodes.hash && pos === 0 && isShebangTrivia(text, pos)) {
@@ -2044,18 +2047,7 @@ namespace ts {
return token = SyntaxKind.Unknown;
}
pos++;
if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
pos++;
while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion)) pos++;
tokenValue = text.substring(tokenPos, pos);
if (ch === CharacterCodes.backslash) {
tokenValue += scanIdentifierParts();
}
}
else {
tokenValue = "#";
error(Diagnostics.Invalid_character);
}
scanIdentifier(codePointAt(text, pos), languageVersion);
return token = SyntaxKind.PrivateIdentifier;
default:
const identifierKind = scanIdentifier(ch, languageVersion);
@@ -2251,6 +2243,14 @@ namespace ts {
return token;
}
function reScanHashToken(): SyntaxKind {
if (token === SyntaxKind.PrivateIdentifier) {
pos = tokenPos + 1;
return token = SyntaxKind.HashToken;
}
return token;
}
function reScanQuestionToken(): SyntaxKind {
Debug.assert(token === SyntaxKind.QuestionQuestionToken, "'reScanQuestionToken' should only be called on a '??'");
pos = tokenPos + 1;
@@ -2437,6 +2437,8 @@ namespace ts {
return token = SyntaxKind.DotToken;
case CharacterCodes.backtick:
return token = SyntaxKind.BacktickToken;
case CharacterCodes.hash:
return token = SyntaxKind.HashToken;
case CharacterCodes.backslash:
pos--;
const extendedCookedChar = peekExtendedUnicodeEscape();
+52 -36
View File
@@ -17,6 +17,7 @@ namespace ts {
const names: string[] = [];
let nameToNameIndexMap: ESMap<string, number> | undefined;
const mappingCharCodes: number[] = [];
let mappings = "";
// Last recorded and encoded mappings
@@ -210,6 +211,15 @@ namespace ts {
|| lastNameIndex !== pendingNameIndex;
}
function appendMappingCharCode(charCode: number) {
mappingCharCodes.push(charCode);
// String.fromCharCode accepts its arguments on the stack, so we have to chunk the input,
// otherwise we can get stack overflows for large source maps
if (mappingCharCodes.length >= 1024) {
flushMappingBuffer();
}
}
function commitPendingMapping() {
if (!hasPending || !shouldCommitMapping()) {
return;
@@ -221,40 +231,41 @@ namespace ts {
if (lastGeneratedLine < pendingGeneratedLine) {
// Emit line delimiters
do {
mappings += ";";
appendMappingCharCode(CharacterCodes.semicolon);
lastGeneratedLine++;
lastGeneratedCharacter = 0;
}
while (lastGeneratedLine < pendingGeneratedLine);
// Only need to set this once
lastGeneratedCharacter = 0;
}
else {
Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
// Emit comma to separate the entry
if (hasLast) {
mappings += ",";
appendMappingCharCode(CharacterCodes.comma);
}
}
// 1. Relative generated character
mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
appendBase64VLQ(pendingGeneratedCharacter - lastGeneratedCharacter);
lastGeneratedCharacter = pendingGeneratedCharacter;
if (hasPendingSource) {
// 2. Relative sourceIndex
mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
appendBase64VLQ(pendingSourceIndex - lastSourceIndex);
lastSourceIndex = pendingSourceIndex;
// 3. Relative source line
mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
appendBase64VLQ(pendingSourceLine - lastSourceLine);
lastSourceLine = pendingSourceLine;
// 4. Relative source character
mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
appendBase64VLQ(pendingSourceCharacter - lastSourceCharacter);
lastSourceCharacter = pendingSourceCharacter;
if (hasPendingName) {
// 5. Relative nameIndex
mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
appendBase64VLQ(pendingNameIndex - lastNameIndex);
lastNameIndex = pendingNameIndex;
}
}
@@ -263,8 +274,16 @@ namespace ts {
exit();
}
function flushMappingBuffer(): void {
if (mappingCharCodes.length > 0) {
mappings += String.fromCharCode.apply(undefined, mappingCharCodes);
mappingCharCodes.length = 0;
}
}
function toJSON(): RawSourceMap {
commitPendingMapping();
flushMappingBuffer();
return {
version: 3,
file,
@@ -275,6 +294,31 @@ namespace ts {
sourcesContent,
};
}
function appendBase64VLQ(inValue: number): void {
// Add a new least significant bit that has the sign of the value.
// if negative number the least significant bit that gets added to the number has value 1
// else least significant bit value that gets added is 0
// eg. -1 changes to binary : 01 [1] => 3
// +1 changes to binary : 01 [0] => 2
if (inValue < 0) {
inValue = ((-inValue) << 1) + 1;
}
else {
inValue = inValue << 1;
}
// Encode 5 bits at a time starting from least significant bits
do {
let currentDigit = inValue & 31; // 11111
inValue = inValue >> 5;
if (inValue > 0) {
// There are still more digits to decode, set the msb (6th bit)
currentDigit = currentDigit | 32;
}
appendMappingCharCode(base64FormatEncode(currentDigit));
} while (inValue > 0);
}
}
// Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
@@ -544,34 +588,6 @@ namespace ts {
-1;
}
function base64VLQFormatEncode(inValue: number) {
// Add a new least significant bit that has the sign of the value.
// if negative number the least significant bit that gets added to the number has value 1
// else least significant bit value that gets added is 0
// eg. -1 changes to binary : 01 [1] => 3
// +1 changes to binary : 01 [0] => 2
if (inValue < 0) {
inValue = ((-inValue) << 1) + 1;
}
else {
inValue = inValue << 1;
}
// Encode 5 bits at a time starting from least significant bits
let encodedStr = "";
do {
let currentDigit = inValue & 31; // 11111
inValue = inValue >> 5;
if (inValue > 0) {
// There are still more digits to decode, set the msb (6th bit)
currentDigit = currentDigit | 32;
}
encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
} while (inValue > 0);
return encodedStr;
}
interface MappedPosition {
generatedPosition: number;
source: string | undefined;
+1 -1
View File
@@ -1370,7 +1370,7 @@ namespace ts {
disableCPUProfiler,
cpuProfilingEnabled: () => !!activeSession || contains(process.execArgv, "--cpu-prof") || contains(process.execArgv, "--prof"),
realpath,
debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || some(<string[]>process.execArgv, arg => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)),
debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || some(process.execArgv as string[], arg => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)),
tryEnableSourceMapsForHost() {
try {
require("source-map-support").install();
+7 -2
View File
@@ -658,13 +658,14 @@ namespace ts {
}
const staticProperties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ true);
let pendingPrivateStateAssignment: BinaryExpression | undefined;
if (shouldTransformPrivateElements && some(node.members, m => hasStaticModifier(m) && !!m.name && isPrivateIdentifier(m.name))) {
const temp = factory.createTempVariable(hoistVariableDeclaration, /* reservedInNestedScopes */ true);
getPrivateIdentifierEnvironment().classConstructor = factory.cloneNode(temp);
getPendingExpressions().push(factory.createAssignment(
pendingPrivateStateAssignment = factory.createAssignment(
temp,
factory.getInternalName(node)
));
);
}
const extendsClauseElement = getEffectiveBaseTypeNode(node);
@@ -682,6 +683,10 @@ namespace ts {
)
];
if (pendingPrivateStateAssignment) {
getPendingExpressions().unshift(pendingPrivateStateAssignment);
}
// Write any pending expressions from elided or moved computed property names
if (some(pendingExpressions)) {
statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
+5 -5
View File
@@ -114,9 +114,9 @@ namespace ts {
function emitBindingOrAssignment(target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node) {
Debug.assertNode(target, createAssignmentCallback ? isIdentifier : isExpression);
const expression = createAssignmentCallback
? createAssignmentCallback(<Identifier>target, value, location)
? createAssignmentCallback(target as Identifier, value, location)
: setTextRange(
context.factory.createAssignment(visitNode(<Expression>target, visitor, isExpression), value),
context.factory.createAssignment(visitNode(target as Expression, visitor, isExpression), value),
location
);
expression.original = original;
@@ -410,7 +410,7 @@ namespace ts {
flattenContext.context.hoistVariableDeclaration(temp);
}
restContainingElements = append(restContainingElements, <[Identifier, BindingOrAssignmentElement]>[temp, element]);
restContainingElements = append(restContainingElements, [temp, element] as [Identifier, BindingOrAssignmentElement]);
bindingElements = append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
}
else {
@@ -518,7 +518,7 @@ namespace ts {
function makeArrayBindingPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) {
Debug.assertEachNode(elements, isArrayBindingElement);
return factory.createArrayBindingPattern(<ArrayBindingElement[]>elements);
return factory.createArrayBindingPattern(elements as ArrayBindingElement[]);
}
function makeArrayAssignmentPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) {
@@ -527,7 +527,7 @@ namespace ts {
function makeObjectBindingPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) {
Debug.assertEachNode(elements, isBindingElement);
return factory.createObjectBindingPattern(<BindingElement[]>elements);
return factory.createObjectBindingPattern(elements as BindingElement[]);
}
function makeObjectAssignmentPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) {
+61 -61
View File
@@ -327,7 +327,7 @@ namespace ts {
function isReturnVoidStatementInConstructorWithCapturedSuper(node: Node): boolean {
return (hierarchyFacts & HierarchyFacts.ConstructorWithCapturedSuper) !== 0
&& node.kind === SyntaxKind.ReturnStatement
&& !(<ReturnStatement>node).expression;
&& !(node as ReturnStatement).expression;
}
function isOrMayContainReturnCompletion(node: Node) {
@@ -375,117 +375,117 @@ namespace ts {
return undefined; // elide static keyword
case SyntaxKind.ClassDeclaration:
return visitClassDeclaration(<ClassDeclaration>node);
return visitClassDeclaration(node as ClassDeclaration);
case SyntaxKind.ClassExpression:
return visitClassExpression(<ClassExpression>node);
return visitClassExpression(node as ClassExpression);
case SyntaxKind.Parameter:
return visitParameter(<ParameterDeclaration>node);
return visitParameter(node as ParameterDeclaration);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.ArrowFunction:
return visitArrowFunction(<ArrowFunction>node);
return visitArrowFunction(node as ArrowFunction);
case SyntaxKind.FunctionExpression:
return visitFunctionExpression(<FunctionExpression>node);
return visitFunctionExpression(node as FunctionExpression);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(<VariableDeclaration>node);
return visitVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.Identifier:
return visitIdentifier(<Identifier>node);
return visitIdentifier(node as Identifier);
case SyntaxKind.VariableDeclarationList:
return visitVariableDeclarationList(<VariableDeclarationList>node);
return visitVariableDeclarationList(node as VariableDeclarationList);
case SyntaxKind.SwitchStatement:
return visitSwitchStatement(<SwitchStatement>node);
return visitSwitchStatement(node as SwitchStatement);
case SyntaxKind.CaseBlock:
return visitCaseBlock(<CaseBlock>node);
return visitCaseBlock(node as CaseBlock);
case SyntaxKind.Block:
return visitBlock(<Block>node, /*isFunctionBody*/ false);
return visitBlock(node as Block, /*isFunctionBody*/ false);
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
return visitBreakOrContinueStatement(<BreakOrContinueStatement>node);
return visitBreakOrContinueStatement(node as BreakOrContinueStatement);
case SyntaxKind.LabeledStatement:
return visitLabeledStatement(<LabeledStatement>node);
return visitLabeledStatement(node as LabeledStatement);
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
return visitDoOrWhileStatement(<DoStatement | WhileStatement>node, /*outermostLabeledStatement*/ undefined);
return visitDoOrWhileStatement(node as DoStatement | WhileStatement, /*outermostLabeledStatement*/ undefined);
case SyntaxKind.ForStatement:
return visitForStatement(<ForStatement>node, /*outermostLabeledStatement*/ undefined);
return visitForStatement(node as ForStatement, /*outermostLabeledStatement*/ undefined);
case SyntaxKind.ForInStatement:
return visitForInStatement(<ForInStatement>node, /*outermostLabeledStatement*/ undefined);
return visitForInStatement(node as ForInStatement, /*outermostLabeledStatement*/ undefined);
case SyntaxKind.ForOfStatement:
return visitForOfStatement(<ForOfStatement>node, /*outermostLabeledStatement*/ undefined);
return visitForOfStatement(node as ForOfStatement, /*outermostLabeledStatement*/ undefined);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(<ExpressionStatement>node);
return visitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.ObjectLiteralExpression:
return visitObjectLiteralExpression(<ObjectLiteralExpression>node);
return visitObjectLiteralExpression(node as ObjectLiteralExpression);
case SyntaxKind.CatchClause:
return visitCatchClause(<CatchClause>node);
return visitCatchClause(node as CatchClause);
case SyntaxKind.ShorthandPropertyAssignment:
return visitShorthandPropertyAssignment(<ShorthandPropertyAssignment>node);
return visitShorthandPropertyAssignment(node as ShorthandPropertyAssignment);
case SyntaxKind.ComputedPropertyName:
return visitComputedPropertyName(<ComputedPropertyName>node);
return visitComputedPropertyName(node as ComputedPropertyName);
case SyntaxKind.ArrayLiteralExpression:
return visitArrayLiteralExpression(<ArrayLiteralExpression>node);
return visitArrayLiteralExpression(node as ArrayLiteralExpression);
case SyntaxKind.CallExpression:
return visitCallExpression(<CallExpression>node);
return visitCallExpression(node as CallExpression);
case SyntaxKind.NewExpression:
return visitNewExpression(<NewExpression>node);
return visitNewExpression(node as NewExpression);
case SyntaxKind.ParenthesizedExpression:
return visitParenthesizedExpression(<ParenthesizedExpression>node, expressionResultIsUnused);
return visitParenthesizedExpression(node as ParenthesizedExpression, expressionResultIsUnused);
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(<BinaryExpression>node, expressionResultIsUnused);
return visitBinaryExpression(node as BinaryExpression, expressionResultIsUnused);
case SyntaxKind.CommaListExpression:
return visitCommaListExpression(<CommaListExpression>node, expressionResultIsUnused);
return visitCommaListExpression(node as CommaListExpression, expressionResultIsUnused);
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.TemplateHead:
case SyntaxKind.TemplateMiddle:
case SyntaxKind.TemplateTail:
return visitTemplateLiteral(<LiteralExpression>node);
return visitTemplateLiteral(node as LiteralExpression);
case SyntaxKind.StringLiteral:
return visitStringLiteral(<StringLiteral>node);
return visitStringLiteral(node as StringLiteral);
case SyntaxKind.NumericLiteral:
return visitNumericLiteral(<NumericLiteral>node);
return visitNumericLiteral(node as NumericLiteral);
case SyntaxKind.TaggedTemplateExpression:
return visitTaggedTemplateExpression(<TaggedTemplateExpression>node);
return visitTaggedTemplateExpression(node as TaggedTemplateExpression);
case SyntaxKind.TemplateExpression:
return visitTemplateExpression(<TemplateExpression>node);
return visitTemplateExpression(node as TemplateExpression);
case SyntaxKind.YieldExpression:
return visitYieldExpression(<YieldExpression>node);
return visitYieldExpression(node as YieldExpression);
case SyntaxKind.SpreadElement:
return visitSpreadElement(<SpreadElement>node);
return visitSpreadElement(node as SpreadElement);
case SyntaxKind.SuperKeyword:
return visitSuperKeyword(/*isExpressionOfCall*/ false);
@@ -494,20 +494,20 @@ namespace ts {
return visitThisKeyword(node);
case SyntaxKind.MetaProperty:
return visitMetaProperty(<MetaProperty>node);
return visitMetaProperty(node as MetaProperty);
case SyntaxKind.MethodDeclaration:
return visitMethodDeclaration(<MethodDeclaration>node);
return visitMethodDeclaration(node as MethodDeclaration);
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return visitAccessorDeclaration(<AccessorDeclaration>node);
return visitAccessorDeclaration(node as AccessorDeclaration);
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.ReturnStatement:
return visitReturnStatement(<ReturnStatement>node);
return visitReturnStatement(node as ReturnStatement);
case SyntaxKind.VoidExpression:
return visitVoidExpression(node as VoidExpression);
@@ -919,7 +919,7 @@ namespace ts {
// If this is the case, we do not include the synthetic `...args` parameter and
// will instead use the `arguments` object in ES5/3.
return visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
|| <ParameterDeclaration[]>[];
|| [] as ParameterDeclaration[];
}
function createDefaultConstructorBody(node: ClassDeclaration | ClassExpression, isDerivedClass: boolean) {
@@ -1578,16 +1578,16 @@ namespace ts {
for (const member of node.members) {
switch (member.kind) {
case SyntaxKind.SemicolonClassElement:
statements.push(transformSemicolonClassElementToStatement(<SemicolonClassElement>member));
statements.push(transformSemicolonClassElementToStatement(member as SemicolonClassElement));
break;
case SyntaxKind.MethodDeclaration:
statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), <MethodDeclaration>member, node));
statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member as MethodDeclaration, node));
break;
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
const accessors = getAllAccessorDeclarations(node.members, <AccessorDeclaration>member);
const accessors = getAllAccessorDeclarations(node.members, member as AccessorDeclaration);
if (member === accessors.firstAccessor) {
statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
}
@@ -2274,13 +2274,13 @@ namespace ts {
switch (node.kind) {
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
return visitDoOrWhileStatement(<DoStatement | WhileStatement>node, outermostLabeledStatement);
return visitDoOrWhileStatement(node as DoStatement | WhileStatement, outermostLabeledStatement);
case SyntaxKind.ForStatement:
return visitForStatement(<ForStatement>node, outermostLabeledStatement);
return visitForStatement(node as ForStatement, outermostLabeledStatement);
case SyntaxKind.ForInStatement:
return visitForInStatement(<ForInStatement>node, outermostLabeledStatement);
return visitForInStatement(node as ForInStatement, outermostLabeledStatement);
case SyntaxKind.ForOfStatement:
return visitForOfStatement(<ForOfStatement>node, outermostLabeledStatement);
return visitForOfStatement(node as ForOfStatement, outermostLabeledStatement);
}
}
@@ -2853,9 +2853,9 @@ namespace ts {
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
const initializer = (<ForStatement | ForInStatement | ForOfStatement>node).initializer;
const initializer = (node as ForStatement | ForInStatement | ForOfStatement).initializer;
if (initializer && initializer.kind === SyntaxKind.VariableDeclarationList) {
loopInitializer = <VariableDeclarationList>initializer;
loopInitializer = initializer as VariableDeclarationList;
}
break;
}
@@ -3243,7 +3243,7 @@ namespace ts {
!state.labeledNonLocalBreaks &&
!state.labeledNonLocalContinues;
const call = factory.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ undefined, map(state.loopParameters, p => <Identifier>p.name));
const call = factory.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ undefined, map(state.loopParameters, p => p.name as Identifier));
const callResult = containsYield
? factory.createYieldExpression(
factory.createToken(SyntaxKind.AsteriskToken),
@@ -4250,8 +4250,8 @@ namespace ts {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.VariableDeclaration:
return (<NamedDeclaration>node.parent).name === node
&& resolver.isDeclarationWithCollidingName(<Declaration>node.parent);
return (node.parent as NamedDeclaration).name === node
&& resolver.isDeclarationWithCollidingName(node.parent as Declaration);
}
return false;
@@ -4265,10 +4265,10 @@ namespace ts {
function substituteExpression(node: Node) {
switch (node.kind) {
case SyntaxKind.Identifier:
return substituteExpressionIdentifier(<Identifier>node);
return substituteExpressionIdentifier(node as Identifier);
case SyntaxKind.ThisKeyword:
return substituteThisKeyword(<PrimaryExpression>node);
return substituteThisKeyword(node as PrimaryExpression);
}
return node;
@@ -4347,22 +4347,22 @@ namespace ts {
return false;
}
const statementExpression = (<ExpressionStatement>statement).expression;
const statementExpression = (statement as ExpressionStatement).expression;
if (!nodeIsSynthesized(statementExpression) || statementExpression.kind !== SyntaxKind.CallExpression) {
return false;
}
const callTarget = (<CallExpression>statementExpression).expression;
const callTarget = (statementExpression as CallExpression).expression;
if (!nodeIsSynthesized(callTarget) || callTarget.kind !== SyntaxKind.SuperKeyword) {
return false;
}
const callArgument = singleOrUndefined((<CallExpression>statementExpression).arguments);
const callArgument = singleOrUndefined((statementExpression as CallExpression).arguments);
if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== SyntaxKind.SpreadElement) {
return false;
}
const expression = (<SpreadElement>callArgument).expression;
const expression = (callArgument as SpreadElement).expression;
return isIdentifier(expression) && expression.escapedText === "arguments";
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ namespace ts {
}
switch (node.kind) {
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(<BinaryExpression>node);
return visitBinaryExpression(node as BinaryExpression);
default:
return visitEachChild(node, visitor, context);
}
+12 -12
View File
@@ -113,19 +113,19 @@ namespace ts {
return undefined;
case SyntaxKind.AwaitExpression:
return visitAwaitExpression(<AwaitExpression>node);
return visitAwaitExpression(node as AwaitExpression);
case SyntaxKind.MethodDeclaration:
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitMethodDeclaration, <MethodDeclaration>node);
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitMethodDeclaration, node as MethodDeclaration);
case SyntaxKind.FunctionDeclaration:
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionDeclaration, <FunctionDeclaration>node);
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionDeclaration, node as FunctionDeclaration);
case SyntaxKind.FunctionExpression:
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionExpression, <FunctionExpression>node);
return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionExpression, node as FunctionExpression);
case SyntaxKind.ArrowFunction:
return doWithContext(ContextFlags.NonTopLevel, visitArrowFunction, <ArrowFunction>node);
return doWithContext(ContextFlags.NonTopLevel, visitArrowFunction, node as ArrowFunction);
case SyntaxKind.PropertyAccessExpression:
if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) {
@@ -134,7 +134,7 @@ namespace ts {
return visitEachChild(node, visitor, context);
case SyntaxKind.ElementAccessExpression:
if (capturedSuperProperties && (<ElementAccessExpression>node).expression.kind === SyntaxKind.SuperKeyword) {
if (capturedSuperProperties && (node as ElementAccessExpression).expression.kind === SyntaxKind.SuperKeyword) {
hasSuperElementAccess = true;
}
return visitEachChild(node, visitor, context);
@@ -481,14 +481,14 @@ namespace ts {
let result: ConciseBody;
if (!isArrowFunction) {
const statements: Statement[] = [];
const statementOffset = factory.copyPrologue((<Block>node.body).statements, statements, /*ensureUseStrict*/ false, visitor);
const statementOffset = factory.copyPrologue((node.body as Block).statements, statements, /*ensureUseStrict*/ false, visitor);
statements.push(
factory.createReturnStatement(
emitHelpers().createAwaiterHelper(
inHasLexicalThisContext(),
hasLexicalArguments,
promiseConstructor,
transformAsyncFunctionBodyWorker(<Block>node.body, statementOffset)
transformAsyncFunctionBodyWorker(node.body as Block, statementOffset)
)
)
);
@@ -632,7 +632,7 @@ namespace ts {
function onSubstituteNode(hint: EmitHint, node: Node) {
node = previousOnSubstituteNode(hint, node);
if (hint === EmitHint.Expression && enclosingSuperContainerFlags) {
return substituteExpression(<Expression>node);
return substituteExpression(node as Expression);
}
return node;
@@ -641,11 +641,11 @@ namespace ts {
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.PropertyAccessExpression:
return substitutePropertyAccessExpression(<PropertyAccessExpression>node);
return substitutePropertyAccessExpression(node as PropertyAccessExpression);
case SyntaxKind.ElementAccessExpression:
return substituteElementAccessExpression(<ElementAccessExpression>node);
return substituteElementAccessExpression(node as ElementAccessExpression);
case SyntaxKind.CallExpression:
return substituteCallExpression(<CallExpression>node);
return substituteCallExpression(node as CallExpression);
}
return node;
}
+7 -7
View File
@@ -250,7 +250,7 @@ namespace ts {
}
return visitEachChild(node, visitor, context);
case SyntaxKind.ElementAccessExpression:
if (capturedSuperProperties && (<ElementAccessExpression>node).expression.kind === SyntaxKind.SuperKeyword) {
if (capturedSuperProperties && (node as ElementAccessExpression).expression.kind === SyntaxKind.SuperKeyword) {
hasSuperElementAccess = true;
}
return visitEachChild(node, visitor, context);
@@ -342,8 +342,8 @@ namespace ts {
function visitLabeledStatement(node: LabeledStatement) {
if (enclosingFunctionFlags & FunctionFlags.Async) {
const statement = unwrapInnermostStatementOfLabel(node);
if (statement.kind === SyntaxKind.ForOfStatement && (<ForOfStatement>statement).awaitModifier) {
return visitForOfStatement(<ForOfStatement>statement, node);
if (statement.kind === SyntaxKind.ForOfStatement && (statement as ForOfStatement).awaitModifier) {
return visitForOfStatement(statement as ForOfStatement, node);
}
return factory.restoreEnclosingLabel(visitNode(statement, visitor, isStatement, factory.liftToBlock), node);
}
@@ -1107,7 +1107,7 @@ namespace ts {
function onSubstituteNode(hint: EmitHint, node: Node) {
node = previousOnSubstituteNode(hint, node);
if (hint === EmitHint.Expression && enclosingSuperContainerFlags) {
return substituteExpression(<Expression>node);
return substituteExpression(node as Expression);
}
return node;
}
@@ -1115,11 +1115,11 @@ namespace ts {
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.PropertyAccessExpression:
return substitutePropertyAccessExpression(<PropertyAccessExpression>node);
return substitutePropertyAccessExpression(node as PropertyAccessExpression);
case SyntaxKind.ElementAccessExpression:
return substituteElementAccessExpression(<ElementAccessExpression>node);
return substituteElementAccessExpression(node as ElementAccessExpression);
case SyntaxKind.CallExpression:
return substituteCallExpression(<CallExpression>node);
return substituteCallExpression(node as CallExpression);
}
return node;
}
+2 -2
View File
@@ -35,8 +35,8 @@ namespace ts {
}
return visitEachChild(node, visitor, context);
case SyntaxKind.BinaryExpression:
if ((<BinaryExpression>node).operatorToken.kind === SyntaxKind.QuestionQuestionToken) {
return transformNullishCoalescingExpression(<BinaryExpression>node);
if ((node as BinaryExpression).operatorToken.kind === SyntaxKind.QuestionQuestionToken) {
return transformNullishCoalescingExpression(node as BinaryExpression);
}
return visitEachChild(node, visitor, context);
case SyntaxKind.DeleteExpression:
+1 -1
View File
@@ -21,7 +21,7 @@ namespace ts {
}
switch (node.kind) {
case SyntaxKind.BinaryExpression:
const binaryExpression = <BinaryExpression>node;
const binaryExpression = node as BinaryExpression;
if (isLogicalOrCoalescingAssignmentExpression(binaryExpression)) {
return transformLogicalAssignment(binaryExpression);
}
+1 -1
View File
@@ -48,7 +48,7 @@ namespace ts {
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.JsxClosingElement:
case SyntaxKind.JsxSelfClosingElement:
const tagName = (<JsxOpeningElement | JsxClosingElement | JsxSelfClosingElement>node).tagName;
const tagName = (node as JsxOpeningElement | JsxClosingElement | JsxSelfClosingElement).tagName;
noSubstitution[getOriginalNodeId(tagName)] = true;
break;
}
+74 -74
View File
@@ -337,13 +337,13 @@ namespace ts {
function visitJavaScriptInStatementContainingYield(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.DoStatement:
return visitDoStatement(<DoStatement>node);
return visitDoStatement(node as DoStatement);
case SyntaxKind.WhileStatement:
return visitWhileStatement(<WhileStatement>node);
return visitWhileStatement(node as WhileStatement);
case SyntaxKind.SwitchStatement:
return visitSwitchStatement(<SwitchStatement>node);
return visitSwitchStatement(node as SwitchStatement);
case SyntaxKind.LabeledStatement:
return visitLabeledStatement(<LabeledStatement>node);
return visitLabeledStatement(node as LabeledStatement);
default:
return visitJavaScriptInGeneratorFunctionBody(node);
}
@@ -357,24 +357,24 @@ namespace ts {
function visitJavaScriptInGeneratorFunctionBody(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.FunctionExpression:
return visitFunctionExpression(<FunctionExpression>node);
return visitFunctionExpression(node as FunctionExpression);
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return visitAccessorDeclaration(<AccessorDeclaration>node);
return visitAccessorDeclaration(node as AccessorDeclaration);
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.ForStatement:
return visitForStatement(<ForStatement>node);
return visitForStatement(node as ForStatement);
case SyntaxKind.ForInStatement:
return visitForInStatement(<ForInStatement>node);
return visitForInStatement(node as ForInStatement);
case SyntaxKind.BreakStatement:
return visitBreakStatement(<BreakStatement>node);
return visitBreakStatement(node as BreakStatement);
case SyntaxKind.ContinueStatement:
return visitContinueStatement(<ContinueStatement>node);
return visitContinueStatement(node as ContinueStatement);
case SyntaxKind.ReturnStatement:
return visitReturnStatement(<ReturnStatement>node);
return visitReturnStatement(node as ReturnStatement);
default:
if (node.transformFlags & TransformFlags.ContainsYield) {
return visitJavaScriptContainingYield(node);
@@ -396,23 +396,23 @@ namespace ts {
function visitJavaScriptContainingYield(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(<BinaryExpression>node);
return visitBinaryExpression(node as BinaryExpression);
case SyntaxKind.CommaListExpression:
return visitCommaListExpression(<CommaListExpression>node);
return visitCommaListExpression(node as CommaListExpression);
case SyntaxKind.ConditionalExpression:
return visitConditionalExpression(<ConditionalExpression>node);
return visitConditionalExpression(node as ConditionalExpression);
case SyntaxKind.YieldExpression:
return visitYieldExpression(<YieldExpression>node);
return visitYieldExpression(node as YieldExpression);
case SyntaxKind.ArrayLiteralExpression:
return visitArrayLiteralExpression(<ArrayLiteralExpression>node);
return visitArrayLiteralExpression(node as ArrayLiteralExpression);
case SyntaxKind.ObjectLiteralExpression:
return visitObjectLiteralExpression(<ObjectLiteralExpression>node);
return visitObjectLiteralExpression(node as ObjectLiteralExpression);
case SyntaxKind.ElementAccessExpression:
return visitElementAccessExpression(<ElementAccessExpression>node);
return visitElementAccessExpression(node as ElementAccessExpression);
case SyntaxKind.CallExpression:
return visitCallExpression(<CallExpression>node);
return visitCallExpression(node as CallExpression);
case SyntaxKind.NewExpression:
return visitNewExpression(<NewExpression>node);
return visitNewExpression(node as NewExpression);
default:
return visitEachChild(node, visitor, context);
}
@@ -426,10 +426,10 @@ namespace ts {
function visitGenerator(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.FunctionExpression:
return visitFunctionExpression(<FunctionExpression>node);
return visitFunctionExpression(node as FunctionExpression);
default:
return Debug.failBadSyntaxKind(node);
@@ -632,7 +632,7 @@ namespace ts {
}
for (const variable of node.declarationList.declarations) {
hoistVariableDeclaration(<Identifier>variable.name);
hoistVariableDeclaration(variable.name as Identifier);
}
const variables = getInitializedVariables(node.declarationList);
@@ -693,9 +693,9 @@ namespace ts {
// _a.b = %sent%;
target = factory.updatePropertyAccessExpression(
<PropertyAccessExpression>left,
cacheExpression(visitNode((<PropertyAccessExpression>left).expression, visitor, isLeftHandSideExpression)),
(<PropertyAccessExpression>left).name
left as PropertyAccessExpression,
cacheExpression(visitNode((left as PropertyAccessExpression).expression, visitor, isLeftHandSideExpression)),
(left as PropertyAccessExpression).name
);
break;
@@ -711,9 +711,9 @@ namespace ts {
// .mark resumeLabel
// _a[_b] = %sent%;
target = factory.updateElementAccessExpression(<ElementAccessExpression>left,
cacheExpression(visitNode((<ElementAccessExpression>left).expression, visitor, isLeftHandSideExpression)),
cacheExpression(visitNode((<ElementAccessExpression>left).argumentExpression, visitor, isExpression))
target = factory.updateElementAccessExpression(left as ElementAccessExpression,
cacheExpression(visitNode((left as ElementAccessExpression).expression, visitor, isLeftHandSideExpression)),
cacheExpression(visitNode((left as ElementAccessExpression).argumentExpression, visitor, isExpression))
);
break;
@@ -1000,7 +1000,7 @@ namespace ts {
leadingElement = undefined;
}
const expressions = reduceLeft(elements, reduceElement, <Expression[]>[], numInitialElements);
const expressions = reduceLeft(elements, reduceElement, [] as Expression[], numInitialElements);
return temp
? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
: setTextRange(
@@ -1067,7 +1067,7 @@ namespace ts {
)
);
const expressions = reduceLeft(properties, reduceProperty, <Expression[]>[], numInitialProperties);
const expressions = reduceLeft(properties, reduceProperty, [] as Expression[], numInitialProperties);
// TODO(rbuckton): Does this need to be parented?
expressions.push(multiLine ? startOnNewLine(setParent(setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
return factory.inlineExpressions(expressions);
@@ -1209,35 +1209,35 @@ namespace ts {
function transformAndEmitStatementWorker(node: Statement): void {
switch (node.kind) {
case SyntaxKind.Block:
return transformAndEmitBlock(<Block>node);
return transformAndEmitBlock(node as Block);
case SyntaxKind.ExpressionStatement:
return transformAndEmitExpressionStatement(<ExpressionStatement>node);
return transformAndEmitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.IfStatement:
return transformAndEmitIfStatement(<IfStatement>node);
return transformAndEmitIfStatement(node as IfStatement);
case SyntaxKind.DoStatement:
return transformAndEmitDoStatement(<DoStatement>node);
return transformAndEmitDoStatement(node as DoStatement);
case SyntaxKind.WhileStatement:
return transformAndEmitWhileStatement(<WhileStatement>node);
return transformAndEmitWhileStatement(node as WhileStatement);
case SyntaxKind.ForStatement:
return transformAndEmitForStatement(<ForStatement>node);
return transformAndEmitForStatement(node as ForStatement);
case SyntaxKind.ForInStatement:
return transformAndEmitForInStatement(<ForInStatement>node);
return transformAndEmitForInStatement(node as ForInStatement);
case SyntaxKind.ContinueStatement:
return transformAndEmitContinueStatement(<ContinueStatement>node);
return transformAndEmitContinueStatement(node as ContinueStatement);
case SyntaxKind.BreakStatement:
return transformAndEmitBreakStatement(<BreakStatement>node);
return transformAndEmitBreakStatement(node as BreakStatement);
case SyntaxKind.ReturnStatement:
return transformAndEmitReturnStatement(<ReturnStatement>node);
return transformAndEmitReturnStatement(node as ReturnStatement);
case SyntaxKind.WithStatement:
return transformAndEmitWithStatement(<WithStatement>node);
return transformAndEmitWithStatement(node as WithStatement);
case SyntaxKind.SwitchStatement:
return transformAndEmitSwitchStatement(<SwitchStatement>node);
return transformAndEmitSwitchStatement(node as SwitchStatement);
case SyntaxKind.LabeledStatement:
return transformAndEmitLabeledStatement(<LabeledStatement>node);
return transformAndEmitLabeledStatement(node as LabeledStatement);
case SyntaxKind.ThrowStatement:
return transformAndEmitThrowStatement(<ThrowStatement>node);
return transformAndEmitThrowStatement(node as ThrowStatement);
case SyntaxKind.TryStatement:
return transformAndEmitTryStatement(<TryStatement>node);
return transformAndEmitTryStatement(node as TryStatement);
default:
return emitStatement(visitNode(node, visitor, isStatement));
}
@@ -1258,7 +1258,7 @@ namespace ts {
function transformAndEmitVariableDeclarationList(node: VariableDeclarationList): VariableDeclarationList | undefined {
for (const variable of node.declarations) {
const name = factory.cloneNode(<Identifier>variable.name);
const name = factory.cloneNode(variable.name as Identifier);
setCommentRange(name, variable.name);
hoistVariableDeclaration(name);
}
@@ -1290,7 +1290,7 @@ namespace ts {
function transformInitializedVariable(node: InitializedVariableDeclaration) {
return setSourceMapRange(
factory.createAssignment(
setSourceMapRange(<Identifier>factory.cloneNode(node.name), node.name),
setSourceMapRange(factory.cloneNode(node.name) as Identifier, node.name),
visitNode(node.initializer, visitor, isExpression)
),
node
@@ -1492,7 +1492,7 @@ namespace ts {
const initializer = node.initializer;
if (initializer && isVariableDeclarationList(initializer)) {
for (const variable of initializer.declarations) {
hoistVariableDeclaration(<Identifier>variable.name);
hoistVariableDeclaration(variable.name as Identifier);
}
const variables = getInitializedVariables(initializer);
@@ -1573,10 +1573,10 @@ namespace ts {
let variable: Expression;
if (isVariableDeclarationList(initializer)) {
for (const variable of initializer.declarations) {
hoistVariableDeclaration(<Identifier>variable.name);
hoistVariableDeclaration(variable.name as Identifier);
}
variable = <Identifier>factory.cloneNode(initializer.declarations[0].name);
variable = factory.cloneNode(initializer.declarations[0].name) as Identifier;
}
else {
variable = visitNode(initializer, visitor, isExpression);
@@ -1618,11 +1618,11 @@ namespace ts {
const initializer = node.initializer;
if (isVariableDeclarationList(initializer)) {
for (const variable of initializer.declarations) {
hoistVariableDeclaration(<Identifier>variable.name);
hoistVariableDeclaration(variable.name as Identifier);
}
node = factory.updateForInStatement(node,
<Identifier>initializer.declarations[0].name,
initializer.declarations[0].name as Identifier,
visitNode(node.expression, visitor, isExpression),
visitNode(node.statement, visitor, isStatement, factory.liftToBlock)
);
@@ -1951,7 +1951,7 @@ namespace ts {
function onSubstituteNode(hint: EmitHint, node: Node): Node {
node = previousOnSubstituteNode(hint, node);
if (hint === EmitHint.Expression) {
return substituteExpression(<Expression>node);
return substituteExpression(node as Expression);
}
return node;
}
@@ -1986,7 +1986,7 @@ namespace ts {
function cacheExpression(node: Expression): Identifier {
if (isGeneratedIdentifier(node) || getEmitFlags(node) & EmitFlags.HelperName) {
return <Identifier>node;
return node as Identifier;
}
const temp = factory.createTempVariable(hoistVariableDeclaration);
@@ -2097,7 +2097,7 @@ namespace ts {
*/
function endWithBlock(): void {
Debug.assert(peekBlockKind() === CodeBlockKind.With);
const block = <WithBlock>endBlock();
const block = endBlock() as WithBlock;
markLabel(block.endLabel);
}
@@ -2133,7 +2133,7 @@ namespace ts {
hoistVariableDeclaration(variable.name);
}
else {
const text = idText(<Identifier>variable.name);
const text = idText(variable.name as Identifier);
name = declareLocal(text);
if (!renamedCatchVariables) {
renamedCatchVariables = new Map<string, boolean>();
@@ -2145,7 +2145,7 @@ namespace ts {
renamedCatchVariableDeclarations[getOriginalNodeId(variable)] = name;
}
const exception = <ExceptionBlock>peekBlock();
const exception = peekBlock() as ExceptionBlock;
Debug.assert(exception.state < ExceptionBlockState.Catch);
const endLabel = exception.endLabel;
@@ -2167,7 +2167,7 @@ namespace ts {
function beginFinallyBlock(): void {
Debug.assert(peekBlockKind() === CodeBlockKind.Exception);
const exception = <ExceptionBlock>peekBlock();
const exception = peekBlock() as ExceptionBlock;
Debug.assert(exception.state < ExceptionBlockState.Finally);
const endLabel = exception.endLabel;
@@ -2184,7 +2184,7 @@ namespace ts {
*/
function endExceptionBlock(): void {
Debug.assert(peekBlockKind() === CodeBlockKind.Exception);
const exception = <ExceptionBlock>endBlock();
const exception = endBlock() as ExceptionBlock;
const state = exception.state;
if (state < ExceptionBlockState.Finally) {
emitBreak(exception.endLabel);
@@ -2238,7 +2238,7 @@ namespace ts {
*/
function endLoopBlock(): void {
Debug.assert(peekBlockKind() === CodeBlockKind.Loop);
const block = <SwitchBlock>endBlock();
const block = endBlock() as SwitchBlock;
const breakLabel = block.breakLabel;
if (!block.isScript) {
markLabel(breakLabel);
@@ -2278,7 +2278,7 @@ namespace ts {
*/
function endSwitchBlock(): void {
Debug.assert(peekBlockKind() === CodeBlockKind.Switch);
const block = <SwitchBlock>endBlock();
const block = endBlock() as SwitchBlock;
const breakLabel = block.breakLabel;
if (!block.isScript) {
markLabel(breakLabel);
@@ -2306,7 +2306,7 @@ namespace ts {
function endLabeledBlock() {
Debug.assert(peekBlockKind() === CodeBlockKind.Labeled);
const block = <LabeledBlock>endBlock();
const block = endBlock() as LabeledBlock;
if (!block.isScript) {
markLabel(block.breakLabel);
}
@@ -2945,27 +2945,27 @@ namespace ts {
const args = operationArguments![operationIndex]!;
if (opcode === OpCode.Statement) {
return writeStatement(<Statement>args[0]);
return writeStatement(args[0] as Statement);
}
const location = operationLocations![operationIndex];
switch (opcode) {
case OpCode.Assign:
return writeAssign(<Expression>args[0], <Expression>args[1], location);
return writeAssign(args[0] as Expression, args[1] as Expression, location);
case OpCode.Break:
return writeBreak(<Label>args[0], location);
return writeBreak(args[0] as Label, location);
case OpCode.BreakWhenTrue:
return writeBreakWhenTrue(<Label>args[0], <Expression>args[1], location);
return writeBreakWhenTrue(args[0] as Label, args[1] as Expression, location);
case OpCode.BreakWhenFalse:
return writeBreakWhenFalse(<Label>args[0], <Expression>args[1], location);
return writeBreakWhenFalse(args[0] as Label, args[1] as Expression, location);
case OpCode.Yield:
return writeYield(<Expression>args[0], location);
return writeYield(args[0] as Expression, location);
case OpCode.YieldStar:
return writeYieldStar(<Expression>args[0], location);
return writeYieldStar(args[0] as Expression, location);
case OpCode.Return:
return writeReturn(<Expression>args[0], location);
return writeReturn(args[0] as Expression, location);
case OpCode.Throw:
return writeThrow(<Expression>args[0], location);
return writeThrow(args[0] as Expression, location);
}
}
+4 -4
View File
@@ -126,16 +126,16 @@ namespace ts {
function visitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.JsxElement:
return visitJsxElement(<JsxElement>node, /*isChild*/ false);
return visitJsxElement(node as JsxElement, /*isChild*/ false);
case SyntaxKind.JsxSelfClosingElement:
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node, /*isChild*/ false);
return visitJsxSelfClosingElement(node as JsxSelfClosingElement, /*isChild*/ false);
case SyntaxKind.JsxFragment:
return visitJsxFragment(<JsxFragment>node, /*isChild*/ false);
return visitJsxFragment(node as JsxFragment, /*isChild*/ false);
case SyntaxKind.JsxExpression:
return visitJsxExpression(<JsxExpression>node);
return visitJsxExpression(node as JsxExpression);
default:
return visitEachChild(node, visitor, context);
@@ -58,7 +58,7 @@ namespace ts {
// Elide `import=` as it is not legal with --module ES6
return undefined;
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
return visitExportAssignment(node as ExportAssignment);
case SyntaxKind.ExportDeclaration:
const exportDecl = (node as ExportDeclaration);
return visitExportDeclaration(exportDecl);
+15 -15
View File
@@ -508,31 +508,31 @@ namespace ts {
function sourceElementVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
return visitImportDeclaration(node as ImportDeclaration);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
return visitImportEqualsDeclaration(node as ImportEqualsDeclaration);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(<ExportDeclaration>node);
return visitExportDeclaration(node as ExportDeclaration);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
return visitExportAssignment(node as ExportAssignment);
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.ClassDeclaration:
return visitClassDeclaration(<ClassDeclaration>node);
return visitClassDeclaration(node as ClassDeclaration);
case SyntaxKind.MergeDeclarationMarker:
return visitMergeDeclarationMarker(<MergeDeclarationMarker>node);
return visitMergeDeclarationMarker(node as MergeDeclarationMarker);
case SyntaxKind.EndOfDeclarationMarker:
return visitEndOfDeclarationMarker(<EndOfDeclarationMarker>node);
return visitEndOfDeclarationMarker(node as EndOfDeclarationMarker);
default:
return visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -1343,7 +1343,7 @@ namespace ts {
// statement.
if (hasAssociatedEndOfDeclarationMarker(node) && node.original!.kind === SyntaxKind.VariableStatement) {
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], <VariableStatement>node.original);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original as VariableStatement);
}
return node;
@@ -1670,7 +1670,7 @@ namespace ts {
*/
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void {
if (node.kind === SyntaxKind.SourceFile) {
currentSourceFile = <SourceFile>node;
currentSourceFile = node as SourceFile;
currentModuleInfo = moduleInfoMap[getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -1702,7 +1702,7 @@ namespace ts {
}
if (hint === EmitHint.Expression) {
return substituteExpression(<Expression>node);
return substituteExpression(node as Expression);
}
else if (isShorthandPropertyAssignment(node)) {
return substituteShorthandPropertyAssignment(node);
@@ -1740,12 +1740,12 @@ namespace ts {
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.Identifier:
return substituteExpressionIdentifier(<Identifier>node);
return substituteExpressionIdentifier(node as Identifier);
case SyntaxKind.BinaryExpression:
return substituteBinaryExpression(<BinaryExpression>node);
return substituteBinaryExpression(node as BinaryExpression);
case SyntaxKind.PostfixUnaryExpression:
case SyntaxKind.PrefixUnaryExpression:
return substituteUnaryExpression(<PrefixUnaryExpression | PostfixUnaryExpression>node);
return substituteUnaryExpression(node as PrefixUnaryExpression | PostfixUnaryExpression);
}
return node;
+31 -31
View File
@@ -569,16 +569,16 @@ namespace ts {
function sourceElementVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
return visitImportDeclaration(node as ImportDeclaration);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
return visitImportEqualsDeclaration(node as ImportEqualsDeclaration);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(<ExportDeclaration>node);
return visitExportDeclaration(node as ExportDeclaration);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
return visitExportAssignment(node as ExportAssignment);
default:
return nestedElementVisitor(node);
@@ -885,7 +885,7 @@ namespace ts {
if (hasAssociatedEndOfDeclarationMarker(node) && node.original!.kind === SyntaxKind.VariableStatement) {
const id = getOriginalNodeId(node);
const isExportedDeclaration = hasSyntacticModifier(node.original!, ModifierFlags.Export);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], <VariableStatement>node.original, isExportedDeclaration);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original as VariableStatement, isExportedDeclaration);
}
return node;
@@ -1156,61 +1156,61 @@ namespace ts {
function nestedElementVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.ClassDeclaration:
return visitClassDeclaration(<ClassDeclaration>node);
return visitClassDeclaration(node as ClassDeclaration);
case SyntaxKind.ForStatement:
return visitForStatement(<ForStatement>node);
return visitForStatement(node as ForStatement);
case SyntaxKind.ForInStatement:
return visitForInStatement(<ForInStatement>node);
return visitForInStatement(node as ForInStatement);
case SyntaxKind.ForOfStatement:
return visitForOfStatement(<ForOfStatement>node);
return visitForOfStatement(node as ForOfStatement);
case SyntaxKind.DoStatement:
return visitDoStatement(<DoStatement>node);
return visitDoStatement(node as DoStatement);
case SyntaxKind.WhileStatement:
return visitWhileStatement(<WhileStatement>node);
return visitWhileStatement(node as WhileStatement);
case SyntaxKind.LabeledStatement:
return visitLabeledStatement(<LabeledStatement>node);
return visitLabeledStatement(node as LabeledStatement);
case SyntaxKind.WithStatement:
return visitWithStatement(<WithStatement>node);
return visitWithStatement(node as WithStatement);
case SyntaxKind.SwitchStatement:
return visitSwitchStatement(<SwitchStatement>node);
return visitSwitchStatement(node as SwitchStatement);
case SyntaxKind.CaseBlock:
return visitCaseBlock(<CaseBlock>node);
return visitCaseBlock(node as CaseBlock);
case SyntaxKind.CaseClause:
return visitCaseClause(<CaseClause>node);
return visitCaseClause(node as CaseClause);
case SyntaxKind.DefaultClause:
return visitDefaultClause(<DefaultClause>node);
return visitDefaultClause(node as DefaultClause);
case SyntaxKind.TryStatement:
return visitTryStatement(<TryStatement>node);
return visitTryStatement(node as TryStatement);
case SyntaxKind.CatchClause:
return visitCatchClause(<CatchClause>node);
return visitCatchClause(node as CatchClause);
case SyntaxKind.Block:
return visitBlock(<Block>node);
return visitBlock(node as Block);
case SyntaxKind.MergeDeclarationMarker:
return visitMergeDeclarationMarker(<MergeDeclarationMarker>node);
return visitMergeDeclarationMarker(node as MergeDeclarationMarker);
case SyntaxKind.EndOfDeclarationMarker:
return visitEndOfDeclarationMarker(<EndOfDeclarationMarker>node);
return visitEndOfDeclarationMarker(node as EndOfDeclarationMarker);
default:
return destructuringAndImportCallVisitor(node);
@@ -1593,7 +1593,7 @@ namespace ts {
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void {
if (node.kind === SyntaxKind.SourceFile) {
const id = getOriginalNodeId(node);
currentSourceFile = <SourceFile>node;
currentSourceFile = node as SourceFile;
moduleInfo = moduleInfoMap[id];
exportFunction = exportFunctionsMap[id];
noSubstitution = noSubstitutionMap[id];
@@ -1633,7 +1633,7 @@ namespace ts {
}
if (hint === EmitHint.Expression) {
return substituteExpression(<Expression>node);
return substituteExpression(node as Expression);
}
else if (hint === EmitHint.Unspecified) {
return substituteUnspecified(node);
@@ -1650,7 +1650,7 @@ namespace ts {
function substituteUnspecified(node: Node) {
switch (node.kind) {
case SyntaxKind.ShorthandPropertyAssignment:
return substituteShorthandPropertyAssignment(<ShorthandPropertyAssignment>node);
return substituteShorthandPropertyAssignment(node as ShorthandPropertyAssignment);
}
return node;
}
@@ -1702,14 +1702,14 @@ namespace ts {
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.Identifier:
return substituteExpressionIdentifier(<Identifier>node);
return substituteExpressionIdentifier(node as Identifier);
case SyntaxKind.BinaryExpression:
return substituteBinaryExpression(<BinaryExpression>node);
return substituteBinaryExpression(node as BinaryExpression);
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
return substituteUnaryExpression(<PrefixUnaryExpression | PostfixUnaryExpression>node);
return substituteUnaryExpression(node as PrefixUnaryExpression | PostfixUnaryExpression);
case SyntaxKind.MetaProperty:
return substituteMetaProperty(<MetaProperty>node);
return substituteMetaProperty(node as MetaProperty);
}
return node;
+53 -53
View File
@@ -162,7 +162,7 @@ namespace ts {
case SyntaxKind.CaseBlock:
case SyntaxKind.ModuleBlock:
case SyntaxKind.Block:
currentLexicalScope = <SourceFile | CaseBlock | ModuleBlock | Block>node;
currentLexicalScope = node as SourceFile | CaseBlock | ModuleBlock | Block;
currentNameScope = undefined;
currentScopeFirstDeclarationsOfName = undefined;
break;
@@ -233,7 +233,7 @@ namespace ts {
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.ExportAssignment:
case SyntaxKind.ExportDeclaration:
return visitElidableStatement(<ImportDeclaration | ImportEqualsDeclaration | ExportAssignment | ExportDeclaration>node);
return visitElidableStatement(node as ImportDeclaration | ImportEqualsDeclaration | ExportAssignment | ExportDeclaration);
default:
return visitorWorker(node);
}
@@ -286,7 +286,7 @@ namespace ts {
node.kind === SyntaxKind.ImportDeclaration ||
node.kind === SyntaxKind.ImportClause ||
(node.kind === SyntaxKind.ImportEqualsDeclaration &&
(<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference)) {
(node as ImportEqualsDeclaration).moduleReference.kind === SyntaxKind.ExternalModuleReference)) {
// do not emit ES6 imports and exports since they are illegal inside a namespace
return undefined;
}
@@ -425,7 +425,7 @@ namespace ts {
return undefined;
case SyntaxKind.Constructor:
return visitConstructor(<ConstructorDeclaration>node);
return visitConstructor(node as ConstructorDeclaration);
case SyntaxKind.InterfaceDeclaration:
// TypeScript interfaces are elided, but some comments may be preserved.
@@ -441,7 +441,7 @@ namespace ts {
// - parameter property assignments in the constructor
// - index signatures
// - method overload signatures
return visitClassDeclaration(<ClassDeclaration>node);
return visitClassDeclaration(node as ClassDeclaration);
case SyntaxKind.ClassExpression:
// This may be a class expression with TypeScript syntax extensions.
@@ -452,43 +452,43 @@ namespace ts {
// - parameter property assignments in the constructor
// - index signatures
// - method overload signatures
return visitClassExpression(<ClassExpression>node);
return visitClassExpression(node as ClassExpression);
case SyntaxKind.HeritageClause:
// This may be a heritage clause with TypeScript syntax extensions.
//
// TypeScript heritage clause extensions include:
// - `implements` clause
return visitHeritageClause(<HeritageClause>node);
return visitHeritageClause(node as HeritageClause);
case SyntaxKind.ExpressionWithTypeArguments:
// TypeScript supports type arguments on an expression in an `extends` heritage clause.
return visitExpressionWithTypeArguments(<ExpressionWithTypeArguments>node);
return visitExpressionWithTypeArguments(node as ExpressionWithTypeArguments);
case SyntaxKind.MethodDeclaration:
// TypeScript method declarations may have decorators, modifiers
// or type annotations.
return visitMethodDeclaration(<MethodDeclaration>node);
return visitMethodDeclaration(node as MethodDeclaration);
case SyntaxKind.GetAccessor:
// Get Accessors can have TypeScript modifiers, decorators, and type annotations.
return visitGetAccessor(<GetAccessorDeclaration>node);
return visitGetAccessor(node as GetAccessorDeclaration);
case SyntaxKind.SetAccessor:
// Set Accessors can have TypeScript modifiers and type annotations.
return visitSetAccessor(<SetAccessorDeclaration>node);
return visitSetAccessor(node as SetAccessorDeclaration);
case SyntaxKind.FunctionDeclaration:
// Typescript function declarations can have modifiers, decorators, and type annotations.
return visitFunctionDeclaration(<FunctionDeclaration>node);
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.FunctionExpression:
// TypeScript function expressions can have modifiers and type annotations.
return visitFunctionExpression(<FunctionExpression>node);
return visitFunctionExpression(node as FunctionExpression);
case SyntaxKind.ArrowFunction:
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(<ArrowFunction>node);
return visitArrowFunction(node as ArrowFunction);
case SyntaxKind.Parameter:
// This may be a parameter declaration with TypeScript syntax extensions.
@@ -499,55 +499,55 @@ namespace ts {
// - the question mark (?) token for optional parameters
// - type annotations
// - this parameters
return visitParameter(<ParameterDeclaration>node);
return visitParameter(node as ParameterDeclaration);
case SyntaxKind.ParenthesizedExpression:
// ParenthesizedExpressions are TypeScript if their expression is a
// TypeAssertion or AsExpression
return visitParenthesizedExpression(<ParenthesizedExpression>node);
return visitParenthesizedExpression(node as ParenthesizedExpression);
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.AsExpression:
// TypeScript type assertions are removed, but their subtrees are preserved.
return visitAssertionExpression(<AssertionExpression>node);
return visitAssertionExpression(node as AssertionExpression);
case SyntaxKind.CallExpression:
return visitCallExpression(<CallExpression>node);
return visitCallExpression(node as CallExpression);
case SyntaxKind.NewExpression:
return visitNewExpression(<NewExpression>node);
return visitNewExpression(node as NewExpression);
case SyntaxKind.TaggedTemplateExpression:
return visitTaggedTemplateExpression(<TaggedTemplateExpression>node);
return visitTaggedTemplateExpression(node as TaggedTemplateExpression);
case SyntaxKind.NonNullExpression:
// TypeScript non-null expressions are removed, but their subtrees are preserved.
return visitNonNullExpression(<NonNullExpression>node);
return visitNonNullExpression(node as NonNullExpression);
case SyntaxKind.EnumDeclaration:
// TypeScript enum declarations do not exist in ES6 and must be rewritten.
return visitEnumDeclaration(<EnumDeclaration>node);
return visitEnumDeclaration(node as EnumDeclaration);
case SyntaxKind.VariableStatement:
// TypeScript namespace exports for variable statements must be transformed.
return visitVariableStatement(<VariableStatement>node);
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.VariableDeclaration:
return visitVariableDeclaration(<VariableDeclaration>node);
return visitVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.ModuleDeclaration:
// TypeScript namespace declarations must be transformed.
return visitModuleDeclaration(<ModuleDeclaration>node);
return visitModuleDeclaration(node as ModuleDeclaration);
case SyntaxKind.ImportEqualsDeclaration:
// TypeScript namespace or external module import.
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
return visitImportEqualsDeclaration(node as ImportEqualsDeclaration);
case SyntaxKind.JsxSelfClosingElement:
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node);
return visitJsxSelfClosingElement(node as JsxSelfClosingElement);
case SyntaxKind.JsxOpeningElement:
return visitJsxJsxOpeningElement(<JsxOpeningElement>node);
return visitJsxJsxOpeningElement(node as JsxOpeningElement);
default:
// node contains some other TypeScript syntax
@@ -1032,13 +1032,13 @@ namespace ts {
switch (member.kind) {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return getAllDecoratorsOfAccessors(node, <AccessorDeclaration>member);
return getAllDecoratorsOfAccessors(node, member as AccessorDeclaration);
case SyntaxKind.MethodDeclaration:
return getAllDecoratorsOfMethod(<MethodDeclaration>member);
return getAllDecoratorsOfMethod(member as MethodDeclaration);
case SyntaxKind.PropertyDeclaration:
return getAllDecoratorsOfProperty(<PropertyDeclaration>member);
return getAllDecoratorsOfProperty(member as PropertyDeclaration);
default:
return undefined;
@@ -1378,7 +1378,7 @@ namespace ts {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return getFirstConstructorWithBody(<ClassLikeDeclaration>node) !== undefined;
return getFirstConstructorWithBody(node as ClassLikeDeclaration) !== undefined;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
@@ -1405,7 +1405,7 @@ namespace ts {
switch (node.kind) {
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.Parameter:
return serializeTypeNode((<PropertyDeclaration | ParameterDeclaration | GetAccessorDeclaration>node).type);
return serializeTypeNode((node as PropertyDeclaration | ParameterDeclaration | GetAccessorDeclaration).type);
case SyntaxKind.SetAccessor:
case SyntaxKind.GetAccessor:
return serializeTypeNode(getAccessorTypeNode(node as AccessorDeclaration));
@@ -1454,7 +1454,7 @@ namespace ts {
function getParametersOfDecoratedDeclaration(node: SignatureDeclaration, container: ClassLikeDeclaration) {
if (container && node.kind === SyntaxKind.GetAccessor) {
const { setAccessor } = getAllAccessorDeclarations(container.members, <AccessorDeclaration>node);
const { setAccessor } = getAllAccessorDeclarations(container.members, node as AccessorDeclaration);
if (setAccessor) {
return setAccessor.parameters;
}
@@ -1508,7 +1508,7 @@ namespace ts {
return factory.createVoidZero();
case SyntaxKind.ParenthesizedType:
return serializeTypeNode((<ParenthesizedTypeNode>node).type);
return serializeTypeNode((node as ParenthesizedTypeNode).type);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
@@ -1529,7 +1529,7 @@ namespace ts {
return factory.createIdentifier("Object");
case SyntaxKind.LiteralType:
switch ((<LiteralTypeNode>node).literal.kind) {
switch ((node as LiteralTypeNode).literal.kind) {
case SyntaxKind.StringLiteral:
case SyntaxKind.NoSubstitutionTemplateLiteral:
return factory.createIdentifier("String");
@@ -1549,7 +1549,7 @@ namespace ts {
return factory.createVoidZero();
default:
return Debug.failBadSyntaxKind((<LiteralTypeNode>node).literal);
return Debug.failBadSyntaxKind((node as LiteralTypeNode).literal);
}
case SyntaxKind.NumberKeyword:
@@ -1564,18 +1564,18 @@ namespace ts {
: factory.createIdentifier("Symbol");
case SyntaxKind.TypeReference:
return serializeTypeReferenceNode(<TypeReferenceNode>node);
return serializeTypeReferenceNode(node as TypeReferenceNode);
case SyntaxKind.IntersectionType:
case SyntaxKind.UnionType:
return serializeTypeList((<UnionOrIntersectionTypeNode>node).types);
return serializeTypeList((node as UnionOrIntersectionTypeNode).types);
case SyntaxKind.ConditionalType:
return serializeTypeList([(<ConditionalTypeNode>node).trueType, (<ConditionalTypeNode>node).falseType]);
return serializeTypeList([(node as ConditionalTypeNode).trueType, (node as ConditionalTypeNode).falseType]);
case SyntaxKind.TypeOperator:
if ((<TypeOperatorNode>node).operator === SyntaxKind.ReadonlyKeyword) {
return serializeTypeNode((<TypeOperatorNode>node).type);
if ((node as TypeOperatorNode).operator === SyntaxKind.ReadonlyKeyword) {
return serializeTypeNode((node as TypeOperatorNode).type);
}
break;
@@ -1600,7 +1600,7 @@ namespace ts {
case SyntaxKind.JSDocNullableType:
case SyntaxKind.JSDocNonNullableType:
case SyntaxKind.JSDocOptionalType:
return serializeTypeNode((<JSDocNullableType | JSDocNonNullableType | JSDocOptionalType>node).type);
return serializeTypeNode((node as JSDocNullableType | JSDocNonNullableType | JSDocOptionalType).type);
default:
return Debug.failBadSyntaxKind(node);
}
@@ -2734,12 +2734,12 @@ namespace ts {
let blockLocation: TextRange | undefined;
if (node.body) {
if (node.body.kind === SyntaxKind.ModuleBlock) {
saveStateAndInvoke(node.body, body => addRange(statements, visitNodes((<ModuleBlock>body).statements, namespaceElementVisitor, isStatement)));
saveStateAndInvoke(node.body, body => addRange(statements, visitNodes((body as ModuleBlock).statements, namespaceElementVisitor, isStatement)));
statementsLocation = node.body.statements;
blockLocation = node.body;
}
else {
const result = visitModuleDeclaration(<ModuleDeclaration>node.body);
const result = visitModuleDeclaration(node.body as ModuleDeclaration);
if (result) {
if (isArray(result)) {
addRange(statements, result);
@@ -2749,7 +2749,7 @@ namespace ts {
}
}
const moduleBlock = <ModuleBlock>getInnerMostModuleDeclarationFromDottedModule(node)!.body;
const moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node)!.body as ModuleBlock;
statementsLocation = moveRangePos(moduleBlock.statements, -1);
}
}
@@ -2796,8 +2796,8 @@ namespace ts {
function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration: ModuleDeclaration): ModuleDeclaration | undefined {
if (moduleDeclaration.body!.kind === SyntaxKind.ModuleDeclaration) {
const recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(<ModuleDeclaration>moduleDeclaration.body);
return recursiveInnerModule || <ModuleDeclaration>moduleDeclaration.body;
const recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body as ModuleDeclaration);
return recursiveInnerModule || moduleDeclaration.body as ModuleDeclaration;
}
}
@@ -3002,7 +3002,7 @@ namespace ts {
return undefined;
}
const moduleReference = createExpressionFromEntityName(factory, <EntityName>node.moduleReference);
const moduleReference = createExpressionFromEntityName(factory, node.moduleReference as EntityName);
setEmitFlags(moduleReference, EmitFlags.NoComments | EmitFlags.NoNestedComments);
if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
@@ -3241,7 +3241,7 @@ namespace ts {
function onSubstituteNode(hint: EmitHint, node: Node) {
node = previousOnSubstituteNode(hint, node);
if (hint === EmitHint.Expression) {
return substituteExpression(<Expression>node);
return substituteExpression(node as Expression);
}
else if (isShorthandPropertyAssignment(node)) {
return substituteShorthandPropertyAssignment(node);
@@ -3270,11 +3270,11 @@ namespace ts {
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.Identifier:
return substituteExpressionIdentifier(<Identifier>node);
return substituteExpressionIdentifier(node as Identifier);
case SyntaxKind.PropertyAccessExpression:
return substitutePropertyAccessExpression(<PropertyAccessExpression>node);
return substitutePropertyAccessExpression(node as PropertyAccessExpression);
case SyntaxKind.ElementAccessExpression:
return substituteElementAccessExpression(<ElementAccessExpression>node);
return substituteElementAccessExpression(node as ElementAccessExpression);
}
return node;
+17 -17
View File
@@ -84,34 +84,34 @@ namespace ts {
// import x from "mod"
// import * as x from "mod"
// import { x, y } from "mod"
externalImports.push(<ImportDeclaration>node);
if (!hasImportStar && getImportNeedsImportStarHelper(<ImportDeclaration>node)) {
externalImports.push(node as ImportDeclaration);
if (!hasImportStar && getImportNeedsImportStarHelper(node as ImportDeclaration)) {
hasImportStar = true;
}
if (!hasImportDefault && getImportNeedsImportDefaultHelper(<ImportDeclaration>node)) {
if (!hasImportDefault && getImportNeedsImportDefaultHelper(node as ImportDeclaration)) {
hasImportDefault = true;
}
break;
case SyntaxKind.ImportEqualsDeclaration:
if ((<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference) {
if ((node as ImportEqualsDeclaration).moduleReference.kind === SyntaxKind.ExternalModuleReference) {
// import x = require("mod")
externalImports.push(<ImportEqualsDeclaration>node);
externalImports.push(node as ImportEqualsDeclaration);
}
break;
case SyntaxKind.ExportDeclaration:
if ((<ExportDeclaration>node).moduleSpecifier) {
if (!(<ExportDeclaration>node).exportClause) {
if ((node as ExportDeclaration).moduleSpecifier) {
if (!(node as ExportDeclaration).exportClause) {
// export * from "mod"
externalImports.push(<ExportDeclaration>node);
externalImports.push(node as ExportDeclaration);
hasExportStarsToExportValues = true;
}
else {
// export * as ns from "mod"
// export { x, y } from "mod"
externalImports.push(<ExportDeclaration>node);
externalImports.push(node as ExportDeclaration);
if (isNamedExports((node as ExportDeclaration).exportClause!)) {
addExportedNamesForExportDeclaration(node as ExportDeclaration);
}
@@ -134,15 +134,15 @@ namespace ts {
break;
case SyntaxKind.ExportAssignment:
if ((<ExportAssignment>node).isExportEquals && !exportEquals) {
if ((node as ExportAssignment).isExportEquals && !exportEquals) {
// export = x
exportEquals = <ExportAssignment>node;
exportEquals = node as ExportAssignment;
}
break;
case SyntaxKind.VariableStatement:
if (hasSyntacticModifier(node, ModifierFlags.Export)) {
for (const decl of (<VariableStatement>node).declarationList.declarations) {
for (const decl of (node as VariableStatement).declarationList.declarations) {
exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
}
}
@@ -153,13 +153,13 @@ namespace ts {
if (hasSyntacticModifier(node, ModifierFlags.Default)) {
// export default function() { }
if (!hasExportDefault) {
multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(<FunctionDeclaration>node));
multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node as FunctionDeclaration));
hasExportDefault = true;
}
}
else {
// export function x() { }
const name = (<FunctionDeclaration>node).name!;
const name = (node as FunctionDeclaration).name!;
if (!uniqueExports.get(idText(name))) {
multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
uniqueExports.set(idText(name), true);
@@ -174,13 +174,13 @@ namespace ts {
if (hasSyntacticModifier(node, ModifierFlags.Default)) {
// export default class { }
if (!hasExportDefault) {
multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(<ClassDeclaration>node));
multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node as ClassDeclaration));
hasExportDefault = true;
}
}
else {
// export class x { }
const name = (<ClassDeclaration>node).name;
const name = (node as ClassDeclaration).name;
if (name && !uniqueExports.get(idText(name))) {
multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
uniqueExports.set(idText(name), true);
@@ -362,7 +362,7 @@ namespace ts {
*/
export function isInitializedProperty(member: ClassElement): member is PropertyDeclaration & { initializer: Expression; } {
return member.kind === SyntaxKind.PropertyDeclaration
&& (<PropertyDeclaration>member).initializer !== undefined;
&& (member as PropertyDeclaration).initializer !== undefined;
}
/**
+104 -59
View File
@@ -88,6 +88,8 @@ namespace ts {
QuestionQuestionToken,
/** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
BacktickToken,
/** Only the JSDoc scanner produces HashToken. The normal scanner produces PrivateIdentifier. */
HashToken,
// Assignments
EqualsToken,
PlusEqualsToken,
@@ -362,6 +364,7 @@ namespace ts {
// JSDoc nodes
JSDocTypeExpression,
JSDocNameReference,
JSDocMemberName, // C#p
JSDocAllType, // The * type
JSDocUnknownType, // The ? type
JSDocNullableType,
@@ -375,6 +378,8 @@ namespace ts {
JSDocTypeLiteral,
JSDocSignature,
JSDocLink,
JSDocLinkCode,
JSDocLinkPlain,
JSDocTag,
JSDocAugmentsTag,
JSDocImplementsTag,
@@ -517,6 +522,7 @@ namespace ts {
| SyntaxKind.ColonToken
| SyntaxKind.AtToken
| SyntaxKind.BacktickToken
| SyntaxKind.HashToken
| SyntaxKind.EqualsToken
| SyntaxKind.PlusEqualsToken
| SyntaxKind.MinusEqualsToken
@@ -722,6 +728,7 @@ namespace ts {
| SyntaxKind.DotToken
| SyntaxKind.Identifier
| SyntaxKind.BacktickToken
| SyntaxKind.HashToken
| SyntaxKind.Unknown
| KeywordSyntaxKind
;
@@ -3123,7 +3130,14 @@ namespace ts {
export interface JSDocNameReference extends Node {
readonly kind: SyntaxKind.JSDocNameReference;
readonly name: EntityName;
readonly name: EntityName | JSDocMemberName;
}
/** Class#method reference in JSDoc */
export interface JSDocMemberName extends Node {
readonly kind: SyntaxKind.JSDocMemberName;
readonly left: EntityName | JSDocMemberName;
readonly right: Identifier;
}
export interface JSDocType extends TypeNode {
@@ -3178,21 +3192,35 @@ namespace ts {
readonly kind: SyntaxKind.JSDocComment;
readonly parent: HasJSDoc;
readonly tags?: NodeArray<JSDocTag>;
readonly comment?: string | NodeArray<JSDocText | JSDocLink>;
readonly comment?: string | NodeArray<JSDocComment>;
}
export interface JSDocTag extends Node {
readonly parent: JSDoc | JSDocTypeLiteral;
readonly tagName: Identifier;
readonly comment?: string | NodeArray<JSDocText | JSDocLink>;
readonly comment?: string | NodeArray<JSDocComment>;
}
export interface JSDocLink extends Node {
readonly kind: SyntaxKind.JSDocLink;
readonly name?: EntityName;
readonly name?: EntityName | JSDocMemberName;
text: string;
}
export interface JSDocLinkCode extends Node {
readonly kind: SyntaxKind.JSDocLinkCode;
readonly name?: EntityName | JSDocMemberName;
text: string;
}
export interface JSDocLinkPlain extends Node {
readonly kind: SyntaxKind.JSDocLinkPlain;
readonly name?: EntityName | JSDocMemberName;
text: string;
}
export type JSDocComment = JSDocText | JSDocLink | JSDocLinkCode | JSDocLinkPlain;
export interface JSDocText extends Node {
readonly kind: SyntaxKind.JSDocText;
text: string;
@@ -4214,7 +4242,7 @@ namespace ts {
/* @internal */ isTypeAssignableTo(source: Type, target: Type): boolean;
/* @internal */ createAnonymousType(symbol: Symbol | undefined, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): Type;
/* @internal */ createSignature(
declaration: SignatureDeclaration,
declaration: SignatureDeclaration | undefined,
typeParameters: readonly TypeParameter[] | undefined,
thisParameter: Symbol | undefined,
parameters: readonly Symbol[],
@@ -5491,17 +5519,28 @@ namespace ts {
resolvedDefaultType?: Type;
}
/* @internal */
export const enum AccessFlags {
None = 0,
IncludeUndefined = 1 << 0,
NoIndexSignatures = 1 << 1,
Writing = 1 << 2,
CacheSymbol = 1 << 3,
NoTupleBoundsCheck = 1 << 4,
ExpressionPosition = 1 << 5,
ReportDeprecated = 1 << 6,
SuppressNoImplicitAnyError = 1 << 7,
Contextual = 1 << 8,
Persistent = IncludeUndefined,
}
// Indexed access types (TypeFlags.IndexedAccess)
// Possible forms are T[xxx], xxx[T], or xxx[keyof T], where T is a type variable
export interface IndexedAccessType extends InstantiableType {
objectType: Type;
indexType: Type;
/**
* @internal
* Indicates that --noUncheckedIndexedAccess may introduce 'undefined' into
* the resulting type, depending on how type variable constraints are resolved.
*/
noUncheckedIndexedAccessCandidate: boolean;
/* @internal */
accessFlags: AccessFlags; // Only includes AccessFlags.Persistent
constraint?: Type;
simplifiedForReading?: Type;
simplifiedForWriting?: Type;
@@ -7268,60 +7307,66 @@ namespace ts {
updateJSDocNamepathType(node: JSDocNamepathType, type: TypeNode): JSDocNamepathType;
createJSDocTypeExpression(type: TypeNode): JSDocTypeExpression;
updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression;
createJSDocNameReference(name: EntityName): JSDocNameReference;
updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference;
createJSDocLink(name: EntityName | undefined, text: string): JSDocLink;
updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink;
createJSDocNameReference(name: EntityName | JSDocMemberName): JSDocNameReference;
updateJSDocNameReference(node: JSDocNameReference, name: EntityName | JSDocMemberName): JSDocNameReference;
createJSDocMemberName(left: EntityName | JSDocMemberName, right: Identifier): JSDocMemberName;
updateJSDocMemberName(node: JSDocMemberName, left: EntityName | JSDocMemberName, right: Identifier): JSDocMemberName;
createJSDocLink(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink;
updateJSDocLink(node: JSDocLink, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink;
createJSDocLinkCode(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode;
updateJSDocLinkCode(node: JSDocLinkCode, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode;
createJSDocLinkPlain(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain;
updateJSDocLinkPlain(node: JSDocLinkPlain, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain;
createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral;
updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean | undefined): JSDocTypeLiteral;
createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature;
updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature;
createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocTemplateTag;
updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocTemplateTag;
createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocTypedefTag;
updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocTypedefTag;
createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocParameterTag;
updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocParameterTag;
createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocPropertyTag;
updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocPropertyTag;
createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocTypeTag;
updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocTypeTag;
createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocSeeTag;
updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocSeeTag;
createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocReturnTag;
updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocReturnTag;
createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocThisTag;
updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocThisTag;
createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocEnumTag;
updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocEnumTag;
createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocCallbackTag;
updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocCallbackTag;
createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocAugmentsTag;
updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocAugmentsTag;
createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocImplementsTag;
updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocImplementsTag;
createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocAuthorTag;
updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocAuthorTag;
createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocClassTag;
updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocClassTag;
createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocPublicTag;
updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocPublicTag;
createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocPrivateTag;
updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocPrivateTag;
createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocProtectedTag;
updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocProtectedTag;
createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocReadonlyTag;
updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocReadonlyTag;
createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocUnknownTag;
updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocUnknownTag;
createJSDocDeprecatedTag(tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocDeprecatedTag;
updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocDeprecatedTag;
createJSDocOverrideTag(tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocOverrideTag;
updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocOverrideTag;
createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray<JSDocComment>): JSDocTemplateTag;
updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray<JSDocComment> | undefined): JSDocTemplateTag;
createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray<JSDocComment>): JSDocTypedefTag;
updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocTypedefTag;
createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray<JSDocComment>): JSDocParameterTag;
updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray<JSDocComment> | undefined): JSDocParameterTag;
createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray<JSDocComment>): JSDocPropertyTag;
updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray<JSDocComment> | undefined): JSDocPropertyTag;
createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray<JSDocComment>): JSDocTypeTag;
updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray<JSDocComment> | undefined): JSDocTypeTag;
createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray<JSDocComment>): JSDocSeeTag;
updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray<JSDocComment>): JSDocSeeTag;
createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray<JSDocComment>): JSDocReturnTag;
updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocReturnTag;
createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray<JSDocComment>): JSDocThisTag;
updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocThisTag;
createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray<JSDocComment>): JSDocEnumTag;
updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray<JSDocComment> | undefined): JSDocEnumTag;
createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray<JSDocComment>): JSDocCallbackTag;
updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocCallbackTag;
createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray<JSDocComment>): JSDocAugmentsTag;
updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray<JSDocComment> | undefined): JSDocAugmentsTag;
createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray<JSDocComment>): JSDocImplementsTag;
updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray<JSDocComment> | undefined): JSDocImplementsTag;
createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocComment>): JSDocAuthorTag;
updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocAuthorTag;
createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocComment>): JSDocClassTag;
updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocClassTag;
createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocComment>): JSDocPublicTag;
updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocPublicTag;
createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocComment>): JSDocPrivateTag;
updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocPrivateTag;
createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocComment>): JSDocProtectedTag;
updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocProtectedTag;
createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocComment>): JSDocReadonlyTag;
updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocComment> | undefined): JSDocReadonlyTag;
createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray<JSDocComment>): JSDocUnknownTag;
updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray<JSDocComment> | undefined): JSDocUnknownTag;
createJSDocDeprecatedTag(tagName: Identifier, comment?: string | NodeArray<JSDocComment>): JSDocDeprecatedTag;
updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string | NodeArray<JSDocComment>): JSDocDeprecatedTag;
createJSDocOverrideTag(tagName: Identifier, comment?: string | NodeArray<JSDocComment>): JSDocOverrideTag;
updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier, comment?: string | NodeArray<JSDocComment>): JSDocOverrideTag;
createJSDocText(text: string): JSDocText;
updateJSDocText(node: JSDocText, text: string): JSDocText;
createJSDocComment(comment?: string | NodeArray<JSDocText | JSDocLink> | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc;
updateJSDocComment(node: JSDoc, comment: string | NodeArray<JSDocText | JSDocLink> | undefined, tags: readonly JSDocTag[] | undefined): JSDoc;
createJSDocComment(comment?: string | NodeArray<JSDocComment> | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc;
updateJSDocComment(node: JSDoc, comment: string | NodeArray<JSDocComment> | undefined, tags: readonly JSDocTag[] | undefined): JSDoc;
//
// JSX
+113 -107
View File
@@ -263,7 +263,7 @@ namespace ts {
while (node && node.kind !== SyntaxKind.SourceFile) {
node = node.parent;
}
return <SourceFile>node;
return node as SourceFile;
}
export function isStatementWithLocals(node: Node) {
@@ -476,8 +476,8 @@ namespace ts {
// the syntax list itself considers them as normal trivia. Therefore if we simply skip
// trivia for the list, we may have skipped the JSDocComment as well. So we should process its
// first child to determine the actual position of its first token.
if (node.kind === SyntaxKind.SyntaxList && (<SyntaxList>node)._children.length > 0) {
return getTokenPosOfNode((<SyntaxList>node)._children[0], sourceFile, includeJsDoc);
if (node.kind === SyntaxKind.SyntaxList && (node as SyntaxList)._children.length > 0) {
return getTokenPosOfNode((node as SyntaxList)._children[0], sourceFile, includeJsDoc);
}
return skipTrivia(
@@ -642,7 +642,7 @@ namespace ts {
const escapeText = flags & GetLiteralTextFlags.JsxAttributeEscape ? escapeJsxAttributeString :
flags & GetLiteralTextFlags.NeverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? escapeString :
escapeNonAsciiString;
if ((<StringLiteral>node).singleQuote) {
if ((node as StringLiteral).singleQuote) {
return "'" + escapeText(node.text, CharacterCodes.singleQuote) + "'";
}
else {
@@ -658,7 +658,7 @@ namespace ts {
const escapeText = flags & GetLiteralTextFlags.NeverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? escapeString :
escapeNonAsciiString;
const rawText = (<TemplateLiteralLikeNode>node).rawText || escapeTemplateSubstitution(escapeText(node.text, CharacterCodes.backtick));
const rawText = (node as TemplateLiteralLikeNode).rawText || escapeTemplateSubstitution(escapeText(node.text, CharacterCodes.backtick));
switch (node.kind) {
case SyntaxKind.NoSubstitutionTemplateLiteral:
return "`" + rawText + "`";
@@ -745,7 +745,7 @@ namespace ts {
function isShorthandAmbientModule(node: Node | undefined): boolean {
// The only kind of module that can be missing a body is a shorthand ambient module.
return !!node && node.kind === SyntaxKind.ModuleDeclaration && (!(<ModuleDeclaration>node).body);
return !!node && node.kind === SyntaxKind.ModuleDeclaration && (!(node as ModuleDeclaration).body);
}
export function isBlockScopedContainerTopLevel(node: Node): boolean {
@@ -962,7 +962,7 @@ namespace ts {
}
}
export function entityNameToString(name: EntityNameOrEntityNameExpression | JsxTagNameExpression | PrivateIdentifier): string {
export function entityNameToString(name: EntityNameOrEntityNameExpression | JSDocMemberName | JsxTagNameExpression | PrivateIdentifier): string {
switch (name.kind) {
case SyntaxKind.ThisKeyword:
return "this";
@@ -978,6 +978,8 @@ namespace ts {
else {
return Debug.assertNever(name.name);
}
case SyntaxKind.JSDocMemberName:
return entityNameToString(name.left) + entityNameToString(name.right);
default:
return Debug.assertNever(name);
}
@@ -1099,14 +1101,14 @@ namespace ts {
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
errorNode = (<NamedDeclaration>node).name;
errorNode = (node as NamedDeclaration).name;
break;
case SyntaxKind.ArrowFunction:
return getErrorSpanForArrowFunction(sourceFile, <ArrowFunction>node);
return getErrorSpanForArrowFunction(sourceFile, node as ArrowFunction);
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
const start = skipTrivia(sourceFile.text, (<CaseOrDefaultClause>node).pos);
const end = (<CaseOrDefaultClause>node).statements.length > 0 ? (<CaseOrDefaultClause>node).statements[0].pos : (<CaseOrDefaultClause>node).end;
const start = skipTrivia(sourceFile.text, (node as CaseOrDefaultClause).pos);
const end = (node as CaseOrDefaultClause).statements.length > 0 ? (node as CaseOrDefaultClause).statements[0].pos : (node as CaseOrDefaultClause).end;
return createTextSpanFromBounds(start, end);
}
@@ -1162,11 +1164,11 @@ namespace ts {
}
export function isSuperCall(n: Node): n is SuperCall {
return n.kind === SyntaxKind.CallExpression && (<CallExpression>n).expression.kind === SyntaxKind.SuperKeyword;
return n.kind === SyntaxKind.CallExpression && (n as CallExpression).expression.kind === SyntaxKind.SuperKeyword;
}
export function isImportCall(n: Node): n is ImportCall {
return n.kind === SyntaxKind.CallExpression && (<CallExpression>n).expression.kind === SyntaxKind.ImportKeyword;
return n.kind === SyntaxKind.CallExpression && (n as CallExpression).expression.kind === SyntaxKind.ImportKeyword;
}
export function isImportMeta(n: Node): n is ImportMetaProperty {
@@ -1181,7 +1183,7 @@ namespace ts {
export function isPrologueDirective(node: Node): node is PrologueDirective {
return node.kind === SyntaxKind.ExpressionStatement
&& (<ExpressionStatement>node).expression.kind === SyntaxKind.StringLiteral;
&& (node as ExpressionStatement).expression.kind === SyntaxKind.StringLiteral;
}
export function isCustomPrologue(node: Statement) {
@@ -1257,10 +1259,10 @@ namespace ts {
// above them to find the lowest container
case SyntaxKind.Identifier:
// If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
if (node.parent.kind === SyntaxKind.QualifiedName && (<QualifiedName>node.parent).right === node) {
if (node.parent.kind === SyntaxKind.QualifiedName && (node.parent as QualifiedName).right === node) {
node = node.parent;
}
else if (node.parent.kind === SyntaxKind.PropertyAccessExpression && (<PropertyAccessExpression>node.parent).name === node) {
else if (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent as PropertyAccessExpression).name === node) {
node = node.parent;
}
// At this point, node is either a qualified name or an identifier
@@ -1291,9 +1293,9 @@ namespace ts {
case SyntaxKind.ExpressionWithTypeArguments:
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case SyntaxKind.TypeParameter:
return node === (<TypeParameterDeclaration>parent).constraint;
return node === (parent as TypeParameterDeclaration).constraint;
case SyntaxKind.JSDocTemplateTag:
return node === (<JSDocTemplateTag>parent).constraint;
return node === (parent as JSDocTemplateTag).constraint;
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
case SyntaxKind.Parameter:
@@ -1307,16 +1309,16 @@ namespace ts {
case SyntaxKind.MethodSignature:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return node === (<FunctionLikeDeclaration>parent).type;
return node === (parent as FunctionLikeDeclaration).type;
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
return node === (<SignatureDeclaration>parent).type;
return node === (parent as SignatureDeclaration).type;
case SyntaxKind.TypeAssertionExpression:
return node === (<TypeAssertion>parent).type;
return node === (parent as TypeAssertion).type;
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
return contains((<CallExpression>parent).typeArguments, node);
return contains((parent as CallExpression).typeArguments, node);
case SyntaxKind.TaggedTemplateExpression:
// TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
return false;
@@ -1346,7 +1348,7 @@ namespace ts {
function traverse(node: Node): T | undefined {
switch (node.kind) {
case SyntaxKind.ReturnStatement:
return visitor(<ReturnStatement>node);
return visitor(node as ReturnStatement);
case SyntaxKind.CaseBlock:
case SyntaxKind.Block:
case SyntaxKind.IfStatement:
@@ -1374,8 +1376,8 @@ namespace ts {
function traverse(node: Node): void {
switch (node.kind) {
case SyntaxKind.YieldExpression:
visitor(<YieldExpression>node);
const operand = (<YieldExpression>node).expression;
visitor(node as YieldExpression);
const operand = (node as YieldExpression).expression;
if (operand) {
traverse(operand);
}
@@ -1413,10 +1415,10 @@ namespace ts {
*/
export function getRestParameterElementType(node: TypeNode | undefined) {
if (node && node.kind === SyntaxKind.ArrayType) {
return (<ArrayTypeNode>node).elementType;
return (node as ArrayTypeNode).elementType;
}
else if (node && node.kind === SyntaxKind.TypeReference) {
return singleOrUndefined((<TypeReferenceNode>node).typeArguments);
return singleOrUndefined((node as TypeReferenceNode).typeArguments);
}
else {
return undefined;
@@ -1429,9 +1431,9 @@ namespace ts {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.TypeLiteral:
return (<ObjectTypeDeclaration>node).members;
return (node as ObjectTypeDeclaration).members;
case SyntaxKind.ObjectLiteralExpression:
return (<ObjectLiteralExpression>node).properties;
return (node as ObjectLiteralExpression).properties;
}
}
@@ -1489,7 +1491,7 @@ namespace ts {
if (node.statement.kind !== SyntaxKind.LabeledStatement) {
return node.statement;
}
node = <LabeledStatement>node.statement;
node = node.statement as LabeledStatement;
}
}
@@ -1724,7 +1726,7 @@ namespace ts {
export function isSuperProperty(node: Node): node is SuperProperty {
const kind = node.kind;
return (kind === SyntaxKind.PropertyAccessExpression || kind === SyntaxKind.ElementAccessExpression)
&& (<PropertyAccessExpression | ElementAccessExpression>node).expression.kind === SyntaxKind.SuperKeyword;
&& (node as PropertyAccessExpression | ElementAccessExpression).expression.kind === SyntaxKind.SuperKeyword;
}
/**
@@ -1733,7 +1735,7 @@ namespace ts {
export function isThisProperty(node: Node): boolean {
const kind = node.kind;
return (kind === SyntaxKind.PropertyAccessExpression || kind === SyntaxKind.ElementAccessExpression)
&& (<PropertyAccessExpression | ElementAccessExpression>node).expression.kind === SyntaxKind.ThisKeyword;
&& (node as PropertyAccessExpression | ElementAccessExpression).expression.kind === SyntaxKind.ThisKeyword;
}
export function isThisInitializedDeclaration(node: Node | undefined): boolean {
@@ -1751,17 +1753,17 @@ namespace ts {
export function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression | undefined {
switch (node.kind) {
case SyntaxKind.TypeReference:
return (<TypeReferenceNode>node).typeName;
return (node as TypeReferenceNode).typeName;
case SyntaxKind.ExpressionWithTypeArguments:
return isEntityNameExpression((<ExpressionWithTypeArguments>node).expression)
? <EntityNameExpression>(<ExpressionWithTypeArguments>node).expression
return isEntityNameExpression((node as ExpressionWithTypeArguments).expression)
? (node as ExpressionWithTypeArguments).expression as EntityNameExpression
: undefined;
// TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s.
case SyntaxKind.Identifier as TypeNodeSyntaxKind:
case SyntaxKind.QualifiedName as TypeNodeSyntaxKind:
return (<EntityName><Node>node);
return (node as Node as EntityName);
}
return undefined;
@@ -1800,12 +1802,12 @@ namespace ts {
case SyntaxKind.SetAccessor:
case SyntaxKind.MethodDeclaration:
// if this method has a body and its parent is a class declaration, this is a valid target.
return (<FunctionLikeDeclaration>node).body !== undefined
return (node as FunctionLikeDeclaration).body !== undefined
&& parent!.kind === SyntaxKind.ClassDeclaration;
case SyntaxKind.Parameter:
// if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
return (<FunctionLikeDeclaration>parent).body !== undefined
return (parent as FunctionLikeDeclaration).body !== undefined
&& (parent!.kind === SyntaxKind.Constructor
|| parent!.kind === SyntaxKind.MethodDeclaration
|| parent!.kind === SyntaxKind.SetAccessor)
@@ -1835,10 +1837,10 @@ namespace ts {
export function childIsDecorated(node: Node, parent?: Node): boolean {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
return some((<ClassDeclaration>node).members, m => nodeOrChildIsDecorated(m, node, parent!)); // TODO: GH#18217
return some((node as ClassDeclaration).members, m => nodeOrChildIsDecorated(m, node, parent!)); // TODO: GH#18217
case SyntaxKind.MethodDeclaration:
case SyntaxKind.SetAccessor:
return some((<FunctionLikeDeclaration>node).parameters, p => nodeIsDecorated(p, node, parent!)); // TODO: GH#18217
return some((node as FunctionLikeDeclaration).parameters, p => nodeIsDecorated(p, node, parent!)); // TODO: GH#18217
default:
return false;
}
@@ -1849,7 +1851,7 @@ namespace ts {
if (parent.kind === SyntaxKind.JsxOpeningElement ||
parent.kind === SyntaxKind.JsxSelfClosingElement ||
parent.kind === SyntaxKind.JsxClosingElement) {
return (<JsxOpeningLikeElement>parent).tagName === node;
return (parent as JsxOpeningLikeElement).tagName === node;
}
return false;
}
@@ -1896,9 +1898,14 @@ namespace ts {
while (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
}
return node.parent.kind === SyntaxKind.TypeQuery || isJSXTagName(node);
return node.parent.kind === SyntaxKind.TypeQuery || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node);
case SyntaxKind.JSDocMemberName:
while (isJSDocMemberName(node.parent)) {
node = node.parent;
}
return node.parent.kind === SyntaxKind.TypeQuery || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node);
case SyntaxKind.Identifier:
if (node.parent.kind === SyntaxKind.TypeQuery || isJSXTagName(node)) {
if (node.parent.kind === SyntaxKind.TypeQuery || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node)) {
return true;
}
// falls through
@@ -1934,33 +1941,33 @@ namespace ts {
case SyntaxKind.SwitchStatement:
case SyntaxKind.CaseClause:
case SyntaxKind.ThrowStatement:
return (<ExpressionStatement>parent).expression === node;
return (parent as ExpressionStatement).expression === node;
case SyntaxKind.ForStatement:
const forStatement = <ForStatement>parent;
const forStatement = parent as ForStatement;
return (forStatement.initializer === node && forStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) ||
forStatement.condition === node ||
forStatement.incrementor === node;
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
const forInStatement = <ForInStatement | ForOfStatement>parent;
const forInStatement = parent as ForInStatement | ForOfStatement;
return (forInStatement.initializer === node && forInStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) ||
forInStatement.expression === node;
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.AsExpression:
return node === (<AssertionExpression>parent).expression;
return node === (parent as AssertionExpression).expression;
case SyntaxKind.TemplateSpan:
return node === (<TemplateSpan>parent).expression;
return node === (parent as TemplateSpan).expression;
case SyntaxKind.ComputedPropertyName:
return node === (<ComputedPropertyName>parent).expression;
return node === (parent as ComputedPropertyName).expression;
case SyntaxKind.Decorator:
case SyntaxKind.JsxExpression:
case SyntaxKind.JsxSpreadAttribute:
case SyntaxKind.SpreadAssignment:
return true;
case SyntaxKind.ExpressionWithTypeArguments:
return (<ExpressionWithTypeArguments>parent).expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
return (parent as ExpressionWithTypeArguments).expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case SyntaxKind.ShorthandPropertyAssignment:
return (<ShorthandPropertyAssignment>parent).objectAssignmentInitializer === node;
return (parent as ShorthandPropertyAssignment).objectAssignmentInitializer === node;
default:
return isExpressionNode(parent);
}
@@ -1978,12 +1985,12 @@ namespace ts {
}
export function isExternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration & { moduleReference: ExternalModuleReference } {
return node.kind === SyntaxKind.ImportEqualsDeclaration && (<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference;
return node.kind === SyntaxKind.ImportEqualsDeclaration && (node as ImportEqualsDeclaration).moduleReference.kind === SyntaxKind.ExternalModuleReference;
}
export function getExternalModuleImportEqualsDeclarationExpression(node: Node) {
Debug.assert(isExternalModuleImportEqualsDeclaration(node));
return (<ExternalModuleReference>(<ImportEqualsDeclaration>node).moduleReference).expression;
return ((node as ImportEqualsDeclaration).moduleReference as ExternalModuleReference).expression;
}
export function getExternalModuleRequireArgument(node: Node) {
@@ -1991,7 +1998,7 @@ namespace ts {
}
export function isInternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration {
return node.kind === SyntaxKind.ImportEqualsDeclaration && (<ImportEqualsDeclaration>node).moduleReference.kind !== SyntaxKind.ExternalModuleReference;
return node.kind === SyntaxKind.ImportEqualsDeclaration && (node as ImportEqualsDeclaration).moduleReference.kind !== SyntaxKind.ExternalModuleReference;
}
export function isSourceFileJS(file: SourceFile): boolean {
@@ -2515,7 +2522,7 @@ namespace ts {
case SyntaxKind.PropertyAssignment:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
return (<ParameterDeclaration | MethodDeclaration | PropertyDeclaration>node).questionToken !== undefined;
return (node as ParameterDeclaration | MethodDeclaration | PropertyDeclaration).questionToken !== undefined;
}
}
@@ -2714,17 +2721,17 @@ namespace ts {
while (true) {
switch (parent.kind) {
case SyntaxKind.BinaryExpression:
const binaryOperator = (<BinaryExpression>parent).operatorToken.kind;
return isAssignmentOperator(binaryOperator) && (<BinaryExpression>parent).left === node ?
const binaryOperator = (parent as BinaryExpression).operatorToken.kind;
return isAssignmentOperator(binaryOperator) && (parent as BinaryExpression).left === node ?
binaryOperator === SyntaxKind.EqualsToken || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? AssignmentKind.Definite : AssignmentKind.Compound :
AssignmentKind.None;
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
const unaryOperator = (<PrefixUnaryExpression | PostfixUnaryExpression>parent).operator;
const unaryOperator = (parent as PrefixUnaryExpression | PostfixUnaryExpression).operator;
return unaryOperator === SyntaxKind.PlusPlusToken || unaryOperator === SyntaxKind.MinusMinusToken ? AssignmentKind.Compound : AssignmentKind.None;
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
return (<ForInOrOfStatement>parent).initializer === node ? AssignmentKind.Definite : AssignmentKind.None;
return (parent as ForInOrOfStatement).initializer === node ? AssignmentKind.Definite : AssignmentKind.None;
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.SpreadElement:
@@ -2841,7 +2848,7 @@ namespace ts {
export function walkUpParenthesizedTypesAndGetParentAndChild(node: Node): [ParenthesizedTypeNode | undefined, Node] {
let child: ParenthesizedTypeNode | undefined;
while (node && node.kind === SyntaxKind.ParenthesizedType) {
child = <ParenthesizedTypeNode>node;
child = node as ParenthesizedTypeNode;
node = node.parent;
}
return [child, node];
@@ -2853,13 +2860,6 @@ namespace ts {
return skipOuterExpressions(node, OuterExpressionKinds.Parentheses);
}
function skipParenthesesUp(node: Node): Node {
while (node.kind === SyntaxKind.ParenthesizedExpression) {
node = node.parent;
}
return node;
}
// a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
export function isDeleteTarget(node: Node): boolean {
if (node.kind !== SyntaxKind.PropertyAccessExpression && node.kind !== SyntaxKind.ElementAccessExpression) {
@@ -2935,14 +2935,14 @@ namespace ts {
case SyntaxKind.PropertyAssignment:
case SyntaxKind.PropertyAccessExpression:
// Name in member declaration or property name in property access
return (<NamedDeclaration | PropertyAccessExpression>parent).name === node;
return (parent as NamedDeclaration | PropertyAccessExpression).name === node;
case SyntaxKind.QualifiedName:
// Name on right hand side of dot in a type query or type reference
return (<QualifiedName>parent).right === node;
return (parent as QualifiedName).right === node;
case SyntaxKind.BindingElement:
case SyntaxKind.ImportSpecifier:
// Property name in binding element or import specifier
return (<BindingElement | ImportSpecifier>parent).propertyName === node;
return (parent as BindingElement | ImportSpecifier).propertyName === node;
case SyntaxKind.ExportSpecifier:
case SyntaxKind.JsxAttribute:
// Any name in an export specifier or JSX Attribute
@@ -2966,12 +2966,12 @@ namespace ts {
export function isAliasSymbolDeclaration(node: Node): boolean {
return node.kind === SyntaxKind.ImportEqualsDeclaration ||
node.kind === SyntaxKind.NamespaceExportDeclaration ||
node.kind === SyntaxKind.ImportClause && !!(<ImportClause>node).name ||
node.kind === SyntaxKind.ImportClause && !!(node as ImportClause).name ||
node.kind === SyntaxKind.NamespaceImport ||
node.kind === SyntaxKind.NamespaceExport ||
node.kind === SyntaxKind.ImportSpecifier ||
node.kind === SyntaxKind.ExportSpecifier ||
node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(<ExportAssignment>node) ||
node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node as ExportAssignment) ||
isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports && exportAssignmentIsAlias(node) ||
isPropertyAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === SyntaxKind.EqualsToken && isAliasableExpression(node.parent.right) ||
node.kind === SyntaxKind.ShorthandPropertyAssignment ||
@@ -3151,8 +3151,8 @@ namespace ts {
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.MethodDeclaration:
return (<FunctionLikeDeclaration>node).body !== undefined
&& (<FunctionLikeDeclaration>node).asteriskToken === undefined
return (node as FunctionLikeDeclaration).body !== undefined
&& (node as FunctionLikeDeclaration).asteriskToken === undefined
&& hasSyntacticModifier(node, ModifierFlags.Async);
}
return false;
@@ -3248,7 +3248,7 @@ namespace ts {
* Includes the word "Symbol" with unicode escapes
*/
export function isESSymbolIdentifier(node: Node): boolean {
return node.kind === SyntaxKind.Identifier && (<Identifier>node).escapedText === "Symbol";
return node.kind === SyntaxKind.Identifier && (node as Identifier).escapedText === "Symbol";
}
export function isPushOrUnshiftIdentifier(node: Identifier) {
@@ -3296,7 +3296,7 @@ namespace ts {
export function getExpressionAssociativity(expression: Expression) {
const operator = getOperator(expression);
const hasArguments = expression.kind === SyntaxKind.NewExpression && (<NewExpression>expression).arguments !== undefined;
const hasArguments = expression.kind === SyntaxKind.NewExpression && (expression as NewExpression).arguments !== undefined;
return getOperatorAssociativity(expression.kind, operator, hasArguments);
}
@@ -3341,16 +3341,16 @@ namespace ts {
export function getExpressionPrecedence(expression: Expression) {
const operator = getOperator(expression);
const hasArguments = expression.kind === SyntaxKind.NewExpression && (<NewExpression>expression).arguments !== undefined;
const hasArguments = expression.kind === SyntaxKind.NewExpression && (expression as NewExpression).arguments !== undefined;
return getOperatorPrecedence(expression.kind, operator, hasArguments);
}
export function getOperator(expression: Expression): SyntaxKind {
if (expression.kind === SyntaxKind.BinaryExpression) {
return (<BinaryExpression>expression).operatorToken.kind;
return (expression as BinaryExpression).operatorToken.kind;
}
else if (expression.kind === SyntaxKind.PrefixUnaryExpression || expression.kind === SyntaxKind.PostfixUnaryExpression) {
return (<PrefixUnaryExpression | PostfixUnaryExpression>expression).operator;
return (expression as PrefixUnaryExpression | PostfixUnaryExpression).operator;
}
else {
return expression.kind;
@@ -4774,7 +4774,7 @@ namespace ts {
*/
export function getSyntacticModifierFlagsNoCache(node: Node): ModifierFlags {
let flags = modifiersToFlags(node.modifiers);
if (node.flags & NodeFlags.NestedNamespace || (node.kind === SyntaxKind.Identifier && (<Identifier>node).isInJSDocNamespace)) {
if (node.flags & NodeFlags.NestedNamespace || (node.kind === SyntaxKind.Identifier && (node as Identifier).isInJSDocNamespace)) {
flags |= ModifierFlags.Export;
}
return flags;
@@ -4903,8 +4903,8 @@ namespace ts {
|| node.kind === SyntaxKind.ThisKeyword
|| node.kind === SyntaxKind.SuperKeyword
|| node.kind === SyntaxKind.MetaProperty
|| node.kind === SyntaxKind.PropertyAccessExpression && isDottedName((<PropertyAccessExpression>node).expression)
|| node.kind === SyntaxKind.ParenthesizedExpression && isDottedName((<ParenthesizedExpression>node).expression);
|| node.kind === SyntaxKind.PropertyAccessExpression && isDottedName((node as PropertyAccessExpression).expression)
|| node.kind === SyntaxKind.ParenthesizedExpression && isDottedName((node as ParenthesizedExpression).expression);
}
export function isPropertyAccessEntityNameExpression(node: Node): node is PropertyAccessEntityNameExpression {
@@ -4935,18 +4935,24 @@ namespace ts {
}
export function isRightSideOfQualifiedNameOrPropertyAccess(node: Node) {
return (node.parent.kind === SyntaxKind.QualifiedName && (<QualifiedName>node.parent).right === node) ||
(node.parent.kind === SyntaxKind.PropertyAccessExpression && (<PropertyAccessExpression>node.parent).name === node);
return (node.parent.kind === SyntaxKind.QualifiedName && (node.parent as QualifiedName).right === node) ||
(node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent as PropertyAccessExpression).name === node);
}
export function isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(node: Node) {
return isQualifiedName(node.parent) && node.parent.right === node
|| isPropertyAccessExpression(node.parent) && node.parent.name === node
|| isJSDocMemberName(node.parent) && node.parent.right === node;
}
export function isEmptyObjectLiteral(expression: Node): boolean {
return expression.kind === SyntaxKind.ObjectLiteralExpression &&
(<ObjectLiteralExpression>expression).properties.length === 0;
(expression as ObjectLiteralExpression).properties.length === 0;
}
export function isEmptyArrayLiteral(expression: Node): boolean {
return expression.kind === SyntaxKind.ArrayLiteralExpression &&
(<ArrayLiteralExpression>expression).elements.length === 0;
(expression as ArrayLiteralExpression).elements.length === 0;
}
export function getLocalSymbolForExportDefault(symbol: Symbol) {
@@ -5291,7 +5297,7 @@ namespace ts {
switch (parseNode.parent.kind) {
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ModuleDeclaration:
return parseNode === (<EnumDeclaration | ModuleDeclaration>parseNode.parent).name;
return parseNode === (parseNode.parent as EnumDeclaration | ModuleDeclaration).name;
}
}
return false;
@@ -5315,7 +5321,7 @@ namespace ts {
}
export function getCheckFlags(symbol: Symbol): CheckFlags {
return symbol.flags & SymbolFlags.Transient ? (<TransientSymbol>symbol).checkFlags : 0;
return symbol.flags & SymbolFlags.Transient ? (symbol as TransientSymbol).checkFlags : 0;
}
export function getDeclarationModifierFlagsFromSymbol(s: Symbol, isWrite = false): ModifierFlags {
@@ -5325,7 +5331,7 @@ namespace ts {
return s.parent && s.parent.flags & SymbolFlags.Class ? flags : flags & ~ModifierFlags.AccessibilityModifier;
}
if (getCheckFlags(s) & CheckFlags.Synthetic) {
const checkFlags = (<TransientSymbol>s).checkFlags;
const checkFlags = (s as TransientSymbol).checkFlags;
const accessModifier = checkFlags & CheckFlags.ContainsPrivate ? ModifierFlags.Private :
checkFlags & CheckFlags.ContainsPublic ? ModifierFlags.Public :
ModifierFlags.Protected;
@@ -5397,7 +5403,7 @@ namespace ts {
function writeOrReadWrite(): AccessKind {
// If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
return parent.parent && skipParenthesesUp(parent.parent).kind === SyntaxKind.ExpressionStatement ? AccessKind.Write : AccessKind.ReadWrite;
return parent.parent && walkUpParenthesizedExpressions(parent.parent).kind === SyntaxKind.ExpressionStatement ? AccessKind.Write : AccessKind.ReadWrite;
}
}
function reverseAccessKind(a: AccessKind): AccessKind {
@@ -5512,7 +5518,7 @@ namespace ts {
}
export function getObjectFlags(type: Type): ObjectFlags {
return type.flags & TypeFlags.ObjectFlagsType ? (<ObjectFlagsType>type).objectFlags : 0;
return type.flags & TypeFlags.ObjectFlagsType ? (type as ObjectFlagsType).objectFlags : 0;
}
export function typeHasCallOrConstructSignatures(type: Type, checker: TypeChecker) {
@@ -5624,19 +5630,19 @@ namespace ts {
while (true) {
switch (node.kind) {
case SyntaxKind.PostfixUnaryExpression:
node = (<PostfixUnaryExpression>node).operand;
node = (node as PostfixUnaryExpression).operand;
continue;
case SyntaxKind.BinaryExpression:
node = (<BinaryExpression>node).left;
node = (node as BinaryExpression).left;
continue;
case SyntaxKind.ConditionalExpression:
node = (<ConditionalExpression>node).condition;
node = (node as ConditionalExpression).condition;
continue;
case SyntaxKind.TaggedTemplateExpression:
node = (<TaggedTemplateExpression>node).tag;
node = (node as TaggedTemplateExpression).tag;
continue;
case SyntaxKind.CallExpression:
@@ -5649,7 +5655,7 @@ namespace ts {
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.NonNullExpression:
case SyntaxKind.PartiallyEmittedExpression:
node = (<CallExpression | PropertyAccessExpression | ElementAccessExpression | AsExpression | NonNullExpression | PartiallyEmittedExpression>node).expression;
node = (node as CallExpression | PropertyAccessExpression | ElementAccessExpression | AsExpression | NonNullExpression | PartiallyEmittedExpression).expression;
continue;
}
@@ -5735,15 +5741,15 @@ namespace ts {
// eslint-disable-next-line prefer-const
export let objectAllocator: ObjectAllocator = {
getNodeConstructor: () => <any>Node,
getTokenConstructor: () => <any>Token,
getIdentifierConstructor: () => <any>Identifier,
getPrivateIdentifierConstructor: () => <any>Node,
getSourceFileConstructor: () => <any>Node,
getSymbolConstructor: () => <any>Symbol,
getTypeConstructor: () => <any>Type,
getSignatureConstructor: () => <any>Signature,
getSourceMapSourceConstructor: () => <any>SourceMapSource,
getNodeConstructor: () => Node as any,
getTokenConstructor: () => Token as any,
getIdentifierConstructor: () => Identifier as any,
getPrivateIdentifierConstructor: () => Node as any,
getSourceFileConstructor: () => Node as any,
getSymbolConstructor: () => Symbol as any,
getTypeConstructor: () => Type as any,
getSignatureConstructor: () => Signature as any,
getSourceMapSourceConstructor: () => SourceMapSource as any,
};
export function setObjectAllocator(alloc: ObjectAllocator) {
@@ -6673,7 +6679,7 @@ namespace ts {
export function getExtensionPriority(path: string, supportedExtensions: readonly string[]): ExtensionPriority {
for (let i = supportedExtensions.length - 1; i >= 0; i--) {
if (fileExtensionIs(path, supportedExtensions[i])) {
return adjustExtensionPriority(<ExtensionPriority>i, supportedExtensions);
return adjustExtensionPriority(i as ExtensionPriority, supportedExtensions);
}
}
@@ -6729,7 +6735,7 @@ namespace ts {
}
export function changeExtension<T extends string | Path>(path: T, newExtension: string): T {
return <T>changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false) as T;
}
export function tryParsePattern(pattern: string): Pattern | undefined {
+11 -7
View File
@@ -249,7 +249,7 @@ namespace ts {
if (d && d.kind === SyntaxKind.TypeParameter) {
for (let current: Node = d; current; current = current.parent) {
if (isFunctionLike(current) || isClassLike(current) || current.kind === SyntaxKind.InterfaceDeclaration) {
return <Declaration>current;
return current as Declaration;
}
}
}
@@ -901,9 +901,10 @@ namespace ts {
}
/** Gets the text of a jsdoc comment, flattening links to their text. */
export function getTextOfJSDocComment(comment?: string | NodeArray<JSDocText | JSDocLink>) {
export function getTextOfJSDocComment(comment?: string | NodeArray<JSDocComment>) {
return typeof comment === "string" ? comment
: comment?.map(c =>
// TODO: Other kinds here
c.kind === SyntaxKind.JSDocText ? c.text : `{@link ${c.name ? entityNameToString(c.name) + " " : ""}${c.text}}`).join("");
}
@@ -1005,7 +1006,7 @@ namespace ts {
}
export function isNullishCoalesce(node: Node) {
return node.kind === SyntaxKind.BinaryExpression && (<BinaryExpression>node).operatorToken.kind === SyntaxKind.QuestionQuestionToken;
return node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.QuestionQuestionToken;
}
export function isConstTypeReference(node: Node) {
@@ -1534,8 +1535,8 @@ namespace ts {
case SyntaxKind.PostfixUnaryExpression:
return true;
case SyntaxKind.PrefixUnaryExpression:
return (<PrefixUnaryExpression>expr).operator === SyntaxKind.PlusPlusToken ||
(<PrefixUnaryExpression>expr).operator === SyntaxKind.MinusMinusToken;
return (expr as PrefixUnaryExpression).operator === SyntaxKind.PlusPlusToken ||
(expr as PrefixUnaryExpression).operator === SyntaxKind.MinusMinusToken;
default:
return false;
}
@@ -1592,7 +1593,7 @@ namespace ts {
case SyntaxKind.WhileStatement:
return true;
case SyntaxKind.LabeledStatement:
return lookInLabeledStatements && isIterationStatement((<LabeledStatement>node).statement, lookInLabeledStatements);
return lookInLabeledStatements && isIterationStatement((node as LabeledStatement).statement, lookInLabeledStatements);
}
return false;
@@ -1875,7 +1876,7 @@ namespace ts {
return node.kind === SyntaxKind.JSDocComment
|| node.kind === SyntaxKind.JSDocNamepathType
|| node.kind === SyntaxKind.JSDocText
|| node.kind === SyntaxKind.JSDocLink
|| isJSDocLinkLike(node)
|| isJSDocTag(node)
|| isJSDocTypeLiteral(node)
|| isJSDocSignature(node);
@@ -1968,5 +1969,8 @@ namespace ts {
return node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NoSubstitutionTemplateLiteral;
}
export function isJSDocLinkLike(node: Node): node is JSDocLink | JSDocLinkCode | JSDocLinkPlain {
return node.kind === SyntaxKind.JSDocLink || node.kind === SyntaxKind.JSDocLinkCode || node.kind === SyntaxKind.JSDocLinkPlain;
}
// #endregion
}
+3 -3
View File
@@ -41,7 +41,7 @@ namespace ts {
}
Debug.assertNode(visitedNode, test);
return <T>visitedNode;
return visitedNode as T;
}
/**
@@ -119,12 +119,12 @@ namespace ts {
if (isArray(visited)) {
for (const visitedNode of visited) {
void Debug.assertNode(visitedNode, test);
updated.push(<T>visitedNode);
updated.push(visitedNode as T);
}
}
else {
void Debug.assertNode(visited, test);
updated.push(<T>visited);
updated.push(visited as T);
}
}
}
+1 -1
View File
@@ -90,7 +90,7 @@ namespace ts {
/** Parses config file using System interface */
export function parseConfigFileWithSystem(configFileName: string, optionsToExtend: CompilerOptions, extendedConfigCache: Map<ExtendedConfigCacheEntry> | undefined, watchOptionsToExtend: WatchOptions | undefined, system: System, reportDiagnostic: DiagnosticReporter) {
const host: ParseConfigFileHost = <any>system;
const host: ParseConfigFileHost = system as any;
host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic);
const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend);
host.onUnRecoverableConfigFileDiagnostic = undefined!; // TODO: GH#18217
+2 -2
View File
@@ -144,8 +144,8 @@ namespace ts {
if (option.name === "lib") {
description = getDiagnosticText(option.description);
const element = (<CommandLineOptionOfListType>option).element;
const typeMap = <ESMap<string, number | string>>element.type;
const element = (option as CommandLineOptionOfListType).element;
const typeMap = element.type as ESMap<string, number | string>;
optionsDescriptionMap.set(description, arrayFrom(typeMap.keys()).map(key => `'${key}'`));
}
else {
+3 -3
View File
@@ -87,7 +87,7 @@ namespace ts.server {
this.writeMessage(JSON.stringify(request));
return <T>request;
return request as T;
}
private processResponse<T extends protocol.Response>(request: protocol.Request, expectEmptyBody = false): T {
@@ -398,9 +398,9 @@ namespace ts.server {
const sourceText = getSnapshotText(this.host.getScriptSnapshot(file)!);
const fakeSourceFile = { fileName: file, text: sourceText } as SourceFile; // Warning! This is a huge lie!
return (<protocol.DiagnosticWithLinePosition[]>response.body).map((entry): DiagnosticWithLocation => {
return (response.body as protocol.DiagnosticWithLinePosition[]).map((entry): DiagnosticWithLocation => {
const category = firstDefined(Object.keys(DiagnosticCategory), id =>
isString(id) && entry.category === id.toLowerCase() ? (<any>DiagnosticCategory)[id] : undefined);
isString(id) && entry.category === id.toLowerCase() ? (DiagnosticCategory as any)[id] : undefined);
return {
file: fakeSourceFile,
start: entry.start,
+1 -1
View File
@@ -7,7 +7,7 @@ namespace evaluator {
// Define a custom "Symbol" constructor to attach missing built-in symbols without
// modifying the global "Symbol" constructor
const FakeSymbol: SymbolConstructor = ((description?: string) => Symbol(description)) as any;
(<any>FakeSymbol).prototype = Symbol.prototype;
(FakeSymbol as any).prototype = Symbol.prototype;
for (const key of Object.getOwnPropertyNames(Symbol)) {
Object.defineProperty(FakeSymbol, key, Object.getOwnPropertyDescriptor(Symbol, key)!);
}
+4 -4
View File
@@ -2442,7 +2442,7 @@ namespace FourSlash {
range.fileName === impl.fileName && range.pos === impl.textSpan.start && length === impl.textSpan.length);
if (matchingImpl) {
if (range.marker && range.marker.data) {
const expected = <{ displayParts?: ts.SymbolDisplayPart[], parts: string[], kind?: string }>range.marker.data;
const expected = range.marker.data as { displayParts?: ts.SymbolDisplayPart[], parts: string[], kind?: string };
if (expected.displayParts) {
if (!ts.arrayIsEqualTo(expected.displayParts, matchingImpl.displayParts, displayPartIsEqualTo)) {
delayedErrors.push(`Mismatched display parts: expected ${JSON.stringify(expected.displayParts)}, actual ${JSON.stringify(matchingImpl.displayParts)}`);
@@ -2713,7 +2713,7 @@ namespace FourSlash {
public verifyProjectInfo(expected: string[]) {
if (this.testType === FourSlashTestType.Server) {
const actual = (<ts.server.SessionClient>this.languageService).getProjectInfo(
const actual = (this.languageService as ts.server.SessionClient).getProjectInfo(
this.activeFile.fileName,
/* needFileNameList */ true
);
@@ -3177,7 +3177,7 @@ namespace FourSlash {
for (const markerName in map) {
this.goToMarker(markerName);
const actual = this.languageService.getJsxClosingTagAtPosition(this.activeFile.fileName, this.currentCaretPosition);
assert.deepEqual(actual, map[markerName]);
assert.deepEqual(actual, map[markerName], markerName);
}
}
@@ -3918,7 +3918,7 @@ namespace FourSlash {
}
public configurePlugin(pluginName: string, configuration: any): void {
(<ts.server.SessionClient>this.languageService).configurePlugin(pluginName, configuration);
(this.languageService as ts.server.SessionClient).configurePlugin(pluginName, configuration);
}
public toggleLineComment(newFileContent: string): void {
+2 -2
View File
@@ -365,7 +365,7 @@ namespace Harness {
case "list":
return ts.parseListTypeOption(option, value, errors);
default:
return ts.parseCustomTypeOption(<ts.CommandLineOptionOfCustomType>option, value, errors);
return ts.parseCustomTypeOption(option as ts.CommandLineOptionOfCustomType, value, errors);
}
}
@@ -1482,5 +1482,5 @@ namespace Harness {
return ts.find(["tsconfig.json" as "tsconfig.json", "jsconfig.json" as "jsconfig.json"], x => x === flc);
}
if (Error) (<any>Error).stackTraceLimit = 100;
if (Error) (Error as any).stackTraceLimit = 100;
}
+1 -1
View File
@@ -86,7 +86,7 @@ namespace Harness.LanguageService {
}
public getChangeRange(oldScript: ts.IScriptSnapshot): ts.TextChangeRange {
const oldShim = <ScriptSnapshot>oldScript;
const oldShim = oldScript as ScriptSnapshot;
return this.scriptInfo.getTextChangeRangeBetweenVersions(oldShim.version, this.version);
}
}
+20 -20
View File
@@ -54,7 +54,7 @@ namespace Utils {
export function memoize<T extends ts.AnyFunction>(f: T, memoKey: (...anything: any[]) => string): T {
const cache = new ts.Map<string, any>();
return <any>(function (this: any, ...args: any[]) {
return (function (this: any, ...args: any[]) {
const key = memoKey(...args);
if (cache.has(key)) {
return cache.get(key);
@@ -64,7 +64,7 @@ namespace Utils {
cache.set(key, value);
return value;
}
});
} as any);
}
export const canonicalizeForHarness = ts.createGetCanonicalFileName(/*caseSensitive*/ false); // This is done so tests work on windows _and_ linux
@@ -121,10 +121,10 @@ namespace Utils {
childName === "jsDocComment" || childName === "checkJsDirective" || childName === "commonJsModuleIndicator") {
continue;
}
const child = (<any>node)[childName];
const child = (node as any)[childName];
if (isNodeOrArray(child)) {
assert.isFalse(childNodesAndArrays.indexOf(child) < 0,
"Missing child when forEach'ing over node: " + (<any>ts).SyntaxKind[node.kind] + "-" + childName);
"Missing child when forEach'ing over node: " + (ts as any).SyntaxKind[node.kind] + "-" + childName);
}
}
}
@@ -159,18 +159,18 @@ namespace Utils {
// For some markers in SyntaxKind, we should print its original syntax name instead of
// the marker name in tests.
if (k === (<any>ts).SyntaxKind.FirstJSDocNode ||
k === (<any>ts).SyntaxKind.LastJSDocNode ||
k === (<any>ts).SyntaxKind.FirstJSDocTagNode ||
k === (<any>ts).SyntaxKind.LastJSDocTagNode) {
for (const kindName in (<any>ts).SyntaxKind) {
if ((<any>ts).SyntaxKind[kindName] === k) {
if (k === (ts as any).SyntaxKind.FirstJSDocNode ||
k === (ts as any).SyntaxKind.LastJSDocNode ||
k === (ts as any).SyntaxKind.FirstJSDocTagNode ||
k === (ts as any).SyntaxKind.LastJSDocTagNode) {
for (const kindName in (ts as any).SyntaxKind) {
if ((ts as any).SyntaxKind[kindName] === k) {
return kindName;
}
}
}
return (<any>ts).SyntaxKind[k];
return (ts as any).SyntaxKind[k];
}
function getFlagName(flags: any, f: number): any {
@@ -198,7 +198,7 @@ namespace Utils {
return result;
}
function getNodeFlagName(f: number) { return getFlagName((<any>ts).NodeFlags, f); }
function getNodeFlagName(f: number) { return getFlagName((ts as any).NodeFlags, f); }
function serializeNode(n: ts.Node): any {
const o: any = { kind: getKindName(n.kind) };
@@ -222,7 +222,7 @@ namespace Utils {
break;
case "originalKeywordKind":
o[propertyName] = getKindName((<any>n)[propertyName]);
o[propertyName] = getKindName((n as any)[propertyName]);
break;
case "flags":
@@ -236,7 +236,7 @@ namespace Utils {
break;
case "parseDiagnostics":
o[propertyName] = convertDiagnostics((<any>n)[propertyName]);
o[propertyName] = convertDiagnostics((n as any)[propertyName]);
break;
case "nextContainer":
@@ -248,12 +248,12 @@ namespace Utils {
case "text":
// Include 'text' field for identifiers/literals, but not for source files.
if (n.kind !== ts.SyntaxKind.SourceFile) {
o[propertyName] = (<any>n)[propertyName];
o[propertyName] = (n as any)[propertyName];
}
break;
default:
o[propertyName] = (<any>n)[propertyName];
o[propertyName] = (n as any)[propertyName];
}
}
@@ -304,13 +304,13 @@ namespace Utils {
ts.forEachChild(node1,
child1 => {
const childName = findChildName(node1, child1);
const child2: ts.Node = (<any>node2)[childName];
const child2: ts.Node = (node2 as any)[childName];
assertStructuralEquals(child1, child2);
},
array1 => {
const childName = findChildName(node1, array1);
const array2: ts.NodeArray<ts.Node> = (<any>node2)[childName];
const array2: ts.NodeArray<ts.Node> = (node2 as any)[childName];
assertArrayStructuralEquals(array1, array2);
});
@@ -345,7 +345,7 @@ namespace Utils {
const maxHarnessFrames = 1;
export function filterStack(error: Error, stackTraceLimit = Infinity) {
const stack = <string>(<any>error).stack;
const stack = (error as any).stack as string;
if (stack) {
const lines = stack.split(/\r\n?|\n/g);
const filtered: string[] = [];
@@ -374,7 +374,7 @@ namespace Utils {
filtered.push(line);
}
(<any>error).stack = filtered.join(Harness.IO.newLine());
(error as any).stack = filtered.join(Harness.IO.newLine());
}
return error;
+10 -10
View File
@@ -93,10 +93,10 @@ namespace Playback {
function memoize<T>(func: (s: string) => T): Memoized<T> {
let lookup: { [s: string]: T } = {};
const run: Memoized<T> = <Memoized<T>>((s: string) => {
const run: Memoized<T> = ((s: string) => {
if (lookup.hasOwnProperty(s)) return lookup[s];
return lookup[s] = func(s);
});
}) as Memoized<T>;
run.reset = () => {
lookup = undefined!; // TODO: GH#18217
};
@@ -209,7 +209,7 @@ namespace Playback {
function initWrapper(wrapper: PlaybackIO, underlying: Harness.IO): void;
function initWrapper(wrapper: PlaybackSystem | PlaybackIO, underlying: ts.System | Harness.IO): void {
ts.forEach(Object.keys(underlying), prop => {
(<any>wrapper)[prop] = (<any>underlying)[prop];
(wrapper as any)[prop] = (underlying as any)[prop];
});
wrapper.startReplayFromString = logString => {
@@ -325,7 +325,7 @@ namespace Playback {
wrapper.readDirectory = recordReplay(wrapper.readDirectory, underlying)(
(path, extensions, exclude, include, depth) => {
const result = (<ts.System>underlying).readDirectory(path, extensions, exclude, include, depth);
const result = (underlying as ts.System).readDirectory(path, extensions, exclude, include, depth);
recordLog!.directoriesRead.push({ path, extensions, exclude, include, depth, result });
return result;
},
@@ -364,7 +364,7 @@ namespace Playback {
function recordReplay<T extends ts.AnyFunction>(original: T, underlying: any) {
function createWrapper(record: T, replay: T): T {
// eslint-disable-next-line only-arrow-functions
return <any>(function () {
return (function () {
if (replayLog !== undefined) {
return replay.apply(undefined, arguments);
}
@@ -374,14 +374,14 @@ namespace Playback {
else {
return original.apply(underlying, arguments);
}
});
} as any);
}
return createWrapper;
}
function callAndRecord<T, U>(underlyingResult: T, logArray: U[], logEntry: U): T {
if (underlyingResult !== undefined) {
(<any>logEntry).result = underlyingResult;
(logEntry as any).result = underlyingResult;
}
logArray.push(logEntry);
return underlyingResult;
@@ -389,7 +389,7 @@ namespace Playback {
function findResultByFields<T>(logArray: { result?: T }[], expectedFields: {}, defaultValue?: T): T | undefined {
const predicate = (entry: { result?: T }) => {
return Object.getOwnPropertyNames(expectedFields).every((name) => (<any>entry)[name] === (<any>expectedFields)[name]);
return Object.getOwnPropertyNames(expectedFields).every((name) => (entry as any)[name] === (expectedFields as any)[name]);
};
const results = logArray.filter(entry => predicate(entry));
if (results.length === 0) {
@@ -425,7 +425,7 @@ namespace Playback {
}
export function wrapIO(underlying: Harness.IO): PlaybackIO {
const wrapper: PlaybackIO = <any>{};
const wrapper: PlaybackIO = {} as any;
initWrapper(wrapper, underlying);
wrapper.directoryName = notSupported;
@@ -442,7 +442,7 @@ namespace Playback {
}
export function wrapSystem(underlying: ts.System): PlaybackSystem {
const wrapper: PlaybackSystem = <any>{};
const wrapper: PlaybackSystem = {} as any;
initWrapper(wrapper, underlying);
return wrapper;
}
+5 -5
View File
@@ -863,7 +863,7 @@ namespace vfs {
private _mknod(dev: number, type: typeof S_IFDIR, mode: number, time?: number): DirectoryInode;
private _mknod(dev: number, type: typeof S_IFLNK, mode: number, time?: number): SymlinkInode;
private _mknod(dev: number, type: number, mode: number, time = this.time()) {
return <Inode>{
return {
dev,
ino: ++inoCount,
mode: (mode & ~S_IFMT & ~0o022 & 0o7777) | (type & S_IFMT),
@@ -872,7 +872,7 @@ namespace vfs {
ctimeMs: time,
birthtimeMs: time,
nlink: 0
};
} as Inode;
}
private _addLink(parent: DirectoryInode | undefined, links: collections.SortedMap<string, Inode>, name: string, node: Inode, time = this.time()) {
@@ -956,7 +956,7 @@ namespace vfs {
let shadow = shadows.get(root.ino);
if (!shadow) {
shadow = <Inode>{
shadow = {
dev: root.dev,
ino: root.ino,
mode: root.mode,
@@ -966,9 +966,9 @@ namespace vfs {
birthtimeMs: root.birthtimeMs,
nlink: root.nlink,
shadowRoot: root
};
} as Inode;
if (isSymlink(root)) (<SymlinkInode>shadow).symlink = root.symlink;
if (isSymlink(root)) (shadow as SymlinkInode).symlink = root.symlink;
shadows.set(shadow.ino, shadow);
}
+6 -6
View File
@@ -15,7 +15,7 @@ interface Array<T> { length: number; [n: number]: T; }`
};
export const safeList = {
path: <Path>"/safeList.json",
path: "/safeList.json" as Path,
content: JSON.stringify({
commander: "commander",
express: "express",
@@ -71,11 +71,11 @@ interface Array<T> { length: number; [n: number]: T; }`
export type FileOrFolderOrSymLink = File | Folder | SymLink;
export function isFile(fileOrFolderOrSymLink: FileOrFolderOrSymLink): fileOrFolderOrSymLink is File {
return isString((<File>fileOrFolderOrSymLink).content);
return isString((fileOrFolderOrSymLink as File).content);
}
export function isSymLink(fileOrFolderOrSymLink: FileOrFolderOrSymLink): fileOrFolderOrSymLink is SymLink {
return isString((<SymLink>fileOrFolderOrSymLink).symLink);
return isString((fileOrFolderOrSymLink as SymLink).symLink);
}
interface FSEntryBase {
@@ -100,15 +100,15 @@ interface Array<T> { length: number; [n: number]: T; }`
type FSEntry = FsFile | FsFolder | FsSymLink;
function isFsFolder(s: FSEntry | undefined): s is FsFolder {
return !!s && isArray((<FsFolder>s).entries);
return !!s && isArray((s as FsFolder).entries);
}
function isFsFile(s: FSEntry | undefined): s is FsFile {
return !!s && isString((<FsFile>s).content);
return !!s && isString((s as FsFile).content);
}
function isFsSymLink(s: FSEntry | undefined): s is FsSymLink {
return !!s && isString((<FsSymLink>s).symLink);
return !!s && isString((s as FsSymLink).symLink);
}
function invokeWatcherCallbacks<T>(callbacks: readonly T[] | undefined, invokeCallback: (cb: T) => void): void {
+1 -1
View File
@@ -23,7 +23,7 @@ interface Array<T> {
findIndex(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): number;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
+1 -1
View File
@@ -143,7 +143,7 @@ interface MapConstructor {
interface WeakMap<K extends object, V> { }
interface WeakMapConstructor {
new <K extends object, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
new <K extends object, V>(iterable: Iterable<readonly [K, V]>): WeakMap<K, V>;
}
interface Set<T> {
+2 -2
View File
@@ -164,7 +164,7 @@ interface BigInt64Array {
every(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
@@ -436,7 +436,7 @@ interface BigUint64Array {
every(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
+9 -9
View File
@@ -1776,7 +1776,7 @@ interface Int8Array {
every(predicate: (value: number, index: number, array: Int8Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
@@ -2058,7 +2058,7 @@ interface Uint8Array {
every(predicate: (value: number, index: number, array: Uint8Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
@@ -2340,7 +2340,7 @@ interface Uint8ClampedArray {
every(predicate: (value: number, index: number, array: Uint8ClampedArray) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
@@ -2621,7 +2621,7 @@ interface Int16Array {
every(predicate: (value: number, index: number, array: Int16Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
@@ -2903,7 +2903,7 @@ interface Uint16Array {
every(predicate: (value: number, index: number, array: Uint16Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
@@ -3185,7 +3185,7 @@ interface Int32Array {
every(predicate: (value: number, index: number, array: Int32Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
@@ -3467,7 +3467,7 @@ interface Uint32Array {
every(predicate: (value: number, index: number, array: Uint32Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
@@ -3748,7 +3748,7 @@ interface Float32Array {
every(predicate: (value: number, index: number, array: Float32Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
@@ -4031,7 +4031,7 @@ interface Float64Array {
every(predicate: (value: number, index: number, array: Float64Array) => unknown, thisArg?: any): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
+1 -1
View File
@@ -7,6 +7,6 @@ declare namespace Intl {
}
interface NumberFormat {
formatToParts(number?: number): NumberFormatPart[];
formatToParts(number?: number | bigint): NumberFormatPart[];
}
}
+8 -8
View File
@@ -162,7 +162,7 @@ namespace ts.server {
const map = new Map<string, ESMap<string, number>>();
for (const option of commandLineOptions) {
if (typeof option.type === "object") {
const optionMap = <ESMap<string, number>>option.type;
const optionMap = option.type as ESMap<string, number>;
// verify that map contains only numbers
optionMap.forEach(value => {
Debug.assert(typeof value === "number");
@@ -239,7 +239,7 @@ namespace ts.server {
protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase());
Debug.assert(protocolOptions.indentStyle !== undefined);
}
return <any>protocolOptions;
return protocolOptions as any;
}
export function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin {
@@ -249,7 +249,7 @@ namespace ts.server {
protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase());
}
});
return <any>protocolOptions;
return protocolOptions as any;
}
export function convertWatchOptions(protocolOptions: protocol.ExternalProjectCompilerOptions, currentDirectory?: string): WatchOptionsAndErrors | undefined {
@@ -1442,15 +1442,15 @@ namespace ts.server {
switch (project.projectKind) {
case ProjectKind.External:
unorderedRemoveItem(this.externalProjects, <ExternalProject>project);
unorderedRemoveItem(this.externalProjects, project as ExternalProject);
this.projectToSizeMap.delete(project.getProjectName());
break;
case ProjectKind.Configured:
this.configuredProjects.delete((<ConfiguredProject>project).canonicalConfigFilePath);
this.configuredProjects.delete((project as ConfiguredProject).canonicalConfigFilePath);
this.projectToSizeMap.delete((project as ConfiguredProject).canonicalConfigFilePath);
break;
case ProjectKind.Inferred:
unorderedRemoveItem(this.inferredProjects, <InferredProject>project);
unorderedRemoveItem(this.inferredProjects, project as InferredProject);
break;
}
}
@@ -2425,10 +2425,10 @@ namespace ts.server {
const diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics();
diagnostics.push(...project.getAllProjectErrors());
this.eventHandler(<ConfigFileDiagEvent>{
this.eventHandler({
eventName: ConfigFileDiagEvent,
data: { configFileName: project.getConfigFilePath(), diagnostics, triggerFile }
});
} as ConfigFileDiagEvent);
}
private getOrCreateInferredProjectForProjectRootPathIfEnabled(info: ScriptInfo, projectRootPath: NormalizedPath | undefined): InferredProject | undefined {
+1 -1
View File
@@ -1573,7 +1573,7 @@ namespace ts.server {
let errorLogs: string[] | undefined;
const logError = (message: string) => { (errorLogs || (errorLogs = [])).push(message); };
const resolvedModule = firstDefined(searchPaths, searchPath =>
<PluginModuleFactory | undefined>Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log, logError));
Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log, logError) as PluginModuleFactory | undefined);
if (resolvedModule) {
const configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name);
if (configurationOverride) {
+15 -15
View File
@@ -76,11 +76,11 @@ namespace ts.server {
let lastZeroCount: LineCollection | undefined;
for (let k = this.endBranch.length - 1; k >= 0; k--) {
(<LineNode>this.endBranch[k]).updateCounts();
(this.endBranch[k] as LineNode).updateCounts();
if (this.endBranch[k].charCount() === 0) {
lastZeroCount = this.endBranch[k];
if (k > 0) {
branchParent = <LineNode>this.endBranch[k - 1];
branchParent = this.endBranch[k - 1] as LineNode;
}
else {
branchParent = this.branchNode;
@@ -92,20 +92,20 @@ namespace ts.server {
}
// path at least length two (root and leaf)
const leafNode = <LineLeaf>this.startPath[this.startPath.length - 1];
const leafNode = this.startPath[this.startPath.length - 1] as LineLeaf;
if (lines.length > 0) {
leafNode.text = lines[0];
if (lines.length > 1) {
let insertedNodes = <LineCollection[]>new Array(lines.length - 1);
let startNode = <LineCollection>leafNode;
let insertedNodes = new Array(lines.length - 1) as LineCollection[];
let startNode = leafNode as LineCollection;
for (let i = 1; i < lines.length; i++) {
insertedNodes[i - 1] = new LineLeaf(lines[i]);
}
let pathIndex = this.startPath.length - 2;
while (pathIndex >= 0) {
const insertionNode = <LineNode>this.startPath[pathIndex];
const insertionNode = this.startPath[pathIndex] as LineNode;
insertedNodes = insertionNode.insertAt(startNode, insertedNodes);
pathIndex--;
startNode = insertionNode;
@@ -122,16 +122,16 @@ namespace ts.server {
}
else {
for (let j = this.startPath.length - 2; j >= 0; j--) {
(<LineNode>this.startPath[j]).updateCounts();
(this.startPath[j] as LineNode).updateCounts();
}
}
}
else {
const insertionNode = <LineNode>this.startPath[this.startPath.length - 2];
const insertionNode = this.startPath[this.startPath.length - 2] as LineNode;
// no content for leaf node, so delete it
insertionNode.remove(leafNode);
for (let j = this.startPath.length - 2; j >= 0; j--) {
(<LineNode>this.startPath[j]).updateCounts();
(this.startPath[j] as LineNode).updateCounts();
}
}
@@ -220,7 +220,7 @@ namespace ts.server {
break;
}
if (this.goSubtree) {
this.stack.push(<LineNode>child);
this.stack.push(child as LineNode);
}
}
// just gather text from the leaves
@@ -544,9 +544,9 @@ namespace ts.server {
const lineMap = computeLineStarts(text);
if (lineMap.length === 0) {
return { lines: <string[]>[], lineMap };
return { lines: [] as string[], lineMap };
}
const lines = <string[]>new Array(lineMap.length);
const lines = new Array(lineMap.length) as string[];
const lc = lineMap.length - 1;
for (let lmi = 0; lmi < lc; lmi++) {
lines[lmi] = text.substring(lineMap[lmi], lineMap[lmi + 1]);
@@ -673,7 +673,7 @@ namespace ts.server {
return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text };
}
else {
return (<LineNode>child).charOffsetToLineInfo(lineNumberAccumulator, relativePosition);
return (child as LineNode).charOffsetToLineInfo(lineNumberAccumulator, relativePosition);
}
}
else {
@@ -696,7 +696,7 @@ namespace ts.server {
for (const child of this.children) {
const childLineCount = child.lineCount();
if (childLineCount >= relativeOneBasedLine) {
return child.isLeaf() ? { position: positionAccumulator, leaf: child } : (<LineNode>child).lineNumberToInfo(relativeOneBasedLine, positionAccumulator);
return child.isLeaf() ? { position: positionAccumulator, leaf: child } : (child as LineNode).lineNumberToInfo(relativeOneBasedLine, positionAccumulator);
}
else {
relativeOneBasedLine -= childLineCount;
@@ -764,7 +764,7 @@ namespace ts.server {
let splitNodeCount = 0;
if (nodeIndex < nodeCount) {
splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity);
splitNodes = <LineNode[]>new Array(splitNodeCount);
splitNodes = new Array(splitNodeCount) as LineNode[];
let splitNodeIndex = 0;
for (let i = 0; i < splitNodeCount; i++) {
splitNodes[i] = new LineNode();
+13 -13
View File
@@ -125,7 +125,7 @@ namespace ts.server {
// we want to ensure the value is maintained in the out since the file is
// built using --preseveConstEnum.
export type CommandNames = protocol.CommandTypes;
export const CommandNames = (<any>protocol).CommandTypes;
export const CommandNames = (protocol as any).CommandTypes;
export function formatMessage<T extends protocol.Message>(msg: T, logger: Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string {
const verboseLogging = logger.hasLevel(LogLevel.verbose);
@@ -226,7 +226,7 @@ namespace ts.server {
tracing?.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId });
}
else {
tracing?.instant(tracing.Phase.Session, "stepError", { seq: this.requestId, message: (<Error>e).message });
tracing?.instant(tracing.Phase.Session, "stepError", { seq: this.requestId, message: (e as Error).message });
this.operationHost.logError(e, `delayed processing of request ${this.requestId}`);
}
}
@@ -896,8 +896,8 @@ namespace ts.server {
let msg = "Exception on executing command " + cmd;
if (err.message) {
msg += ":\n" + indent(err.message);
if ((<StackTraceError>err).stack) {
msg += "\n" + indent((<StackTraceError>err).stack!);
if ((err as StackTraceError).stack) {
msg += "\n" + indent((err as StackTraceError).stack!);
}
}
@@ -1179,7 +1179,7 @@ namespace ts.server {
}
private convertToDiagnosticsWithLinePosition(diagnostics: readonly Diagnostic[], scriptInfo: ScriptInfo | undefined): protocol.DiagnosticWithLinePosition[] {
return diagnostics.map(d => <protocol.DiagnosticWithLinePosition>{
return diagnostics.map(d => ({
message: flattenDiagnosticMessageText(d.messageText, this.host.newLine),
start: d.start,
length: d.length,
@@ -1191,7 +1191,7 @@ namespace ts.server {
reportsUnnecessary: d.reportsUnnecessary,
reportsDeprecated: d.reportsDeprecated,
relatedInformation: map(d.relatedInformation, formatRelatedInformation),
});
}) as protocol.DiagnosticWithLinePosition);
}
private getDiagnosticsWorker(
@@ -1316,7 +1316,7 @@ namespace ts.server {
if (def.originalFileName) {
Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is");
return {
...<any>def,
...def as any,
fileName: def.originalFileName,
textSpan: def.originalTextSpan,
targetFileName: def.fileName,
@@ -2138,7 +2138,7 @@ namespace ts.server {
}
private isLocation(locationOrSpan: protocol.FileLocationOrRangeRequestArgs): locationOrSpan is protocol.FileLocationRequestArgs {
return (<protocol.FileLocationRequestArgs>locationOrSpan).line !== undefined;
return (locationOrSpan as protocol.FileLocationRequestArgs).line !== undefined;
}
private extractPositionOrRange(args: protocol.FileLocationOrRangeRequestArgs, scriptInfo: ScriptInfo): number | TextRange {
@@ -2823,12 +2823,12 @@ namespace ts.server {
return this.requiredResponse({ reloadFinished: true });
},
[CommandNames.Saveto]: (request: protocol.Request) => {
const savetoArgs = <protocol.SavetoRequestArgs>request.arguments;
const savetoArgs = request.arguments as protocol.SavetoRequestArgs;
this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile);
return this.notRequired();
},
[CommandNames.Close]: (request: protocol.Request) => {
const closeArgs = <protocol.FileRequestArgs>request.arguments;
const closeArgs = request.arguments as protocol.FileRequestArgs;
this.closeClientFile(closeArgs.file);
return this.notRequired();
},
@@ -3065,19 +3065,19 @@ namespace ts.server {
this.logErrorWorker(err, this.toStringMessage(message), relevantFile);
perfLogger.logStopCommand("" + (request && request.command), "Error: " + err);
tracing?.instant(tracing.Phase.Session, "commandError", { seq: request?.seq, command: request?.command, message: (<Error>err).message });
tracing?.instant(tracing.Phase.Session, "commandError", { seq: request?.seq, command: request?.command, message: (err as Error).message });
this.doOutput(
/*info*/ undefined,
request ? request.command : CommandNames.Unknown,
request ? request.seq : 0,
/*success*/ false,
"Error processing request. " + (<StackTraceError>err).message + "\n" + (<StackTraceError>err).stack);
"Error processing request. " + (err as StackTraceError).message + "\n" + (err as StackTraceError).stack);
}
}
protected parseMessage(message: TMessage): protocol.Request {
return <protocol.Request>JSON.parse(message as any as string);
return JSON.parse(message as any as string) as protocol.Request;
}
protected toStringMessage(message: TMessage): string {
+3 -3
View File
@@ -60,16 +60,16 @@ namespace ts.server {
export type NormalizedPath = string & { __normalizedPathTag: any };
export function toNormalizedPath(fileName: string): NormalizedPath {
return <NormalizedPath>normalizePath(fileName);
return normalizePath(fileName) as NormalizedPath;
}
export function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path {
const f = isRootedDiskPath(normalizedPath) ? normalizedPath : getNormalizedAbsolutePath(normalizedPath, currentDirectory);
return <Path>getCanonicalFileName(f);
return getCanonicalFileName(f) as Path;
}
export function asNormalizedPath(fileName: string): NormalizedPath {
return <NormalizedPath>fileName;
return fileName as NormalizedPath;
}
export interface NormalizedPathMap<T> {
+52 -52
View File
@@ -70,15 +70,15 @@ namespace ts.BreakpointResolver {
switch (node.kind) {
case SyntaxKind.VariableStatement:
// Span on first variable declaration
return spanInVariableDeclaration((<VariableStatement>node).declarationList.declarations[0]);
return spanInVariableDeclaration((node as VariableStatement).declarationList.declarations[0]);
case SyntaxKind.VariableDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
return spanInVariableDeclaration(<VariableDeclaration | PropertyDeclaration | PropertySignature>node);
return spanInVariableDeclaration(node as VariableDeclaration | PropertyDeclaration | PropertySignature);
case SyntaxKind.Parameter:
return spanInParameterDeclaration(<ParameterDeclaration>node);
return spanInParameterDeclaration(node as ParameterDeclaration);
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.MethodDeclaration:
@@ -88,34 +88,34 @@ namespace ts.BreakpointResolver {
case SyntaxKind.Constructor:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
return spanInFunctionDeclaration(<FunctionLikeDeclaration>node);
return spanInFunctionDeclaration(node as FunctionLikeDeclaration);
case SyntaxKind.Block:
if (isFunctionBlock(node)) {
return spanInFunctionBlock(<Block>node);
return spanInFunctionBlock(node as Block);
}
// falls through
case SyntaxKind.ModuleBlock:
return spanInBlock(<Block>node);
return spanInBlock(node as Block);
case SyntaxKind.CatchClause:
return spanInBlock((<CatchClause>node).block);
return spanInBlock((node as CatchClause).block);
case SyntaxKind.ExpressionStatement:
// span on the expression
return textSpan((<ExpressionStatement>node).expression);
return textSpan((node as ExpressionStatement).expression);
case SyntaxKind.ReturnStatement:
// span on return keyword and expression if present
return textSpan(node.getChildAt(0), (<ReturnStatement>node).expression);
return textSpan(node.getChildAt(0), (node as ReturnStatement).expression);
case SyntaxKind.WhileStatement:
// Span on while(...)
return textSpanEndingAtNextToken(node, (<WhileStatement>node).expression);
return textSpanEndingAtNextToken(node, (node as WhileStatement).expression);
case SyntaxKind.DoStatement:
// span in statement of the do statement
return spanInNode((<DoStatement>node).statement);
return spanInNode((node as DoStatement).statement);
case SyntaxKind.DebuggerStatement:
// span on debugger keyword
@@ -123,60 +123,60 @@ namespace ts.BreakpointResolver {
case SyntaxKind.IfStatement:
// set on if(..) span
return textSpanEndingAtNextToken(node, (<IfStatement>node).expression);
return textSpanEndingAtNextToken(node, (node as IfStatement).expression);
case SyntaxKind.LabeledStatement:
// span in statement
return spanInNode((<LabeledStatement>node).statement);
return spanInNode((node as LabeledStatement).statement);
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
// On break or continue keyword and label if present
return textSpan(node.getChildAt(0), (<BreakOrContinueStatement>node).label);
return textSpan(node.getChildAt(0), (node as BreakOrContinueStatement).label);
case SyntaxKind.ForStatement:
return spanInForStatement(<ForStatement>node);
return spanInForStatement(node as ForStatement);
case SyntaxKind.ForInStatement:
// span of for (a in ...)
return textSpanEndingAtNextToken(node, (<ForInStatement>node).expression);
return textSpanEndingAtNextToken(node, (node as ForInStatement).expression);
case SyntaxKind.ForOfStatement:
// span in initializer
return spanInInitializerOfForLike(<ForOfStatement>node);
return spanInInitializerOfForLike(node as ForOfStatement);
case SyntaxKind.SwitchStatement:
// span on switch(...)
return textSpanEndingAtNextToken(node, (<SwitchStatement>node).expression);
return textSpanEndingAtNextToken(node, (node as SwitchStatement).expression);
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
// span in first statement of the clause
return spanInNode((<CaseOrDefaultClause>node).statements[0]);
return spanInNode((node as CaseOrDefaultClause).statements[0]);
case SyntaxKind.TryStatement:
// span in try block
return spanInBlock((<TryStatement>node).tryBlock);
return spanInBlock((node as TryStatement).tryBlock);
case SyntaxKind.ThrowStatement:
// span in throw ...
return textSpan(node, (<ThrowStatement>node).expression);
return textSpan(node, (node as ThrowStatement).expression);
case SyntaxKind.ExportAssignment:
// span on export = id
return textSpan(node, (<ExportAssignment>node).expression);
return textSpan(node, (node as ExportAssignment).expression);
case SyntaxKind.ImportEqualsDeclaration:
// import statement without including semicolon
return textSpan(node, (<ImportEqualsDeclaration>node).moduleReference);
return textSpan(node, (node as ImportEqualsDeclaration).moduleReference);
case SyntaxKind.ImportDeclaration:
// import statement without including semicolon
return textSpan(node, (<ImportDeclaration>node).moduleSpecifier);
return textSpan(node, (node as ImportDeclaration).moduleSpecifier);
case SyntaxKind.ExportDeclaration:
// import statement without including semicolon
return textSpan(node, (<ExportDeclaration>node).moduleSpecifier);
return textSpan(node, (node as ExportDeclaration).moduleSpecifier);
case SyntaxKind.ModuleDeclaration:
// span on complete module if it is instantiated
@@ -194,14 +194,14 @@ namespace ts.BreakpointResolver {
case SyntaxKind.WithStatement:
// span in statement
return spanInNode((<WithStatement>node).statement);
return spanInNode((node as WithStatement).statement);
case SyntaxKind.Decorator:
return spanInNodeArray(parent.decorators!);
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
return spanInBindingPattern(<BindingPattern>node);
return spanInBindingPattern(node as BindingPattern);
// No breakpoint in interface, type alias
case SyntaxKind.InterfaceDeclaration:
@@ -255,7 +255,7 @@ namespace ts.BreakpointResolver {
// [a, b, c] of
// [a, b, c] = expression
if (isArrayLiteralOrObjectLiteralDestructuringPattern(node)) {
return spanInArrayLiteralOrObjectLiteralDestructuringPattern(<DestructuringPattern>node);
return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node as DestructuringPattern);
}
// Set breakpoint on identifier element of destructuring pattern
@@ -270,14 +270,14 @@ namespace ts.BreakpointResolver {
}
if (node.kind === SyntaxKind.BinaryExpression) {
const { left, operatorToken } = <BinaryExpression>node;
const { left, operatorToken } = node as BinaryExpression;
// Set breakpoint in destructuring pattern if its destructuring assignment
// [a, b, c] or {a, b, c} of
// [a, b, c] = expression or
// {a, b, c} = expression
if (isArrayLiteralOrObjectLiteralDestructuringPattern(left)) {
return spanInArrayLiteralOrObjectLiteralDestructuringPattern(
<ArrayLiteralExpression | ObjectLiteralExpression>left);
left as ArrayLiteralExpression | ObjectLiteralExpression);
}
if (operatorToken.kind === SyntaxKind.EqualsToken && isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
@@ -308,14 +308,14 @@ namespace ts.BreakpointResolver {
return textSpan(node);
case SyntaxKind.BinaryExpression:
if ((<BinaryExpression>node.parent).operatorToken.kind === SyntaxKind.CommaToken) {
if ((node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken) {
// If this is a comma expression, the breakpoint is possible in this expression
return textSpan(node);
}
break;
case SyntaxKind.ArrowFunction:
if ((<FunctionLikeDeclaration>node.parent).body === node) {
if ((node.parent as FunctionLikeDeclaration).body === node) {
// If this is body of arrow function, it is allowed to have the breakpoint
return textSpan(node);
}
@@ -326,28 +326,28 @@ namespace ts.BreakpointResolver {
switch (node.parent.kind) {
case SyntaxKind.PropertyAssignment:
// If this is name of property assignment, set breakpoint in the initializer
if ((<PropertyAssignment>node.parent).name === node &&
if ((node.parent as PropertyAssignment).name === node &&
!isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
return spanInNode((<PropertyAssignment>node.parent).initializer);
return spanInNode((node.parent as PropertyAssignment).initializer);
}
break;
case SyntaxKind.TypeAssertionExpression:
// Breakpoint in type assertion goes to its operand
if ((<TypeAssertion>node.parent).type === node) {
return spanInNextNode((<TypeAssertion>node.parent).type);
if ((node.parent as TypeAssertion).type === node) {
return spanInNextNode((node.parent as TypeAssertion).type);
}
break;
case SyntaxKind.VariableDeclaration:
case SyntaxKind.Parameter: {
// initializer of variable/parameter declaration go to previous node
const { initializer, type } = <VariableDeclaration | ParameterDeclaration>node.parent;
const { initializer, type } = node.parent as VariableDeclaration | ParameterDeclaration;
if (initializer === node || type === node || isAssignmentOperator(node.kind)) {
return spanInPreviousNode(node);
}
break;
}
case SyntaxKind.BinaryExpression: {
const { left } = <BinaryExpression>node.parent;
const { left } = node.parent as BinaryExpression;
if (isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) {
// If initializer of destructuring assignment move to previous token
return spanInPreviousNode(node);
@@ -422,7 +422,7 @@ namespace ts.BreakpointResolver {
return textSpan(parameter);
}
else {
const functionDeclaration = <FunctionLikeDeclaration>parameter.parent;
const functionDeclaration = parameter.parent as FunctionLikeDeclaration;
const indexOfParameter = functionDeclaration.parameters.indexOf(parameter);
Debug.assert(indexOfParameter !== -1);
if (indexOfParameter !== 0) {
@@ -458,7 +458,7 @@ namespace ts.BreakpointResolver {
function spanInFunctionBlock(block: Block): TextSpan | undefined {
const nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
if (canFunctionHaveSpanInWholeDeclaration(<FunctionLikeDeclaration>block.parent)) {
if (canFunctionHaveSpanInWholeDeclaration(block.parent as FunctionLikeDeclaration)) {
return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
}
@@ -492,7 +492,7 @@ namespace ts.BreakpointResolver {
function spanInInitializerOfForLike(forLikeStatement: ForStatement | ForOfStatement | ForInStatement): TextSpan | undefined {
if (forLikeStatement.initializer!.kind === SyntaxKind.VariableDeclarationList) {
// Declaration list - set breakpoint in first declaration
const variableDeclarationList = <VariableDeclarationList>forLikeStatement.initializer;
const variableDeclarationList = forLikeStatement.initializer as VariableDeclarationList;
if (variableDeclarationList.declarations.length > 0) {
return spanInNode(variableDeclarationList.declarations[0]);
}
@@ -531,7 +531,7 @@ namespace ts.BreakpointResolver {
}
// Variable declaration is used as the span
return textSpanFromVariableDeclaration(<VariableDeclaration>bindingPattern.parent);
return textSpanFromVariableDeclaration(bindingPattern.parent as VariableDeclaration);
}
function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node: DestructuringPattern): TextSpan | undefined {
@@ -556,15 +556,15 @@ namespace ts.BreakpointResolver {
function spanInOpenBraceToken(node: Node): TextSpan | undefined {
switch (node.parent.kind) {
case SyntaxKind.EnumDeclaration:
const enumDeclaration = <EnumDeclaration>node.parent;
const enumDeclaration = node.parent as EnumDeclaration;
return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));
case SyntaxKind.ClassDeclaration:
const classDeclaration = <ClassDeclaration>node.parent;
const classDeclaration = node.parent as ClassDeclaration;
return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));
case SyntaxKind.CaseBlock:
return spanInNodeIfStartsOnSameLine(node.parent.parent, (<CaseBlock>node.parent).clauses[0]);
return spanInNodeIfStartsOnSameLine(node.parent.parent, (node.parent as CaseBlock).clauses[0]);
}
// Default to parent node
@@ -593,11 +593,11 @@ namespace ts.BreakpointResolver {
// falls through
case SyntaxKind.CatchClause:
return spanInNode(lastOrUndefined((<Block>node.parent).statements));
return spanInNode(lastOrUndefined((node.parent as Block).statements));
case SyntaxKind.CaseBlock:
// breakpoint in last statement of the last clause
const caseBlock = <CaseBlock>node.parent;
const caseBlock = node.parent as CaseBlock;
const lastClause = lastOrUndefined(caseBlock.clauses);
if (lastClause) {
return spanInNode(lastOrUndefined(lastClause.statements));
@@ -606,14 +606,14 @@ namespace ts.BreakpointResolver {
case SyntaxKind.ObjectBindingPattern:
// Breakpoint in last binding element or binding pattern if it contains no elements
const bindingPattern = <BindingPattern>node.parent;
const bindingPattern = node.parent as BindingPattern;
return spanInNode(lastOrUndefined(bindingPattern.elements) || bindingPattern);
// Default to parent node
default:
if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
// Breakpoint in last binding element or binding pattern if it contains no elements
const objectLiteral = <ObjectLiteralExpression>node.parent;
const objectLiteral = node.parent as ObjectLiteralExpression;
return textSpan(lastOrUndefined(objectLiteral.properties) || objectLiteral);
}
return spanInNode(node.parent);
@@ -624,13 +624,13 @@ namespace ts.BreakpointResolver {
switch (node.parent.kind) {
case SyntaxKind.ArrayBindingPattern:
// Breakpoint in last binding element or binding pattern if it contains no elements
const bindingPattern = <BindingPattern>node.parent;
const bindingPattern = node.parent as BindingPattern;
return textSpan(lastOrUndefined(bindingPattern.elements) || bindingPattern);
default:
if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
// Breakpoint in last binding element or binding pattern if it contains no elements
const arrayLiteral = <ArrayLiteralExpression>node.parent;
const arrayLiteral = node.parent as ArrayLiteralExpression;
return textSpan(lastOrUndefined(arrayLiteral.elements) || arrayLiteral);
}
@@ -702,7 +702,7 @@ namespace ts.BreakpointResolver {
function spanInWhileKeyword(node: Node): TextSpan | undefined {
if (node.parent.kind === SyntaxKind.DoStatement) {
// Set span on while expression
return textSpanEndingAtNextToken(node, (<DoStatement>node.parent).expression);
return textSpanEndingAtNextToken(node, (node.parent as DoStatement).expression);
}
// Default to parent node
+14 -14
View File
@@ -261,7 +261,7 @@ namespace ts {
for (let i = 0; i < dense.length; i += 3) {
const start = dense[i];
const length = dense[i + 1];
const type = <ClassificationType>dense[i + 2];
const type = dense[i + 2] as ClassificationType;
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
@@ -735,7 +735,7 @@ namespace ts {
commentStart = prop.isNameFirst && prop.typeExpression?.end || prop.name.end;
break;
case SyntaxKind.JSDocTemplateTag:
processJSDocTemplateTag(<JSDocTemplateTag>tag);
processJSDocTemplateTag(tag as JSDocTemplateTag);
pos = tag.end;
commentStart = (tag as JSDocTemplateTag).typeParameters.end;
break;
@@ -747,7 +747,7 @@ namespace ts {
commentStart = (tag as JSDocCallbackTag).typeExpression.end;
break;
case SyntaxKind.JSDocTypeTag:
processElement((<JSDocTypeTag>tag).typeExpression);
processElement((tag as JSDocTypeTag).typeExpression);
pos = tag.end;
commentStart = (tag as JSDocTypeTag).typeExpression.end;
break;
@@ -756,7 +756,7 @@ namespace ts {
commentStart = (tag as JSDocThisTag | JSDocEnumTag).typeExpression.end;
break;
case SyntaxKind.JSDocReturnTag:
processElement((<JSDocReturnTag>tag).typeExpression);
processElement((tag as JSDocReturnTag).typeExpression);
pos = tag.end;
commentStart = (tag as JSDocReturnTag).typeExpression?.end || commentStart;
break;
@@ -956,22 +956,22 @@ namespace ts {
function tryClassifyJsxElementName(token: Node): ClassificationType | undefined {
switch (token.parent && token.parent.kind) {
case SyntaxKind.JsxOpeningElement:
if ((<JsxOpeningElement>token.parent).tagName === token) {
if ((token.parent as JsxOpeningElement).tagName === token) {
return ClassificationType.jsxOpenTagName;
}
break;
case SyntaxKind.JsxClosingElement:
if ((<JsxClosingElement>token.parent).tagName === token) {
if ((token.parent as JsxClosingElement).tagName === token) {
return ClassificationType.jsxCloseTagName;
}
break;
case SyntaxKind.JsxSelfClosingElement:
if ((<JsxSelfClosingElement>token.parent).tagName === token) {
if ((token.parent as JsxSelfClosingElement).tagName === token) {
return ClassificationType.jsxSelfClosingTagName;
}
break;
case SyntaxKind.JsxAttribute:
if ((<JsxAttribute>token.parent).name === token) {
if ((token.parent as JsxAttribute).name === token) {
return ClassificationType.jsxAttribute;
}
break;
@@ -1044,32 +1044,32 @@ namespace ts {
if (token) {
switch (token.parent.kind) {
case SyntaxKind.ClassDeclaration:
if ((<ClassDeclaration>token.parent).name === token) {
if ((token.parent as ClassDeclaration).name === token) {
return ClassificationType.className;
}
return;
case SyntaxKind.TypeParameter:
if ((<TypeParameterDeclaration>token.parent).name === token) {
if ((token.parent as TypeParameterDeclaration).name === token) {
return ClassificationType.typeParameterName;
}
return;
case SyntaxKind.InterfaceDeclaration:
if ((<InterfaceDeclaration>token.parent).name === token) {
if ((token.parent as InterfaceDeclaration).name === token) {
return ClassificationType.interfaceName;
}
return;
case SyntaxKind.EnumDeclaration:
if ((<EnumDeclaration>token.parent).name === token) {
if ((token.parent as EnumDeclaration).name === token) {
return ClassificationType.enumName;
}
return;
case SyntaxKind.ModuleDeclaration:
if ((<ModuleDeclaration>token.parent).name === token) {
if ((token.parent as ModuleDeclaration).name === token) {
return ClassificationType.moduleName;
}
return;
case SyntaxKind.Parameter:
if ((<ParameterDeclaration>token.parent).name === token) {
if ((token.parent as ParameterDeclaration).name === token) {
return isThisIdentifier(token) ? ClassificationType.keyword : ClassificationType.parameterName;
}
return;
+1 -1
View File
@@ -90,7 +90,7 @@ namespace ts.classifier.v2020 {
let modifierSet = 0;
if (node.parent) {
const parentIsDeclaration = (isBindingElement(node.parent) || tokenFromDeclarationMapping.get(node.parent.kind) === typeIdx);
if (parentIsDeclaration && (<NamedDeclaration>node.parent).name === node) {
if (parentIsDeclaration && (node.parent as NamedDeclaration).name === node) {
modifierSet = 1 << TokenModifier.declaration;
}
}
@@ -37,7 +37,7 @@ namespace ts.codefix {
}
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, { indexSignature, container }: Info): void {
const members = isInterfaceDeclaration(container) ? container.members : (<TypeLiteralNode>container.type).members;
const members = isInterfaceDeclaration(container) ? container.members : (container.type as TypeLiteralNode).members;
const otherMembers = members.filter(member => !isIndexSignatureDeclaration(member));
const parameter = first(indexSignature.parameters);
const mappedTypeParameter = factory.createTypeParameterDeclaration(cast(parameter.name, isIdentifier), parameter.type);
@@ -21,7 +21,7 @@ namespace ts.codefix {
const token = getTokenAtPosition(sourceFile, pos);
Debug.assert(token.kind === SyntaxKind.ImportKeyword, "This token should be an ImportKeyword");
Debug.assert(token.parent.kind === SyntaxKind.ImportType, "Token parent should be an ImportType");
return <ImportTypeNode>token.parent;
return token.parent as ImportTypeNode;
}
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, importType: ImportTypeNode) {
@@ -63,7 +63,7 @@ namespace ts.codefix {
if (canDeleteEntireVariableStatement(sourceFile, token)) {
return [
createDeleteFix(textChanges.ChangeTracker.with(context, t =>
deleteEntireVariableStatement(t, sourceFile, <VariableDeclarationList>token.parent)), Diagnostics.Remove_variable_statement)
deleteEntireVariableStatement(t, sourceFile, token.parent as VariableDeclarationList)), Diagnostics.Remove_variable_statement)
];
}
@@ -132,7 +132,7 @@ namespace ts.codefix {
break;
}
else if (canDeleteEntireVariableStatement(sourceFile, token)) {
deleteEntireVariableStatement(changes, sourceFile, <VariableDeclarationList>token.parent);
deleteEntireVariableStatement(changes, sourceFile, token.parent as VariableDeclarationList);
}
else {
tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ true);
+4 -4
View File
@@ -52,7 +52,7 @@ namespace ts.codefix {
if (isReadonly) {
// readonly modifier only existed in classLikeDeclaration
const constructor = getFirstConstructorWithBody(<ClassLikeDeclaration>container);
const constructor = getFirstConstructorWithBody(container as ClassLikeDeclaration);
if (constructor) {
updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName.text, originalName);
}
@@ -79,7 +79,7 @@ namespace ts.codefix {
}
function createAccessorAccessExpression(fieldName: AcceptedNameType, isStatic: boolean, container: ContainerDeclaration) {
const leftHead = isStatic ? (<ClassLikeDeclaration>container).name! : factory.createThis(); // TODO: GH#18217
const leftHead = isStatic ? (container as ClassLikeDeclaration).name! : factory.createThis(); // TODO: GH#18217
return isIdentifier(fieldName) ? factory.createPropertyAccessExpression(leftHead, fieldName) : factory.createElementAccessExpression(leftHead, factory.createStringLiteralFromNode(fieldName));
}
@@ -135,7 +135,7 @@ namespace ts.codefix {
isReadonly: hasEffectiveReadonlyModifier(declaration),
type: getDeclarationType(declaration, program),
container: declaration.kind === SyntaxKind.Parameter ? declaration.parent.parent : declaration.parent,
originalName: (<AcceptedNameType>declaration.name).text,
originalName: (declaration.name as AcceptedNameType).text,
declaration,
fieldName,
accessorName,
@@ -214,7 +214,7 @@ namespace ts.codefix {
}
function insertAccessor(changeTracker: textChanges.ChangeTracker, file: SourceFile, accessor: AccessorDeclaration, declaration: AcceptedDeclaration, container: ContainerDeclaration) {
isParameterPropertyDeclaration(declaration, declaration.parent) ? changeTracker.insertNodeAtClassStart(file, <ClassLikeDeclaration>container, accessor) :
isParameterPropertyDeclaration(declaration, declaration.parent) ? changeTracker.insertNodeAtClassStart(file, container as ClassLikeDeclaration, accessor) :
isPropertyAssignment(declaration) ? changeTracker.insertNodeAfterComma(file, declaration, accessor) :
changeTracker.insertNodeAfter(file, declaration, accessor);
}
+1 -1
View File
@@ -165,7 +165,7 @@ namespace ts.codefix {
const checker = program.getTypeChecker();
const scriptTarget = getEmitScriptTarget(program.getCompilerOptions());
const flags = NodeBuilderFlags.NoTruncation | NodeBuilderFlags.NoUndefinedOptionalParameterType | NodeBuilderFlags.SuppressAnyReturnType | (quotePreference === QuotePreference.Single ? NodeBuilderFlags.UseSingleQuotesForStringLiteralType : 0);
const signatureDeclaration = <MethodDeclaration>checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context));
const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)) as MethodDeclaration;
if (!signatureDeclaration) {
return undefined;
}
+15 -15
View File
@@ -282,6 +282,7 @@ namespace ts.codefix {
program: Program,
host: LanguageServiceHost,
cancellationToken: CancellationToken,
): void {
const param = firstOrUndefined(setAccessorDeclaration.parameters);
if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) {
@@ -380,7 +381,7 @@ namespace ts.codefix {
}
export function addJSDocTags(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parent: HasJSDoc, newTags: readonly JSDocTag[]): void {
const comments = flatMap(parent.jsDoc, j => typeof j.comment === "string" ? factory.createJSDocText(j.comment) : j.comment) as (JSDocText | JSDocLink)[];
const comments = flatMap(parent.jsDoc, j => typeof j.comment === "string" ? factory.createJSDocText(j.comment) : j.comment) as JSDocComment[];
const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags);
const unmergedNewTags = newTags.filter(newTag => !oldTags || !oldTags.some((tag, i) => {
const merged = tryMergeJsdocTags(tag, newTag);
@@ -396,9 +397,9 @@ namespace ts.codefix {
function getJsDocNodeForArrowFunction(signature: ArrowFunction): HasJSDoc {
if (signature.parent.kind === SyntaxKind.PropertyDeclaration) {
return <HasJSDoc>signature.parent;
return signature.parent as HasJSDoc;
}
return <HasJSDoc>signature.parent.parent;
return signature.parent.parent as HasJSDoc;
}
function tryMergeJsdocTags(oldTag: JSDocTag, newTag: JSDocTag): JSDocTag | undefined {
@@ -627,7 +628,7 @@ namespace ts.codefix {
function calculateUsageOfNode(node: Expression, usage: Usage): void {
while (isRightSideOfQualifiedNameOrPropertyAccess(node)) {
node = <Expression>node.parent;
node = node.parent as Expression;
}
switch (node.parent.kind) {
@@ -638,36 +639,36 @@ namespace ts.codefix {
usage.isNumber = true;
break;
case SyntaxKind.PrefixUnaryExpression:
inferTypeFromPrefixUnaryExpression(<PrefixUnaryExpression>node.parent, usage);
inferTypeFromPrefixUnaryExpression(node.parent as PrefixUnaryExpression, usage);
break;
case SyntaxKind.BinaryExpression:
inferTypeFromBinaryExpression(node, <BinaryExpression>node.parent, usage);
inferTypeFromBinaryExpression(node, node.parent as BinaryExpression, usage);
break;
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
inferTypeFromSwitchStatementLabel(<CaseOrDefaultClause>node.parent, usage);
inferTypeFromSwitchStatementLabel(node.parent as CaseOrDefaultClause, usage);
break;
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
if ((<CallExpression | NewExpression>node.parent).expression === node) {
inferTypeFromCallExpression(<CallExpression | NewExpression>node.parent, usage);
if ((node.parent as CallExpression | NewExpression).expression === node) {
inferTypeFromCallExpression(node.parent as CallExpression | NewExpression, usage);
}
else {
inferTypeFromContextualType(node, usage);
}
break;
case SyntaxKind.PropertyAccessExpression:
inferTypeFromPropertyAccessExpression(<PropertyAccessExpression>node.parent, usage);
inferTypeFromPropertyAccessExpression(node.parent as PropertyAccessExpression, usage);
break;
case SyntaxKind.ElementAccessExpression:
inferTypeFromPropertyElementExpression(<ElementAccessExpression>node.parent, node, usage);
inferTypeFromPropertyElementExpression(node.parent as ElementAccessExpression, node, usage);
break;
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
inferTypeFromPropertyAssignment(<PropertyAssignment | ShorthandPropertyAssignment>node.parent, usage);
inferTypeFromPropertyAssignment(node.parent as PropertyAssignment | ShorthandPropertyAssignment, usage);
break;
case SyntaxKind.PropertyDeclaration:
inferTypeFromPropertyDeclaration(<PropertyDeclaration>node.parent, usage);
inferTypeFromPropertyDeclaration(node.parent as PropertyDeclaration, usage);
break;
case SyntaxKind.VariableDeclaration: {
const { name, initializer } = node.parent as VariableDeclaration;
@@ -1135,8 +1136,7 @@ namespace ts.codefix {
parameters.push(symbol);
}
const returnType = combineFromUsage(combineUsages(calls.map(call => call.return_)));
// TODO: GH#18217
return checker.createSignature(/*declaration*/ undefined!, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, SignatureFlags.None);
return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, SignatureFlags.None);
}
function addCandidateType(usage: Usage, type: Type | undefined) {
+1 -1
View File
@@ -173,7 +173,7 @@ namespace ts.codefix {
return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /* isFunctionType */ false);
case Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code:
if (!declaration || !isCallExpression(declaration.parent) || !declaration.body) return undefined;
const pos = declaration.parent.arguments.indexOf(<Expression>declaration);
const pos = declaration.parent.arguments.indexOf(declaration as Expression);
const type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos);
if (!type) return undefined;
return getFixInfo(checker, declaration, type, /* isFunctionType */ true);
+1 -5
View File
@@ -5,10 +5,6 @@ namespace ts.codefix {
registerCodeFix({
errorCodes,
getCodeActions: context => {
const { jsx } = context.program.getCompilerOptions();
if (jsx !== JsxEmit.React && jsx !== JsxEmit.ReactNative) {
return undefined;
}
const { sourceFile, span } = context;
const node = findNodeToFix(sourceFile, span.start);
if (!node) return undefined;
@@ -51,7 +47,7 @@ namespace ts.codefix {
let current = node;
while (true) {
if (isBinaryExpression(current) && nodeIsMissing(current.operatorToken) && current.operatorToken.kind === SyntaxKind.CommaToken) {
children.push(<JsxChild>current.left);
children.push(current.left as JsxChild);
if (isJsxChild(current.right)) {
children.push(current.right);
// Indicates the tree has go to the bottom
+101 -45
View File
@@ -1,5 +1,7 @@
/* @internal */
namespace ts.Completions {
export type Log = (message: string) => void;
export enum SortText {
LocalDeclarationPriority = "0",
LocationPriority = "1",
@@ -8,9 +10,28 @@ namespace ts.Completions {
SuggestedClassMembers = "4",
GlobalsOrKeywords = "5",
AutoImportSuggestions = "6",
JavascriptIdentifiers = "7"
JavascriptIdentifiers = "7",
DeprecatedLocalDeclarationPriority = "8",
DeprecatedLocationPriority = "9",
DeprecatedOptionalMember = "10",
DeprecatedMemberDeclaredBySpreadAssignment = "11",
DeprecatedSuggestedClassMembers = "12",
DeprecatedGlobalsOrKeywords = "13",
DeprecatedAutoImportSuggestions = "14"
}
export type Log = (message: string) => void;
enum SortTextId {
LocalDeclarationPriority,
LocationPriority,
OptionalMember,
MemberDeclaredBySpreadAssignment,
SuggestedClassMembers,
GlobalsOrKeywords,
AutoImportSuggestions
}
// for JavaScript identifiers since they are preferred over deprecated symbols
const DeprecatedSortTextStart = SortTextId.AutoImportSuggestions + 2;
/**
* Special values for `CompletionInfo['source']` used to disambiguate
@@ -105,8 +126,8 @@ namespace ts.Completions {
*/
type SymbolOriginInfoMap = Record<number, SymbolOriginInfo>;
/** Map from symbol id -> SortText. */
type SymbolSortTextMap = (SortText | undefined)[];
/** Map from symbol id -> SortTextId. */
type SymbolSortTextIdMap = (SortTextId | undefined)[];
const enum KeywordCompletionFilters {
None, // No keywords
@@ -174,6 +195,8 @@ namespace ts.Completions {
return jsdocCompletionInfo(JsDoc.getJSDocTagCompletions());
case CompletionDataKind.JsDocParameterName:
return jsdocCompletionInfo(JsDoc.getJSDocParameterNameCompletions(completionData.tag));
case CompletionDataKind.Keywords:
return specificKeywordCompletionInfo(completionData.keywords);
default:
return Debug.assertNever(completionData);
}
@@ -183,6 +206,20 @@ namespace ts.Completions {
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries };
}
function specificKeywordCompletionInfo(keywords: readonly SyntaxKind[]): CompletionInfo {
return {
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: false,
entries: keywords.map(k => ({
name: tokenToString(k)!,
kind: ScriptElementKind.keyword,
kindModifiers: ScriptElementKindModifier.none,
sortText: SortText.GlobalsOrKeywords,
})),
};
}
function getOptionalReplacementSpan(location: Node | undefined) {
// StringLiteralLike locations are handled separately in stringCompletions.ts
return location?.kind === SyntaxKind.Identifier ? createTextSpanFromNode(location) : undefined;
@@ -205,7 +242,7 @@ namespace ts.Completions {
isJsxIdentifierExpected,
importCompletionNode,
insideJsDocTagTypeExpression,
symbolToSortTextMap,
symbolToSortTextIdMap,
} = completionData;
// Verify if the file is JSX language variant
@@ -238,7 +275,7 @@ namespace ts.Completions {
importCompletionNode,
recommendedCompletion,
symbolToOriginInfoMap,
symbolToSortTextMap
symbolToSortTextIdMap
);
getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217
}
@@ -266,7 +303,7 @@ namespace ts.Completions {
importCompletionNode,
recommendedCompletion,
symbolToOriginInfoMap,
symbolToSortTextMap
symbolToSortTextIdMap
);
}
@@ -566,7 +603,7 @@ namespace ts.Completions {
importCompletionNode?: Node,
recommendedCompletion?: Symbol,
symbolToOriginInfoMap?: SymbolOriginInfoMap,
symbolToSortTextMap?: SymbolSortTextMap,
symbolToSortTextIdMap?: SymbolSortTextIdMap,
): UniqueNameSet {
const start = timestamp();
const variableDeclaration = getVariableDeclaration(location);
@@ -580,14 +617,16 @@ namespace ts.Completions {
const symbol = symbols[i];
const origin = symbolToOriginInfoMap?.[i];
const info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected);
if (!info || uniques.get(info.name) || kind === CompletionKind.Global && symbolToSortTextMap && !shouldIncludeSymbol(symbol, symbolToSortTextMap)) {
if (!info || uniques.get(info.name) || kind === CompletionKind.Global && symbolToSortTextIdMap && !shouldIncludeSymbol(symbol, symbolToSortTextIdMap)) {
continue;
}
const { name, needsConvertPropertyAccess } = info;
const sortTextId = symbolToSortTextIdMap?.[getSymbolId(symbol)] ?? SortTextId.LocationPriority;
const sortText = (isDeprecated(symbol, typeChecker) ? DeprecatedSortTextStart + sortTextId : sortTextId).toString() as SortText;
const entry = createCompletionEntry(
symbol,
symbolToSortTextMap && symbolToSortTextMap[getSymbolId(symbol)] || SortText.LocationPriority,
sortText,
contextToken,
location,
sourceFile,
@@ -623,7 +662,7 @@ namespace ts.Completions {
add: name => uniques.set(name, true),
};
function shouldIncludeSymbol(symbol: Symbol, symbolToSortTextMap: SymbolSortTextMap): boolean {
function shouldIncludeSymbol(symbol: Symbol, symbolToSortTextIdMap: SymbolSortTextIdMap): boolean {
if (!isSourceFile(location)) {
// export = /**/ here we want to get all meanings, so any symbol is ok
if (isExportAssignment(location.parent)) {
@@ -645,9 +684,9 @@ namespace ts.Completions {
// Auto Imports are not available for scripts so this conditional is always false
if (!!sourceFile.externalModuleIndicator
&& !compilerOptions.allowUmdGlobalAccess
&& symbolToSortTextMap[getSymbolId(symbol)] === SortText.GlobalsOrKeywords
&& (symbolToSortTextMap[getSymbolId(symbolOrigin)] === SortText.AutoImportSuggestions
|| symbolToSortTextMap[getSymbolId(symbolOrigin)] === SortText.LocationPriority)) {
&& symbolToSortTextIdMap[getSymbolId(symbol)] === SortTextId.GlobalsOrKeywords
&& (symbolToSortTextIdMap[getSymbolId(symbolOrigin)] === SortTextId.AutoImportSuggestions
|| symbolToSortTextIdMap[getSymbolId(symbolOrigin)] === SortTextId.LocationPriority)) {
return false;
}
// Continue with origin symbol
@@ -669,8 +708,6 @@ namespace ts.Completions {
}
}
function getLabelCompletionAtPosition(node: BreakOrContinueStatement): CompletionInfo | undefined {
const entries = getLabelStatementCompletions(node);
if (entries.length) {
@@ -802,6 +839,8 @@ namespace ts.Completions {
return JsDoc.getJSDocTagCompletionDetails(name);
case CompletionDataKind.JsDocParameterName:
return JsDoc.getJSDocParameterNameCompletionDetails(name);
case CompletionDataKind.Keywords:
return request.keywords.indexOf(stringToToken(name)!) > -1 ? createSimpleDetails(name, ScriptElementKind.keyword, SymbolDisplayPartKind.keyword) : undefined;
default:
return Debug.assertNever(request);
}
@@ -893,7 +932,7 @@ namespace ts.Completions {
return completion.type === "symbol" ? completion.symbol : undefined;
}
const enum CompletionDataKind { Data, JsDocTagName, JsDocTag, JsDocParameterName }
const enum CompletionDataKind { Data, JsDocTagName, JsDocTag, JsDocParameterName, Keywords }
/** true: after the `=` sign but no identifier has been typed yet. Else is the Identifier after the initializer. */
type IsJsxInitializer = boolean | Identifier;
interface CompletionData {
@@ -912,13 +951,16 @@ namespace ts.Completions {
readonly previousToken: Node | undefined;
readonly isJsxInitializer: IsJsxInitializer;
readonly insideJsDocTagTypeExpression: boolean;
readonly symbolToSortTextMap: SymbolSortTextMap;
readonly symbolToSortTextIdMap: SymbolSortTextIdMap;
readonly isTypeOnlyLocation: boolean;
/** In JSX tag name and attribute names, identifiers like "my-tag" or "aria-name" is valid identifier. */
readonly isJsxIdentifierExpected: boolean;
readonly importCompletionNode?: Node;
}
type Request = { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag };
type Request =
| { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag }
| { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag }
| { readonly kind: CompletionDataKind.Keywords, keywords: readonly SyntaxKind[] };
export const enum CompletionKind {
ObjectPropertyDeclaration,
@@ -1052,7 +1094,7 @@ namespace ts.Completions {
if (!currentToken ||
(!isDeclarationName(currentToken) &&
(currentToken.parent.kind !== SyntaxKind.JSDocPropertyTag ||
(<JSDocPropertyTag>currentToken.parent).name !== currentToken))) {
(currentToken.parent as JSDocPropertyTag).name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
}
@@ -1101,13 +1143,17 @@ namespace ts.Completions {
let location = getTouchingPropertyName(sourceFile, position);
if (contextToken) {
const importCompletionCandidate = getImportCompletionNode(contextToken);
if (importCompletionCandidate === SyntaxKind.FromKeyword) {
return { kind: CompletionDataKind.Keywords, keywords: [SyntaxKind.FromKeyword] };
}
// Import statement completions use `insertText`, and also require the `data` property of `CompletionEntryIdentifier`
// added in TypeScript 4.3 to be sent back from the client during `getCompletionEntryDetails`. Since this feature
// is not backward compatible with older clients, the language service defaults to disabling it, allowing newer clients
// to opt in with the `includeCompletionsForImportStatements` user preference.
importCompletionNode = preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText
? getImportCompletionNode(contextToken)
: undefined;
if (importCompletionCandidate && preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) {
importCompletionNode = importCompletionCandidate;
}
// Bail out if this is a known invalid completion location
if (!importCompletionNode && isCompletionListBlocker(contextToken)) {
log("Returning an empty list because completion was requested in an invalid position.");
@@ -1239,7 +1285,7 @@ namespace ts.Completions {
// This also gets mutated in nested-functions after the return
let symbols: Symbol[] = [];
const symbolToOriginInfoMap: SymbolOriginInfoMap = [];
const symbolToSortTextMap: SymbolSortTextMap = [];
const symbolToSortTextIdMap: SymbolSortTextIdMap = [];
const seenPropertySymbols = new Map<SymbolId, true>();
const isTypeOnly = isTypeOnlyCompletion();
const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson: boolean) => {
@@ -1258,7 +1304,7 @@ namespace ts.Completions {
keywordFilters = KeywordCompletionFilters.None;
}
else if (isStartingCloseTag) {
const tagName = (<JsxElement>contextToken.parent.parent).openingElement.tagName;
const tagName = (contextToken.parent.parent as JsxElement).openingElement.tagName;
const tagSymbol = typeChecker.getSymbolAtLocation(tagName);
if (tagSymbol) {
symbols = [tagSymbol];
@@ -1295,7 +1341,7 @@ namespace ts.Completions {
previousToken,
isJsxInitializer,
insideJsDocTagTypeExpression,
symbolToSortTextMap,
symbolToSortTextIdMap,
isTypeOnlyLocation: isTypeOnly,
isJsxIdentifierExpected,
importCompletionNode,
@@ -1337,7 +1383,7 @@ namespace ts.Completions {
// Extract module or enum members
const exportedSymbols = typeChecker.getExportsOfModule(symbol);
Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined");
const isValidValueAccess = (symbol: Symbol) => typeChecker.isValidPropertyAccess(isImportType ? <ImportTypeNode>node : <PropertyAccessExpression>(node.parent), symbol.name);
const isValidValueAccess = (symbol: Symbol) => typeChecker.isValidPropertyAccess(isImportType ? node as ImportTypeNode : (node.parent as PropertyAccessExpression), symbol.name);
const isValidTypeAccess = (symbol: Symbol) => symbolCanBeReferencedAtTypeLocation(symbol, typeChecker);
const isValidAccess: (symbol: Symbol) => boolean =
isNamespaceName
@@ -1412,7 +1458,7 @@ namespace ts.Completions {
isNewIdentifierLocation = true;
}
const propertyAccess = node.kind === SyntaxKind.ImportType ? <ImportTypeNode>node : <PropertyAccessExpression | QualifiedName>node.parent;
const propertyAccess = node.kind === SyntaxKind.ImportType ? node as ImportTypeNode : node.parent as PropertyAccessExpression | QualifiedName;
if (isUncheckedFile) {
// In javascript files, for union types, we don't just get the members that
// the individual types have in common, we also include all the members that
@@ -1484,7 +1530,7 @@ namespace ts.Completions {
function addSymbolSortInfo(symbol: Symbol) {
if (isStaticProperty(symbol)) {
symbolToSortTextMap[getSymbolId(symbol)] = SortText.LocalDeclarationPriority;
symbolToSortTextIdMap[getSymbolId(symbol)] = SortTextId.LocalDeclarationPriority;
}
}
@@ -1601,7 +1647,7 @@ namespace ts.Completions {
for (const symbol of symbols) {
if (!typeChecker.isArgumentsSymbol(symbol) &&
!some(symbol.declarations, d => d.getSourceFile() === sourceFile)) {
symbolToSortTextMap[getSymbolId(symbol)] = SortText.GlobalsOrKeywords;
symbolToSortTextIdMap[getSymbolId(symbol)] = SortTextId.GlobalsOrKeywords;
}
}
@@ -1612,7 +1658,7 @@ namespace ts.Completions {
for (const symbol of getPropertiesForCompletion(thisType, typeChecker)) {
symbolToOriginInfoMap[symbols.length] = { kind: SymbolOriginInfoKind.ThisType };
symbols.push(symbol);
symbolToSortTextMap[getSymbolId(symbol)] = SortText.SuggestedClassMembers;
symbolToSortTextIdMap[getSymbolId(symbol)] = SortTextId.SuggestedClassMembers;
}
}
}
@@ -1694,7 +1740,7 @@ namespace ts.Completions {
return false;
}
/** Mutates `symbols`, `symbolToOriginInfoMap`, and `symbolToSortTextMap` */
/** Mutates `symbols`, `symbolToOriginInfoMap`, and `symbolToSortTextIdMap` */
function collectAutoImports(resolveModuleSpecifiers: boolean) {
if (!shouldOfferImportCompletions()) return;
Debug.assert(!detailsEntryId?.data);
@@ -1765,12 +1811,12 @@ namespace ts.Completions {
function pushAutoImportSymbol(symbol: Symbol, origin: SymbolOriginInfoResolvedExport | SymbolOriginInfoExport) {
const symbolId = getSymbolId(symbol);
if (symbolToSortTextMap[symbolId] === SortText.GlobalsOrKeywords) {
if (symbolToSortTextIdMap[symbolId] === SortTextId.GlobalsOrKeywords) {
// If an auto-importable symbol is available as a global, don't add the auto import
return;
}
symbolToOriginInfoMap[symbols.length] = origin;
symbolToSortTextMap[symbolId] = importCompletionNode ? SortText.LocationPriority : SortText.AutoImportSuggestions;
symbolToSortTextIdMap[symbolId] = importCompletionNode ? SortTextId.LocationPriority : SortTextId.AutoImportSuggestions;
symbols.push(symbol);
}
@@ -1998,10 +2044,10 @@ namespace ts.Completions {
let canGetType = hasInitializer(rootDeclaration) || hasType(rootDeclaration) || rootDeclaration.parent.parent.kind === SyntaxKind.ForOfStatement;
if (!canGetType && rootDeclaration.kind === SyntaxKind.Parameter) {
if (isExpression(rootDeclaration.parent)) {
canGetType = !!typeChecker.getContextualType(<Expression>rootDeclaration.parent);
canGetType = !!typeChecker.getContextualType(rootDeclaration.parent as Expression);
}
else if (rootDeclaration.parent.kind === SyntaxKind.MethodDeclaration || rootDeclaration.parent.kind === SyntaxKind.SetAccessor) {
canGetType = isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(<Expression>rootDeclaration.parent.parent);
canGetType = isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent as Expression);
}
}
if (canGetType) {
@@ -2085,7 +2131,7 @@ namespace ts.Completions {
localsContainer.locals?.forEach((symbol, name) => {
symbols.push(symbol);
if (localsContainer.symbol?.exports?.has(name)) {
symbolToSortTextMap[getSymbolId(symbol)] = SortText.OptionalMember;
symbolToSortTextIdMap[getSymbolId(symbol)] = SortTextId.OptionalMember;
}
});
return GlobalsSearch.Success;
@@ -2227,7 +2273,7 @@ namespace ts.Completions {
const precedingToken = findPrecedingToken(contextToken.pos, sourceFile, /*startNode*/ undefined);
if (!(parent as JsxOpeningLikeElement).typeArguments || (precedingToken && precedingToken.kind === SyntaxKind.SlashToken)) break;
}
return <JsxOpeningLikeElement>parent;
return parent as JsxOpeningLikeElement;
}
else if (parent.kind === SyntaxKind.JsxAttribute) {
// Currently we parse JsxOpeningLikeElement as:
@@ -2521,7 +2567,7 @@ namespace ts.Completions {
const expression = declaration.expression;
const symbol = typeChecker.getSymbolAtLocation(expression);
const type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, expression);
const properties = type && (<ObjectType>type).properties;
const properties = type && (type as ObjectType).properties;
if (properties) {
properties.forEach(property => {
membersDeclaredBySpreadAssignment.add(property.name);
@@ -2533,7 +2579,8 @@ namespace ts.Completions {
function setSortTextToOptionalMember() {
symbols.forEach(m => {
if (m.flags & SymbolFlags.Optional) {
symbolToSortTextMap[getSymbolId(m)] = symbolToSortTextMap[getSymbolId(m)] || SortText.OptionalMember;
const symbolId = getSymbolId(m);
symbolToSortTextIdMap[symbolId] = symbolToSortTextIdMap[symbolId] ?? SortTextId.OptionalMember;
}
});
}
@@ -2545,7 +2592,7 @@ namespace ts.Completions {
}
for (const contextualMemberSymbol of contextualMemberSymbols) {
if (membersDeclaredBySpreadAssignment.has(contextualMemberSymbol.name)) {
symbolToSortTextMap[getSymbolId(contextualMemberSymbol)] = SortText.MemberDeclaredBySpreadAssignment;
symbolToSortTextIdMap[getSymbolId(contextualMemberSymbol)] = SortTextId.MemberDeclaredBySpreadAssignment;
}
}
}
@@ -3041,7 +3088,7 @@ namespace ts.Completions {
function getImportCompletionNode(contextToken: Node) {
const candidate = getCandidate();
return candidate && rangeIsOnSingleLine(candidate, candidate.getSourceFile()) ? candidate : undefined;
return candidate === SyntaxKind.FromKeyword || candidate && rangeIsOnSingleLine(candidate, candidate.getSourceFile()) ? candidate : undefined;
function getCandidate() {
const parent = contextToken.parent;
@@ -3049,9 +3096,13 @@ namespace ts.Completions {
return isModuleSpecifierMissingOrEmpty(parent.moduleReference) ? parent : undefined;
}
if (isNamedImports(parent) || isNamespaceImport(parent)) {
return isModuleSpecifierMissingOrEmpty(parent.parent.parent.moduleSpecifier) && (isNamespaceImport(parent) || parent.elements.length < 2) && !parent.parent.name
? parent.parent.parent
: undefined;
if (isModuleSpecifierMissingOrEmpty(parent.parent.parent.moduleSpecifier) && (isNamespaceImport(parent) || parent.elements.length < 2) && !parent.parent.name) {
// At `import { ... } |` or `import * as Foo |`, the only possible completion is `from`
return contextToken.kind === SyntaxKind.CloseBraceToken || contextToken.kind === SyntaxKind.Identifier
? SyntaxKind.FromKeyword
: parent.parent.parent;
}
return undefined;
}
if (isImportKeyword(contextToken) && isSourceFile(parent)) {
// A lone import keyword with nothing following it does not parse as a statement at all
@@ -3091,4 +3142,9 @@ namespace ts.Completions {
addToSeen(seenModules, getSymbolId(sym)) &&
checker.getExportsOfModule(sym).some(e => symbolCanBeReferencedAtTypeLocation(e, checker, seenModules));
}
function isDeprecated(symbol: Symbol, checker: TypeChecker) {
const declarations = skipAlias(symbol, checker).declarations;
return !!length(declarations) && every(declarations, isDeprecatedDeclaration);
}
}
+5 -5
View File
@@ -296,9 +296,9 @@ namespace ts {
case SyntaxKind.ForOfStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
return getLoopBreakContinueOccurrences(<IterationStatement>owner);
return getLoopBreakContinueOccurrences(owner as IterationStatement);
case SyntaxKind.SwitchStatement:
return getSwitchCaseDefaultOccurrences(<SwitchStatement>owner);
return getSwitchCaseDefaultOccurrences(owner as SwitchStatement);
}
}
@@ -358,7 +358,7 @@ namespace ts {
// If the "owner" is a function, then we equate 'return' and 'throw' statements in their
// ability to "jump out" of the function, and include occurrences for both.
if (isFunctionBlock(owner)) {
forEachReturnStatement(<Block>owner, returnStatement => {
forEachReturnStatement(owner as Block, returnStatement => {
keywords.push(findChildOfKind(returnStatement, SyntaxKind.ReturnKeyword, sourceFile)!);
});
}
@@ -367,7 +367,7 @@ namespace ts {
}
function getReturnOccurrences(returnStatement: ReturnStatement, sourceFile: SourceFile): Node[] | undefined {
const func = <FunctionLikeDeclaration>getContainingFunction(returnStatement);
const func = getContainingFunction(returnStatement) as FunctionLikeDeclaration;
if (!func) {
return undefined;
}
@@ -386,7 +386,7 @@ namespace ts {
}
function getAsyncAndAwaitOccurrences(node: Node): Node[] | undefined {
const func = <FunctionLikeDeclaration>getContainingFunction(node);
const func = getContainingFunction(node) as FunctionLikeDeclaration;
if (!func) {
return undefined;
}
+14 -10
View File
@@ -1218,7 +1218,7 @@ namespace ts.FindAllReferences {
function getPropertySymbolOfDestructuringAssignment(location: Node, checker: TypeChecker): Symbol | undefined {
return isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent)
? checker.getPropertySymbolOfDestructuringAssignment(<Identifier>location)
? checker.getPropertySymbolOfDestructuringAssignment(location as Identifier)
: undefined;
}
@@ -1278,7 +1278,7 @@ namespace ts.FindAllReferences {
return undefined;
}
if (!container || container.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(<SourceFile>container)) {
if (!container || container.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(container as SourceFile)) {
// This is a global variable and not an external module, any declaration defined
// within this scope is visible outside the file
return undefined;
@@ -1401,6 +1401,10 @@ namespace ts.FindAllReferences {
// Compare the length so we filter out strict superstrings of the symbol we are looking for
switch (node.kind) {
case SyntaxKind.PrivateIdentifier:
if (isJSDocMemberName(node.parent)) {
return true;
}
// falls through I guess
case SyntaxKind.Identifier:
return (node as PrivateIdentifier | Identifier).text.length === searchSymbolName.length;
case SyntaxKind.NoSubstitutionTemplateLiteral:
@@ -1710,7 +1714,7 @@ namespace ts.FindAllReferences {
classSymbol.exports.forEach(member => {
const decl = member.valueDeclaration;
if (decl && decl.kind === SyntaxKind.MethodDeclaration) {
const body = (<MethodDeclaration>decl).body;
const body = (decl as MethodDeclaration).body;
if (body) {
forEachDescendantOfKind(body, SyntaxKind.ThisKeyword, thisKeyword => {
if (isNewExpressionTarget(thisKeyword)) {
@@ -1736,7 +1740,7 @@ namespace ts.FindAllReferences {
for (const decl of constructor.declarations) {
Debug.assert(decl.kind === SyntaxKind.Constructor);
const body = (<ConstructorDeclaration>decl).body;
const body = (decl as ConstructorDeclaration).body;
if (body) {
forEachDescendantOfKind(body, SyntaxKind.SuperKeyword, node => {
if (isCallExpressionTarget(node)) {
@@ -1792,7 +1796,7 @@ namespace ts.FindAllReferences {
else if (isFunctionLike(typeHavingNode) && (typeHavingNode as FunctionLikeDeclaration).body) {
const body = (typeHavingNode as FunctionLikeDeclaration).body!;
if (body.kind === SyntaxKind.Block) {
forEachReturnStatement(<Block>body, returnStatement => {
forEachReturnStatement(body as Block, returnStatement => {
if (returnStatement.expression) addIfImplementation(returnStatement.expression);
});
}
@@ -1821,7 +1825,7 @@ namespace ts.FindAllReferences {
function isImplementationExpression(node: Expression): boolean {
switch (node.kind) {
case SyntaxKind.ParenthesizedExpression:
return isImplementationExpression((<ParenthesizedExpression>node).expression);
return isImplementationExpression((node as ParenthesizedExpression).expression);
case SyntaxKind.ArrowFunction:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ObjectLiteralExpression:
@@ -1916,7 +1920,7 @@ namespace ts.FindAllReferences {
}
function isParameterName(node: Node) {
return node.kind === SyntaxKind.Identifier && node.parent.kind === SyntaxKind.Parameter && (<ParameterDeclaration>node.parent).name === node;
return node.kind === SyntaxKind.Identifier && node.parent.kind === SyntaxKind.Parameter && (node.parent as ParameterDeclaration).name === node;
}
function getReferencesForThisKeyword(thisOrSuperKeyword: Node, sourceFiles: readonly SourceFile[], cancellationToken: CancellationToken): SymbolAndEntries[] | undefined {
@@ -1943,7 +1947,7 @@ namespace ts.FindAllReferences {
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
case SyntaxKind.SourceFile:
if (isExternalModule(<SourceFile>searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
if (isExternalModule(searchSpaceNode as SourceFile) || isParameterName(thisOrSuperKeyword)) {
return undefined;
}
// falls through
@@ -1977,7 +1981,7 @@ namespace ts.FindAllReferences {
// and has the appropriate static modifier from the original container.
return container.parent && searchSpaceNode.symbol === container.parent.symbol && (getSyntacticModifierFlags(container) & ModifierFlags.Static) === staticFlag;
case SyntaxKind.SourceFile:
return container.kind === SyntaxKind.SourceFile && !isExternalModule(<SourceFile>container) && !isParameterName(node);
return container.kind === SyntaxKind.SourceFile && !isExternalModule(container as SourceFile) && !isParameterName(node);
}
});
}).map(n => nodeEntry(n));
@@ -2292,7 +2296,7 @@ namespace ts.FindAllReferences {
* being accessed (i.e. it is declared in some parent class or interface)
*/
function getParentSymbolsOfPropertyAccess(location: Node, symbol: Symbol, checker: TypeChecker): readonly Symbol[] | undefined {
const propertyAccessExpression = isRightSideOfPropertyAccess(location) ? <PropertyAccessExpression>location.parent : undefined;
const propertyAccessExpression = isRightSideOfPropertyAccess(location) ? location.parent as PropertyAccessExpression : undefined;
const lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression);
const res = mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), t =>
t.symbol && t.symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? t.symbol : undefined);
+11 -11
View File
@@ -201,16 +201,16 @@ namespace ts.formatting {
switch (parent.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
return rangeContainsRange((<InterfaceDeclaration>parent).members, node);
return rangeContainsRange((parent as InterfaceDeclaration).members, node);
case SyntaxKind.ModuleDeclaration:
const body = (<ModuleDeclaration>parent).body;
const body = (parent as ModuleDeclaration).body;
return !!body && body.kind === SyntaxKind.ModuleBlock && rangeContainsRange(body.statements, node);
case SyntaxKind.SourceFile:
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
return rangeContainsRange((<Block>parent).statements, node);
return rangeContainsRange((parent as Block).statements, node);
case SyntaxKind.CatchClause:
return rangeContainsRange((<CatchClause>parent).block.statements, node);
return rangeContainsRange((parent as CatchClause).block.statements, node);
}
return false;
@@ -531,14 +531,14 @@ namespace ts.formatting {
case SyntaxKind.GetAccessor: return SyntaxKind.GetKeyword;
case SyntaxKind.SetAccessor: return SyntaxKind.SetKeyword;
case SyntaxKind.MethodDeclaration:
if ((<MethodDeclaration>node).asteriskToken) {
if ((node as MethodDeclaration).asteriskToken) {
return SyntaxKind.AsteriskToken;
}
// falls through
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.Parameter:
const name = getNameOfDeclaration(<Declaration>node);
const name = getNameOfDeclaration(node as Declaration);
if (name) {
return name.kind;
}
@@ -1277,24 +1277,24 @@ namespace ts.formatting {
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.ArrowFunction:
if ((<FunctionDeclaration>node).typeParameters === list) {
if ((node as FunctionDeclaration).typeParameters === list) {
return SyntaxKind.LessThanToken;
}
else if ((<FunctionDeclaration>node).parameters === list) {
else if ((node as FunctionDeclaration).parameters === list) {
return SyntaxKind.OpenParenToken;
}
break;
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
if ((<CallExpression>node).typeArguments === list) {
if ((node as CallExpression).typeArguments === list) {
return SyntaxKind.LessThanToken;
}
else if ((<CallExpression>node).arguments === list) {
else if ((node as CallExpression).arguments === list) {
return SyntaxKind.OpenParenToken;
}
break;
case SyntaxKind.TypeReference:
if ((<TypeReferenceNode>node).typeArguments === list) {
if ((node as TypeReferenceNode).typeArguments === list) {
return SyntaxKind.LessThanToken;
}
break;
+2 -2
View File
@@ -440,7 +440,7 @@ namespace ts.formatting {
function isBinaryOpContext(context: FormattingContext): boolean {
switch (context.contextNode.kind) {
case SyntaxKind.BinaryExpression:
return (<BinaryExpression>context.contextNode).operatorToken.kind !== SyntaxKind.CommaToken;
return (context.contextNode as BinaryExpression).operatorToken.kind !== SyntaxKind.CommaToken;
case SyntaxKind.ConditionalExpression:
case SyntaxKind.ConditionalType:
case SyntaxKind.AsExpression:
@@ -796,7 +796,7 @@ namespace ts.formatting {
}
function isYieldOrYieldStarWithOperand(context: FormattingContext): boolean {
return context.contextNode.kind === SyntaxKind.YieldExpression && (<YieldExpression>context.contextNode).expression !== undefined;
return context.contextNode.kind === SyntaxKind.YieldExpression && (context.contextNode as YieldExpression).expression !== undefined;
}
function isNonNullAssertionContext(context: FormattingContext): boolean {
+12 -12
View File
@@ -330,7 +330,7 @@ namespace ts.formatting {
}
export function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFileLike): boolean {
if (parent.kind === SyntaxKind.IfStatement && (<IfStatement>parent).elseStatement === child) {
if (parent.kind === SyntaxKind.IfStatement && (parent as IfStatement).elseStatement === child) {
const elseKeyword = findChildOfKind(parent, SyntaxKind.ElseKeyword, sourceFile)!;
Debug.assert(elseKeyword !== undefined);
@@ -415,13 +415,13 @@ namespace ts.formatting {
function getListByRange(start: number, end: number, node: Node, sourceFile: SourceFile): NodeArray<Node> | undefined {
switch (node.kind) {
case SyntaxKind.TypeReference:
return getList((<TypeReferenceNode>node).typeArguments);
return getList((node as TypeReferenceNode).typeArguments);
case SyntaxKind.ObjectLiteralExpression:
return getList((<ObjectLiteralExpression>node).properties);
return getList((node as ObjectLiteralExpression).properties);
case SyntaxKind.ArrayLiteralExpression:
return getList((<ArrayLiteralExpression>node).elements);
return getList((node as ArrayLiteralExpression).elements);
case SyntaxKind.TypeLiteral:
return getList((<TypeLiteralNode>node).members);
return getList((node as TypeLiteralNode).members);
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
@@ -431,24 +431,24 @@ namespace ts.formatting {
case SyntaxKind.Constructor:
case SyntaxKind.ConstructorType:
case SyntaxKind.ConstructSignature:
return getList((<SignatureDeclaration>node).typeParameters) || getList((<SignatureDeclaration>node).parameters);
return getList((node as SignatureDeclaration).typeParameters) || getList((node as SignatureDeclaration).parameters);
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.JSDocTemplateTag:
return getList((<ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag>node).typeParameters);
return getList((node as ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag).typeParameters);
case SyntaxKind.NewExpression:
case SyntaxKind.CallExpression:
return getList((<CallExpression>node).typeArguments) || getList((<CallExpression>node).arguments);
return getList((node as CallExpression).typeArguments) || getList((node as CallExpression).arguments);
case SyntaxKind.VariableDeclarationList:
return getList((<VariableDeclarationList>node).declarations);
return getList((node as VariableDeclarationList).declarations);
case SyntaxKind.NamedImports:
case SyntaxKind.NamedExports:
return getList((<NamedImportsOrExports>node).elements);
return getList((node as NamedImportsOrExports).elements);
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
return getList((<ObjectBindingPattern | ArrayBindingPattern>node).elements);
return getList((node as ObjectBindingPattern | ArrayBindingPattern).elements);
}
function getList(list: NodeArray<Node> | undefined): NodeArray<Node> | undefined {
@@ -632,7 +632,7 @@ namespace ts.formatting {
return childKind !== SyntaxKind.NamedExports;
case SyntaxKind.ImportDeclaration:
return childKind !== SyntaxKind.ImportClause ||
(!!(<ImportClause>child).namedBindings && (<ImportClause>child).namedBindings!.kind !== SyntaxKind.NamedImports);
(!!(child as ImportClause).namedBindings && (child as ImportClause).namedBindings!.kind !== SyntaxKind.NamedImports);
case SyntaxKind.JsxElement:
return childKind !== SyntaxKind.JsxClosingElement;
case SyntaxKind.JsxFragment:
+1 -1
View File
@@ -290,7 +290,7 @@ namespace ts.GoToDefinition {
return undefined;
}
const declarations = signatureDeclarations.filter(selectConstructors ? isConstructorDeclaration : isFunctionLike);
const declarationsWithBody = declarations.filter(d => !!(<FunctionLikeDeclaration>d).body);
const declarationsWithBody = declarations.filter(d => !!(d as FunctionLikeDeclaration).body);
// declarations defined on the global scope can be defined on multiple files. Get all of them.
return declarations.length
+4 -4
View File
@@ -131,7 +131,7 @@ namespace ts.JsDoc {
return tags;
}
function getDisplayPartsFromComment(comment: string | readonly (JSDocText | JSDocLink)[], checker: TypeChecker | undefined): SymbolDisplayPart[] {
function getDisplayPartsFromComment(comment: string | readonly JSDocComment[], checker: TypeChecker | undefined): SymbolDisplayPart[] {
if (typeof comment === "string") {
return [textPart(comment)];
}
@@ -394,7 +394,7 @@ namespace ts.JsDoc {
return { commentOwner };
case SyntaxKind.VariableStatement: {
const varStatement = <VariableStatement>commentOwner;
const varStatement = commentOwner as VariableStatement;
const varDeclarations = varStatement.declarationList.declarations;
const host = varDeclarations.length === 1 && varDeclarations[0].initializer
? getRightHandSideOfAssignment(varDeclarations[0].initializer)
@@ -440,13 +440,13 @@ namespace ts.JsDoc {
function getRightHandSideOfAssignment(rightHandSide: Expression): FunctionExpression | ArrowFunction | ConstructorDeclaration | undefined {
while (rightHandSide.kind === SyntaxKind.ParenthesizedExpression) {
rightHandSide = (<ParenthesizedExpression>rightHandSide).expression;
rightHandSide = (rightHandSide as ParenthesizedExpression).expression;
}
switch (rightHandSide.kind) {
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
return (<FunctionExpression>rightHandSide);
return (rightHandSide as FunctionExpression);
case SyntaxKind.ClassExpression:
return find((rightHandSide as ClassExpression).members, isConstructorDeclaration);
}
+1 -1
View File
@@ -129,7 +129,7 @@ namespace ts.NavigateTo {
fileName: rawItem.fileName,
textSpan: createTextSpanFromNode(declaration),
// TODO(jfreeman): What should be the containerName when the container has a computed name?
containerName: containerName ? (<Identifier>containerName).text : "",
containerName: containerName ? (containerName as Identifier).text : "",
containerKind: containerName ? getNodeKind(container!) : ScriptElementKind.unknown, // TODO: GH#18217 Just use `container ? ...`
};
}
+29 -29
View File
@@ -220,7 +220,7 @@ namespace ts.NavigationBar {
switch (node.kind) {
case SyntaxKind.Constructor:
// Get parameter properties, and treat them as being on the *same* level as the constructor, not under it.
const ctr = <ConstructorDeclaration>node;
const ctr = node as ConstructorDeclaration;
addNodeWithRecursiveChild(ctr, ctr.body);
// Parameter properties are children of the class, not the constructor.
@@ -235,24 +235,24 @@ namespace ts.NavigationBar {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.MethodSignature:
if (hasNavigationBarName((<ClassElement | TypeElement>node))) {
addNodeWithRecursiveChild(node, (<FunctionLikeDeclaration>node).body);
if (hasNavigationBarName(node as ClassElement | TypeElement)) {
addNodeWithRecursiveChild(node, (node as FunctionLikeDeclaration).body);
}
break;
case SyntaxKind.PropertyDeclaration:
if (hasNavigationBarName(<ClassElement>node)) {
addNodeWithRecursiveInitializer(<PropertyDeclaration>node);
if (hasNavigationBarName(node as ClassElement)) {
addNodeWithRecursiveInitializer(node as PropertyDeclaration);
}
break;
case SyntaxKind.PropertySignature:
if (hasNavigationBarName(<TypeElement>node)) {
if (hasNavigationBarName(node as TypeElement)) {
addLeafNode(node);
}
break;
case SyntaxKind.ImportClause:
const importClause = <ImportClause>node;
const importClause = node as ImportClause;
// Handle default import case e.g.:
// import d from "mod";
if (importClause.name) {
@@ -276,17 +276,17 @@ namespace ts.NavigationBar {
break;
case SyntaxKind.ShorthandPropertyAssignment:
addNodeWithRecursiveChild(node, (<ShorthandPropertyAssignment>node).name);
addNodeWithRecursiveChild(node, (node as ShorthandPropertyAssignment).name);
break;
case SyntaxKind.SpreadAssignment:
const { expression } = <SpreadAssignment>node;
const { expression } = node as SpreadAssignment;
// Use the expression as the name of the SpreadAssignment, otherwise show as <unknown>.
isIdentifier(expression) ? addLeafNode(node, expression) : addLeafNode(node);
break;
case SyntaxKind.BindingElement:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.VariableDeclaration: {
const child = <VariableDeclaration | PropertyAssignment | BindingElement>node;
const child = node as VariableDeclaration | PropertyAssignment | BindingElement;
if (isBindingPattern(child.name)) {
addChildrenRecursively(child.name);
}
@@ -296,21 +296,21 @@ namespace ts.NavigationBar {
break;
}
case SyntaxKind.FunctionDeclaration:
const nameNode = (<FunctionLikeDeclaration>node).name;
const nameNode = (node as FunctionLikeDeclaration).name;
// If we see a function declaration track as a possible ES5 class
if (nameNode && isIdentifier(nameNode)) {
addTrackedEs5Class(nameNode.text);
}
addNodeWithRecursiveChild(node, (<FunctionLikeDeclaration>node).body);
addNodeWithRecursiveChild(node, (node as FunctionLikeDeclaration).body);
break;
case SyntaxKind.ArrowFunction:
case SyntaxKind.FunctionExpression:
addNodeWithRecursiveChild(node, (<FunctionLikeDeclaration>node).body);
addNodeWithRecursiveChild(node, (node as FunctionLikeDeclaration).body);
break;
case SyntaxKind.EnumDeclaration:
startNode(node);
for (const member of (<EnumDeclaration>node).members) {
for (const member of (node as EnumDeclaration).members) {
if (!isComputedProperty(member)) {
addLeafNode(member);
}
@@ -322,18 +322,18 @@ namespace ts.NavigationBar {
case SyntaxKind.ClassExpression:
case SyntaxKind.InterfaceDeclaration:
startNode(node);
for (const member of (<InterfaceDeclaration>node).members) {
for (const member of (node as InterfaceDeclaration).members) {
addChildrenRecursively(member);
}
endNode();
break;
case SyntaxKind.ModuleDeclaration:
addNodeWithRecursiveChild(node, getInteriorModule(<ModuleDeclaration>node).body);
addNodeWithRecursiveChild(node, getInteriorModule(node as ModuleDeclaration).body);
break;
case SyntaxKind.ExportAssignment: {
const expression = (<ExportAssignment>node).expression;
const expression = (node as ExportAssignment).expression;
const child = isObjectLiteralExpression(expression) || isCallExpression(expression) ? expression :
isArrowFunction(expression) || isFunctionExpression(expression) ? expression.body : undefined;
if (child) {
@@ -469,7 +469,7 @@ namespace ts.NavigationBar {
function mergeChildren(children: NavigationBarNode[], node: NavigationBarNode): void {
const nameToItems = new Map<string, NavigationBarNode | NavigationBarNode[]>();
filterMutate(children, (child, index) => {
const declName = child.name || getNameOfDeclaration(<Declaration>child.node);
const declName = child.name || getNameOfDeclaration(child.node as Declaration);
const name = declName && nodeText(declName);
if (!name) {
// Anonymous items are never merged.
@@ -629,8 +629,8 @@ namespace ts.NavigationBar {
case SyntaxKind.SetAccessor:
return hasSyntacticModifier(a, ModifierFlags.Static) === hasSyntacticModifier(b, ModifierFlags.Static);
case SyntaxKind.ModuleDeclaration:
return areSameModule(<ModuleDeclaration>a, <ModuleDeclaration>b)
&& getFullyQualifiedModuleName(<ModuleDeclaration>a) === getFullyQualifiedModuleName(<ModuleDeclaration>b);
return areSameModule(a as ModuleDeclaration, b as ModuleDeclaration)
&& getFullyQualifiedModuleName(a as ModuleDeclaration) === getFullyQualifiedModuleName(b as ModuleDeclaration);
default:
return true;
}
@@ -650,7 +650,7 @@ namespace ts.NavigationBar {
// We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes.
// Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'!
function areSameModule(a: ModuleDeclaration, b: ModuleDeclaration): boolean {
return a.body!.kind === b.body!.kind && (a.body!.kind !== SyntaxKind.ModuleDeclaration || areSameModule(<ModuleDeclaration>a.body, <ModuleDeclaration>b.body));
return a.body!.kind === b.body!.kind && (a.body!.kind !== SyntaxKind.ModuleDeclaration || areSameModule(a.body as ModuleDeclaration, b.body as ModuleDeclaration));
}
/** Merge source into target. Source should be thrown away after this is called. */
@@ -685,10 +685,10 @@ namespace ts.NavigationBar {
*/
function tryGetName(node: Node): string | undefined {
if (node.kind === SyntaxKind.ModuleDeclaration) {
return getModuleName(<ModuleDeclaration>node);
return getModuleName(node as ModuleDeclaration);
}
const declName = getNameOfDeclaration(<Declaration>node);
const declName = getNameOfDeclaration(node as Declaration);
if (declName && isPropertyName(declName)) {
const propertyName = getPropertyNameForPropertyNameNode(declName);
return propertyName && unescapeLeadingUnderscores(propertyName);
@@ -697,7 +697,7 @@ namespace ts.NavigationBar {
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.ClassExpression:
return getFunctionOrClassName(<FunctionExpression | ArrowFunction | ClassExpression>node);
return getFunctionOrClassName(node as FunctionExpression | ArrowFunction | ClassExpression);
default:
return undefined;
}
@@ -705,7 +705,7 @@ namespace ts.NavigationBar {
function getItemName(node: Node, name: Node | undefined): string {
if (node.kind === SyntaxKind.ModuleDeclaration) {
return cleanText(getModuleName(<ModuleDeclaration>node));
return cleanText(getModuleName(node as ModuleDeclaration));
}
if (name) {
@@ -719,7 +719,7 @@ namespace ts.NavigationBar {
switch (node.kind) {
case SyntaxKind.SourceFile:
const sourceFile = <SourceFile>node;
const sourceFile = node as SourceFile;
return isExternalModule(sourceFile)
? `"${escapeString(getBaseFileName(removeFileExtension(normalizePath(sourceFile.fileName))))}"`
: "<global>";
@@ -737,7 +737,7 @@ namespace ts.NavigationBar {
// We may get a string with newlines or other whitespace in the case of an object dereference
// (eg: "app\n.onactivated"), so we should remove the whitespace for readability in the
// navigation bar.
return getFunctionOrClassName(<ArrowFunction | FunctionExpression | ClassExpression>node);
return getFunctionOrClassName(node as ArrowFunction | FunctionExpression | ClassExpression);
case SyntaxKind.Constructor:
return "constructor";
case SyntaxKind.ConstructSignature:
@@ -799,7 +799,7 @@ namespace ts.NavigationBar {
return false;
}
function isTopLevelFunctionDeclaration(item: NavigationBarNode): boolean {
if (!(<FunctionDeclaration>item.node).body) {
if (!(item.node as FunctionDeclaration).body) {
return false;
}
@@ -876,7 +876,7 @@ namespace ts.NavigationBar {
// Otherwise, we need to aggregate each identifier to build up the qualified name.
const result = [getTextOfIdentifierOrLiteral(moduleDeclaration.name)];
while (moduleDeclaration.body && moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) {
moduleDeclaration = <ModuleDeclaration>moduleDeclaration.body;
moduleDeclaration = moduleDeclaration.body;
result.push(getTextOfIdentifierOrLiteral(moduleDeclaration.name));
}
return result.join(".");
+7 -7
View File
@@ -170,7 +170,7 @@ namespace ts.OutliningElementsCollector {
return spanForNode(n.parent);
case SyntaxKind.TryStatement:
// Could be the try-block, or the finally-block.
const tryStatement = <TryStatement>n.parent;
const tryStatement = n.parent as TryStatement;
if (tryStatement.tryBlock === n) {
return spanForNode(n.parent);
}
@@ -204,21 +204,21 @@ namespace ts.OutliningElementsCollector {
case SyntaxKind.ArrayLiteralExpression:
return spanForObjectOrArrayLiteral(n, SyntaxKind.OpenBracketToken);
case SyntaxKind.JsxElement:
return spanForJSXElement(<JsxElement>n);
return spanForJSXElement(n as JsxElement);
case SyntaxKind.JsxFragment:
return spanForJSXFragment(<JsxFragment>n);
return spanForJSXFragment(n as JsxFragment);
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
return spanForJSXAttributes((<JsxOpeningLikeElement>n).attributes);
return spanForJSXAttributes((n as JsxOpeningLikeElement).attributes);
case SyntaxKind.TemplateExpression:
case SyntaxKind.NoSubstitutionTemplateLiteral:
return spanForTemplateLiteral(<TemplateExpression | NoSubstitutionTemplateLiteral>n);
return spanForTemplateLiteral(n as TemplateExpression | NoSubstitutionTemplateLiteral);
case SyntaxKind.ArrayBindingPattern:
return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !isBindingElement(n.parent), SyntaxKind.OpenBracketToken);
case SyntaxKind.ArrowFunction:
return spanForArrowFunction(<ArrowFunction>n);
return spanForArrowFunction(n as ArrowFunction);
case SyntaxKind.CallExpression:
return spanForCallExpression(<CallExpression>n);
return spanForCallExpression(n as CallExpression);
}
function spanForCallExpression(node: CallExpression): OutliningSpan | undefined {
+14 -5
View File
@@ -57,7 +57,7 @@ namespace ts.refactor {
};
function getInfo(context: RefactorContext, considerPartialSpans = true): ExportInfo | RefactorErrorInfo | undefined {
const { file } = context;
const { file, program } = context;
const span = getRefactorContextSpan(context);
const token = getTokenAtPosition(file, span.start);
const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & ModifierFlags.Export) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span);
@@ -75,6 +75,11 @@ namespace ts.refactor {
return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) };
}
const checker = program.getTypeChecker();
const noSymbolError = (id: Node) =>
(isIdentifier(id) && checker.getSymbolAtLocation(id)) ? undefined
: { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) };
switch (exportNode.kind) {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ClassDeclaration:
@@ -83,7 +88,9 @@ namespace ts.refactor {
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.ModuleDeclaration: {
const node = exportNode as FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | EnumDeclaration | TypeAliasDeclaration | NamespaceDeclaration;
return node.name && isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol } : undefined;
if (!node.name) return undefined;
return noSymbolError(node.name)
|| { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol };
}
case SyntaxKind.VariableStatement: {
const vs = exportNode as VariableStatement;
@@ -94,12 +101,14 @@ namespace ts.refactor {
const decl = first(vs.declarationList.declarations);
if (!decl.initializer) return undefined;
Debug.assert(!wasDefault, "Can't have a default flag here");
return isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol } : undefined;
return noSymbolError(decl.name)
|| { exportNode: vs, exportName: decl.name as Identifier, wasDefault, exportingModuleSymbol };
}
case SyntaxKind.ExportAssignment: {
const node = exportNode as ExportAssignment;
const exp = node.expression as Identifier;
return node.isExportEquals ? undefined : { exportNode: node, exportName: exp, wasDefault, exportingModuleSymbol };
if (node.isExportEquals) return undefined;
return noSymbolError(node.expression)
|| { exportNode: node, exportName: node.expression as Identifier, wasDefault, exportingModuleSymbol };
}
default:
return undefined;
@@ -220,7 +220,7 @@ namespace ts.refactor.convertParamsToDestructuredObject {
function getSymbolForContextualType(node: Node, checker: TypeChecker): Symbol | undefined {
const element = getContainingObjectLiteralElement(node);
if (element) {
const contextualType = checker.getContextualTypeForObjectLiteralElement(<ObjectLiteralElementLike>element);
const contextualType = checker.getContextualTypeForObjectLiteralElement(element as ObjectLiteralElementLike);
const symbol = contextualType?.getSymbol();
if (symbol && !(getCheckFlags(symbol) & CheckFlags.Synthetic)) {
return symbol;
+6 -6
View File
@@ -539,7 +539,7 @@ namespace ts.refactor.extractSymbol {
permittedJumps = PermittedJumps.None;
break;
case SyntaxKind.Block:
if (node.parent && node.parent.kind === SyntaxKind.TryStatement && (<TryStatement>node.parent).finallyBlock === node) {
if (node.parent && node.parent.kind === SyntaxKind.TryStatement && (node.parent as TryStatement).finallyBlock === node) {
// allow unconditional returns from finally blocks
permittedJumps = PermittedJumps.Return;
}
@@ -563,7 +563,7 @@ namespace ts.refactor.extractSymbol {
rangeFacts |= RangeFacts.UsesThis;
break;
case SyntaxKind.LabeledStatement: {
const label = (<LabeledStatement>node).label;
const label = (node as LabeledStatement).label;
(seenLabels || (seenLabels = [])).push(label.escapedText);
forEachChild(node, visit);
seenLabels.pop();
@@ -571,7 +571,7 @@ namespace ts.refactor.extractSymbol {
}
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement: {
const label = (<BreakStatement | ContinueStatement>node).label;
const label = (node as BreakStatement | ContinueStatement).label;
if (label) {
if (!contains(seenLabels, label.escapedText)) {
// attempts to jump to label that is not in range to be extracted
@@ -1376,7 +1376,7 @@ namespace ts.refactor.extractSymbol {
}
let returnValueProperty: string | undefined;
let ignoreReturns = false;
const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : factory.createReturnStatement(<Expression>body)]);
const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : factory.createReturnStatement(body as Expression)]);
// rewrite body if either there are writes that should be propagated back via return statements or there are substitutions
if (hasWritesOrVariableDeclarations || substitutions.size) {
const rewrittenStatements = visitNodes(statements, visitor).slice();
@@ -1948,8 +1948,8 @@ namespace ts.refactor.extractSymbol {
return undefined;
}
return isTypeNode
? factory.createQualifiedName(<EntityName>prefix, factory.createIdentifier(symbol.name))
: factory.createPropertyAccessExpression(<Expression>prefix, symbol.name);
? factory.createQualifiedName(prefix as EntityName, factory.createIdentifier(symbol.name))
: factory.createPropertyAccessExpression(prefix as Expression, symbol.name);
}
}
+10 -10
View File
@@ -728,7 +728,7 @@ namespace ts {
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
const functionDeclaration = <FunctionLikeDeclaration>node;
const functionDeclaration = node as FunctionLikeDeclaration;
const declarationName = getDeclarationName(functionDeclaration);
if (declarationName) {
@@ -739,7 +739,7 @@ namespace ts {
if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) {
// Overwrite the last declaration if it was an overload
// and this one is an implementation.
if (functionDeclaration.body && !(<FunctionLikeDeclaration>lastDeclaration).body) {
if (functionDeclaration.body && !(lastDeclaration as FunctionLikeDeclaration).body) {
declarations[declarations.length - 1] = functionDeclaration;
}
}
@@ -764,7 +764,7 @@ namespace ts {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.TypeLiteral:
addDeclaration(<Declaration>node);
addDeclaration(node as Declaration);
forEachChild(node, visit);
break;
@@ -777,7 +777,7 @@ namespace ts {
case SyntaxKind.VariableDeclaration:
case SyntaxKind.BindingElement: {
const decl = <VariableDeclaration>node;
const decl = node as VariableDeclaration;
if (isBindingPattern(decl.name)) {
forEachChild(decl.name, visit);
break;
@@ -790,13 +790,13 @@ namespace ts {
case SyntaxKind.EnumMember:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
addDeclaration(<Declaration>node);
addDeclaration(node as Declaration);
break;
case SyntaxKind.ExportDeclaration:
// Handle named exports case e.g.:
// export {a, b as B} from "mod";
const exportDeclaration = (<ExportDeclaration>node);
const exportDeclaration = node as ExportDeclaration;
if (exportDeclaration.exportClause) {
if (isNamedExports(exportDeclaration.exportClause)) {
forEach(exportDeclaration.exportClause.elements, visit);
@@ -808,7 +808,7 @@ namespace ts {
break;
case SyntaxKind.ImportDeclaration:
const importClause = (<ImportDeclaration>node).importClause;
const importClause = (node as ImportDeclaration).importClause;
if (importClause) {
// Handle default import case e.g.:
// import d from "mod";
@@ -1849,9 +1849,9 @@ namespace ts {
// If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of
// Then this name is name from dotted module
if (nodeForStartPos.parent.parent.kind === SyntaxKind.ModuleDeclaration &&
(<ModuleDeclaration>nodeForStartPos.parent.parent).body === nodeForStartPos.parent) {
(nodeForStartPos.parent.parent as ModuleDeclaration).body === nodeForStartPos.parent) {
// Use parent module declarations name for start pos
nodeForStartPos = (<ModuleDeclaration>nodeForStartPos.parent.parent).name;
nodeForStartPos = (nodeForStartPos.parent.parent as ModuleDeclaration).name;
}
else {
// We have to use this name for start pos
@@ -2755,7 +2755,7 @@ namespace ts {
return node &&
node.parent &&
node.parent.kind === SyntaxKind.ElementAccessExpression &&
(<ElementAccessExpression>node.parent).argumentExpression === node;
(node.parent as ElementAccessExpression).argumentExpression === node;
}
/// getDefaultLibraryFilePath
+11 -11
View File
@@ -322,7 +322,7 @@ namespace ts {
}
public getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange | undefined {
const oldSnapshotShim = <ScriptSnapshotShimAdapter>oldSnapshot;
const oldSnapshotShim = oldSnapshot as ScriptSnapshotShimAdapter;
const encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
/* eslint-disable no-null/no-null */
if (encoded === null) {
@@ -357,7 +357,7 @@ namespace ts {
// 'in' does not have this effect.
if ("getModuleResolutionsForFile" in this.shimHost) {
this.resolveModuleNames = (moduleNames, containingFile) => {
const resolutionsInFile = <MapLike<string>>JSON.parse(this.shimHost.getModuleResolutionsForFile!(containingFile)); // TODO: GH#18217
const resolutionsInFile = JSON.parse(this.shimHost.getModuleResolutionsForFile!(containingFile)) as MapLike<string>; // TODO: GH#18217
return map(moduleNames, name => {
const result = getProperty(resolutionsInFile, name);
return result ? { resolvedFileName: result, extension: extensionFromPath(result), isExternalLibraryImport: false } : undefined;
@@ -369,7 +369,7 @@ namespace ts {
}
if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
this.resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile) => {
const typeDirectivesForFile = <MapLike<ResolvedTypeReferenceDirective>>JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile!(containingFile)); // TODO: GH#18217
const typeDirectivesForFile = JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile!(containingFile)) as MapLike<ResolvedTypeReferenceDirective>; // TODO: GH#18217
return map(typeDirectiveNames, name => getProperty(typeDirectivesForFile, name));
};
}
@@ -417,7 +417,7 @@ namespace ts {
if (settingsJson === null || settingsJson === "") {
throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
}
const compilerOptions = <CompilerOptions>JSON.parse(settingsJson);
const compilerOptions = JSON.parse(settingsJson) as CompilerOptions;
// permit language service to handle all files (filtering should be performed on the host side)
compilerOptions.allowNonTsExtensions = true;
return compilerOptions;
@@ -577,7 +577,7 @@ namespace ts {
}
function forwardJSONCall(logger: Logger, actionDescription: string, action: () => {} | null | undefined, logPerformance: boolean): string {
return <string>forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance);
return forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance) as string;
}
function forwardCall<T>(logger: Logger, actionDescription: string, returnJson: boolean, action: () => T, logPerformance: boolean): T | string {
@@ -1162,7 +1162,7 @@ namespace ts {
public resolveModuleName(fileName: string, moduleName: string, compilerOptionsJson: string): string {
return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => {
const compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson);
const compilerOptions = JSON.parse(compilerOptionsJson) as CompilerOptions;
const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host);
let resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined;
if (result.resolvedModule && result.resolvedModule.extension !== Extension.Ts && result.resolvedModule.extension !== Extension.Tsx && result.resolvedModule.extension !== Extension.Dts) {
@@ -1178,7 +1178,7 @@ namespace ts {
public resolveTypeReferenceDirective(fileName: string, typeReferenceDirective: string, compilerOptionsJson: string): string {
return this.forwardJSONCall(`resolveTypeReferenceDirective(${fileName})`, () => {
const compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson);
const compilerOptions = JSON.parse(compilerOptionsJson) as CompilerOptions;
const result = resolveTypeReferenceDirective(typeReferenceDirective, normalizeSlashes(fileName), compilerOptions, this.host);
return {
resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined,
@@ -1209,7 +1209,7 @@ namespace ts {
return this.forwardJSONCall(
`getAutomaticTypeDirectiveNames('${compilerOptionsJson}')`,
() => {
const compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson);
const compilerOptions = JSON.parse(compilerOptionsJson) as CompilerOptions;
return getAutomaticTypeDirectiveNames(compilerOptions, this.host);
}
);
@@ -1258,7 +1258,7 @@ namespace ts {
public discoverTypings(discoverTypingsJson: string): string {
const getCanonicalFileName = createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false);
return this.forwardJSONCall("discoverTypings()", () => {
const info = <DiscoverTypingsInfo>JSON.parse(discoverTypingsJson);
const info = JSON.parse(discoverTypingsJson) as DiscoverTypingsInfo;
if (this.safeList === undefined) {
this.safeList = JsTyping.loadSafeList(this.host, toPath(info.safeListPath, info.safeListPath, getCanonicalFileName));
}
@@ -1315,10 +1315,10 @@ namespace ts {
public createCoreServicesShim(host: CoreServicesShimHost): CoreServicesShim {
try {
const adapter = new CoreServicesShimHostAdapter(host);
return new CoreServicesShimObject(this, <Logger>host, adapter);
return new CoreServicesShimObject(this, host as Logger, adapter);
}
catch (err) {
logInternalError(<Logger>host, err);
logInternalError(host as Logger, err);
throw err;
}
}
+12 -11
View File
@@ -237,8 +237,8 @@ namespace ts.SignatureHelp {
return undefined;
}
else if (isTemplateHead(node) && parent.parent.kind === SyntaxKind.TaggedTemplateExpression) {
const templateExpression = <TemplateExpression>parent;
const tagExpression = <TaggedTemplateExpression>templateExpression.parent;
const templateExpression = parent as TemplateExpression;
const tagExpression = templateExpression.parent as TaggedTemplateExpression;
Debug.assert(templateExpression.kind === SyntaxKind.TemplateExpression);
const argumentIndex = isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1;
@@ -624,7 +624,6 @@ namespace ts.SignatureHelp {
}
function itemInfoForParameters(candidateSignature: Signature, checker: TypeChecker, enclosingDeclaration: Node, sourceFile: SourceFile): SignatureHelpItemInfo[] {
const isVariadic = checker.hasEffectiveRestParameter(candidateSignature);
const printer = createPrinter({ removeComments: true });
const typeParameterParts = mapToDisplayParts(writer => {
if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
@@ -633,14 +632,16 @@ namespace ts.SignatureHelp {
}
});
const lists = checker.getExpandedParameters(candidateSignature);
return lists.map(parameterList => {
return {
isVariadic: isVariadic && (lists.length === 1 || !!((parameterList[parameterList.length - 1] as TransientSymbol).checkFlags & CheckFlags.RestParameter)),
parameters: parameterList.map(p => createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer)),
prefix: [...typeParameterParts, punctuationPart(SyntaxKind.OpenParenToken)],
suffix: [punctuationPart(SyntaxKind.CloseParenToken)]
};
});
const isVariadic: (parameterList: readonly Symbol[]) => boolean =
!checker.hasEffectiveRestParameter(candidateSignature) ? _ => false
: lists.length === 1 ? _ => true
: pList => !!(pList.length && (pList[pList.length - 1] as TransientSymbol).checkFlags & CheckFlags.RestParameter);
return lists.map(parameterList => ({
isVariadic: isVariadic(parameterList),
parameters: parameterList.map(p => createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer)),
prefix: [...typeParameterParts, punctuationPart(SyntaxKind.OpenParenToken)],
suffix: [punctuationPart(SyntaxKind.CloseParenToken)]
}));
}
function createSignatureHelpParameterForParameter(parameter: Symbol, checker: TypeChecker, enclosingDeclaration: Node, sourceFile: SourceFile, printer: Printer): SignatureHelpParameter {
+1 -1
View File
@@ -151,7 +151,7 @@ namespace ts.Completions.StringCompletions {
}
}
case SyntaxKind.PropertyAssignment:
if (isObjectLiteralExpression(parent.parent) && (<PropertyAssignment>parent).name === node) {
if (isObjectLiteralExpression(parent.parent) && (parent as PropertyAssignment).name === node) {
// Get quoted name of properties of the object literal expression
// i.e. interface ConfigFiles {
// 'jspm:dev': string
+9 -13
View File
@@ -64,7 +64,7 @@ namespace ts.SymbolDisplay {
if (flags & SymbolFlags.Constructor) return ScriptElementKind.constructorImplementationElement;
if (flags & SymbolFlags.Property) {
if (flags & SymbolFlags.Transient && (<TransientSymbol>symbol).checkFlags & CheckFlags.Synthetic) {
if (flags & SymbolFlags.Transient && (symbol as TransientSymbol).checkFlags & CheckFlags.Synthetic) {
// If union property is result of union of non method (property/accessors/variables), it is labeled as property
const unionPropertyKind = forEach(typeChecker.getRootSymbols(symbol), rootSymbol => {
const rootSymbolFlags = rootSymbol.getFlags();
@@ -100,10 +100,6 @@ namespace ts.SymbolDisplay {
return ScriptElementKind.unknown;
}
function isDeprecatedDeclaration(decl: Declaration) {
return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & ModifierFlags.Deprecated);
}
function getNormalizedSymbolModifiers(symbol: Symbol) {
if (symbol.declarations && symbol.declarations.length) {
const [declaration, ...declarations] = symbol.declarations;
@@ -177,7 +173,7 @@ namespace ts.SymbolDisplay {
type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location);
if (location.parent && location.parent.kind === SyntaxKind.PropertyAccessExpression) {
const right = (<PropertyAccessExpression>location.parent).name;
const right = (location.parent as PropertyAccessExpression).name;
// Either the location is on the right of a property access, or on the left and the right is missing
if (right === location || (right && right.getFullWidth() === 0)) {
location = location.parent;
@@ -190,7 +186,7 @@ namespace ts.SymbolDisplay {
callExpressionLike = location;
}
else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) {
callExpressionLike = <CallExpression | NewExpression>location.parent;
callExpressionLike = location.parent as CallExpression | NewExpression;
}
else if (location.parent && (isJsxOpeningLikeElement(location.parent) || isTaggedTemplateExpression(location.parent)) && isFunctionLike(symbol.valueDeclaration)) {
callExpressionLike = location.parent;
@@ -270,7 +266,7 @@ namespace ts.SymbolDisplay {
else if ((isNameOfFunctionDeclaration(location) && !(symbolFlags & SymbolFlags.Accessor)) || // name of function declaration
(location.kind === SyntaxKind.ConstructorKeyword && location.parent.kind === SyntaxKind.Constructor)) { // At constructor keyword of constructor declaration
// get the signature from the declaration and write it
const functionDeclaration = <SignatureDeclaration>location.parent;
const functionDeclaration = location.parent as SignatureDeclaration;
// Use function declaration to write the signatures only if the symbol corresponding to this declaration
const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, declaration =>
declaration === (location.kind === SyntaxKind.ConstructorKeyword ? functionDeclaration.parent : functionDeclaration));
@@ -376,12 +372,12 @@ namespace ts.SymbolDisplay {
if (declaration) {
if (isFunctionLikeKind(declaration.kind)) {
addInPrefix();
const signature = typeChecker.getSignatureFromDeclaration(<SignatureDeclaration>declaration)!; // TODO: GH#18217
const signature = typeChecker.getSignatureFromDeclaration(declaration as SignatureDeclaration)!; // TODO: GH#18217
if (declaration.kind === SyntaxKind.ConstructSignature) {
displayParts.push(keywordPart(SyntaxKind.NewKeyword));
displayParts.push(spacePart());
}
else if (declaration.kind !== SyntaxKind.CallSignature && (<SignatureDeclaration>declaration).name) {
else if (declaration.kind !== SyntaxKind.CallSignature && (declaration as SignatureDeclaration).name) {
addFullSymbolName(declaration.symbol);
}
addRange(displayParts, signatureToDisplayParts(typeChecker, signature, sourceFile, TypeFormatFlags.WriteTypeArgumentsOfSignature));
@@ -404,7 +400,7 @@ namespace ts.SymbolDisplay {
addPrefixForAnyFunctionOrVar(symbol, "enum member");
const declaration = symbol.declarations?.[0];
if (declaration?.kind === SyntaxKind.EnumMember) {
const constantValue = typeChecker.getConstantValue(<EnumMember>declaration);
const constantValue = typeChecker.getConstantValue(declaration as EnumMember);
if (constantValue !== undefined) {
displayParts.push(spacePart());
displayParts.push(operatorPart(SyntaxKind.EqualsToken));
@@ -470,7 +466,7 @@ namespace ts.SymbolDisplay {
addFullSymbolName(symbol);
forEach(symbol.declarations, declaration => {
if (declaration.kind === SyntaxKind.ImportEqualsDeclaration) {
const importEqualsDeclaration = <ImportEqualsDeclaration>declaration;
const importEqualsDeclaration = declaration as ImportEqualsDeclaration;
if (isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) {
displayParts.push(spacePart());
displayParts.push(operatorPart(SyntaxKind.EqualsToken));
@@ -565,7 +561,7 @@ namespace ts.SymbolDisplay {
continue;
}
const rhsSymbol = typeChecker.getSymbolAtLocation((<BinaryExpression>declaration.parent).right);
const rhsSymbol = typeChecker.getSymbolAtLocation((declaration.parent as BinaryExpression).right);
if (!rhsSymbol) {
continue;
}
+4 -4
View File
@@ -6,25 +6,25 @@ namespace ts.textChanges {
* It can be changed to side-table later if we decide that current design is too invasive.
*/
function getPos(n: TextRange): number {
const result = (<any>n).__pos;
const result = (n as any).__pos;
Debug.assert(typeof result === "number");
return result;
}
function setPos(n: TextRange, pos: number): void {
Debug.assert(typeof pos === "number");
(<any>n).__pos = pos;
(n as any).__pos = pos;
}
function getEnd(n: TextRange): number {
const result = (<any>n).__end;
const result = (n as any).__end;
Debug.assert(typeof result === "number");
return result;
}
function setEnd(n: TextRange, end: number): void {
Debug.assert(typeof end === "number");
(<any>n).__end = end;
(n as any).__end = end;
}
export interface ConfigurableStart {
+2 -2
View File
@@ -117,8 +117,8 @@ namespace ts {
/*@internal*/
export function fixupCompilerOptions(options: CompilerOptions, diagnostics: Diagnostic[]): CompilerOptions {
// Lazily create this value to fix module loading errors.
commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || <CommandLineOptionOfCustomType[]>filter(optionDeclarations, o =>
typeof o.type === "object" && !forEachEntry(o.type, v => typeof v !== "number"));
commandLineOptionsStringToEnum = commandLineOptionsStringToEnum ||
filter(optionDeclarations, o => typeof o.type === "object" && !forEachEntry(o.type, v => typeof v !== "number")) as CommandLineOptionOfCustomType[];
options = cloneCompilerOptions(options);
+57 -50
View File
@@ -60,7 +60,7 @@ namespace ts {
return SemanticMeaning.Value | SemanticMeaning.Type;
case SyntaxKind.ModuleDeclaration:
if (isAmbientModule(<ModuleDeclaration>node)) {
if (isAmbientModule(node as ModuleDeclaration)) {
return SemanticMeaning.Namespace | SemanticMeaning.Value;
}
else if (getModuleInstanceState(node as ModuleDeclaration) === ModuleInstanceState.Instantiated) {
@@ -105,7 +105,7 @@ namespace ts {
else if (isDeclarationName(node)) {
return getMeaningFromDeclaration(node.parent);
}
else if (isEntityName(node) && (isJSDocNameReference(node.parent) || isJSDocLink(node.parent))) {
else if (isEntityName(node) && findAncestor(node, or(isJSDocNameReference, isJSDocLinkLike, isJSDocMemberName))) {
return SemanticMeaning.All;
}
else if (isTypeReference(node)) {
@@ -154,7 +154,7 @@ namespace ts {
root = root.parent;
}
isLastClause = (<QualifiedName>root).right === node;
isLastClause = (root as QualifiedName).right === node;
}
return root.parent.kind === SyntaxKind.TypeReference && !isLastClause;
@@ -168,13 +168,13 @@ namespace ts {
root = root.parent;
}
isLastClause = (<PropertyAccessExpression>root).name === node;
isLastClause = (root as PropertyAccessExpression).name === node;
}
if (!isLastClause && root.parent.kind === SyntaxKind.ExpressionWithTypeArguments && root.parent.parent.kind === SyntaxKind.HeritageClause) {
const decl = root.parent.parent.parent;
return (decl.kind === SyntaxKind.ClassDeclaration && (<HeritageClause>root.parent.parent).token === SyntaxKind.ImplementsKeyword) ||
(decl.kind === SyntaxKind.InterfaceDeclaration && (<HeritageClause>root.parent.parent).token === SyntaxKind.ExtendsKeyword);
return (decl.kind === SyntaxKind.ClassDeclaration && (root.parent.parent as HeritageClause).token === SyntaxKind.ImplementsKeyword) ||
(decl.kind === SyntaxKind.InterfaceDeclaration && (root.parent.parent as HeritageClause).token === SyntaxKind.ExtendsKeyword);
}
return false;
@@ -198,7 +198,7 @@ namespace ts {
case SyntaxKind.ImportType:
return !(node.parent as ImportTypeNode).isTypeOf;
case SyntaxKind.ExpressionWithTypeArguments:
return !isExpressionWithTypeArgumentsInClassExtendsClause(<ExpressionWithTypeArguments>node.parent);
return !isExpressionWithTypeArgumentsInClassExtendsClause(node.parent as ExpressionWithTypeArguments);
}
return false;
@@ -258,8 +258,8 @@ namespace ts {
export function getTargetLabel(referenceNode: Node, labelName: string): Identifier | undefined {
while (referenceNode) {
if (referenceNode.kind === SyntaxKind.LabeledStatement && (<LabeledStatement>referenceNode).label.escapedText === labelName) {
return (<LabeledStatement>referenceNode).label;
if (referenceNode.kind === SyntaxKind.LabeledStatement && (referenceNode as LabeledStatement).label.escapedText === labelName) {
return (referenceNode as LabeledStatement).label;
}
referenceNode = referenceNode.parent;
}
@@ -321,9 +321,9 @@ namespace ts {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.ModuleDeclaration:
return getNameOfDeclaration(<Declaration>node.parent) === node;
return getNameOfDeclaration(node.parent as Declaration) === node;
case SyntaxKind.ElementAccessExpression:
return (<ElementAccessExpression>node.parent).argumentExpression === node;
return (node.parent as ElementAccessExpression).argumentExpression === node;
case SyntaxKind.ComputedPropertyName:
return true;
case SyntaxKind.LiteralType:
@@ -363,7 +363,7 @@ namespace ts {
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ModuleDeclaration:
return <Declaration>node;
return node as Declaration;
}
}
}
@@ -371,7 +371,7 @@ namespace ts {
export function getNodeKind(node: Node): ScriptElementKind {
switch (node.kind) {
case SyntaxKind.SourceFile:
return isExternalModule(<SourceFile>node) ? ScriptElementKind.moduleElement : ScriptElementKind.scriptElement;
return isExternalModule(node as SourceFile) ? ScriptElementKind.moduleElement : ScriptElementKind.scriptElement;
case SyntaxKind.ModuleDeclaration:
return ScriptElementKind.moduleElement;
case SyntaxKind.ClassDeclaration:
@@ -384,9 +384,9 @@ namespace ts {
return ScriptElementKind.typeElement;
case SyntaxKind.EnumDeclaration: return ScriptElementKind.enumElement;
case SyntaxKind.VariableDeclaration:
return getKindOfVariableDeclaration(<VariableDeclaration>node);
return getKindOfVariableDeclaration(node as VariableDeclaration);
case SyntaxKind.BindingElement:
return getKindOfVariableDeclaration(<VariableDeclaration>getRootDeclaration(node));
return getKindOfVariableDeclaration(getRootDeclaration(node) as VariableDeclaration);
case SyntaxKind.ArrowFunction:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
@@ -555,9 +555,9 @@ namespace ts {
case SyntaxKind.NamedExports:
return nodeEndsWith(n, SyntaxKind.CloseBraceToken, sourceFile);
case SyntaxKind.CatchClause:
return isCompletedNode((<CatchClause>n).block, sourceFile);
return isCompletedNode((n as CatchClause).block, sourceFile);
case SyntaxKind.NewExpression:
if (!(<NewExpression>n).arguments) {
if (!(n as NewExpression).arguments) {
return true;
}
// falls through
@@ -569,7 +569,7 @@ namespace ts {
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return isCompletedNode((<SignatureDeclaration>n).type, sourceFile);
return isCompletedNode((n as SignatureDeclaration).type, sourceFile);
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
@@ -581,12 +581,12 @@ namespace ts {
case SyntaxKind.ConstructSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ArrowFunction:
if ((<FunctionLikeDeclaration>n).body) {
return isCompletedNode((<FunctionLikeDeclaration>n).body, sourceFile);
if ((n as FunctionLikeDeclaration).body) {
return isCompletedNode((n as FunctionLikeDeclaration).body, sourceFile);
}
if ((<FunctionLikeDeclaration>n).type) {
return isCompletedNode((<FunctionLikeDeclaration>n).type, sourceFile);
if ((n as FunctionLikeDeclaration).type) {
return isCompletedNode((n as FunctionLikeDeclaration).type, sourceFile);
}
// Even though type parameters can be unclosed, we can get away with
@@ -594,16 +594,16 @@ namespace ts {
return hasChildOfKind(n, SyntaxKind.CloseParenToken, sourceFile);
case SyntaxKind.ModuleDeclaration:
return !!(<ModuleDeclaration>n).body && isCompletedNode((<ModuleDeclaration>n).body, sourceFile);
return !!(n as ModuleDeclaration).body && isCompletedNode((n as ModuleDeclaration).body, sourceFile);
case SyntaxKind.IfStatement:
if ((<IfStatement>n).elseStatement) {
return isCompletedNode((<IfStatement>n).elseStatement, sourceFile);
if ((n as IfStatement).elseStatement) {
return isCompletedNode((n as IfStatement).elseStatement, sourceFile);
}
return isCompletedNode((<IfStatement>n).thenStatement, sourceFile);
return isCompletedNode((n as IfStatement).thenStatement, sourceFile);
case SyntaxKind.ExpressionStatement:
return isCompletedNode((<ExpressionStatement>n).expression, sourceFile) ||
return isCompletedNode((n as ExpressionStatement).expression, sourceFile) ||
hasChildOfKind(n, SyntaxKind.SemicolonToken, sourceFile);
case SyntaxKind.ArrayLiteralExpression:
@@ -614,8 +614,8 @@ namespace ts {
return nodeEndsWith(n, SyntaxKind.CloseBracketToken, sourceFile);
case SyntaxKind.IndexSignature:
if ((<IndexSignatureDeclaration>n).type) {
return isCompletedNode((<IndexSignatureDeclaration>n).type, sourceFile);
if ((n as IndexSignatureDeclaration).type) {
return isCompletedNode((n as IndexSignatureDeclaration).type, sourceFile);
}
return hasChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile);
@@ -629,15 +629,15 @@ namespace ts {
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
case SyntaxKind.WhileStatement:
return isCompletedNode((<IterationStatement>n).statement, sourceFile);
return isCompletedNode((n as IterationStatement).statement, sourceFile);
case SyntaxKind.DoStatement:
// rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
return hasChildOfKind(n, SyntaxKind.WhileKeyword, sourceFile)
? nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile)
: isCompletedNode((<DoStatement>n).statement, sourceFile);
: isCompletedNode((n as DoStatement).statement, sourceFile);
case SyntaxKind.TypeQuery:
return isCompletedNode((<TypeQueryNode>n).exprName, sourceFile);
return isCompletedNode((n as TypeQueryNode).exprName, sourceFile);
case SyntaxKind.TypeOfExpression:
case SyntaxKind.DeleteExpression:
@@ -648,23 +648,23 @@ namespace ts {
return isCompletedNode(unaryWordExpression.expression, sourceFile);
case SyntaxKind.TaggedTemplateExpression:
return isCompletedNode((<TaggedTemplateExpression>n).template, sourceFile);
return isCompletedNode((n as TaggedTemplateExpression).template, sourceFile);
case SyntaxKind.TemplateExpression:
const lastSpan = lastOrUndefined((<TemplateExpression>n).templateSpans);
const lastSpan = lastOrUndefined((n as TemplateExpression).templateSpans);
return isCompletedNode(lastSpan, sourceFile);
case SyntaxKind.TemplateSpan:
return nodeIsPresent((<TemplateSpan>n).literal);
return nodeIsPresent((n as TemplateSpan).literal);
case SyntaxKind.ExportDeclaration:
case SyntaxKind.ImportDeclaration:
return nodeIsPresent((<ExportDeclaration | ImportDeclaration>n).moduleSpecifier);
return nodeIsPresent((n as ExportDeclaration | ImportDeclaration).moduleSpecifier);
case SyntaxKind.PrefixUnaryExpression:
return isCompletedNode((<PrefixUnaryExpression>n).operand, sourceFile);
return isCompletedNode((n as PrefixUnaryExpression).operand, sourceFile);
case SyntaxKind.BinaryExpression:
return isCompletedNode((<BinaryExpression>n).right, sourceFile);
return isCompletedNode((n as BinaryExpression).right, sourceFile);
case SyntaxKind.ConditionalExpression:
return isCompletedNode((<ConditionalExpression>n).whenFalse, sourceFile);
return isCompletedNode((n as ConditionalExpression).whenFalse, sourceFile);
default:
return true;
@@ -1307,7 +1307,7 @@ namespace ts {
}
if (position === end) {
return !!(<LiteralExpression>previousToken).isUnterminated;
return !!(previousToken as LiteralExpression).isUnterminated;
}
}
@@ -1623,11 +1623,11 @@ namespace ts {
export function getTypeArgumentOrTypeParameterList(node: Node): NodeArray<Node> | undefined {
if (node.kind === SyntaxKind.TypeReference || node.kind === SyntaxKind.CallExpression) {
return (<CallExpression>node).typeArguments;
return (node as CallExpression).typeArguments;
}
if (isFunctionLike(node) || node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.InterfaceDeclaration) {
return (<FunctionLikeDeclaration>node).typeParameters;
return (node as FunctionLikeDeclaration).typeParameters;
}
return undefined;
@@ -1678,15 +1678,15 @@ namespace ts {
// [a,b,c] from:
// [a, b, c] = someExpression;
if (node.parent.kind === SyntaxKind.BinaryExpression &&
(<BinaryExpression>node.parent).left === node &&
(<BinaryExpression>node.parent).operatorToken.kind === SyntaxKind.EqualsToken) {
(node.parent as BinaryExpression).left === node &&
(node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) {
return true;
}
// [a, b, c] from:
// for([a, b, c] of expression)
if (node.parent.kind === SyntaxKind.ForOfStatement &&
(<ForOfStatement>node.parent).initializer === node) {
(node.parent as ForOfStatement).initializer === node) {
return true;
}
@@ -1721,7 +1721,7 @@ namespace ts {
switch (contextToken.kind) {
case SyntaxKind.StringLiteral:
case SyntaxKind.NoSubstitutionTemplateLiteral:
return createTextSpanFromStringLiteralLikeContent(<StringLiteralLike>contextToken);
return createTextSpanFromStringLiteralLikeContent(contextToken as StringLiteralLike);
default:
return createTextSpanFromNode(contextToken);
}
@@ -2218,7 +2218,7 @@ namespace ts {
return displayPart(text, SymbolDisplayPartKind.linkText);
}
export function linkNamePart(name: EntityName, target: Declaration): JSDocLinkDisplayPart {
export function linkNamePart(name: EntityName | JSDocMemberName, target: Declaration): JSDocLinkDisplayPart {
return {
text: getTextOfNode(name),
kind: SymbolDisplayPartKind[SymbolDisplayPartKind.linkName],
@@ -2233,8 +2233,11 @@ namespace ts {
return displayPart(text, SymbolDisplayPartKind.link);
}
export function buildLinkParts(link: JSDocLink, checker?: TypeChecker): SymbolDisplayPart[] {
const parts = [linkPart("{@link ")];
export function buildLinkParts(link: JSDocLink | JSDocLinkCode | JSDocLinkPlain, checker?: TypeChecker): SymbolDisplayPart[] {
const prefix = isJSDocLink(link) ? "link"
: isJSDocLinkCode(link) ? "linkcode"
: "linkplain";
const parts = [linkPart(`{@${prefix} `)];
if (!link.name) {
if (link.text) {parts.push(linkTextPart(link.text));}
}
@@ -2246,7 +2249,7 @@ namespace ts {
if (link.text) {parts.push(linkTextPart(link.text));}
}
else {
parts.push(linkTextPart(getTextOfNode(link.name) + link.text));
parts.push(linkTextPart(getTextOfNode(link.name) + " " + link.text));
}
}
parts.push(linkPart("}"));
@@ -3354,5 +3357,9 @@ namespace ts {
|| (!!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent));
}
export function isDeprecatedDeclaration(decl: Declaration) {
return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & ModifierFlags.Deprecated);
}
// #endregion
}
+2 -2
View File
@@ -183,7 +183,7 @@ namespace project {
}
try {
testCase = <ProjectRunnerTestCase & ts.CompilerOptions>JSON.parse(testFileText!);
testCase = JSON.parse(testFileText!) as ProjectRunnerTestCase & ts.CompilerOptions;
}
catch (e) {
throw assert(false, "Testcase: " + testCaseFileName + " does not contain valid json format: " + e.message);
@@ -444,7 +444,7 @@ namespace project {
const option = optionNameMap.get(name);
if (option) {
const optType = option.type;
let value = <any>testCase[name];
let value = testCase[name] as any;
if (!ts.isString(optType)) {
const key = value.toLowerCase();
const optTypeValue = optType.get(key);
+3 -3
View File
@@ -94,7 +94,7 @@ namespace Harness {
export let globalTimeout: number;
function handleTestConfig() {
if (testConfigContent !== "") {
const testConfig = <TestConfig>JSON.parse(testConfigContent);
const testConfig = JSON.parse(testConfigContent) as TestConfig;
if (testConfig.light) {
setLightMode(true);
}
@@ -122,11 +122,11 @@ namespace Harness {
}
if (testConfig.stackTraceLimit === "full") {
(<any>Error).stackTraceLimit = Infinity;
(Error as any).stackTraceLimit = Infinity;
stackTraceLimit = testConfig.stackTraceLimit;
}
else if ((+testConfig.stackTraceLimit! | 0) > 0) {
(<any>Error).stackTraceLimit = +testConfig.stackTraceLimit! | 0;
(Error as any).stackTraceLimit = +testConfig.stackTraceLimit! | 0;
stackTraceLimit = +testConfig.stackTraceLimit! | 0;
}
if (testConfig.listenForWork) {
@@ -67,7 +67,7 @@ namespace ts {
include: ["0.d.ts", "1.d.ts"],
exclude: ["0.js", "1.js"]
},
errors: <Diagnostic[]>[]
errors: [] as Diagnostic[]
}
);
});
@@ -90,7 +90,7 @@ namespace ts {
include: ["0.d.ts", "1.d.ts"],
exclude: ["0.js", "1.js"]
},
errors: <Diagnostic[]>[]
errors: [] as Diagnostic[]
});
});
@@ -131,7 +131,7 @@ namespace ts {
include: [],
exclude: []
},
errors: <Diagnostic[]>[]
errors: [] as Diagnostic[]
});
});
@@ -150,7 +150,7 @@ namespace ts {
include: [],
exclude: []
},
errors: <Diagnostic[]>[]
errors: [] as Diagnostic[]
});
});
@@ -172,7 +172,7 @@ namespace ts {
include: ["0.d.ts"],
exclude: ["0.js"]
},
errors: <Diagnostic[]>[]
errors: [] as Diagnostic[]
});
});
@@ -185,7 +185,7 @@ namespace ts {
include: [],
exclude: []
},
errors: <Diagnostic[]>[]
errors: [] as Diagnostic[]
});
});
@@ -232,7 +232,7 @@ namespace ts {
include: [],
exclude: []
},
errors: <Diagnostic[]>[]
errors: [] as Diagnostic[]
});
});
});
@@ -136,11 +136,11 @@ namespace ts {
function createDiagnosticForConfigFile(json: any, start: number, length: number, diagnosticMessage: DiagnosticMessage, arg0: string) {
const text = JSON.stringify(json);
const file = <SourceFile>{
const file = {
fileName: caseInsensitiveTsconfigPath,
kind: SyntaxKind.SourceFile,
text
};
} as SourceFile;
return createFileDiagnostic(file, start, length, diagnosticMessage, arg0);
}
@@ -709,7 +709,7 @@ namespace ts {
include: [
"**/a.ts"
],
exclude: <string[]>[]
exclude: [] as string[]
};
const expected: ParsedCommandLine = {
options: {},

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