aboutsummaryrefslogtreecommitdiff
path: root/node_modules/typescript/lib/typescriptServices.js
diff options
context:
space:
mode:
Diffstat (limited to 'node_modules/typescript/lib/typescriptServices.js')
-rw-r--r--node_modules/typescript/lib/typescriptServices.js37612
1 files changed, 22409 insertions, 15203 deletions
diff --git a/node_modules/typescript/lib/typescriptServices.js b/node_modules/typescript/lib/typescriptServices.js
index d4ad545cf..ad7cbabef 100644
--- a/node_modules/typescript/lib/typescriptServices.js
+++ b/node_modules/typescript/lib/typescriptServices.js
@@ -13,11 +13,24 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
-var __extends = (this && this.__extends) || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+var __assign = (this && this.__assign) || Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
};
+var __extends = (this && this.__extends) || (function () {
+ var extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return function (d, b) {
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+})();
var ts;
(function (ts) {
// token > SyntaxKind.Identifer => token is a keyword
@@ -168,191 +181,191 @@ var ts;
SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 130] = "ReadonlyKeyword";
SyntaxKind[SyntaxKind["RequireKeyword"] = 131] = "RequireKeyword";
SyntaxKind[SyntaxKind["NumberKeyword"] = 132] = "NumberKeyword";
- SyntaxKind[SyntaxKind["SetKeyword"] = 133] = "SetKeyword";
- SyntaxKind[SyntaxKind["StringKeyword"] = 134] = "StringKeyword";
- SyntaxKind[SyntaxKind["SymbolKeyword"] = 135] = "SymbolKeyword";
- SyntaxKind[SyntaxKind["TypeKeyword"] = 136] = "TypeKeyword";
- SyntaxKind[SyntaxKind["UndefinedKeyword"] = 137] = "UndefinedKeyword";
- SyntaxKind[SyntaxKind["FromKeyword"] = 138] = "FromKeyword";
- SyntaxKind[SyntaxKind["GlobalKeyword"] = 139] = "GlobalKeyword";
- SyntaxKind[SyntaxKind["OfKeyword"] = 140] = "OfKeyword";
+ SyntaxKind[SyntaxKind["ObjectKeyword"] = 133] = "ObjectKeyword";
+ SyntaxKind[SyntaxKind["SetKeyword"] = 134] = "SetKeyword";
+ SyntaxKind[SyntaxKind["StringKeyword"] = 135] = "StringKeyword";
+ SyntaxKind[SyntaxKind["SymbolKeyword"] = 136] = "SymbolKeyword";
+ SyntaxKind[SyntaxKind["TypeKeyword"] = 137] = "TypeKeyword";
+ SyntaxKind[SyntaxKind["UndefinedKeyword"] = 138] = "UndefinedKeyword";
+ SyntaxKind[SyntaxKind["FromKeyword"] = 139] = "FromKeyword";
+ SyntaxKind[SyntaxKind["GlobalKeyword"] = 140] = "GlobalKeyword";
+ SyntaxKind[SyntaxKind["OfKeyword"] = 141] = "OfKeyword";
// Parse tree nodes
// Names
- SyntaxKind[SyntaxKind["QualifiedName"] = 141] = "QualifiedName";
- SyntaxKind[SyntaxKind["ComputedPropertyName"] = 142] = "ComputedPropertyName";
+ SyntaxKind[SyntaxKind["QualifiedName"] = 142] = "QualifiedName";
+ SyntaxKind[SyntaxKind["ComputedPropertyName"] = 143] = "ComputedPropertyName";
// Signature elements
- SyntaxKind[SyntaxKind["TypeParameter"] = 143] = "TypeParameter";
- SyntaxKind[SyntaxKind["Parameter"] = 144] = "Parameter";
- SyntaxKind[SyntaxKind["Decorator"] = 145] = "Decorator";
+ SyntaxKind[SyntaxKind["TypeParameter"] = 144] = "TypeParameter";
+ SyntaxKind[SyntaxKind["Parameter"] = 145] = "Parameter";
+ SyntaxKind[SyntaxKind["Decorator"] = 146] = "Decorator";
// TypeMember
- SyntaxKind[SyntaxKind["PropertySignature"] = 146] = "PropertySignature";
- SyntaxKind[SyntaxKind["PropertyDeclaration"] = 147] = "PropertyDeclaration";
- SyntaxKind[SyntaxKind["MethodSignature"] = 148] = "MethodSignature";
- SyntaxKind[SyntaxKind["MethodDeclaration"] = 149] = "MethodDeclaration";
- SyntaxKind[SyntaxKind["Constructor"] = 150] = "Constructor";
- SyntaxKind[SyntaxKind["GetAccessor"] = 151] = "GetAccessor";
- SyntaxKind[SyntaxKind["SetAccessor"] = 152] = "SetAccessor";
- SyntaxKind[SyntaxKind["CallSignature"] = 153] = "CallSignature";
- SyntaxKind[SyntaxKind["ConstructSignature"] = 154] = "ConstructSignature";
- SyntaxKind[SyntaxKind["IndexSignature"] = 155] = "IndexSignature";
+ SyntaxKind[SyntaxKind["PropertySignature"] = 147] = "PropertySignature";
+ SyntaxKind[SyntaxKind["PropertyDeclaration"] = 148] = "PropertyDeclaration";
+ SyntaxKind[SyntaxKind["MethodSignature"] = 149] = "MethodSignature";
+ SyntaxKind[SyntaxKind["MethodDeclaration"] = 150] = "MethodDeclaration";
+ SyntaxKind[SyntaxKind["Constructor"] = 151] = "Constructor";
+ SyntaxKind[SyntaxKind["GetAccessor"] = 152] = "GetAccessor";
+ SyntaxKind[SyntaxKind["SetAccessor"] = 153] = "SetAccessor";
+ SyntaxKind[SyntaxKind["CallSignature"] = 154] = "CallSignature";
+ SyntaxKind[SyntaxKind["ConstructSignature"] = 155] = "ConstructSignature";
+ SyntaxKind[SyntaxKind["IndexSignature"] = 156] = "IndexSignature";
// Type
- SyntaxKind[SyntaxKind["TypePredicate"] = 156] = "TypePredicate";
- SyntaxKind[SyntaxKind["TypeReference"] = 157] = "TypeReference";
- SyntaxKind[SyntaxKind["FunctionType"] = 158] = "FunctionType";
- SyntaxKind[SyntaxKind["ConstructorType"] = 159] = "ConstructorType";
- SyntaxKind[SyntaxKind["TypeQuery"] = 160] = "TypeQuery";
- SyntaxKind[SyntaxKind["TypeLiteral"] = 161] = "TypeLiteral";
- SyntaxKind[SyntaxKind["ArrayType"] = 162] = "ArrayType";
- SyntaxKind[SyntaxKind["TupleType"] = 163] = "TupleType";
- SyntaxKind[SyntaxKind["UnionType"] = 164] = "UnionType";
- SyntaxKind[SyntaxKind["IntersectionType"] = 165] = "IntersectionType";
- SyntaxKind[SyntaxKind["ParenthesizedType"] = 166] = "ParenthesizedType";
- SyntaxKind[SyntaxKind["ThisType"] = 167] = "ThisType";
- SyntaxKind[SyntaxKind["TypeOperator"] = 168] = "TypeOperator";
- SyntaxKind[SyntaxKind["IndexedAccessType"] = 169] = "IndexedAccessType";
- SyntaxKind[SyntaxKind["MappedType"] = 170] = "MappedType";
- SyntaxKind[SyntaxKind["LiteralType"] = 171] = "LiteralType";
+ SyntaxKind[SyntaxKind["TypePredicate"] = 157] = "TypePredicate";
+ SyntaxKind[SyntaxKind["TypeReference"] = 158] = "TypeReference";
+ SyntaxKind[SyntaxKind["FunctionType"] = 159] = "FunctionType";
+ SyntaxKind[SyntaxKind["ConstructorType"] = 160] = "ConstructorType";
+ SyntaxKind[SyntaxKind["TypeQuery"] = 161] = "TypeQuery";
+ SyntaxKind[SyntaxKind["TypeLiteral"] = 162] = "TypeLiteral";
+ SyntaxKind[SyntaxKind["ArrayType"] = 163] = "ArrayType";
+ SyntaxKind[SyntaxKind["TupleType"] = 164] = "TupleType";
+ SyntaxKind[SyntaxKind["UnionType"] = 165] = "UnionType";
+ SyntaxKind[SyntaxKind["IntersectionType"] = 166] = "IntersectionType";
+ SyntaxKind[SyntaxKind["ParenthesizedType"] = 167] = "ParenthesizedType";
+ SyntaxKind[SyntaxKind["ThisType"] = 168] = "ThisType";
+ SyntaxKind[SyntaxKind["TypeOperator"] = 169] = "TypeOperator";
+ SyntaxKind[SyntaxKind["IndexedAccessType"] = 170] = "IndexedAccessType";
+ SyntaxKind[SyntaxKind["MappedType"] = 171] = "MappedType";
+ SyntaxKind[SyntaxKind["LiteralType"] = 172] = "LiteralType";
// Binding patterns
- SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 172] = "ObjectBindingPattern";
- SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 173] = "ArrayBindingPattern";
- SyntaxKind[SyntaxKind["BindingElement"] = 174] = "BindingElement";
+ SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 173] = "ObjectBindingPattern";
+ SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 174] = "ArrayBindingPattern";
+ SyntaxKind[SyntaxKind["BindingElement"] = 175] = "BindingElement";
// Expression
- SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 175] = "ArrayLiteralExpression";
- SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 176] = "ObjectLiteralExpression";
- SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 177] = "PropertyAccessExpression";
- SyntaxKind[SyntaxKind["ElementAccessExpression"] = 178] = "ElementAccessExpression";
- SyntaxKind[SyntaxKind["CallExpression"] = 179] = "CallExpression";
- SyntaxKind[SyntaxKind["NewExpression"] = 180] = "NewExpression";
- SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 181] = "TaggedTemplateExpression";
- SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 182] = "TypeAssertionExpression";
- SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 183] = "ParenthesizedExpression";
- SyntaxKind[SyntaxKind["FunctionExpression"] = 184] = "FunctionExpression";
- SyntaxKind[SyntaxKind["ArrowFunction"] = 185] = "ArrowFunction";
- SyntaxKind[SyntaxKind["DeleteExpression"] = 186] = "DeleteExpression";
- SyntaxKind[SyntaxKind["TypeOfExpression"] = 187] = "TypeOfExpression";
- SyntaxKind[SyntaxKind["VoidExpression"] = 188] = "VoidExpression";
- SyntaxKind[SyntaxKind["AwaitExpression"] = 189] = "AwaitExpression";
- SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 190] = "PrefixUnaryExpression";
- SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 191] = "PostfixUnaryExpression";
- SyntaxKind[SyntaxKind["BinaryExpression"] = 192] = "BinaryExpression";
- SyntaxKind[SyntaxKind["ConditionalExpression"] = 193] = "ConditionalExpression";
- SyntaxKind[SyntaxKind["TemplateExpression"] = 194] = "TemplateExpression";
- SyntaxKind[SyntaxKind["YieldExpression"] = 195] = "YieldExpression";
- SyntaxKind[SyntaxKind["SpreadElement"] = 196] = "SpreadElement";
- SyntaxKind[SyntaxKind["ClassExpression"] = 197] = "ClassExpression";
- SyntaxKind[SyntaxKind["OmittedExpression"] = 198] = "OmittedExpression";
- SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 199] = "ExpressionWithTypeArguments";
- SyntaxKind[SyntaxKind["AsExpression"] = 200] = "AsExpression";
- SyntaxKind[SyntaxKind["NonNullExpression"] = 201] = "NonNullExpression";
+ SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 176] = "ArrayLiteralExpression";
+ SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 177] = "ObjectLiteralExpression";
+ SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 178] = "PropertyAccessExpression";
+ SyntaxKind[SyntaxKind["ElementAccessExpression"] = 179] = "ElementAccessExpression";
+ SyntaxKind[SyntaxKind["CallExpression"] = 180] = "CallExpression";
+ SyntaxKind[SyntaxKind["NewExpression"] = 181] = "NewExpression";
+ SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 182] = "TaggedTemplateExpression";
+ SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 183] = "TypeAssertionExpression";
+ SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 184] = "ParenthesizedExpression";
+ SyntaxKind[SyntaxKind["FunctionExpression"] = 185] = "FunctionExpression";
+ SyntaxKind[SyntaxKind["ArrowFunction"] = 186] = "ArrowFunction";
+ SyntaxKind[SyntaxKind["DeleteExpression"] = 187] = "DeleteExpression";
+ SyntaxKind[SyntaxKind["TypeOfExpression"] = 188] = "TypeOfExpression";
+ SyntaxKind[SyntaxKind["VoidExpression"] = 189] = "VoidExpression";
+ SyntaxKind[SyntaxKind["AwaitExpression"] = 190] = "AwaitExpression";
+ SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 191] = "PrefixUnaryExpression";
+ SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 192] = "PostfixUnaryExpression";
+ SyntaxKind[SyntaxKind["BinaryExpression"] = 193] = "BinaryExpression";
+ SyntaxKind[SyntaxKind["ConditionalExpression"] = 194] = "ConditionalExpression";
+ SyntaxKind[SyntaxKind["TemplateExpression"] = 195] = "TemplateExpression";
+ SyntaxKind[SyntaxKind["YieldExpression"] = 196] = "YieldExpression";
+ SyntaxKind[SyntaxKind["SpreadElement"] = 197] = "SpreadElement";
+ SyntaxKind[SyntaxKind["ClassExpression"] = 198] = "ClassExpression";
+ SyntaxKind[SyntaxKind["OmittedExpression"] = 199] = "OmittedExpression";
+ SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 200] = "ExpressionWithTypeArguments";
+ SyntaxKind[SyntaxKind["AsExpression"] = 201] = "AsExpression";
+ SyntaxKind[SyntaxKind["NonNullExpression"] = 202] = "NonNullExpression";
+ SyntaxKind[SyntaxKind["MetaProperty"] = 203] = "MetaProperty";
// Misc
- SyntaxKind[SyntaxKind["TemplateSpan"] = 202] = "TemplateSpan";
- SyntaxKind[SyntaxKind["SemicolonClassElement"] = 203] = "SemicolonClassElement";
+ SyntaxKind[SyntaxKind["TemplateSpan"] = 204] = "TemplateSpan";
+ SyntaxKind[SyntaxKind["SemicolonClassElement"] = 205] = "SemicolonClassElement";
// Element
- SyntaxKind[SyntaxKind["Block"] = 204] = "Block";
- SyntaxKind[SyntaxKind["VariableStatement"] = 205] = "VariableStatement";
- SyntaxKind[SyntaxKind["EmptyStatement"] = 206] = "EmptyStatement";
- SyntaxKind[SyntaxKind["ExpressionStatement"] = 207] = "ExpressionStatement";
- SyntaxKind[SyntaxKind["IfStatement"] = 208] = "IfStatement";
- SyntaxKind[SyntaxKind["DoStatement"] = 209] = "DoStatement";
- SyntaxKind[SyntaxKind["WhileStatement"] = 210] = "WhileStatement";
- SyntaxKind[SyntaxKind["ForStatement"] = 211] = "ForStatement";
- SyntaxKind[SyntaxKind["ForInStatement"] = 212] = "ForInStatement";
- SyntaxKind[SyntaxKind["ForOfStatement"] = 213] = "ForOfStatement";
- SyntaxKind[SyntaxKind["ContinueStatement"] = 214] = "ContinueStatement";
- SyntaxKind[SyntaxKind["BreakStatement"] = 215] = "BreakStatement";
- SyntaxKind[SyntaxKind["ReturnStatement"] = 216] = "ReturnStatement";
- SyntaxKind[SyntaxKind["WithStatement"] = 217] = "WithStatement";
- SyntaxKind[SyntaxKind["SwitchStatement"] = 218] = "SwitchStatement";
- SyntaxKind[SyntaxKind["LabeledStatement"] = 219] = "LabeledStatement";
- SyntaxKind[SyntaxKind["ThrowStatement"] = 220] = "ThrowStatement";
- SyntaxKind[SyntaxKind["TryStatement"] = 221] = "TryStatement";
- SyntaxKind[SyntaxKind["DebuggerStatement"] = 222] = "DebuggerStatement";
- SyntaxKind[SyntaxKind["VariableDeclaration"] = 223] = "VariableDeclaration";
- SyntaxKind[SyntaxKind["VariableDeclarationList"] = 224] = "VariableDeclarationList";
- SyntaxKind[SyntaxKind["FunctionDeclaration"] = 225] = "FunctionDeclaration";
- SyntaxKind[SyntaxKind["ClassDeclaration"] = 226] = "ClassDeclaration";
- SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 227] = "InterfaceDeclaration";
- SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 228] = "TypeAliasDeclaration";
- SyntaxKind[SyntaxKind["EnumDeclaration"] = 229] = "EnumDeclaration";
- SyntaxKind[SyntaxKind["ModuleDeclaration"] = 230] = "ModuleDeclaration";
- SyntaxKind[SyntaxKind["ModuleBlock"] = 231] = "ModuleBlock";
- SyntaxKind[SyntaxKind["CaseBlock"] = 232] = "CaseBlock";
- SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 233] = "NamespaceExportDeclaration";
- SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 234] = "ImportEqualsDeclaration";
- SyntaxKind[SyntaxKind["ImportDeclaration"] = 235] = "ImportDeclaration";
- SyntaxKind[SyntaxKind["ImportClause"] = 236] = "ImportClause";
- SyntaxKind[SyntaxKind["NamespaceImport"] = 237] = "NamespaceImport";
- SyntaxKind[SyntaxKind["NamedImports"] = 238] = "NamedImports";
- SyntaxKind[SyntaxKind["ImportSpecifier"] = 239] = "ImportSpecifier";
- SyntaxKind[SyntaxKind["ExportAssignment"] = 240] = "ExportAssignment";
- SyntaxKind[SyntaxKind["ExportDeclaration"] = 241] = "ExportDeclaration";
- SyntaxKind[SyntaxKind["NamedExports"] = 242] = "NamedExports";
- SyntaxKind[SyntaxKind["ExportSpecifier"] = 243] = "ExportSpecifier";
- SyntaxKind[SyntaxKind["MissingDeclaration"] = 244] = "MissingDeclaration";
+ SyntaxKind[SyntaxKind["Block"] = 206] = "Block";
+ SyntaxKind[SyntaxKind["VariableStatement"] = 207] = "VariableStatement";
+ SyntaxKind[SyntaxKind["EmptyStatement"] = 208] = "EmptyStatement";
+ SyntaxKind[SyntaxKind["ExpressionStatement"] = 209] = "ExpressionStatement";
+ SyntaxKind[SyntaxKind["IfStatement"] = 210] = "IfStatement";
+ SyntaxKind[SyntaxKind["DoStatement"] = 211] = "DoStatement";
+ SyntaxKind[SyntaxKind["WhileStatement"] = 212] = "WhileStatement";
+ SyntaxKind[SyntaxKind["ForStatement"] = 213] = "ForStatement";
+ SyntaxKind[SyntaxKind["ForInStatement"] = 214] = "ForInStatement";
+ SyntaxKind[SyntaxKind["ForOfStatement"] = 215] = "ForOfStatement";
+ SyntaxKind[SyntaxKind["ContinueStatement"] = 216] = "ContinueStatement";
+ SyntaxKind[SyntaxKind["BreakStatement"] = 217] = "BreakStatement";
+ SyntaxKind[SyntaxKind["ReturnStatement"] = 218] = "ReturnStatement";
+ SyntaxKind[SyntaxKind["WithStatement"] = 219] = "WithStatement";
+ SyntaxKind[SyntaxKind["SwitchStatement"] = 220] = "SwitchStatement";
+ SyntaxKind[SyntaxKind["LabeledStatement"] = 221] = "LabeledStatement";
+ SyntaxKind[SyntaxKind["ThrowStatement"] = 222] = "ThrowStatement";
+ SyntaxKind[SyntaxKind["TryStatement"] = 223] = "TryStatement";
+ SyntaxKind[SyntaxKind["DebuggerStatement"] = 224] = "DebuggerStatement";
+ SyntaxKind[SyntaxKind["VariableDeclaration"] = 225] = "VariableDeclaration";
+ SyntaxKind[SyntaxKind["VariableDeclarationList"] = 226] = "VariableDeclarationList";
+ SyntaxKind[SyntaxKind["FunctionDeclaration"] = 227] = "FunctionDeclaration";
+ SyntaxKind[SyntaxKind["ClassDeclaration"] = 228] = "ClassDeclaration";
+ SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 229] = "InterfaceDeclaration";
+ SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 230] = "TypeAliasDeclaration";
+ SyntaxKind[SyntaxKind["EnumDeclaration"] = 231] = "EnumDeclaration";
+ SyntaxKind[SyntaxKind["ModuleDeclaration"] = 232] = "ModuleDeclaration";
+ SyntaxKind[SyntaxKind["ModuleBlock"] = 233] = "ModuleBlock";
+ SyntaxKind[SyntaxKind["CaseBlock"] = 234] = "CaseBlock";
+ SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 235] = "NamespaceExportDeclaration";
+ SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 236] = "ImportEqualsDeclaration";
+ SyntaxKind[SyntaxKind["ImportDeclaration"] = 237] = "ImportDeclaration";
+ SyntaxKind[SyntaxKind["ImportClause"] = 238] = "ImportClause";
+ SyntaxKind[SyntaxKind["NamespaceImport"] = 239] = "NamespaceImport";
+ SyntaxKind[SyntaxKind["NamedImports"] = 240] = "NamedImports";
+ SyntaxKind[SyntaxKind["ImportSpecifier"] = 241] = "ImportSpecifier";
+ SyntaxKind[SyntaxKind["ExportAssignment"] = 242] = "ExportAssignment";
+ SyntaxKind[SyntaxKind["ExportDeclaration"] = 243] = "ExportDeclaration";
+ SyntaxKind[SyntaxKind["NamedExports"] = 244] = "NamedExports";
+ SyntaxKind[SyntaxKind["ExportSpecifier"] = 245] = "ExportSpecifier";
+ SyntaxKind[SyntaxKind["MissingDeclaration"] = 246] = "MissingDeclaration";
// Module references
- SyntaxKind[SyntaxKind["ExternalModuleReference"] = 245] = "ExternalModuleReference";
+ SyntaxKind[SyntaxKind["ExternalModuleReference"] = 247] = "ExternalModuleReference";
// JSX
- SyntaxKind[SyntaxKind["JsxElement"] = 246] = "JsxElement";
- SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 247] = "JsxSelfClosingElement";
- SyntaxKind[SyntaxKind["JsxOpeningElement"] = 248] = "JsxOpeningElement";
- SyntaxKind[SyntaxKind["JsxClosingElement"] = 249] = "JsxClosingElement";
- SyntaxKind[SyntaxKind["JsxAttribute"] = 250] = "JsxAttribute";
- SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 251] = "JsxSpreadAttribute";
- SyntaxKind[SyntaxKind["JsxExpression"] = 252] = "JsxExpression";
+ SyntaxKind[SyntaxKind["JsxElement"] = 248] = "JsxElement";
+ SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 249] = "JsxSelfClosingElement";
+ SyntaxKind[SyntaxKind["JsxOpeningElement"] = 250] = "JsxOpeningElement";
+ SyntaxKind[SyntaxKind["JsxClosingElement"] = 251] = "JsxClosingElement";
+ SyntaxKind[SyntaxKind["JsxAttribute"] = 252] = "JsxAttribute";
+ SyntaxKind[SyntaxKind["JsxAttributes"] = 253] = "JsxAttributes";
+ SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 254] = "JsxSpreadAttribute";
+ SyntaxKind[SyntaxKind["JsxExpression"] = 255] = "JsxExpression";
// Clauses
- SyntaxKind[SyntaxKind["CaseClause"] = 253] = "CaseClause";
- SyntaxKind[SyntaxKind["DefaultClause"] = 254] = "DefaultClause";
- SyntaxKind[SyntaxKind["HeritageClause"] = 255] = "HeritageClause";
- SyntaxKind[SyntaxKind["CatchClause"] = 256] = "CatchClause";
+ SyntaxKind[SyntaxKind["CaseClause"] = 256] = "CaseClause";
+ SyntaxKind[SyntaxKind["DefaultClause"] = 257] = "DefaultClause";
+ SyntaxKind[SyntaxKind["HeritageClause"] = 258] = "HeritageClause";
+ SyntaxKind[SyntaxKind["CatchClause"] = 259] = "CatchClause";
// Property assignments
- SyntaxKind[SyntaxKind["PropertyAssignment"] = 257] = "PropertyAssignment";
- SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 258] = "ShorthandPropertyAssignment";
- SyntaxKind[SyntaxKind["SpreadAssignment"] = 259] = "SpreadAssignment";
+ SyntaxKind[SyntaxKind["PropertyAssignment"] = 260] = "PropertyAssignment";
+ SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 261] = "ShorthandPropertyAssignment";
+ SyntaxKind[SyntaxKind["SpreadAssignment"] = 262] = "SpreadAssignment";
// Enum
- SyntaxKind[SyntaxKind["EnumMember"] = 260] = "EnumMember";
+ SyntaxKind[SyntaxKind["EnumMember"] = 263] = "EnumMember";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 261] = "SourceFile";
+ SyntaxKind[SyntaxKind["SourceFile"] = 264] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 265] = "Bundle";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 262] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 266] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 263] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 267] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 264] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocArrayType"] = 265] = "JSDocArrayType";
- SyntaxKind[SyntaxKind["JSDocUnionType"] = 266] = "JSDocUnionType";
- SyntaxKind[SyntaxKind["JSDocTupleType"] = 267] = "JSDocTupleType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 268] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 269] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocRecordType"] = 270] = "JSDocRecordType";
- SyntaxKind[SyntaxKind["JSDocRecordMember"] = 271] = "JSDocRecordMember";
- SyntaxKind[SyntaxKind["JSDocTypeReference"] = 272] = "JSDocTypeReference";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 273] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 274] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 275] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocConstructorType"] = 276] = "JSDocConstructorType";
- SyntaxKind[SyntaxKind["JSDocThisType"] = 277] = "JSDocThisType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 278] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTag"] = 279] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 280] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 281] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 282] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 283] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 284] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 285] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 286] = "JSDocPropertyTag";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 287] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocLiteralType"] = 288] = "JSDocLiteralType";
- SyntaxKind[SyntaxKind["JSDocNullKeyword"] = 289] = "JSDocNullKeyword";
- SyntaxKind[SyntaxKind["JSDocUndefinedKeyword"] = 290] = "JSDocUndefinedKeyword";
- SyntaxKind[SyntaxKind["JSDocNeverKeyword"] = 291] = "JSDocNeverKeyword";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 268] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocArrayType"] = 269] = "JSDocArrayType";
+ SyntaxKind[SyntaxKind["JSDocUnionType"] = 270] = "JSDocUnionType";
+ SyntaxKind[SyntaxKind["JSDocTupleType"] = 271] = "JSDocTupleType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 272] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 273] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocRecordType"] = 274] = "JSDocRecordType";
+ SyntaxKind[SyntaxKind["JSDocRecordMember"] = 275] = "JSDocRecordMember";
+ SyntaxKind[SyntaxKind["JSDocTypeReference"] = 276] = "JSDocTypeReference";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 277] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 278] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 279] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocConstructorType"] = 280] = "JSDocConstructorType";
+ SyntaxKind[SyntaxKind["JSDocThisType"] = 281] = "JSDocThisType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 282] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 283] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 284] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 285] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 286] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 287] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 288] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 289] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 290] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 291] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocLiteralType"] = 292] = "JSDocLiteralType";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 292] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 293] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 293] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 294] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 295] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 296] = "EndOfDeclarationMarker";
- SyntaxKind[SyntaxKind["RawExpression"] = 297] = "RawExpression";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 294] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 295] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 296] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 297] = "EndOfDeclarationMarker";
// Enum value count
SyntaxKind[SyntaxKind["Count"] = 298] = "Count";
// Markers
@@ -363,15 +376,15 @@ var ts;
SyntaxKind[SyntaxKind["FirstReservedWord"] = 71] = "FirstReservedWord";
SyntaxKind[SyntaxKind["LastReservedWord"] = 106] = "LastReservedWord";
SyntaxKind[SyntaxKind["FirstKeyword"] = 71] = "FirstKeyword";
- SyntaxKind[SyntaxKind["LastKeyword"] = 140] = "LastKeyword";
+ SyntaxKind[SyntaxKind["LastKeyword"] = 141] = "LastKeyword";
SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 107] = "FirstFutureReservedWord";
SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 115] = "LastFutureReservedWord";
- SyntaxKind[SyntaxKind["FirstTypeNode"] = 156] = "FirstTypeNode";
- SyntaxKind[SyntaxKind["LastTypeNode"] = 171] = "LastTypeNode";
+ SyntaxKind[SyntaxKind["FirstTypeNode"] = 157] = "FirstTypeNode";
+ SyntaxKind[SyntaxKind["LastTypeNode"] = 172] = "LastTypeNode";
SyntaxKind[SyntaxKind["FirstPunctuation"] = 16] = "FirstPunctuation";
SyntaxKind[SyntaxKind["LastPunctuation"] = 69] = "LastPunctuation";
SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
- SyntaxKind[SyntaxKind["LastToken"] = 140] = "LastToken";
+ SyntaxKind[SyntaxKind["LastToken"] = 141] = "LastToken";
SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
@@ -380,11 +393,11 @@ var ts;
SyntaxKind[SyntaxKind["LastTemplateToken"] = 15] = "LastTemplateToken";
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 26] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 69] = "LastBinaryOperator";
- SyntaxKind[SyntaxKind["FirstNode"] = 141] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 262] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 288] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 278] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 291] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstNode"] = 142] = "FirstNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 266] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 292] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 282] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 292] = "LastJSDocTagNode";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
var NodeFlags;
(function (NodeFlags) {
@@ -399,28 +412,22 @@ var ts;
NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn";
NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn";
NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation";
- NodeFlags[NodeFlags["HasClassExtends"] = 1024] = "HasClassExtends";
- NodeFlags[NodeFlags["HasDecorators"] = 2048] = "HasDecorators";
- NodeFlags[NodeFlags["HasParamDecorators"] = 4096] = "HasParamDecorators";
- NodeFlags[NodeFlags["HasAsyncFunctions"] = 8192] = "HasAsyncFunctions";
- NodeFlags[NodeFlags["HasSpreadAttribute"] = 16384] = "HasSpreadAttribute";
- NodeFlags[NodeFlags["HasRestAttribute"] = 32768] = "HasRestAttribute";
- NodeFlags[NodeFlags["DisallowInContext"] = 65536] = "DisallowInContext";
- NodeFlags[NodeFlags["YieldContext"] = 131072] = "YieldContext";
- NodeFlags[NodeFlags["DecoratorContext"] = 262144] = "DecoratorContext";
- NodeFlags[NodeFlags["AwaitContext"] = 524288] = "AwaitContext";
- NodeFlags[NodeFlags["ThisNodeHasError"] = 1048576] = "ThisNodeHasError";
- NodeFlags[NodeFlags["JavaScriptFile"] = 2097152] = "JavaScriptFile";
- NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 4194304] = "ThisNodeOrAnySubNodesHasError";
- NodeFlags[NodeFlags["HasAggregatedChildData"] = 8388608] = "HasAggregatedChildData";
+ NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions";
+ NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext";
+ NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext";
+ NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext";
+ NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext";
+ NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError";
+ NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile";
+ NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError";
+ NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData";
NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags";
- NodeFlags[NodeFlags["EmitHelperFlags"] = 64512] = "EmitHelperFlags";
- NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 64896] = "ReachabilityAndEmitFlags";
+ NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags";
// Parsing context flags
- NodeFlags[NodeFlags["ContextFlags"] = 3080192] = "ContextFlags";
+ NodeFlags[NodeFlags["ContextFlags"] = 96256] = "ContextFlags";
// Exclude these flags when parsing a Type
- NodeFlags[NodeFlags["TypeExcludesFlags"] = 655360] = "TypeExcludesFlags";
+ NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags";
})(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
var ModifierFlags;
(function (ModifierFlags) {
@@ -469,6 +476,17 @@ var ts;
GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique";
GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node";
})(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {}));
+ /* @internal */
+ var NumericLiteralFlags;
+ (function (NumericLiteralFlags) {
+ NumericLiteralFlags[NumericLiteralFlags["None"] = 0] = "None";
+ NumericLiteralFlags[NumericLiteralFlags["Scientific"] = 2] = "Scientific";
+ NumericLiteralFlags[NumericLiteralFlags["Octal"] = 4] = "Octal";
+ NumericLiteralFlags[NumericLiteralFlags["HexSpecifier"] = 8] = "HexSpecifier";
+ NumericLiteralFlags[NumericLiteralFlags["BinarySpecifier"] = 16] = "BinarySpecifier";
+ NumericLiteralFlags[NumericLiteralFlags["OctalSpecifier"] = 32] = "OctalSpecifier";
+ NumericLiteralFlags[NumericLiteralFlags["BinaryOrOctalSpecifier"] = 48] = "BinaryOrOctalSpecifier";
+ })(NumericLiteralFlags = ts.NumericLiteralFlags || (ts.NumericLiteralFlags = {}));
var FlowFlags;
(function (FlowFlags) {
FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
@@ -482,6 +500,8 @@ var ts;
FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced";
FlowFlags[FlowFlags["Shared"] = 1024] = "Shared";
+ FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally";
+ FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally";
FlowFlags[FlowFlags["Label"] = 12] = "Label";
FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
})(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
@@ -503,6 +523,16 @@ var ts;
// Diagnostics were produced and outputs were generated in spite of them.
ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
})(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
+ var NodeBuilderFlags;
+ (function (NodeBuilderFlags) {
+ NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
+ NodeBuilderFlags[NodeBuilderFlags["allowThisInObjectLiteral"] = 1] = "allowThisInObjectLiteral";
+ NodeBuilderFlags[NodeBuilderFlags["allowQualifedNameInPlaceOfIdentifier"] = 2] = "allowQualifedNameInPlaceOfIdentifier";
+ NodeBuilderFlags[NodeBuilderFlags["allowTypeParameterInQualifiedName"] = 4] = "allowTypeParameterInQualifiedName";
+ NodeBuilderFlags[NodeBuilderFlags["allowAnonymousIdentifier"] = 8] = "allowAnonymousIdentifier";
+ NodeBuilderFlags[NodeBuilderFlags["allowEmptyUnionOrIntersection"] = 16] = "allowEmptyUnionOrIntersection";
+ NodeBuilderFlags[NodeBuilderFlags["allowEmptyTuple"] = 32] = "allowEmptyTuple";
+ })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
var TypeFormatFlags;
(function (TypeFormatFlags) {
TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
@@ -517,6 +547,8 @@ var ts;
TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument";
TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias";
TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue";
+ TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 2048] = "SuppressAnyReturnType";
+ TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 4096] = "AddUndefined";
})(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
var SymbolFormatFlags;
(function (SymbolFormatFlags) {
@@ -549,8 +581,7 @@ var ts;
TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
})(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
- /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator
- * metadata */
+ /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
/* @internal */
var TypeReferenceSerializationKind;
(function (TypeReferenceSerializationKind) {
@@ -598,13 +629,10 @@ var ts;
SymbolFlags[SymbolFlags["ExportType"] = 2097152] = "ExportType";
SymbolFlags[SymbolFlags["ExportNamespace"] = 4194304] = "ExportNamespace";
SymbolFlags[SymbolFlags["Alias"] = 8388608] = "Alias";
- SymbolFlags[SymbolFlags["Instantiated"] = 16777216] = "Instantiated";
- SymbolFlags[SymbolFlags["Merged"] = 33554432] = "Merged";
- SymbolFlags[SymbolFlags["Transient"] = 67108864] = "Transient";
- SymbolFlags[SymbolFlags["Prototype"] = 134217728] = "Prototype";
- SymbolFlags[SymbolFlags["SyntheticProperty"] = 268435456] = "SyntheticProperty";
- SymbolFlags[SymbolFlags["Optional"] = 536870912] = "Optional";
- SymbolFlags[SymbolFlags["ExportStar"] = 1073741824] = "ExportStar";
+ SymbolFlags[SymbolFlags["Prototype"] = 16777216] = "Prototype";
+ SymbolFlags[SymbolFlags["ExportStar"] = 33554432] = "ExportStar";
+ SymbolFlags[SymbolFlags["Optional"] = 67108864] = "Optional";
+ SymbolFlags[SymbolFlags["Transient"] = 134217728] = "Transient";
SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
SymbolFlags[SymbolFlags["Value"] = 107455] = "Value";
@@ -648,11 +676,27 @@ var ts;
SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable";
})(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
/* @internal */
+ var CheckFlags;
+ (function (CheckFlags) {
+ CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
+ CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
+ CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
+ CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
+ CheckFlags[CheckFlags["Partial"] = 16] = "Partial";
+ CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType";
+ CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic";
+ CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected";
+ CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate";
+ CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic";
+ CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
+ })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
+ /* @internal */
var NodeCheckFlags;
(function (NodeCheckFlags) {
NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
+ NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
@@ -701,6 +745,9 @@ var ts;
TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral";
/* @internal */
TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType";
+ TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive";
+ /* @internal */
+ TypeFlags[TypeFlags["JsxAttributes"] = 33554432] = "JsxAttributes";
/* @internal */
TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable";
TypeFlags[TypeFlags["Literal"] = 480] = "Literal";
@@ -709,7 +756,7 @@ var ts;
TypeFlags[TypeFlags["DefinitelyFalsy"] = 7392] = "DefinitelyFalsy";
TypeFlags[TypeFlags["PossiblyFalsy"] = 7406] = "PossiblyFalsy";
/* @internal */
- TypeFlags[TypeFlags["Intrinsic"] = 16015] = "Intrinsic";
+ TypeFlags[TypeFlags["Intrinsic"] = 16793231] = "Intrinsic";
/* @internal */
TypeFlags[TypeFlags["Primitive"] = 8190] = "Primitive";
TypeFlags[TypeFlags["StringLike"] = 262178] = "StringLike";
@@ -718,11 +765,12 @@ var ts;
TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike";
TypeFlags[TypeFlags["UnionOrIntersection"] = 196608] = "UnionOrIntersection";
TypeFlags[TypeFlags["StructuredType"] = 229376] = "StructuredType";
- TypeFlags[TypeFlags["StructuredOrTypeParameter"] = 507904] = "StructuredOrTypeParameter";
+ TypeFlags[TypeFlags["StructuredOrTypeVariable"] = 1032192] = "StructuredOrTypeVariable";
+ TypeFlags[TypeFlags["TypeVariable"] = 540672] = "TypeVariable";
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
- TypeFlags[TypeFlags["Narrowable"] = 1033215] = "Narrowable";
- TypeFlags[TypeFlags["NotUnionOrUnit"] = 33281] = "NotUnionOrUnit";
+ TypeFlags[TypeFlags["Narrowable"] = 17810431] = "Narrowable";
+ TypeFlags[TypeFlags["NotUnionOrUnit"] = 16810497] = "NotUnionOrUnit";
/* @internal */
TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening";
/* @internal */
@@ -764,6 +812,8 @@ var ts;
SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty";
/// this.name = expr
SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty";
+ // F.name = expr
+ SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property";
})(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {}));
var DiagnosticCategory;
(function (DiagnosticCategory) {
@@ -790,6 +840,7 @@ var ts;
JsxEmit[JsxEmit["None"] = 0] = "None";
JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
JsxEmit[JsxEmit["React"] = 2] = "React";
+ JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
})(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
var NewLineKind;
(function (NewLineKind) {
@@ -803,6 +854,7 @@ var ts;
ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
ScriptKind[ScriptKind["TS"] = 3] = "TS";
ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
+ ScriptKind[ScriptKind["External"] = 5] = "External";
})(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
var ScriptTarget;
(function (ScriptTarget) {
@@ -1037,7 +1089,6 @@ var ts;
TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask";
TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask";
})(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
- /* @internal */
var EmitFlags;
(function (EmitFlags) {
EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
@@ -1065,15 +1116,45 @@ var ts;
EmitFlags[EmitFlags["CustomPrologue"] = 524288] = "CustomPrologue";
EmitFlags[EmitFlags["NoHoisting"] = 1048576] = "NoHoisting";
EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 2097152] = "HasEndOfDeclarationMarker";
+ EmitFlags[EmitFlags["Iterator"] = 4194304] = "Iterator";
})(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
+ /**
+ * Used by the checker, this enum keeps track of external emit helpers that should be type
+ * checked.
+ */
/* @internal */
- var EmitContext;
- (function (EmitContext) {
- EmitContext[EmitContext["SourceFile"] = 0] = "SourceFile";
- EmitContext[EmitContext["Expression"] = 1] = "Expression";
- EmitContext[EmitContext["IdentifierName"] = 2] = "IdentifierName";
- EmitContext[EmitContext["Unspecified"] = 3] = "Unspecified";
- })(EmitContext = ts.EmitContext || (ts.EmitContext = {}));
+ var ExternalEmitHelpers;
+ (function (ExternalEmitHelpers) {
+ ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
+ ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
+ ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
+ ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
+ ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
+ ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
+ ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
+ ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
+ ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
+ ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
+ ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator";
+ ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues";
+ // Helpers included by ES2015 for..of
+ ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
+ // Helpers included by ES2017 for..await..of
+ ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes";
+ // Helpers included by ES2015 spread
+ ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
+ ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
+ ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper";
+ })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
+ var EmitHint;
+ (function (EmitHint) {
+ EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
+ EmitHint[EmitHint["Expression"] = 1] = "Expression";
+ EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
+ EmitHint[EmitHint["Unspecified"] = 3] = "Unspecified";
+ })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
})(ts || (ts = {}));
/*@internal*/
var ts;
@@ -1101,8 +1182,8 @@ var ts;
*/
function mark(markName) {
if (enabled) {
- marks[markName] = ts.timestamp();
- counts[markName] = (counts[markName] || 0) + 1;
+ marks.set(markName, ts.timestamp());
+ counts.set(markName, (counts.get(markName) || 0) + 1);
profilerEvent(markName);
}
}
@@ -1118,9 +1199,9 @@ var ts;
*/
function measure(measureName, startMarkName, endMarkName) {
if (enabled) {
- var end = endMarkName && marks[endMarkName] || ts.timestamp();
- var start = startMarkName && marks[startMarkName] || profilerStart;
- measures[measureName] = (measures[measureName] || 0) + (end - start);
+ var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
+ var start = startMarkName && marks.get(startMarkName) || profilerStart;
+ measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
}
}
performance.measure = measure;
@@ -1130,7 +1211,7 @@ var ts;
* @param markName The name of the mark.
*/
function getCount(markName) {
- return counts && counts[markName] || 0;
+ return counts && counts.get(markName) || 0;
}
performance.getCount = getCount;
/**
@@ -1139,7 +1220,7 @@ var ts;
* @param measureName The name of the measure whose durations should be accumulated.
*/
function getDuration(measureName) {
- return measures && measures[measureName] || 0;
+ return measures && measures.get(measureName) || 0;
}
performance.getDuration = getDuration;
/**
@@ -1148,9 +1229,9 @@ var ts;
* @param cb The action to perform for each measure
*/
function forEachMeasure(cb) {
- for (var key in measures) {
- cb(key, measures[key]);
- }
+ measures.forEach(function (measure, key) {
+ cb(key, measure);
+ });
}
performance.forEachMeasure = forEachMeasure;
/** Enables (and resets) performance measurements for the compiler. */
@@ -1174,7 +1255,7 @@ var ts;
var ts;
(function (ts) {
/** The version of the TypeScript compiler release */
- ts.version = "2.2.0-dev.20161127";
+ ts.version = "2.3.0-dev.20170419";
})(ts || (ts = {}));
/* @internal */
(function (ts) {
@@ -1193,25 +1274,106 @@ var ts;
Ternary[Ternary["Maybe"] = 1] = "Maybe";
Ternary[Ternary["True"] = -1] = "True";
})(Ternary = ts.Ternary || (ts.Ternary = {}));
- var createObject = Object.create;
// More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times.
- ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined;
- function createMap(template) {
- var map = createObject(null); // tslint:disable-line:no-null-keyword
+ ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(/*locales*/ undefined, { usage: "sort", sensitivity: "accent" }) : undefined;
+ // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B".
+ ts.localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0;
+ /** Create a MapLike with good performance. */
+ function createDictionaryObject() {
+ var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword
// Using 'delete' on an object causes V8 to put the object in dictionary mode.
// This disables creation of hidden classes, which are expensive when an object is
// constantly changing shape.
map["__"] = undefined;
delete map["__"];
+ return map;
+ }
+ /** Create a new map. If a template object is provided, the map will copy entries from it. */
+ function createMap() {
+ return new MapCtr();
+ }
+ ts.createMap = createMap;
+ function createMapFromTemplate(template) {
+ var map = new MapCtr();
// Copies keys/values from template. Note that for..in will not throw if
// template is undefined, and instead will just exit the loop.
for (var key in template)
if (hasOwnProperty.call(template, key)) {
- map[key] = template[key];
+ map.set(key, template[key]);
}
return map;
}
- ts.createMap = createMap;
+ ts.createMapFromTemplate = createMapFromTemplate;
+ // Internet Explorer's Map doesn't support iteration, so don't use it.
+ // tslint:disable-next-line:no-in-operator
+ var MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap();
+ // Keep the class inside a function so it doesn't get compiled if it's not used.
+ function shimMap() {
+ var MapIterator = (function () {
+ function MapIterator(data, selector) {
+ this.index = 0;
+ this.data = data;
+ this.selector = selector;
+ this.keys = Object.keys(data);
+ }
+ MapIterator.prototype.next = function () {
+ var index = this.index;
+ if (index < this.keys.length) {
+ this.index++;
+ return { value: this.selector(this.data, this.keys[index]), done: false };
+ }
+ return { value: undefined, done: true };
+ };
+ return MapIterator;
+ }());
+ return (function () {
+ function class_1() {
+ this.data = createDictionaryObject();
+ this.size = 0;
+ }
+ class_1.prototype.get = function (key) {
+ return this.data[key];
+ };
+ class_1.prototype.set = function (key, value) {
+ if (!this.has(key)) {
+ this.size++;
+ }
+ this.data[key] = value;
+ return this;
+ };
+ class_1.prototype.has = function (key) {
+ // tslint:disable-next-line:no-in-operator
+ return key in this.data;
+ };
+ class_1.prototype.delete = function (key) {
+ if (this.has(key)) {
+ this.size--;
+ delete this.data[key];
+ return true;
+ }
+ return false;
+ };
+ class_1.prototype.clear = function () {
+ this.data = createDictionaryObject();
+ this.size = 0;
+ };
+ class_1.prototype.keys = function () {
+ return new MapIterator(this.data, function (_data, key) { return key; });
+ };
+ class_1.prototype.values = function () {
+ return new MapIterator(this.data, function (data, key) { return data[key]; });
+ };
+ class_1.prototype.entries = function () {
+ return new MapIterator(this.data, function (data, key) { return [key, data[key]]; });
+ };
+ class_1.prototype.forEach = function (action) {
+ for (var key in this.data) {
+ action(this.data[key], key);
+ }
+ };
+ return class_1;
+ }());
+ }
function createFileMap(keyMapper) {
var files = createMap();
return {
@@ -1224,33 +1386,28 @@ var ts;
clear: clear,
};
function forEachValueInMap(f) {
- for (var key in files) {
- f(key, files[key]);
- }
+ files.forEach(function (file, key) {
+ f(key, file);
+ });
}
function getKeys() {
- var keys = [];
- for (var key in files) {
- keys.push(key);
- }
- return keys;
+ return arrayFrom(files.keys());
}
// path should already be well-formed so it does not need to be normalized
function get(path) {
- return files[toKey(path)];
+ return files.get(toKey(path));
}
function set(path, value) {
- files[toKey(path)] = value;
+ files.set(toKey(path), value);
}
function contains(path) {
- return toKey(path) in files;
+ return files.has(toKey(path));
}
function remove(path) {
- var key = toKey(path);
- delete files[key];
+ files.delete(toKey(path));
}
function clear() {
- files = createMap();
+ files.clear();
}
function toKey(path) {
return keyMapper ? keyMapper(path) : path;
@@ -1270,6 +1427,10 @@ var ts;
Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
})(Comparison = ts.Comparison || (ts.Comparison = {}));
+ function length(array) {
+ return array ? array.length : 0;
+ }
+ ts.length = length;
/**
* Iterates through 'array' by index and performs the callback on each element of array until the callback
* returns a truthy value, then returns that value.
@@ -1277,7 +1438,7 @@ var ts;
*/
function forEach(array, callback) {
if (array) {
- for (var i = 0, len = array.length; i < len; i++) {
+ for (var i = 0; i < array.length; i++) {
var result = callback(array[i], i);
if (result) {
return result;
@@ -1287,6 +1448,26 @@ var ts;
return undefined;
}
ts.forEach = forEach;
+ /**
+ * Iterates through the parent chain of a node and performs the callback on each parent until the callback
+ * returns a truthy value, then returns that value.
+ * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit"
+ * At that point findAncestor returns undefined.
+ */
+ function findAncestor(node, callback) {
+ while (node) {
+ var result = callback(node);
+ if (result === "quit") {
+ return undefined;
+ }
+ else if (result) {
+ return node;
+ }
+ node = node.parent;
+ }
+ return undefined;
+ }
+ ts.findAncestor = findAncestor;
function zipWith(arrayA, arrayB, callback) {
Debug.assert(arrayA.length === arrayB.length);
for (var i = 0; i < arrayA.length; i++) {
@@ -1301,7 +1482,7 @@ var ts;
*/
function every(array, callback) {
if (array) {
- for (var i = 0, len = array.length; i < len; i++) {
+ for (var i = 0; i < array.length; i++) {
if (!callback(array[i], i)) {
return false;
}
@@ -1312,7 +1493,7 @@ var ts;
ts.every = every;
/** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */
function find(array, predicate) {
- for (var i = 0, len = array.length; i < len; i++) {
+ for (var i = 0; i < array.length; i++) {
var value = array[i];
if (predicate(value, i)) {
return value;
@@ -1321,12 +1502,22 @@ var ts;
return undefined;
}
ts.find = find;
+ /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
+ function findIndex(array, predicate) {
+ for (var i = 0; i < array.length; i++) {
+ if (predicate(array[i], i)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ ts.findIndex = findIndex;
/**
* Returns the first truthy result of `callback`, or else fails.
* This is like `forEach`, but never returns undefined.
*/
function findMap(array, callback) {
- for (var i = 0, len = array.length; i < len; i++) {
+ for (var i = 0; i < array.length; i++) {
var result = callback(array[i], i);
if (result) {
return result;
@@ -1349,7 +1540,7 @@ var ts;
ts.contains = contains;
function indexOf(array, value) {
if (array) {
- for (var i = 0, len = array.length; i < len; i++) {
+ for (var i = 0; i < array.length; i++) {
if (array[i] === value) {
return i;
}
@@ -1359,7 +1550,7 @@ var ts;
}
ts.indexOf = indexOf;
function indexOfAnyCharCode(text, charCodes, start) {
- for (var i = start || 0, len = text.length; i < len; i++) {
+ for (var i = start || 0; i < text.length; i++) {
if (contains(charCodes, text.charCodeAt(i))) {
return i;
}
@@ -1569,21 +1760,18 @@ var ts;
return result;
}
ts.spanMap = spanMap;
- function mapObject(object, f) {
- var result;
- if (object) {
- result = {};
- for (var _i = 0, _a = getOwnKeys(object); _i < _a.length; _i++) {
- var v = _a[_i];
- var _b = f(v, object[v]) || [undefined, undefined], key = _b[0], value = _b[1];
- if (key !== undefined) {
- result[key] = value;
- }
- }
+ function mapEntries(map, f) {
+ if (!map) {
+ return undefined;
}
+ var result = createMap();
+ map.forEach(function (value, key) {
+ var _a = f(key, value), newKey = _a[0], newValue = _a[1];
+ result.set(newKey, newValue);
+ });
return result;
}
- ts.mapObject = mapObject;
+ ts.mapEntries = mapEntries;
function some(array, predicate) {
if (array) {
if (predicate) {
@@ -1901,9 +2089,6 @@ var ts;
/**
* Indicates whether a map-like contains an own property with the specified key.
*
- * NOTE: This is intended for use only with MapLike<T> objects. For Map<T> objects, use
- * the 'in' operator.
- *
* @param map A map-like.
* @param key A property key.
*/
@@ -1914,9 +2099,6 @@ var ts;
/**
* Gets the value of an owned property in a map-like.
*
- * NOTE: This is intended for use only with MapLike<T> objects. For Map<T> objects, use
- * an indexer.
- *
* @param map A map-like.
* @param key A property key.
*/
@@ -1941,56 +2123,61 @@ var ts;
return keys;
}
ts.getOwnKeys = getOwnKeys;
- /**
- * Enumerates the properties of a Map<T>, invoking a callback and returning the first truthy result.
- *
- * @param map A map for which properties should be enumerated.
- * @param callback A callback to invoke for each property.
- */
- function forEachProperty(map, callback) {
- var result;
- for (var key in map) {
- if (result = callback(map[key], key))
- break;
+ function arrayFrom(iterator, map) {
+ var result = [];
+ for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ result.push(map ? map(value) : value);
}
return result;
+ var _b;
}
- ts.forEachProperty = forEachProperty;
- /**
- * Returns true if a Map<T> has some matching property.
- *
- * @param map A map whose properties should be tested.
- * @param predicate An optional callback used to test each property.
- */
- function someProperties(map, predicate) {
- for (var key in map) {
- if (!predicate || predicate(map[key], key))
- return true;
+ ts.arrayFrom = arrayFrom;
+ function convertToArray(iterator, f) {
+ var result = [];
+ for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ result.push(f(value));
}
- return false;
+ return result;
+ var _b;
}
- ts.someProperties = someProperties;
+ ts.convertToArray = convertToArray;
/**
- * Performs a shallow copy of the properties from a source Map<T> to a target MapLike<T>
- *
- * @param source A map from which properties should be copied.
- * @param target A map to which properties should be copied.
+ * Calls `callback` for each entry in the map, returning the first truthy result.
+ * Use `map.forEach` instead for normal iteration.
*/
- function copyProperties(source, target) {
- for (var key in source) {
- target[key] = source[key];
+ function forEachEntry(map, callback) {
+ var iterator = map.entries();
+ for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) {
+ var key = pair[0], value = pair[1];
+ var result = callback(value, key);
+ if (result) {
+ return result;
+ }
}
+ return undefined;
+ var _b;
}
- ts.copyProperties = copyProperties;
- function appendProperty(map, key, value) {
- if (key === undefined || value === undefined)
- return map;
- if (map === undefined)
- map = createMap();
- map[key] = value;
- return map;
+ ts.forEachEntry = forEachEntry;
+ /** `forEachEntry` for just keys. */
+ function forEachKey(map, callback) {
+ var iterator = map.keys();
+ for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) {
+ var result = callback(key);
+ if (result) {
+ return result;
+ }
+ }
+ return undefined;
+ var _b;
}
- ts.appendProperty = appendProperty;
+ ts.forEachKey = forEachKey;
+ /** Copy entries from `source` to `target`. */
+ function copyEntries(source, target) {
+ source.forEach(function (value, key) {
+ target.set(key, value);
+ });
+ }
+ ts.copyEntries = copyEntries;
function assign(t) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
@@ -1998,52 +2185,15 @@ var ts;
}
for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
var arg = args_1[_a];
- for (var _b = 0, _c = getOwnKeys(arg); _b < _c.length; _b++) {
- var p = _c[_b];
- t[p] = arg[p];
- }
+ for (var p in arg)
+ if (hasProperty(arg, p)) {
+ t[p] = arg[p];
+ }
}
return t;
}
ts.assign = assign;
/**
- * Reduce the properties of a map.
- *
- * NOTE: This is intended for use with Map<T> objects. For MapLike<T> objects, use
- * reduceOwnProperties instead as it offers better runtime safety.
- *
- * @param map The map to reduce
- * @param callback An aggregation function that is called for each entry in the map
- * @param initial The initial value for the reduction.
- */
- function reduceProperties(map, callback, initial) {
- var result = initial;
- for (var key in map) {
- result = callback(result, map[key], String(key));
- }
- return result;
- }
- ts.reduceProperties = reduceProperties;
- /**
- * Reduce the properties defined on a map-like (but not from its prototype chain).
- *
- * NOTE: This is intended for use with MapLike<T> objects. For Map<T> objects, use
- * reduceProperties instead as it offers better performance.
- *
- * @param map The map-like to reduce
- * @param callback An aggregation function that is called for each entry in the map
- * @param initial The initial value for the reduction.
- */
- function reduceOwnProperties(map, callback, initial) {
- var result = initial;
- for (var key in map)
- if (hasOwnProperty.call(map, key)) {
- result = callback(result, map[key], String(key));
- }
- return result;
- }
- ts.reduceOwnProperties = reduceOwnProperties;
- /**
* Performs a shallow equality comparison of the contents of two map-likes.
*
* @param left A map-like whose properties should be compared.
@@ -2073,23 +2223,14 @@ var ts;
var result = createMap();
for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
var value = array_8[_i];
- result[makeKey(value)] = makeValue ? makeValue(value) : value;
+ result.set(makeKey(value), makeValue ? makeValue(value) : value);
}
return result;
}
ts.arrayToMap = arrayToMap;
- function isEmpty(map) {
- for (var id in map) {
- if (hasProperty(map, id)) {
- return false;
- }
- }
- return true;
- }
- ts.isEmpty = isEmpty;
function cloneMap(map) {
var clone = createMap();
- copyProperties(map, clone);
+ copyEntries(map, clone);
return clone;
}
ts.cloneMap = cloneMap;
@@ -2116,36 +2257,32 @@ var ts;
return result;
}
ts.extend = extend;
- /**
- * Adds the value to an array of values associated with the key, and returns the array.
- * Creates the array if it does not already exist.
- */
- function multiMapAdd(map, key, value) {
- var values = map[key];
+ function createMultiMap() {
+ var map = createMap();
+ map.add = multiMapAdd;
+ map.remove = multiMapRemove;
+ return map;
+ }
+ ts.createMultiMap = createMultiMap;
+ function multiMapAdd(key, value) {
+ var values = this.get(key);
if (values) {
values.push(value);
- return values;
}
else {
- return map[key] = [value];
+ this.set(key, values = [value]);
}
+ return values;
}
- ts.multiMapAdd = multiMapAdd;
- /**
- * Removes a value from an array of values associated with the key.
- * Does not preserve the order of those values.
- * Does nothing if `key` is not in `map`, or `value` is not in `map[key]`.
- */
- function multiMapRemove(map, key, value) {
- var values = map[key];
+ function multiMapRemove(key, value) {
+ var values = this.get(key);
if (values) {
unorderedRemoveItem(values, value);
if (!values.length) {
- delete map[key];
+ this.delete(key);
}
}
}
- ts.multiMapRemove = multiMapRemove;
/**
* Tests whether a value is an array.
*/
@@ -2226,6 +2363,7 @@ var ts;
baseIndex = baseIndex || 0;
return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; });
}
+ ts.formatStringFromArgs = formatStringFromArgs;
ts.localizedDiagnosticMessages = undefined;
function getLocaleSpecificMessage(message) {
return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
@@ -2328,9 +2466,12 @@ var ts;
if (b === undefined)
return 1 /* GreaterThan */;
if (ignoreCase) {
- if (ts.collator && String.prototype.localeCompare) {
- // accent means a ≠ b, a ≠ á, a = A
- var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" });
+ // Checking if "collator exists indicates that Intl is available.
+ // We still have to check if "collator.compare" is correct. If it is not, use "String.localeComapre"
+ if (ts.collator) {
+ var result = ts.localeCompareIsCorrect ?
+ ts.collator.compare(a, b) :
+ a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); // accent means a ≠ b, a ≠ á, a = A
return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
}
a = a.toUpperCase();
@@ -2403,7 +2544,7 @@ var ts;
ts.normalizeSlashes = normalizeSlashes;
/**
* Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files")
- */
+ */
function getRootLength(path) {
if (path.charCodeAt(0) === 47 /* slash */) {
if (path.charCodeAt(1) !== 47 /* slash */)
@@ -2775,6 +2916,17 @@ var ts;
var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*";
var singleAsteriskRegexFragmentOther = "[^/]*";
function getRegularExpressionForWildcard(specs, basePath, usage) {
+ var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
+ if (!patterns || !patterns.length) {
+ return undefined;
+ }
+ var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
+ // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
+ var terminator = usage === "exclude" ? "($|/)" : "$";
+ return "^(" + pattern + ")" + terminator;
+ }
+ ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
+ function getRegularExpressionsForWildcards(specs, basePath, usage) {
if (specs === undefined || specs.length === 0) {
return undefined;
}
@@ -2785,31 +2937,10 @@ var ts;
* files or directories, does not match subdirectories that start with a . character
*/
var doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?";
- var pattern = "";
- var hasWrittenSubpattern = false;
- for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) {
- var spec = specs_1[_i];
- if (!spec) {
- continue;
- }
- var subPattern = getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter);
- if (subPattern === undefined) {
- continue;
- }
- if (hasWrittenSubpattern) {
- pattern += "|";
- }
- pattern += "(" + subPattern + ")";
- hasWrittenSubpattern = true;
- }
- if (!pattern) {
- return undefined;
- }
- // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
- var terminator = usage === "exclude" ? "($|/)" : "$";
- return "^(" + pattern + ")" + terminator;
+ return flatMap(specs, function (spec) {
+ return spec && getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter);
+ });
}
- ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
/**
* An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
* and does not contain any glob characters itself.
@@ -2888,6 +3019,7 @@ var ts;
currentDirectory = normalizePath(currentDirectory);
var absolutePath = combinePaths(currentDirectory, path);
return {
+ includeFilePatterns: map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
@@ -2900,34 +3032,50 @@ var ts;
currentDirectory = normalizePath(currentDirectory);
var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
var regexFlag = useCaseSensitiveFileNames ? "" : "i";
- var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag);
+ var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); });
var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag);
var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag);
- var result = [];
+ // Associate an array of results with each include regex. This keeps results in order of the "include" order.
+ // If there are no "includes", then just put everything in results[0].
+ var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
+ var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive;
for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
var basePath = _a[_i];
visitDirectory(basePath, combinePaths(currentDirectory, basePath));
}
- return result;
+ return flatten(results);
function visitDirectory(path, absolutePath) {
var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
- for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
- var current = files_1[_i];
- var name_1 = combinePaths(path, current);
+ files = files.slice().sort(comparer);
+ directories = directories.slice().sort(comparer);
+ var _loop_1 = function (current) {
+ var name = combinePaths(path, current);
var absoluteName = combinePaths(absolutePath, current);
- if ((!extensions || fileExtensionIsAny(name_1, extensions)) &&
- (!includeFileRegex || includeFileRegex.test(absoluteName)) &&
- (!excludeRegex || !excludeRegex.test(absoluteName))) {
- result.push(name_1);
+ if (extensions && !fileExtensionIsAny(name, extensions))
+ return "continue";
+ if (excludeRegex && excludeRegex.test(absoluteName))
+ return "continue";
+ if (!includeFileRegexes) {
+ results[0].push(name);
+ }
+ else {
+ var includeIndex = findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
+ if (includeIndex !== -1) {
+ results[includeIndex].push(name);
+ }
}
+ };
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
+ var current = files_1[_i];
+ _loop_1(current);
}
for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) {
var current = directories_1[_b];
- var name_2 = combinePaths(path, current);
+ var name = combinePaths(path, current);
var absoluteName = combinePaths(absolutePath, current);
if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
(!excludeRegex || !excludeRegex.test(absoluteName))) {
- visitDirectory(name_2, absoluteName);
+ visitDirectory(name, absoluteName);
}
}
}
@@ -2952,7 +3100,7 @@ var ts;
}
// Sort the offsets array using either the literal or canonical path representations.
includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive);
- var _loop_1 = function (includeBasePath) {
+ var _loop_2 = function (includeBasePath) {
if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
basePaths.push(includeBasePath);
}
@@ -2961,7 +3109,7 @@ var ts;
// subpath of an existing base path
for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
var includeBasePath = includeBasePaths_1[_a];
- _loop_1(includeBasePath);
+ _loop_2(includeBasePath);
}
}
return basePaths;
@@ -3010,8 +3158,19 @@ var ts;
ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"];
ts.supportedJavascriptExtensions = [".js", ".jsx"];
var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions);
- function getSupportedExtensions(options) {
- return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
+ function getSupportedExtensions(options, extraFileExtensions) {
+ var needAllExtensions = options && options.allowJs;
+ if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
+ return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
+ }
+ var extensions = allSupportedExtensions.slice(0);
+ for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) {
+ var extInfo = extraFileExtensions_1[_i];
+ if (extensions.indexOf(extInfo.extension) === -1) {
+ extensions.push(extInfo.extension);
+ }
+ }
+ return extensions;
}
ts.getSupportedExtensions = getSupportedExtensions;
function hasJavaScriptFileExtension(fileName) {
@@ -3022,11 +3181,11 @@ var ts;
return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
}
ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension;
- function isSupportedSourceFileName(fileName, compilerOptions) {
+ function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
if (!fileName) {
return false;
}
- for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) {
var extension = _a[_i];
if (fileExtensionIs(fileName, extension)) {
return true;
@@ -3044,14 +3203,13 @@ var ts;
(function (ExtensionPriority) {
ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
- ExtensionPriority[ExtensionPriority["Limit"] = 5] = "Limit";
ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
})(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
function getExtensionPriority(path, supportedExtensions) {
for (var i = supportedExtensions.length - 1; i >= 0; i--) {
if (fileExtensionIs(path, supportedExtensions[i])) {
- return adjustExtensionPriority(i);
+ return adjustExtensionPriority(i, supportedExtensions);
}
}
// If its not in the list of supported extensions, this is likely a
@@ -3062,27 +3220,27 @@ var ts;
/**
* Adjusts an extension priority to be the highest priority within the same range.
*/
- function adjustExtensionPriority(extensionPriority) {
+ function adjustExtensionPriority(extensionPriority, supportedExtensions) {
if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
return 0 /* TypeScriptFiles */;
}
- else if (extensionPriority < 5 /* Limit */) {
+ else if (extensionPriority < supportedExtensions.length) {
return 2 /* DeclarationAndJavaScriptFiles */;
}
else {
- return 5 /* Limit */;
+ return supportedExtensions.length;
}
}
ts.adjustExtensionPriority = adjustExtensionPriority;
/**
* Gets the next lowest extension priority for a given priority.
*/
- function getNextLowestExtensionPriority(extensionPriority) {
+ function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
return 2 /* DeclarationAndJavaScriptFiles */;
}
else {
- return 5 /* Limit */;
+ return supportedExtensions.length;
}
}
ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
@@ -3329,144 +3487,30 @@ var ts;
}
}
ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
+ function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
+ return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
+ }
+ ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
})(ts || (ts = {}));
/// <reference path="core.ts"/>
var ts;
(function (ts) {
- ts.sys = (function () {
- function getWScriptSystem() {
- var fso = new ActiveXObject("Scripting.FileSystemObject");
- var shell = new ActiveXObject("WScript.Shell");
- var fileStream = new ActiveXObject("ADODB.Stream");
- fileStream.Type = 2 /*text*/;
- var binaryStream = new ActiveXObject("ADODB.Stream");
- binaryStream.Type = 1 /*binary*/;
- var args = [];
- for (var i = 0; i < WScript.Arguments.length; i++) {
- args[i] = WScript.Arguments.Item(i);
- }
- function readFile(fileName, encoding) {
- if (!fso.FileExists(fileName)) {
- return undefined;
- }
- fileStream.Open();
- try {
- if (encoding) {
- fileStream.Charset = encoding;
- fileStream.LoadFromFile(fileName);
- }
- else {
- // Load file and read the first two bytes into a string with no interpretation
- fileStream.Charset = "x-ansi";
- fileStream.LoadFromFile(fileName);
- var bom = fileStream.ReadText(2) || "";
- // Position must be at 0 before encoding can be changed
- fileStream.Position = 0;
- // [0xFF,0xFE] and [0xFE,0xFF] mean utf-16 (little or big endian), otherwise default to utf-8
- fileStream.Charset = bom.length >= 2 && (bom.charCodeAt(0) === 0xFF && bom.charCodeAt(1) === 0xFE || bom.charCodeAt(0) === 0xFE && bom.charCodeAt(1) === 0xFF) ? "unicode" : "utf-8";
- }
- // ReadText method always strips byte order mark from resulting string
- return fileStream.ReadText();
- }
- catch (e) {
- throw e;
- }
- finally {
- fileStream.Close();
- }
- }
- function writeFile(fileName, data, writeByteOrderMark) {
- fileStream.Open();
- binaryStream.Open();
- try {
- // Write characters in UTF-8 encoding
- fileStream.Charset = "utf-8";
- fileStream.WriteText(data);
- // If we don't want the BOM, then skip it by setting the starting location to 3 (size of BOM).
- // If not, start from position 0, as the BOM will be added automatically when charset==utf8.
- if (writeByteOrderMark) {
- fileStream.Position = 0;
- }
- else {
- fileStream.Position = 3;
- }
- fileStream.CopyTo(binaryStream);
- binaryStream.SaveToFile(fileName, 2 /*overwrite*/);
- }
- finally {
- binaryStream.Close();
- fileStream.Close();
- }
- }
- function getNames(collection) {
- var result = [];
- for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) {
- result.push(e.item().Name);
- }
- return result.sort();
- }
- function getDirectories(path) {
- var folder = fso.GetFolder(path);
- return getNames(folder.subfolders);
- }
- function getAccessibleFileSystemEntries(path) {
- try {
- var folder = fso.GetFolder(path || ".");
- var files = getNames(folder.files);
- var directories = getNames(folder.subfolders);
- return { files: files, directories: directories };
- }
- catch (e) {
- return { files: [], directories: [] };
- }
- }
- function readDirectory(path, extensions, excludes, includes) {
- return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
- }
- var wscriptSystem = {
- args: args,
- newLine: "\r\n",
- useCaseSensitiveFileNames: false,
- write: function (s) {
- WScript.StdOut.Write(s);
- },
- readFile: readFile,
- writeFile: writeFile,
- resolvePath: function (path) {
- return fso.GetAbsolutePathName(path);
- },
- fileExists: function (path) {
- return fso.FileExists(path);
- },
- directoryExists: function (path) {
- return fso.FolderExists(path);
- },
- createDirectory: function (directoryName) {
- if (!wscriptSystem.directoryExists(directoryName)) {
- fso.CreateFolder(directoryName);
- }
- },
- getExecutingFilePath: function () {
- return WScript.ScriptFullName;
- },
- getCurrentDirectory: function () {
- return shell.CurrentDirectory;
- },
- getDirectories: getDirectories,
- getEnvironmentVariable: function (name) {
- return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings("%" + name + "%");
- },
- readDirectory: readDirectory,
- exit: function (exitCode) {
- try {
- WScript.Quit(exitCode);
- }
- catch (e) {
- }
- }
- };
- return wscriptSystem;
+ function getNodeMajorVersion() {
+ if (typeof process === "undefined") {
+ return undefined;
}
+ var version = process.version;
+ if (!version) {
+ return undefined;
+ }
+ var dot = version.indexOf(".");
+ if (dot === -1) {
+ return undefined;
+ }
+ return parseInt(version.substring(1, dot));
+ }
+ ts.getNodeMajorVersion = getNodeMajorVersion;
+ ts.sys = (function () {
function getNodeSystem() {
var _fs = require("fs");
var _path = require("path");
@@ -3476,32 +3520,32 @@ var ts;
function createWatchedFileSet() {
var dirWatchers = ts.createMap();
// One file can have multiple watchers
- var fileWatcherCallbacks = ts.createMap();
+ var fileWatcherCallbacks = ts.createMultiMap();
return { addFile: addFile, removeFile: removeFile };
function reduceDirWatcherRefCountForFile(fileName) {
var dirName = ts.getDirectoryPath(fileName);
- var watcher = dirWatchers[dirName];
+ var watcher = dirWatchers.get(dirName);
if (watcher) {
watcher.referenceCount -= 1;
if (watcher.referenceCount <= 0) {
watcher.close();
- delete dirWatchers[dirName];
+ dirWatchers.delete(dirName);
}
}
}
function addDirWatcher(dirPath) {
- var watcher = dirWatchers[dirPath];
+ var watcher = dirWatchers.get(dirPath);
if (watcher) {
watcher.referenceCount += 1;
return;
}
watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); });
watcher.referenceCount = 1;
- dirWatchers[dirPath] = watcher;
+ dirWatchers.set(dirPath, watcher);
return;
}
function addFileWatcherCallback(filePath, callback) {
- ts.multiMapAdd(fileWatcherCallbacks, filePath, callback);
+ fileWatcherCallbacks.add(filePath, callback);
}
function addFile(fileName, callback) {
addFileWatcherCallback(fileName, callback);
@@ -3513,7 +3557,7 @@ var ts;
reduceDirWatcherRefCountForFile(watchedFile.fileName);
}
function removeFileWatcherCallback(filePath, callback) {
- ts.multiMapRemove(fileWatcherCallbacks, filePath, callback);
+ fileWatcherCallbacks.remove(filePath, callback);
}
function fileEventHandler(eventName, relativeFileName, baseDirPath) {
// When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
@@ -3521,18 +3565,20 @@ var ts;
? undefined
: ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath);
// Some applications save a working file via rename operations
- if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) {
- for (var _i = 0, _a = fileWatcherCallbacks[fileName]; _i < _a.length; _i++) {
- var fileCallback = _a[_i];
- fileCallback(fileName);
+ if ((eventName === "change" || eventName === "rename")) {
+ var callbacks = fileWatcherCallbacks.get(fileName);
+ if (callbacks) {
+ for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
+ var fileCallback = callbacks_1[_i];
+ fileCallback(fileName);
+ }
}
}
}
}
var watchedFileSet = createWatchedFileSet();
- function isNode4OrLater() {
- return parseInt(process.version.charAt(1)) >= 4;
- }
+ var nodeVersion = getNodeMajorVersion();
+ var isNode4OrLater = nodeVersion >= 4;
function isFileSystemCaseSensitive() {
// win32\win64 are case insensitive platforms
if (platform === "win32" || platform === "win64") {
@@ -3553,7 +3599,7 @@ var ts;
if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
// Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
// flip all byte pairs and treat as little endian.
- len &= ~1;
+ len &= ~1; // Round down to a multiple of 2
for (var i = 0; i < len; i += 2) {
var temp = buffer[i];
buffer[i] = buffer[i + 1];
@@ -3580,7 +3626,7 @@ var ts;
var fd;
try {
fd = _fs.openSync(fileName, "w");
- _fs.writeSync(fd, data, undefined, "utf8");
+ _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
}
finally {
if (fd !== undefined) {
@@ -3600,10 +3646,10 @@ var ts;
if (entry === "." || entry === "..") {
continue;
}
- var name_3 = ts.combinePaths(path, entry);
+ var name = ts.combinePaths(path, entry);
var stat = void 0;
try {
- stat = _fs.statSync(name_3);
+ stat = _fs.statSync(name);
}
catch (e) {
continue;
@@ -3685,9 +3731,10 @@ var ts;
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
var options;
if (!directoryExists(directoryName)) {
+ // do nothing if target folder does not exist
return noOpFileWatcher;
}
- if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) {
+ if (isNode4OrLater && (process.platform === "win32" || process.platform === "darwin")) {
options = { persistent: true, recursive: !!recursive };
}
else {
@@ -3701,7 +3748,6 @@ var ts;
// When deleting a file, the passed baseFileName is null
callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
}
- ;
});
},
resolvePath: function (path) {
@@ -3765,6 +3811,7 @@ var ts;
require("source-map-support").install();
}
catch (e) {
+ // Could not enable source maps.
}
},
setTimeout: setTimeout,
@@ -3820,9 +3867,6 @@ var ts;
if (typeof ChakraHost !== "undefined") {
sys = getChakraSystem();
}
- else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
- sys = getWScriptSystem();
- }
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
// process and process.nextTick checks if current environment is node-like
// process.browser check excludes webpack and browserify
@@ -3897,11 +3941,11 @@ var ts;
Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." },
Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." },
An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." },
- Operand_for_await_does_not_have_a_valid_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "Operand_for_await_does_not_have_a_valid_callable_then_member_1058", message: "Operand for 'await' does not have a valid callable 'then' member." },
- Return_expression_in_async_function_does_not_have_a_valid_callable_then_member: { code: 1059, category: ts.DiagnosticCategory.Error, key: "Return_expression_in_async_function_does_not_have_a_valid_callable_then_member_1059", message: "Return expression in async function does not have a valid callable 'then' member." },
- Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member: { code: 1060, category: ts.DiagnosticCategory.Error, key: "Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member_1060", message: "Expression body for async arrow function does not have a valid callable 'then' member." },
+ The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", message: "The return type of an async function must either be a valid promise or must not contain a callable 'then' member." },
+ A_promise_must_have_a_then_method: { code: 1059, category: ts.DiagnosticCategory.Error, key: "A_promise_must_have_a_then_method_1059", message: "A promise must have a 'then' method." },
+ The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: { code: 1060, category: ts.DiagnosticCategory.Error, key: "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", message: "The first parameter of the 'then' method of a promise must be a callback." },
Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." },
- _0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "{0} is referenced directly or indirectly in the fulfillment callback of its own 'then' method." },
+ Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method." },
An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." },
The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise<T> type." },
In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." },
@@ -3910,7 +3954,7 @@ var ts;
_0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." },
A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." },
Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." },
- Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher." },
+ Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'." },
An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_be_declared_in_an_ambient_context_1086", message: "An accessor cannot be declared in an ambient context." },
_0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", message: "'{0}' modifier cannot appear on a constructor declaration." },
_0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_parameter_1090", message: "'{0}' modifier cannot appear on a parameter." },
@@ -3926,6 +3970,7 @@ var ts;
Invalid_use_of_0_in_strict_mode: { code: 1100, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_in_strict_mode_1100", message: "Invalid use of '{0}' in strict mode." },
with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_strict_mode_1101", message: "'with' statements are not allowed in strict mode." },
delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: ts.DiagnosticCategory.Error, key: "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", message: "'delete' cannot be called on an identifier in strict mode." },
+ A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: { code: 1103, category: ts.DiagnosticCategory.Error, key: "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", message: "A 'for-await-of' statement is only allowed within an async function or async generator." },
A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", message: "A 'continue' statement can only be used within an enclosing iteration statement." },
A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", message: "A 'break' statement can only be used within an enclosing iteration or switch statement." },
Jump_target_cannot_cross_function_boundary: { code: 1107, category: ts.DiagnosticCategory.Error, key: "Jump_target_cannot_cross_function_boundary_1107", message: "Jump target cannot cross function boundary." },
@@ -3933,7 +3978,7 @@ var ts;
Expression_expected: { code: 1109, category: ts.DiagnosticCategory.Error, key: "Expression_expected_1109", message: "Expression expected." },
Type_expected: { code: 1110, category: ts.DiagnosticCategory.Error, key: "Type_expected_1110", message: "Type expected." },
A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: ts.DiagnosticCategory.Error, key: "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", message: "A 'default' clause cannot appear more than once in a 'switch' statement." },
- Duplicate_label_0: { code: 1114, category: ts.DiagnosticCategory.Error, key: "Duplicate_label_0_1114", message: "Duplicate label '{0}'" },
+ Duplicate_label_0: { code: 1114, category: ts.DiagnosticCategory.Error, key: "Duplicate_label_0_1114", message: "Duplicate label '{0}'." },
A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", message: "A 'continue' statement can only jump to a label of an enclosing iteration statement." },
A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", message: "A 'break' statement can only jump to a label of an enclosing statement." },
An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", message: "An object literal cannot have multiple properties with the same name in strict mode." },
@@ -3965,9 +4010,9 @@ var ts;
Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." },
Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." },
Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." },
- File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing" },
+ File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing." },
new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead." },
- const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized" },
+ const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized." },
const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: ts.DiagnosticCategory.Error, key: "const_declarations_can_only_be_declared_inside_a_block_1156", message: "'const' declarations can only be declared inside a block." },
let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: ts.DiagnosticCategory.Error, key: "let_declarations_can_only_be_declared_inside_a_block_1157", message: "'let' declarations can only be declared inside a block." },
Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated_template_literal_1160", message: "Unterminated template literal." },
@@ -4016,11 +4061,12 @@ var ts;
Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." },
Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", message: "Ambient const enums are not allowed when the '--isolatedModules' flag is provided." },
Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: { code: 1210, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", message: "Invalid use of '{0}'. Class definitions are automatically in strict mode." },
- A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: ts.DiagnosticCategory.Error, key: "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", message: "A class declaration without the 'default' modifier must have a name" },
- Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", message: "Identifier expected. '{0}' is a reserved word in strict mode" },
+ A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: ts.DiagnosticCategory.Error, key: "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", message: "A class declaration without the 'default' modifier must have a name." },
+ Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", message: "Identifier expected. '{0}' is a reserved word in strict mode." },
Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." },
Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." },
Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." },
+ Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." },
Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." },
Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." },
Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." },
@@ -4066,6 +4112,11 @@ var ts;
Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." },
Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." },
A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." },
+ An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." },
+ A_default_export_can_only_be_used_in_an_ECMAScript_style_module: { code: 1319, category: ts.DiagnosticCategory.Error, key: "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", message: "A default export can only be used in an ECMAScript-style module." },
+ Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1320, category: ts.DiagnosticCategory.Error, key: "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", message: "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member." },
+ Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1321, category: ts.DiagnosticCategory.Error, key: "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", message: "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member." },
+ Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1322, category: ts.DiagnosticCategory.Error, key: "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", message: "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member." },
Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." },
Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." },
Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." },
@@ -4109,6 +4160,7 @@ var ts;
Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." },
Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." },
An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." },
+ This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: { code: 2343, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", message: "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'." },
Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type_0_does_not_satisfy_the_constraint_1_2344", message: "Type '{0}' does not satisfy the constraint '{1}'." },
Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", message: "Argument of type '{0}' is not assignable to parameter of type '{1}'." },
Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied_parameters_do_not_match_any_signature_of_call_target_2346", message: "Supplied parameters do not match any signature of call target." },
@@ -4119,19 +4171,20 @@ var ts;
Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." },
Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." },
Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." },
+ This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." },
A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." },
An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." },
The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." },
The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." },
The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." },
The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." },
- The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" },
+ The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter." },
The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." },
The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." },
The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." },
Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." },
Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." },
- Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'" },
+ Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'." },
A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", message: "A parameter property is only allowed in a constructor implementation." },
A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_of_an_array_type_2370", message: "A rest parameter must be of an array type." },
A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 2371, category: ts.DiagnosticCategory.Error, key: "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", message: "A parameter initializer is only allowed in a function or constructor implementation." },
@@ -4171,12 +4224,12 @@ var ts;
The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." },
The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." },
Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." },
- Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" },
+ Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class." },
The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." },
Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." },
Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." },
Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." },
- Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'" },
+ Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'." },
Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." },
Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." },
Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." },
@@ -4185,19 +4238,19 @@ var ts;
Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." },
Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." },
Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." },
- Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'" },
+ Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'." },
All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." },
Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." },
- Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'" },
+ Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'." },
In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." },
- A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", message: "A namespace declaration cannot be in a different file from a class or function with which it is merged" },
- A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", message: "A namespace declaration cannot be located prior to a class or function with which it is merged" },
+ A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", message: "A namespace declaration cannot be in a different file from a class or function with which it is merged." },
+ A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", message: "A namespace declaration cannot be located prior to a class or function with which it is merged." },
Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: { code: 2435, category: ts.DiagnosticCategory.Error, key: "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", message: "Ambient modules cannot be nested in other modules or namespaces." },
Ambient_module_declaration_cannot_specify_relative_module_name: { code: 2436, category: ts.DiagnosticCategory.Error, key: "Ambient_module_declaration_cannot_specify_relative_module_name_2436", message: "Ambient module declaration cannot specify relative module name." },
- Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: ts.DiagnosticCategory.Error, key: "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", message: "Module '{0}' is hidden by a local declaration with the same name" },
- Import_name_cannot_be_0: { code: 2438, category: ts.DiagnosticCategory.Error, key: "Import_name_cannot_be_0_2438", message: "Import name cannot be '{0}'" },
+ Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: ts.DiagnosticCategory.Error, key: "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", message: "Module '{0}' is hidden by a local declaration with the same name." },
+ Import_name_cannot_be_0: { code: 2438, category: ts.DiagnosticCategory.Error, key: "Import_name_cannot_be_0_2438", message: "Import name cannot be '{0}'." },
Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: { code: 2439, category: ts.DiagnosticCategory.Error, key: "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", message: "Import or export declaration in an ambient module declaration cannot reference module through relative module name." },
- Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: ts.DiagnosticCategory.Error, key: "Import_declaration_conflicts_with_local_declaration_of_0_2440", message: "Import declaration conflicts with local declaration of '{0}'" },
+ Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: ts.DiagnosticCategory.Error, key: "Import_declaration_conflicts_with_local_declaration_of_0_2440", message: "Import declaration conflicts with local declaration of '{0}'." },
Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: { code: 2441, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module." },
Types_have_separate_declarations_of_a_private_property_0: { code: 2442, category: ts.DiagnosticCategory.Error, key: "Types_have_separate_declarations_of_a_private_property_0_2442", message: "Types have separate declarations of a private property '{0}'." },
Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: { code: 2443, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", message: "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'." },
@@ -4206,18 +4259,20 @@ var ts;
Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." },
The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." },
Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." },
+ Class_0_used_before_its_declaration: { code: 2449, category: ts.DiagnosticCategory.Error, key: "Class_0_used_before_its_declaration_2449", message: "Class '{0}' used before its declaration." },
+ Enum_0_used_before_its_declaration: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Enum_0_used_before_its_declaration_2450", message: "Enum '{0}' used before its declaration." },
Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." },
An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." },
The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." },
Variable_0_is_used_before_being_assigned: { code: 2454, category: ts.DiagnosticCategory.Error, key: "Variable_0_is_used_before_being_assigned_2454", message: "Variable '{0}' is used before being assigned." },
Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: ts.DiagnosticCategory.Error, key: "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", message: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." },
Type_alias_0_circularly_references_itself: { code: 2456, category: ts.DiagnosticCategory.Error, key: "Type_alias_0_circularly_references_itself_2456", message: "Type alias '{0}' circularly references itself." },
- Type_alias_name_cannot_be_0: { code: 2457, category: ts.DiagnosticCategory.Error, key: "Type_alias_name_cannot_be_0_2457", message: "Type alias name cannot be '{0}'" },
+ Type_alias_name_cannot_be_0: { code: 2457, category: ts.DiagnosticCategory.Error, key: "Type_alias_name_cannot_be_0_2457", message: "Type alias name cannot be '{0}'." },
An_AMD_module_cannot_have_multiple_name_assignments: { code: 2458, category: ts.DiagnosticCategory.Error, key: "An_AMD_module_cannot_have_multiple_name_assignments_2458", message: "An AMD module cannot have multiple name assignments." },
Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." },
Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." },
Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." },
- A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern" },
+ A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern." },
A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." },
A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." },
this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." },
@@ -4238,13 +4293,13 @@ var ts;
let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: { code: 2480, category: ts.DiagnosticCategory.Error, key: "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", message: "'let' is not allowed to be used as a name in 'let' or 'const' declarations." },
Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." },
The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." },
- Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'" },
+ Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'." },
The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." },
Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." },
An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." },
The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." },
The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: { code: 2491, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", message: "The left-hand side of a 'for...in' statement cannot be a destructuring pattern." },
- Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_identifier_0_in_catch_clause_2492", message: "Cannot redeclare identifier '{0}' in catch clause" },
+ Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_identifier_0_in_catch_clause_2492", message: "Cannot redeclare identifier '{0}' in catch clause." },
Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: { code: 2493, category: ts.DiagnosticCategory.Error, key: "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", message: "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'." },
Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: { code: 2494, category: ts.DiagnosticCategory.Error, key: "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", message: "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher." },
Type_0_is_not_an_array_type_or_a_string_type: { code: 2495, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_2495", message: "Type '{0}' is not an array type or a string type." },
@@ -4256,6 +4311,7 @@ var ts;
A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." },
_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." },
Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." },
+ Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: { code: 2504, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", message: "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator." },
A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." },
_0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." },
Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." },
@@ -4270,6 +4326,7 @@ var ts;
All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." },
Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." },
A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." },
+ An_async_iterator_must_have_a_next_method: { code: 2519, category: ts.DiagnosticCategory.Error, key: "An_async_iterator_must_have_a_next_method_2519", message: "An async iterator must have a 'next()' method." },
Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." },
Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." },
The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." },
@@ -4293,23 +4350,33 @@ var ts;
Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." },
The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." },
Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." },
+ Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." },
+ Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." },
+ A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." },
+ Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." },
+ The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: { code: 2547, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", message: "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property." },
+ Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2548, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", message: "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator." },
+ Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2549, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", message: "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator." },
+ Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: { code: 2550, category: ts.DiagnosticCategory.Error, key: "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", message: "Generic type instantiation is excessively deep and possibly infinite." },
JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." },
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." },
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." },
- Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'" },
+ Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'." },
JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", message: "JSX element type '{0}' does not have any construct or call signatures." },
JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", message: "JSX element type '{0}' is not a constructor function for JSX elements." },
Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: ts.DiagnosticCategory.Error, key: "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", message: "Property '{0}' of JSX spread attribute is not assignable to target property." },
- JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: ts.DiagnosticCategory.Error, key: "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", message: "JSX element class does not support attributes because it does not have a '{0}' property" },
- The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: ts.DiagnosticCategory.Error, key: "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", message: "The global type 'JSX.{0}' may not have more than one property" },
- Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: ts.DiagnosticCategory.Error, key: "Cannot_emit_namespaced_JSX_elements_in_React_2650", message: "Cannot emit namespaced JSX elements in React" },
+ JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: ts.DiagnosticCategory.Error, key: "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", message: "JSX element class does not support attributes because it does not have a '{0}' property." },
+ The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: ts.DiagnosticCategory.Error, key: "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", message: "The global type 'JSX.{0}' may not have more than one property." },
+ JSX_spread_child_must_be_an_array_type: { code: 2609, category: ts.DiagnosticCategory.Error, key: "JSX_spread_child_must_be_an_array_type_2609", message: "JSX spread child must be an array type." },
+ Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: { code: 2649, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", message: "Cannot augment module '{0}' with value exports because it resolves to a non-module entity." },
+ Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: ts.DiagnosticCategory.Error, key: "Cannot_emit_namespaced_JSX_elements_in_React_2650", message: "Cannot emit namespaced JSX elements in React." },
A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: ts.DiagnosticCategory.Error, key: "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", message: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." },
Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: ts.DiagnosticCategory.Error, key: "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", message: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." },
Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: { code: 2653, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", message: "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'." },
Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." },
Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." },
- JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element" },
- Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'" },
+ JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element." },
+ Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'." },
super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." },
super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." },
Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", message: "Cannot export '{0}'. Only local declarations can be exported from a module." },
@@ -4341,7 +4408,6 @@ var ts;
All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." },
Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." },
Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" },
- A_class_must_be_declared_after_its_base_class: { code: 2690, category: ts.DiagnosticCategory.Error, key: "A_class_must_be_declared_after_its_base_class_2690", message: "A class must be declared after its base class." },
An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." },
_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." },
_0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." },
@@ -4350,9 +4416,17 @@ var ts;
The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" },
An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." },
Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." },
+ Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: { code: 2699, category: ts.DiagnosticCategory.Error, key: "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", message: "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'." },
Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." },
The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." },
_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." },
+ The_operand_of_a_delete_operator_must_be_a_property_reference: { code: 2703, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", message: "The operand of a delete operator must be a property reference." },
+ The_operand_of_a_delete_operator_cannot_be_a_read_only_property: { code: 2704, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", message: "The operand of a delete operator cannot be a read-only property." },
+ An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: { code: 2705, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", message: "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option." },
+ Required_type_parameters_may_not_follow_optional_type_parameters: { code: 2706, category: ts.DiagnosticCategory.Error, key: "Required_type_parameters_may_not_follow_optional_type_parameters_2706", message: "Required type parameters may not follow optional type parameters." },
+ Generic_type_0_requires_between_1_and_2_type_arguments: { code: 2707, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_between_1_and_2_type_arguments_2707", message: "Generic type '{0}' requires between {1} and {2} type arguments." },
+ Cannot_use_namespace_0_as_a_value: { code: 2708, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_value_2708", message: "Cannot use namespace '{0}' as a value." },
+ Cannot_use_namespace_0_as_a_type: { code: 2709, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_type_2709", message: "Cannot use namespace '{0}' as a type." },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
@@ -4363,8 +4437,8 @@ var ts;
Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4014, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", message: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." },
Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4016, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", message: "Type parameter '{0}' of exported function has or is using private name '{1}'." },
Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4019, category: ts.DiagnosticCategory.Error, key: "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", message: "Implements clause of exported class '{0}' has or is using private name '{1}'." },
- Extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: ts.DiagnosticCategory.Error, key: "Extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", message: "Extends clause of exported class '{0}' has or is using private name '{1}'." },
- Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: ts.DiagnosticCategory.Error, key: "Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", message: "Extends clause of exported interface '{0}' has or is using private name '{1}'." },
+ extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", message: "'extends' clause of exported class '{0}' has or is using private name '{1}'." },
+ extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", message: "'extends' clause of exported interface '{0}' has or is using private name '{1}'." },
Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4023, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", message: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." },
Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 4024, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", message: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." },
Exported_variable_0_has_or_is_using_private_name_1: { code: 4025, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_private_name_1_4025", message: "Exported variable '{0}' has or is using private name '{1}'." },
@@ -4425,16 +4499,18 @@ var ts;
Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." },
Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." },
Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." },
+ Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." },
+ Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." },
+ extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced: { code: 4093, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced_4093", message: "'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced." },
The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." },
Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." },
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." },
File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." },
- Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" },
- Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." },
+ Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}." },
Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." },
Unknown_compiler_option_0: { code: 5023, category: ts.DiagnosticCategory.Error, key: "Unknown_compiler_option_0_5023", message: "Unknown compiler option '{0}'." },
Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_requires_a_value_of_type_1_5024", message: "Compiler option '{0}' requires a value of type {1}." },
- Could_not_write_file_0_Colon_1: { code: 5033, category: ts.DiagnosticCategory.Error, key: "Could_not_write_file_0_Colon_1_5033", message: "Could not write file '{0}': {1}" },
+ Could_not_write_file_0_Colon_1: { code: 5033, category: ts.DiagnosticCategory.Error, key: "Could_not_write_file_0_Colon_1_5033", message: "Could not write file '{0}': {1}." },
Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: ts.DiagnosticCategory.Error, key: "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", message: "Option 'project' cannot be mixed with source files on a command line." },
Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", message: "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher." },
Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: { code: 5051, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", message: "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided." },
@@ -4443,12 +4519,12 @@ var ts;
A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." },
Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." },
Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." },
- Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'" },
- The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'" },
+ Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'." },
+ The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'." },
Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." },
Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." },
- Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character" },
- Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character" },
+ Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character." },
+ Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character." },
Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." },
Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." },
File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." },
@@ -4466,11 +4542,11 @@ var ts;
Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." },
Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." },
Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." },
- Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'" },
- Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" },
+ Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'." },
+ Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'." },
Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." },
Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." },
- Compile_the_project_in_the_given_directory: { code: 6020, category: ts.DiagnosticCategory.Message, key: "Compile_the_project_in_the_given_directory_6020", message: "Compile the project in the given directory." },
+ Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: { code: 6020, category: ts.DiagnosticCategory.Message, key: "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", message: "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'." },
Syntax_Colon_0: { code: 6023, category: ts.DiagnosticCategory.Message, key: "Syntax_Colon_0_6023", message: "Syntax: {0}" },
options: { code: 6024, category: ts.DiagnosticCategory.Message, key: "options_6024", message: "options" },
file: { code: 6025, category: ts.DiagnosticCategory.Message, key: "file_6025", message: "file" },
@@ -4485,11 +4561,12 @@ var ts;
LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" },
DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" },
STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" },
+ FILE_OR_DIRECTORY: { code: 6040, category: ts.DiagnosticCategory.Message, key: "FILE_OR_DIRECTORY_6040", message: "FILE OR DIRECTORY" },
Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." },
Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." },
Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." },
Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." },
- Argument_for_0_option_must_be_Colon_1: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_0_option_must_be_Colon_1_6046", message: "Argument for '{0}' option must be: {1}" },
+ Argument_for_0_option_must_be_Colon_1: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_0_option_must_be_Colon_1_6046", message: "Argument for '{0}' option must be: {1}." },
Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'." },
Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." },
Unable_to_open_file_0: { code: 6050, category: ts.DiagnosticCategory.Error, key: "Unable_to_open_file_0_6050", message: "Unable to open file '{0}'." },
@@ -4511,17 +4588,18 @@ var ts;
Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." },
Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." },
Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." },
- Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context. (experimental)" },
+ Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context (experimental)." },
Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." },
Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." },
Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." },
Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." },
Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." },
Specify_library_files_to_be_included_in_the_compilation_Colon: { code: 6079, category: ts.DiagnosticCategory.Message, key: "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", message: "Specify library files to be included in the compilation: " },
- Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" },
+ Specify_JSX_code_generation_Colon_preserve_react_native_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", message: "Specify JSX code generation: 'preserve', 'react-native', or 'react'." },
+ File_0_has_an_unsupported_extension_so_skipping_it: { code: 6081, category: ts.DiagnosticCategory.Message, key: "File_0_has_an_unsupported_extension_so_skipping_it_6081", message: "File '{0}' has an unsupported extension, so skipping it." },
Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." },
Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." },
- Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit_6084", message: "Specify the object invoked for createElement and __spread when targeting 'react' JSX emit" },
+ Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", message: "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit" },
Enable_tracing_of_the_name_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_name_resolution_process_6085", message: "Enable tracing of the name resolution process." },
Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" },
Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." },
@@ -4532,23 +4610,23 @@ var ts;
Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." },
Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." },
Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." },
- Loading_module_as_file_Slash_folder_candidate_module_location_0: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_6095", message: "Loading module as file / folder, candidate module location '{0}'." },
+ Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", message: "Loading module as file / folder, candidate module location '{0}', target file type '{1}'." },
File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." },
File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." },
- Loading_module_0_from_node_modules_folder: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_6098", message: "Loading module '{0}' from 'node_modules' folder." },
+ Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." },
Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." },
- package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." },
+ package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." },
package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." },
Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." },
Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." },
Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." },
Expected_type_of_0_field_in_package_json_to_be_string_got_1: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", message: "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'." },
- baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'" },
- rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'" },
- Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'" },
- Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'" },
- Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'" },
- Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed" },
+ baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'." },
+ rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'." },
+ Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'." },
+ Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'." },
+ Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'." },
+ Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed." },
Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." },
Enable_strict_null_checks: { code: 6113, category: ts.DiagnosticCategory.Message, key: "Enable_strict_null_checks_6113", message: "Enable strict null checks." },
Unknown_option_excludes_Did_you_mean_exclude: { code: 6114, category: ts.DiagnosticCategory.Error, key: "Unknown_option_excludes_Did_you_mean_exclude_6114", message: "Unknown option 'excludes'. Did you mean 'exclude'?" },
@@ -4558,32 +4636,67 @@ var ts;
Resolving_from_node_modules_folder: { code: 6118, category: ts.DiagnosticCategory.Message, key: "Resolving_from_node_modules_folder_6118", message: "Resolving from node_modules folder..." },
Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: { code: 6119, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", message: "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========" },
Type_reference_directive_0_was_not_resolved: { code: 6120, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_not_resolved_6120", message: "======== Type reference directive '{0}' was not resolved. ========" },
- Resolving_with_primary_search_path_0: { code: 6121, category: ts.DiagnosticCategory.Message, key: "Resolving_with_primary_search_path_0_6121", message: "Resolving with primary search path '{0}'" },
+ Resolving_with_primary_search_path_0: { code: 6121, category: ts.DiagnosticCategory.Message, key: "Resolving_with_primary_search_path_0_6121", message: "Resolving with primary search path '{0}'." },
Root_directory_cannot_be_determined_skipping_primary_search_paths: { code: 6122, category: ts.DiagnosticCategory.Message, key: "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", message: "Root directory cannot be determined, skipping primary search paths." },
Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: { code: 6123, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========" },
Type_declaration_files_to_be_included_in_compilation: { code: 6124, category: ts.DiagnosticCategory.Message, key: "Type_declaration_files_to_be_included_in_compilation_6124", message: "Type declaration files to be included in compilation." },
- Looking_up_in_node_modules_folder_initial_location_0: { code: 6125, category: ts.DiagnosticCategory.Message, key: "Looking_up_in_node_modules_folder_initial_location_0_6125", message: "Looking up in 'node_modules' folder, initial location '{0}'" },
+ Looking_up_in_node_modules_folder_initial_location_0: { code: 6125, category: ts.DiagnosticCategory.Message, key: "Looking_up_in_node_modules_folder_initial_location_0_6125", message: "Looking up in 'node_modules' folder, initial location '{0}'." },
Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: { code: 6126, category: ts.DiagnosticCategory.Message, key: "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", message: "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder." },
Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: { code: 6127, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", message: "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========" },
Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" },
The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." },
- Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'" },
+ Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'." },
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
- File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
+ File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it." },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
- The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
- No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" },
+ The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files." },
Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." },
Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." },
Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." },
- Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" },
+ Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file." },
Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." },
Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." },
Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." },
Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." },
Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." },
+ Resolution_for_module_0_was_found_in_cache: { code: 6147, category: ts.DiagnosticCategory.Message, key: "Resolution_for_module_0_was_found_in_cache_6147", message: "Resolution for module '{0}' was found in cache." },
+ Directory_0_does_not_exist_skipping_all_lookups_in_it: { code: 6148, category: ts.DiagnosticCategory.Message, key: "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", message: "Directory '{0}' does not exist, skipping all lookups in it." },
+ Show_diagnostic_information: { code: 6149, category: ts.DiagnosticCategory.Message, key: "Show_diagnostic_information_6149", message: "Show diagnostic information." },
+ Show_verbose_diagnostic_information: { code: 6150, category: ts.DiagnosticCategory.Message, key: "Show_verbose_diagnostic_information_6150", message: "Show verbose diagnostic information." },
+ Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: { code: 6151, category: ts.DiagnosticCategory.Message, key: "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", message: "Emit a single file with source maps instead of having a separate file." },
+ Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: { code: 6152, category: ts.DiagnosticCategory.Message, key: "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", message: "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set." },
+ Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: { code: 6153, category: ts.DiagnosticCategory.Message, key: "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", message: "Transpile each file as a separate module (similar to 'ts.transpileModule')." },
+ Print_names_of_generated_files_part_of_the_compilation: { code: 6154, category: ts.DiagnosticCategory.Message, key: "Print_names_of_generated_files_part_of_the_compilation_6154", message: "Print names of generated files part of the compilation." },
+ Print_names_of_files_part_of_the_compilation: { code: 6155, category: ts.DiagnosticCategory.Message, key: "Print_names_of_files_part_of_the_compilation_6155", message: "Print names of files part of the compilation." },
+ The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: { code: 6156, category: ts.DiagnosticCategory.Message, key: "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", message: "The locale used when displaying messages to the user (e.g. 'en-us')" },
+ Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: { code: 6157, category: ts.DiagnosticCategory.Message, key: "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", message: "Do not generate custom helper functions like '__extends' in compiled output." },
+ Do_not_include_the_default_library_file_lib_d_ts: { code: 6158, category: ts.DiagnosticCategory.Message, key: "Do_not_include_the_default_library_file_lib_d_ts_6158", message: "Do not include the default library file (lib.d.ts)." },
+ Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: { code: 6159, category: ts.DiagnosticCategory.Message, key: "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", message: "Do not add triple-slash references or imported modules to the list of compiled files." },
+ Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: { code: 6160, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", message: "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files." },
+ List_of_folders_to_include_type_definitions_from: { code: 6161, category: ts.DiagnosticCategory.Message, key: "List_of_folders_to_include_type_definitions_from_6161", message: "List of folders to include type definitions from." },
+ Disable_size_limitations_on_JavaScript_projects: { code: 6162, category: ts.DiagnosticCategory.Message, key: "Disable_size_limitations_on_JavaScript_projects_6162", message: "Disable size limitations on JavaScript projects." },
+ The_character_set_of_the_input_files: { code: 6163, category: ts.DiagnosticCategory.Message, key: "The_character_set_of_the_input_files_6163", message: "The character set of the input files." },
+ Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: { code: 6164, category: ts.DiagnosticCategory.Message, key: "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", message: "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files." },
+ Do_not_truncate_error_messages: { code: 6165, category: ts.DiagnosticCategory.Message, key: "Do_not_truncate_error_messages_6165", message: "Do not truncate error messages." },
+ Output_directory_for_generated_declaration_files: { code: 6166, category: ts.DiagnosticCategory.Message, key: "Output_directory_for_generated_declaration_files_6166", message: "Output directory for generated declaration files." },
+ A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: { code: 6167, category: ts.DiagnosticCategory.Message, key: "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", message: "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'." },
+ List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: { code: 6168, category: ts.DiagnosticCategory.Message, key: "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", message: "List of root folders whose combined content represents the structure of the project at runtime." },
+ Show_all_compiler_options: { code: 6169, category: ts.DiagnosticCategory.Message, key: "Show_all_compiler_options_6169", message: "Show all compiler options." },
+ Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: { code: 6170, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", message: "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file" },
+ Command_line_Options: { code: 6171, category: ts.DiagnosticCategory.Message, key: "Command_line_Options_6171", message: "Command-line Options" },
+ Basic_Options: { code: 6172, category: ts.DiagnosticCategory.Message, key: "Basic_Options_6172", message: "Basic Options" },
+ Strict_Type_Checking_Options: { code: 6173, category: ts.DiagnosticCategory.Message, key: "Strict_Type_Checking_Options_6173", message: "Strict Type-Checking Options" },
+ Module_Resolution_Options: { code: 6174, category: ts.DiagnosticCategory.Message, key: "Module_Resolution_Options_6174", message: "Module Resolution Options" },
+ Source_Map_Options: { code: 6175, category: ts.DiagnosticCategory.Message, key: "Source_Map_Options_6175", message: "Source Map Options" },
+ Additional_Checks: { code: 6176, category: ts.DiagnosticCategory.Message, key: "Additional_Checks_6176", message: "Additional Checks" },
+ Experimental_Options: { code: 6177, category: ts.DiagnosticCategory.Message, key: "Experimental_Options_6177", message: "Experimental Options" },
+ Advanced_Options: { code: 6178, category: ts.DiagnosticCategory.Message, key: "Advanced_Options_6178", message: "Advanced Options" },
+ Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: { code: 6179, category: ts.DiagnosticCategory.Message, key: "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", message: "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'." },
+ Enable_all_strict_type_checking_options: { code: 6180, category: ts.DiagnosticCategory.Message, key: "Enable_all_strict_type_checking_options_6180", message: "Enable all strict type-checking options." },
+ List_of_language_service_plugins: { code: 6181, category: ts.DiagnosticCategory.Message, key: "List_of_language_service_plugins_6181", message: "List of language service plugins." },
+ Scoped_package_detected_looking_in_0: { code: 6182, category: ts.DiagnosticCategory.Message, key: "Scoped_package_detected_looking_in_0_6182", message: "Scoped package detected, looking in '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." },
@@ -4601,7 +4714,7 @@ var ts;
_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7023, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", message: "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." },
Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." },
Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." },
- JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists" },
+ JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists." },
Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." },
Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." },
Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." },
@@ -4625,7 +4738,7 @@ var ts;
parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." },
enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." },
type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." },
- Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." },
+ Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause." },
class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." },
Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." },
JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." },
@@ -4633,28 +4746,40 @@ var ts;
Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." },
JSX_attribute_expected: { code: 17003, category: ts.DiagnosticCategory.Error, key: "JSX_attribute_expected_17003", message: "JSX attribute expected." },
Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." },
- A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'" },
+ A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'." },
An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." },
A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." },
JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." },
super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." },
Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." },
+ super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." },
+ _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: { code: 17012, category: ts.DiagnosticCategory.Error, key: "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", message: "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?" },
+ Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: { code: 17013, category: ts.DiagnosticCategory.Error, key: "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", message: "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor." },
Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" },
A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." },
The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." },
No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." },
Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." },
Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." },
- Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" },
- Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" },
- Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" },
- Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" },
- Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" },
- Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig" },
+ Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'." },
+ Remove_declaration_for_Colon_0: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_declaration_for_Colon_0_90004", message: "Remove declaration for: '{0}'." },
+ Implement_interface_0: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_0_90006", message: "Implement interface '{0}'." },
+ Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class." },
+ Add_this_to_unresolved_variable: { code: 90008, category: ts.DiagnosticCategory.Message, key: "Add_this_to_unresolved_variable_90008", message: "Add 'this.' to unresolved variable." },
+ Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig." },
Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." },
- Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}" },
- Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}" },
- Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}" },
+ Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}." },
+ Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}." },
+ Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}." },
+ Add_declaration_for_missing_property_0: { code: 90016, category: ts.DiagnosticCategory.Message, key: "Add_declaration_for_missing_property_0_90016", message: "Add declaration for missing property '{0}'." },
+ Add_index_signature_for_missing_property_0: { code: 90017, category: ts.DiagnosticCategory.Message, key: "Add_index_signature_for_missing_property_0_90017", message: "Add index signature for missing property '{0}'." },
+ Disable_checking_for_this_file: { code: 90018, category: ts.DiagnosticCategory.Message, key: "Disable_checking_for_this_file_90018", message: "Disable checking for this file." },
+ Ignore_this_error_message: { code: 90019, category: ts.DiagnosticCategory.Message, key: "Ignore_this_error_message_90019", message: "Ignore this error message." },
+ Initialize_property_0_in_the_constructor: { code: 90020, category: ts.DiagnosticCategory.Message, key: "Initialize_property_0_in_the_constructor_90020", message: "Initialize property '{0}' in the constructor." },
+ Initialize_static_property_0: { code: 90021, category: ts.DiagnosticCategory.Message, key: "Initialize_static_property_0_90021", message: "Initialize static property '{0}'." },
+ Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." },
+ Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: { code: 8018, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", message: "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'." },
+ Report_errors_in_js_files: { code: 8019, category: ts.DiagnosticCategory.Message, key: "Report_errors_in_js_files_8019", message: "Report errors in .js files." },
};
})(ts || (ts = {}));
/// <reference path="core.ts"/>
@@ -4666,7 +4791,7 @@ var ts;
return token >= 70 /* Identifier */;
}
ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
- var textToToken = ts.createMap({
+ var textToToken = ts.createMapFromTemplate({
"abstract": 116 /* AbstractKeyword */,
"any": 118 /* AnyKeyword */,
"as": 117 /* AsKeyword */,
@@ -4690,7 +4815,7 @@ var ts;
"false": 85 /* FalseKeyword */,
"finally": 86 /* FinallyKeyword */,
"for": 87 /* ForKeyword */,
- "from": 138 /* FromKeyword */,
+ "from": 139 /* FromKeyword */,
"function": 88 /* FunctionKeyword */,
"get": 124 /* GetKeyword */,
"if": 89 /* IfKeyword */,
@@ -4708,27 +4833,28 @@ var ts;
"new": 93 /* NewKeyword */,
"null": 94 /* NullKeyword */,
"number": 132 /* NumberKeyword */,
+ "object": 133 /* ObjectKeyword */,
"package": 110 /* PackageKeyword */,
"private": 111 /* PrivateKeyword */,
"protected": 112 /* ProtectedKeyword */,
"public": 113 /* PublicKeyword */,
"readonly": 130 /* ReadonlyKeyword */,
"require": 131 /* RequireKeyword */,
- "global": 139 /* GlobalKeyword */,
+ "global": 140 /* GlobalKeyword */,
"return": 95 /* ReturnKeyword */,
- "set": 133 /* SetKeyword */,
+ "set": 134 /* SetKeyword */,
"static": 114 /* StaticKeyword */,
- "string": 134 /* StringKeyword */,
+ "string": 135 /* StringKeyword */,
"super": 96 /* SuperKeyword */,
"switch": 97 /* SwitchKeyword */,
- "symbol": 135 /* SymbolKeyword */,
+ "symbol": 136 /* SymbolKeyword */,
"this": 98 /* ThisKeyword */,
"throw": 99 /* ThrowKeyword */,
"true": 100 /* TrueKeyword */,
"try": 101 /* TryKeyword */,
- "type": 136 /* TypeKeyword */,
+ "type": 137 /* TypeKeyword */,
"typeof": 102 /* TypeOfKeyword */,
- "undefined": 137 /* UndefinedKeyword */,
+ "undefined": 138 /* UndefinedKeyword */,
"var": 103 /* VarKeyword */,
"void": 104 /* VoidKeyword */,
"while": 105 /* WhileKeyword */,
@@ -4736,7 +4862,7 @@ var ts;
"yield": 115 /* YieldKeyword */,
"async": 119 /* AsyncKeyword */,
"await": 120 /* AwaitKeyword */,
- "of": 140 /* OfKeyword */,
+ "of": 141 /* OfKeyword */,
"{": 16 /* OpenBraceToken */,
"}": 17 /* CloseBraceToken */,
"(": 18 /* OpenParenToken */,
@@ -4876,9 +5002,9 @@ var ts;
}
function makeReverseMap(source) {
var result = [];
- for (var name_4 in source) {
- result[source[name_4]] = name_4;
- }
+ source.forEach(function (value, name) {
+ result[value] = name;
+ });
return result;
}
var tokenStrings = makeReverseMap(textToToken);
@@ -4888,7 +5014,7 @@ var ts;
ts.tokenToString = tokenToString;
/* @internal */
function stringToToken(s) {
- return textToToken[s];
+ return textToToken.get(s);
}
ts.stringToToken = stringToToken;
/* @internal */
@@ -4904,6 +5030,7 @@ var ts;
if (text.charCodeAt(pos) === 10 /* lineFeed */) {
pos++;
}
+ // falls through
case 10 /* lineFeed */:
result.push(lineStart);
lineStart = pos;
@@ -4962,7 +5089,6 @@ var ts;
return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
}
ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
function isWhiteSpace(ch) {
return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
}
@@ -5049,6 +5175,7 @@ var ts;
if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
pos++;
}
+ // falls through
case 10 /* lineFeed */:
pos++;
if (stopAfterLineBreak) {
@@ -5121,7 +5248,7 @@ var ts;
if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
var ch = text.charCodeAt(pos);
if ((pos + mergeConflictMarkerLength) < text.length) {
- for (var i = 0, n = mergeConflictMarkerLength; i < n; i++) {
+ for (var i = 0; i < mergeConflictMarkerLength; i++) {
if (text.charCodeAt(pos + i) !== ch) {
return false;
}
@@ -5203,6 +5330,7 @@ var ts;
if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
pos++;
}
+ // falls through
case 10 /* lineFeed */:
pos++;
if (trailing) {
@@ -5298,15 +5426,15 @@ var ts;
if (!comments) {
comments = [];
}
- comments.push({ pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine, kind: kind });
+ comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
return comments;
}
function getLeadingCommentRanges(text, pos) {
- return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined);
+ return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
}
ts.getLeadingCommentRanges = getLeadingCommentRanges;
function getTrailingCommentRanges(text, pos) {
- return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined);
+ return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
}
ts.getTrailingCommentRanges = getTrailingCommentRanges;
/** Optionally, get the shebang */
@@ -5333,7 +5461,7 @@ var ts;
if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) {
return false;
}
- for (var i = 1, n = name.length; i < n; i++) {
+ for (var i = 1; i < name.length; i++) {
if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) {
return false;
}
@@ -5357,6 +5485,7 @@ var ts;
var precedingLineBreak;
var hasExtendedUnicodeEscape;
var tokenIsUnterminated;
+ var numericLiteralFlags;
setText(text, start, length);
return {
getStartPos: function () { return startPos; },
@@ -5370,6 +5499,7 @@ var ts;
isIdentifier: function () { return token === 70 /* Identifier */ || token > 106 /* LastReservedWord */; },
isReservedWord: function () { return token >= 71 /* FirstReservedWord */ && token <= 106 /* LastReservedWord */; },
isUnterminated: function () { return tokenIsUnterminated; },
+ getNumericLiteralFlags: function () { return numericLiteralFlags; },
reScanGreaterToken: reScanGreaterToken,
reScanSlashToken: reScanSlashToken,
reScanTemplateToken: reScanTemplateToken,
@@ -5406,6 +5536,7 @@ var ts;
var end = pos;
if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
pos++;
+ numericLiteralFlags = 2 /* Scientific */;
if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
pos++;
if (isDigit(text.charCodeAt(pos))) {
@@ -5604,7 +5735,7 @@ var ts;
if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
pos++;
}
- // fall through
+ // falls through
case 10 /* lineFeed */:
case 8232 /* lineSeparator */:
case 8233 /* paragraphSeparator */:
@@ -5705,8 +5836,11 @@ var ts;
var len = tokenValue.length;
if (len >= 2 && len <= 11) {
var ch = tokenValue.charCodeAt(0);
- if (ch >= 97 /* a */ && ch <= 122 /* z */ && hasOwnProperty.call(textToToken, tokenValue)) {
- return token = textToToken[tokenValue];
+ if (ch >= 97 /* a */ && ch <= 122 /* z */) {
+ token = textToToken.get(tokenValue);
+ if (token !== undefined) {
+ return token;
+ }
}
}
return token = 70 /* Identifier */;
@@ -5738,6 +5872,7 @@ var ts;
hasExtendedUnicodeEscape = false;
precedingLineBreak = false;
tokenIsUnterminated = false;
+ numericLiteralFlags = 0;
while (true) {
tokenPos = pos;
if (pos >= end) {
@@ -5923,6 +6058,7 @@ var ts;
value = 0;
}
tokenValue = "" + value;
+ numericLiteralFlags = 8 /* HexSpecifier */;
return token = 8 /* NumericLiteral */;
}
else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
@@ -5933,6 +6069,7 @@ var ts;
value = 0;
}
tokenValue = "" + value;
+ numericLiteralFlags = 16 /* BinarySpecifier */;
return token = 8 /* NumericLiteral */;
}
else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
@@ -5943,16 +6080,19 @@ var ts;
value = 0;
}
tokenValue = "" + value;
+ numericLiteralFlags = 32 /* OctalSpecifier */;
return token = 8 /* NumericLiteral */;
}
// Try to parse as an octal
if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
tokenValue = "" + scanOctalDigits();
+ numericLiteralFlags = 4 /* Octal */;
return token = 8 /* NumericLiteral */;
}
// This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
// can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
// permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
+ // falls through
case 49 /* _1 */:
case 50 /* _2 */:
case 51 /* _3 */:
@@ -6206,7 +6346,14 @@ var ts;
while (pos < end) {
pos++;
char = text.charCodeAt(pos);
- if ((char === 123 /* openBrace */) || (char === 60 /* lessThan */)) {
+ if (char === 123 /* openBrace */) {
+ break;
+ }
+ if (char === 60 /* lessThan */) {
+ if (isConflictMarkerTrivia(text, pos)) {
+ pos = scanConflictMarkerTrivia(text, pos, error);
+ return token = 7 /* ConflictMarkerTrivia */;
+ }
break;
}
}
@@ -6399,6 +6546,19 @@ var ts;
return undefined;
}
ts.getDeclarationOfKind = getDeclarationOfKind;
+ function findDeclaration(symbol, predicate) {
+ var declarations = symbol.declarations;
+ if (declarations) {
+ for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
+ var declaration = declarations_2[_i];
+ if (predicate(declaration)) {
+ return declaration;
+ }
+ }
+ }
+ return undefined;
+ }
+ ts.findDeclaration = findDeclaration;
// Pool writers to avoid needing to allocate them for every symbol we write.
var stringWriters = [];
function getSingleLineStringWriter() {
@@ -6413,6 +6573,7 @@ var ts;
writeSpace: writeText,
writeStringLiteral: writeText,
writeParameter: writeText,
+ writeProperty: writeText,
writeSymbol: writeText,
// Completely ignore indentation for string writers. And map newlines to
// a single space.
@@ -6421,7 +6582,8 @@ var ts;
decreaseIndent: ts.noop,
clear: function () { return str_1 = ""; },
trackSymbol: ts.noop,
- reportInaccessibleThisError: ts.noop
+ reportInaccessibleThisError: ts.noop,
+ reportIllegalExtends: ts.noop
};
}
return stringWriters.pop();
@@ -6437,25 +6599,25 @@ var ts;
}
ts.getFullWidth = getFullWidth;
function hasResolvedModule(sourceFile, moduleNameText) {
- return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]);
+ return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText));
}
ts.hasResolvedModule = hasResolvedModule;
function getResolvedModule(sourceFile, moduleNameText) {
- return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules[moduleNameText] : undefined;
+ return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules.get(moduleNameText) : undefined;
}
ts.getResolvedModule = getResolvedModule;
function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
if (!sourceFile.resolvedModules) {
sourceFile.resolvedModules = ts.createMap();
}
- sourceFile.resolvedModules[moduleNameText] = resolvedModule;
+ sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
}
ts.setResolvedModule = setResolvedModule;
function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
}
- sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective;
+ sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
}
ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
/* @internal */
@@ -6477,7 +6639,7 @@ var ts;
}
for (var i = 0; i < names.length; i++) {
var newResolution = newResolutions[i];
- var oldResolution = oldResolutions && oldResolutions[names[i]];
+ var oldResolution = oldResolutions && oldResolutions.get(names[i]);
var changed = oldResolution
? !newResolution || !comparer(oldResolution, newResolution)
: newResolution;
@@ -6491,28 +6653,28 @@ var ts;
// Returns true if this node contains a parse error anywhere underneath it.
function containsParseError(node) {
aggregateChildData(node);
- return (node.flags & 4194304 /* ThisNodeOrAnySubNodesHasError */) !== 0;
+ return (node.flags & 131072 /* ThisNodeOrAnySubNodesHasError */) !== 0;
}
ts.containsParseError = containsParseError;
function aggregateChildData(node) {
- if (!(node.flags & 8388608 /* HasAggregatedChildData */)) {
+ if (!(node.flags & 262144 /* HasAggregatedChildData */)) {
// A node is considered to contain a parse error if:
// a) the parser explicitly marked that it had an error
// b) any of it's children reported that it had an error.
- var thisNodeOrAnySubNodesHasError = ((node.flags & 1048576 /* ThisNodeHasError */) !== 0) ||
+ var thisNodeOrAnySubNodesHasError = ((node.flags & 32768 /* ThisNodeHasError */) !== 0) ||
ts.forEachChild(node, containsParseError);
// If so, mark ourselves accordingly.
if (thisNodeOrAnySubNodesHasError) {
- node.flags |= 4194304 /* ThisNodeOrAnySubNodesHasError */;
+ node.flags |= 131072 /* ThisNodeOrAnySubNodesHasError */;
}
// Also mark that we've propagated the child information to this node. This way we can
// always consult the bit directly on this node without needing to check its children
// again.
- node.flags |= 8388608 /* HasAggregatedChildData */;
+ node.flags |= 262144 /* HasAggregatedChildData */;
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 261 /* SourceFile */) {
+ while (node && node.kind !== 264 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -6520,11 +6682,11 @@ var ts;
ts.getSourceFileOfNode = getSourceFileOfNode;
function isStatementWithLocals(node) {
switch (node.kind) {
- case 204 /* Block */:
- case 232 /* CaseBlock */:
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
+ case 206 /* Block */:
+ case 234 /* CaseBlock */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
return true;
}
return false;
@@ -6599,6 +6761,10 @@ var ts;
return !nodeIsMissing(node);
}
ts.nodeIsPresent = nodeIsPresent;
+ function isToken(n) {
+ return n.kind >= 0 /* FirstToken */ && n.kind <= 141 /* LastToken */;
+ }
+ ts.isToken = isToken;
function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
// With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
// want to skip trivia because this will launch us forward to the next token.
@@ -6615,18 +6781,18 @@ var 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 === 292 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 293 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
}
ts.getTokenPosOfNode = getTokenPosOfNode;
function isJSDocNode(node) {
- return node.kind >= 262 /* FirstJSDocNode */ && node.kind <= 288 /* LastJSDocNode */;
+ return node.kind >= 266 /* FirstJSDocNode */ && node.kind <= 292 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
function isJSDocTag(node) {
- return node.kind >= 278 /* FirstJSDocTagNode */ && node.kind <= 291 /* LastJSDocTagNode */;
+ return node.kind >= 282 /* FirstJSDocTagNode */ && node.kind <= 292 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function getNonDecoratorTokenPosOfNode(node, sourceFile) {
@@ -6657,20 +6823,11 @@ var ts;
return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
}
ts.getTextOfNode = getTextOfNode;
- function getLiteralText(node, sourceFile, languageVersion) {
- // Any template literal or string literal with an extended escape
- // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal.
- if (languageVersion < 2 /* ES2015 */ && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
- return getQuotedEscapedLiteralText('"', node.text, '"');
- }
+ function getLiteralText(node, sourceFile) {
// If we don't need to downlevel and we can reach the original source text using
// the node's parent reference, then simply get the text as it was originally written.
if (!nodeIsSynthesized(node) && node.parent) {
- var text = getSourceTextOfNodeFromSourceFile(sourceFile, node);
- if (languageVersion < 2 /* ES2015 */ && isBinaryOrOctalIntegerLiteral(node, text)) {
- return node.text;
- }
- return text;
+ return getSourceTextOfNodeFromSourceFile(sourceFile, node);
}
// If we can't reach the original source text, use the canonical form if it's a number,
// or an escaped quoted form of the original text if it's string-like.
@@ -6691,19 +6848,6 @@ var ts;
ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
}
ts.getLiteralText = getLiteralText;
- function isBinaryOrOctalIntegerLiteral(node, text) {
- if (node.kind === 8 /* NumericLiteral */ && text.length > 1) {
- switch (text.charCodeAt(1)) {
- case 98 /* b */:
- case 66 /* B */:
- case 111 /* o */:
- case 79 /* O */:
- return true;
- }
- }
- return false;
- }
- ts.isBinaryOrOctalIntegerLiteral = isBinaryOrOctalIntegerLiteral;
function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) {
return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote;
}
@@ -6712,11 +6856,6 @@ var ts;
return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier;
}
ts.escapeIdentifier = escapeIdentifier;
- // Remove extra underscore from escaped identifier
- function unescapeIdentifier(identifier) {
- return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier;
- }
- ts.unescapeIdentifier = unescapeIdentifier;
// Make an identifier from an external module name by extracting the string after the last "/" and replacing
// all non-alphanumeric characters with underscores
function makeIdentifierFromModuleName(moduleName) {
@@ -6730,26 +6869,26 @@ var ts;
ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
var node = getRootDeclaration(declaration);
- return node.kind === 223 /* VariableDeclaration */ && node.parent.kind === 256 /* CatchClause */;
+ return node.kind === 225 /* VariableDeclaration */ && node.parent.kind === 259 /* CatchClause */;
}
ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
function isAmbientModule(node) {
- return node && node.kind === 230 /* ModuleDeclaration */ &&
+ return node && node.kind === 232 /* ModuleDeclaration */ &&
(node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node));
}
ts.isAmbientModule = isAmbientModule;
- /** Given a symbol for a module, checks that it is either an untyped import or a shorthand ambient module. */
+ /** Given a symbol for a module, checks that it is a shorthand ambient module. */
function isShorthandAmbientModuleSymbol(moduleSymbol) {
return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
}
ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
function isShorthandAmbientModule(node) {
// The only kind of module that can be missing a body is a shorthand ambient module.
- return node.kind === 230 /* ModuleDeclaration */ && (!node.body);
+ return node && node.kind === 232 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 261 /* SourceFile */ ||
- node.kind === 230 /* ModuleDeclaration */ ||
+ return node.kind === 264 /* SourceFile */ ||
+ node.kind === 232 /* ModuleDeclaration */ ||
isFunctionLike(node);
}
ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
@@ -6765,32 +6904,36 @@ var ts;
return false;
}
switch (node.parent.kind) {
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
return ts.isExternalModule(node.parent);
- case 231 /* ModuleBlock */:
+ case 233 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
}
return false;
}
ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
+ function isEffectiveExternalModule(node, compilerOptions) {
+ return ts.isExternalModule(node) || compilerOptions.isolatedModules;
+ }
+ ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 261 /* SourceFile */:
- case 232 /* CaseBlock */:
- case 256 /* CatchClause */:
- case 230 /* ModuleDeclaration */:
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- case 150 /* Constructor */:
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
+ case 264 /* SourceFile */:
+ case 234 /* CaseBlock */:
+ case 259 /* CatchClause */:
+ case 232 /* ModuleDeclaration */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ case 151 /* Constructor */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
return true;
- case 204 /* Block */:
+ case 206 /* Block */:
// function block is not considered block-scope container
// see comment in binder.ts: bind(...), case for SyntaxKind.Block
return parentNode && !isFunctionLike(parentNode);
@@ -6817,6 +6960,10 @@ var ts;
return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
}
ts.declarationNameToString = declarationNameToString;
+ function getNameFromIndexInfo(info) {
+ return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
+ }
+ ts.getNameFromIndexInfo = getNameFromIndexInfo;
function getTextOfPropertyName(name) {
switch (name.kind) {
case 70 /* Identifier */:
@@ -6824,7 +6971,7 @@ var ts;
case 9 /* StringLiteral */:
case 8 /* NumericLiteral */:
return name.text;
- case 142 /* ComputedPropertyName */:
+ case 143 /* ComputedPropertyName */:
if (isStringOrNumericLiteral(name.expression)) {
return name.expression.text;
}
@@ -6835,10 +6982,10 @@ var ts;
function entityNameToString(name) {
switch (name.kind) {
case 70 /* Identifier */:
- return getFullWidth(name) === 0 ? unescapeIdentifier(name.text) : getTextOfNode(name);
- case 141 /* QualifiedName */:
+ return getFullWidth(name) === 0 ? ts.unescapeIdentifier(name.text) : getTextOfNode(name);
+ case 142 /* QualifiedName */:
return entityNameToString(name.left) + "." + entityNameToString(name.right);
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
return entityNameToString(name.expression) + "." + entityNameToString(name.name);
}
}
@@ -6875,7 +7022,7 @@ var ts;
ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
function getErrorSpanForArrowFunction(sourceFile, node) {
var pos = ts.skipTrivia(sourceFile.text, node.pos);
- if (node.body && node.body.kind === 204 /* Block */) {
+ if (node.body && node.body.kind === 206 /* Block */) {
var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
if (startLine < endLine) {
@@ -6889,7 +7036,7 @@ var ts;
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
if (pos_1 === sourceFile.text.length) {
// file is empty - return span for the beginning of the file
@@ -6898,23 +7045,23 @@ var ts;
return getSpanOfTokenAtPosition(sourceFile, pos_1);
// This list is a work in progress. Add missing node kinds to improve their error
// spans.
- case 223 /* VariableDeclaration */:
- case 174 /* BindingElement */:
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 227 /* InterfaceDeclaration */:
- case 230 /* ModuleDeclaration */:
- case 229 /* EnumDeclaration */:
- case 260 /* EnumMember */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 228 /* TypeAliasDeclaration */:
+ case 225 /* VariableDeclaration */:
+ case 175 /* BindingElement */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 229 /* InterfaceDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 263 /* EnumMember */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 230 /* TypeAliasDeclaration */:
errorNode = node.name;
break;
- case 185 /* ArrowFunction */:
+ case 186 /* ArrowFunction */:
return getErrorSpanForArrowFunction(sourceFile, node);
}
if (errorNode === undefined) {
@@ -6937,7 +7084,7 @@ var ts;
}
ts.isDeclarationFile = isDeclarationFile;
function isConstEnumDeclaration(node) {
- return node.kind === 229 /* EnumDeclaration */ && isConst(node);
+ return node.kind === 231 /* EnumDeclaration */ && isConst(node);
}
ts.isConstEnumDeclaration = isConstEnumDeclaration;
function isConst(node) {
@@ -6950,11 +7097,11 @@ var ts;
}
ts.isLet = isLet;
function isSuperCall(n) {
- return n.kind === 179 /* CallExpression */ && n.expression.kind === 96 /* SuperKeyword */;
+ return n.kind === 180 /* CallExpression */ && n.expression.kind === 96 /* SuperKeyword */;
}
ts.isSuperCall = isSuperCall;
function isPrologueDirective(node) {
- return node.kind === 207 /* ExpressionStatement */
+ return node.kind === 209 /* ExpressionStatement */
&& node.expression.kind === 9 /* StringLiteral */;
}
ts.isPrologueDirective = isPrologueDirective;
@@ -6967,10 +7114,10 @@ var ts;
}
ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText;
function getJSDocCommentRanges(node, text) {
- var commentRanges = (node.kind === 144 /* Parameter */ ||
- node.kind === 143 /* TypeParameter */ ||
- node.kind === 184 /* FunctionExpression */ ||
- node.kind === 185 /* ArrowFunction */) ?
+ var commentRanges = (node.kind === 145 /* Parameter */ ||
+ node.kind === 144 /* TypeParameter */ ||
+ node.kind === 185 /* FunctionExpression */ ||
+ node.kind === 186 /* ArrowFunction */) ?
ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
getLeadingCommentRangesOfNodeFromText(node, text);
// True if the comment starts with '/**' but not if it is '/**/'
@@ -6985,79 +7132,80 @@ var ts;
ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
function isPartOfTypeNode(node) {
- if (156 /* FirstTypeNode */ <= node.kind && node.kind <= 171 /* LastTypeNode */) {
+ if (157 /* FirstTypeNode */ <= node.kind && node.kind <= 172 /* LastTypeNode */) {
return true;
}
switch (node.kind) {
case 118 /* AnyKeyword */:
case 132 /* NumberKeyword */:
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
case 121 /* BooleanKeyword */:
- case 135 /* SymbolKeyword */:
- case 137 /* UndefinedKeyword */:
+ case 136 /* SymbolKeyword */:
+ case 138 /* UndefinedKeyword */:
case 129 /* NeverKeyword */:
return true;
case 104 /* VoidKeyword */:
- return node.parent.kind !== 188 /* VoidExpression */;
- case 199 /* ExpressionWithTypeArguments */:
+ return node.parent.kind !== 189 /* VoidExpression */;
+ case 200 /* ExpressionWithTypeArguments */:
return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
// Identifiers and qualified names may be type nodes, depending on their context. Climb
// above them to find the lowest container
case 70 /* Identifier */:
// If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
- if (node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node) {
+ if (node.parent.kind === 142 /* QualifiedName */ && node.parent.right === node) {
node = node.parent;
}
- else if (node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.name === node) {
+ else if (node.parent.kind === 178 /* PropertyAccessExpression */ && node.parent.name === node) {
node = node.parent;
}
// At this point, node is either a qualified name or an identifier
- ts.Debug.assert(node.kind === 70 /* Identifier */ || node.kind === 141 /* QualifiedName */ || node.kind === 177 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
- case 141 /* QualifiedName */:
- case 177 /* PropertyAccessExpression */:
+ ts.Debug.assert(node.kind === 70 /* Identifier */ || node.kind === 142 /* QualifiedName */ || node.kind === 178 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
+ // falls through
+ case 142 /* QualifiedName */:
+ case 178 /* PropertyAccessExpression */:
case 98 /* ThisKeyword */:
- var parent_1 = node.parent;
- if (parent_1.kind === 160 /* TypeQuery */) {
+ var parent = node.parent;
+ if (parent.kind === 161 /* TypeQuery */) {
return false;
}
// Do not recursively call isPartOfTypeNode on the parent. In the example:
//
// let a: A.B.C;
//
- // Calling isPartOfTypeNode would consider the qualified name A.B a type node. Only C or
- // A.B.C is a type node.
- if (156 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 171 /* LastTypeNode */) {
+ // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
+ // Only C and A.B.C are type nodes.
+ if (157 /* FirstTypeNode */ <= parent.kind && parent.kind <= 172 /* LastTypeNode */) {
return true;
}
- switch (parent_1.kind) {
- case 199 /* ExpressionWithTypeArguments */:
- return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1);
- case 143 /* TypeParameter */:
- return node === parent_1.constraint;
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 144 /* Parameter */:
- case 223 /* VariableDeclaration */:
- return node === parent_1.type;
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 150 /* Constructor */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- return node === parent_1.type;
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
- return node === parent_1.type;
- case 182 /* TypeAssertionExpression */:
- return node === parent_1.type;
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
- return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0;
- case 181 /* TaggedTemplateExpression */:
+ switch (parent.kind) {
+ case 200 /* ExpressionWithTypeArguments */:
+ return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
+ case 144 /* TypeParameter */:
+ return node === parent.constraint;
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 145 /* Parameter */:
+ case 225 /* VariableDeclaration */:
+ return node === parent.type;
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 151 /* Constructor */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ return node === parent.type;
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
+ return node === parent.type;
+ case 183 /* TypeAssertionExpression */:
+ return node === parent.type;
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
+ return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0;
+ case 182 /* TaggedTemplateExpression */:
// TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
return false;
}
@@ -7065,29 +7213,43 @@ var ts;
return false;
}
ts.isPartOfTypeNode = isPartOfTypeNode;
+ function isChildOfNodeWithKind(node, kind) {
+ while (node) {
+ if (node.kind === kind) {
+ return true;
+ }
+ node = node.parent;
+ }
+ return false;
+ }
+ ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
+ function isPrefixUnaryExpression(node) {
+ return node.kind === 191 /* PrefixUnaryExpression */;
+ }
+ ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
// Warning: This has the same semantics as the forEach family of functions,
// in that traversal terminates in the event that 'visitor' supplies a truthy value.
function forEachReturnStatement(body, visitor) {
return traverse(body);
function traverse(node) {
switch (node.kind) {
- case 216 /* ReturnStatement */:
+ case 218 /* ReturnStatement */:
return visitor(node);
- case 232 /* CaseBlock */:
- case 204 /* Block */:
- case 208 /* IfStatement */:
- case 209 /* DoStatement */:
- case 210 /* WhileStatement */:
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- case 217 /* WithStatement */:
- case 218 /* SwitchStatement */:
- case 253 /* CaseClause */:
- case 254 /* DefaultClause */:
- case 219 /* LabeledStatement */:
- case 221 /* TryStatement */:
- case 256 /* CatchClause */:
+ case 234 /* CaseBlock */:
+ case 206 /* Block */:
+ case 210 /* IfStatement */:
+ case 211 /* DoStatement */:
+ case 212 /* WhileStatement */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ case 219 /* WithStatement */:
+ case 220 /* SwitchStatement */:
+ case 256 /* CaseClause */:
+ case 257 /* DefaultClause */:
+ case 221 /* LabeledStatement */:
+ case 223 /* TryStatement */:
+ case 259 /* CatchClause */:
return ts.forEachChild(node, traverse);
}
}
@@ -7097,29 +7259,30 @@ var ts;
return traverse(body);
function traverse(node) {
switch (node.kind) {
- case 195 /* YieldExpression */:
+ case 196 /* YieldExpression */:
visitor(node);
var operand = node.expression;
if (operand) {
traverse(operand);
}
- case 229 /* EnumDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 230 /* ModuleDeclaration */:
- case 228 /* TypeAliasDeclaration */:
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
+ return;
+ case 231 /* EnumDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
// These are not allowed inside a generator now, but eventually they may be allowed
// as local types. Regardless, any yield statements contained within them should be
// skipped in this traversal.
return;
default:
if (isFunctionLike(node)) {
- var name_5 = node.name;
- if (name_5 && name_5.kind === 142 /* ComputedPropertyName */) {
+ var name = node.name;
+ if (name && name.kind === 143 /* ComputedPropertyName */) {
// Note that we will not include methods/accessors of a class because they would require
// first descending into the class. This is by design.
- traverse(name_5.expression);
+ traverse(name.expression);
return;
}
}
@@ -7132,17 +7295,35 @@ var ts;
}
}
ts.forEachYieldExpression = forEachYieldExpression;
+ /**
+ * Gets the most likely element type for a TypeNode. This is not an exhaustive test
+ * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
+ *
+ * @param node The type node.
+ */
+ function getRestParameterElementType(node) {
+ if (node && node.kind === 163 /* ArrayType */) {
+ return node.elementType;
+ }
+ else if (node && node.kind === 158 /* TypeReference */) {
+ return ts.singleOrUndefined(node.typeArguments);
+ }
+ else {
+ return undefined;
+ }
+ }
+ ts.getRestParameterElementType = getRestParameterElementType;
function isVariableLike(node) {
if (node) {
switch (node.kind) {
- case 174 /* BindingElement */:
- case 260 /* EnumMember */:
- case 144 /* Parameter */:
- case 257 /* PropertyAssignment */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 258 /* ShorthandPropertyAssignment */:
- case 223 /* VariableDeclaration */:
+ case 175 /* BindingElement */:
+ case 263 /* EnumMember */:
+ case 145 /* Parameter */:
+ case 260 /* PropertyAssignment */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 261 /* ShorthandPropertyAssignment */:
+ case 225 /* VariableDeclaration */:
return true;
}
}
@@ -7150,11 +7331,11 @@ var ts;
}
ts.isVariableLike = isVariableLike;
function isAccessor(node) {
- return node && (node.kind === 151 /* GetAccessor */ || node.kind === 152 /* SetAccessor */);
+ return node && (node.kind === 152 /* GetAccessor */ || node.kind === 153 /* SetAccessor */);
}
ts.isAccessor = isAccessor;
function isClassLike(node) {
- return node && (node.kind === 226 /* ClassDeclaration */ || node.kind === 197 /* ClassExpression */);
+ return node && (node.kind === 228 /* ClassDeclaration */ || node.kind === 198 /* ClassExpression */);
}
ts.isClassLike = isClassLike;
function isFunctionLike(node) {
@@ -7163,19 +7344,19 @@ var ts;
ts.isFunctionLike = isFunctionLike;
function isFunctionLikeKind(kind) {
switch (kind) {
- case 150 /* Constructor */:
- case 184 /* FunctionExpression */:
- case 225 /* FunctionDeclaration */:
- case 185 /* ArrowFunction */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
+ case 151 /* Constructor */:
+ case 185 /* FunctionExpression */:
+ case 227 /* FunctionDeclaration */:
+ case 186 /* ArrowFunction */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
return true;
}
return false;
@@ -7183,13 +7364,13 @@ var ts;
ts.isFunctionLikeKind = isFunctionLikeKind;
function introducesArgumentsExoticObject(node) {
switch (node.kind) {
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
return true;
}
return false;
@@ -7197,30 +7378,42 @@ var ts;
ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
function isIterationStatement(node, lookInLabeledStatements) {
switch (node.kind) {
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- case 209 /* DoStatement */:
- case 210 /* WhileStatement */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ case 211 /* DoStatement */:
+ case 212 /* WhileStatement */:
return true;
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
}
return false;
}
ts.isIterationStatement = isIterationStatement;
+ function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
+ while (true) {
+ if (beforeUnwrapLabelCallback) {
+ beforeUnwrapLabelCallback(node);
+ }
+ if (node.statement.kind !== 221 /* LabeledStatement */) {
+ return node.statement;
+ }
+ node = node.statement;
+ }
+ }
+ ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
function isFunctionBlock(node) {
- return node && node.kind === 204 /* Block */ && isFunctionLike(node.parent);
+ return node && node.kind === 206 /* Block */ && isFunctionLike(node.parent);
}
ts.isFunctionBlock = isFunctionBlock;
function isObjectLiteralMethod(node) {
- return node && node.kind === 149 /* MethodDeclaration */ && node.parent.kind === 176 /* ObjectLiteralExpression */;
+ return node && node.kind === 150 /* MethodDeclaration */ && node.parent.kind === 177 /* ObjectLiteralExpression */;
}
ts.isObjectLiteralMethod = isObjectLiteralMethod;
function isObjectLiteralOrClassExpressionMethod(node) {
- return node.kind === 149 /* MethodDeclaration */ &&
- (node.parent.kind === 176 /* ObjectLiteralExpression */ ||
- node.parent.kind === 197 /* ClassExpression */);
+ return node.kind === 150 /* MethodDeclaration */ &&
+ (node.parent.kind === 177 /* ObjectLiteralExpression */ ||
+ node.parent.kind === 198 /* ClassExpression */);
}
ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
function isIdentifierTypePredicate(predicate) {
@@ -7256,7 +7449,7 @@ var ts;
return undefined;
}
switch (node.kind) {
- case 142 /* ComputedPropertyName */:
+ case 143 /* ComputedPropertyName */:
// If the grandparent node is an object literal (as opposed to a class),
// then the computed property is not a 'this' container.
// A computed property name in a class needs to be a this container
@@ -7271,9 +7464,9 @@ var ts;
// the *body* of the container.
node = node.parent;
break;
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
// Decorators are always applied outside of the body of a class or method.
- if (node.parent.kind === 144 /* Parameter */ && isClassElement(node.parent.parent)) {
+ if (node.parent.kind === 145 /* Parameter */ && isClassElement(node.parent.parent)) {
// If the decorator's parent is a Parameter, we resolve the this container from
// the grandparent class declaration.
node = node.parent.parent;
@@ -7284,39 +7477,52 @@ var ts;
node = node.parent;
}
break;
- case 185 /* ArrowFunction */:
+ case 186 /* ArrowFunction */:
if (!includeArrowFunctions) {
continue;
}
- // Fall through
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 230 /* ModuleDeclaration */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
- case 229 /* EnumDeclaration */:
- case 261 /* SourceFile */:
+ // falls through
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 232 /* ModuleDeclaration */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
+ case 231 /* EnumDeclaration */:
+ case 264 /* SourceFile */:
return node;
}
}
}
ts.getThisContainer = getThisContainer;
+ function getNewTargetContainer(node) {
+ var container = getThisContainer(node, /*includeArrowFunctions*/ false);
+ if (container) {
+ switch (container.kind) {
+ case 151 /* Constructor */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ return container;
+ }
+ }
+ return undefined;
+ }
+ ts.getNewTargetContainer = getNewTargetContainer;
/**
- * Given an super call/property node, returns the closest node where
- * - a super call/property access is legal in the node and not legal in the parent node the node.
- * i.e. super call is legal in constructor but not legal in the class body.
- * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
- * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
- * i.e. super property access is illegal in function declaration but can be legal in the statement list
- */
+ * Given an super call/property node, returns the closest node where
+ * - a super call/property access is legal in the node and not legal in the parent node the node.
+ * i.e. super call is legal in constructor but not legal in the class body.
+ * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
+ * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
+ * i.e. super property access is illegal in function declaration but can be legal in the statement list
+ */
function getSuperContainer(node, stopOnFunctions) {
while (true) {
node = node.parent;
@@ -7324,26 +7530,27 @@ var ts;
return node;
}
switch (node.kind) {
- case 142 /* ComputedPropertyName */:
+ case 143 /* ComputedPropertyName */:
node = node.parent;
break;
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
if (!stopOnFunctions) {
continue;
}
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ // falls through
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
return node;
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
// Decorators are always applied outside of the body of a class or method.
- if (node.parent.kind === 144 /* Parameter */ && isClassElement(node.parent.parent)) {
+ if (node.parent.kind === 145 /* Parameter */ && isClassElement(node.parent.parent)) {
// If the decorator's parent is a Parameter, we resolve the this container from
// the grandparent class declaration.
node = node.parent.parent;
@@ -7359,15 +7566,15 @@ var ts;
}
ts.getSuperContainer = getSuperContainer;
function getImmediatelyInvokedFunctionExpression(func) {
- if (func.kind === 184 /* FunctionExpression */ || func.kind === 185 /* ArrowFunction */) {
+ if (func.kind === 185 /* FunctionExpression */ || func.kind === 186 /* ArrowFunction */) {
var prev = func;
- var parent_2 = func.parent;
- while (parent_2.kind === 183 /* ParenthesizedExpression */) {
- prev = parent_2;
- parent_2 = parent_2.parent;
+ var parent = func.parent;
+ while (parent.kind === 184 /* ParenthesizedExpression */) {
+ prev = parent;
+ parent = parent.parent;
}
- if (parent_2.kind === 179 /* CallExpression */ && parent_2.expression === prev) {
- return parent_2;
+ if (parent.kind === 180 /* CallExpression */ && parent.expression === prev) {
+ return parent;
}
}
}
@@ -7377,21 +7584,21 @@ var ts;
*/
function isSuperProperty(node) {
var kind = node.kind;
- return (kind === 177 /* PropertyAccessExpression */ || kind === 178 /* ElementAccessExpression */)
+ return (kind === 178 /* PropertyAccessExpression */ || kind === 179 /* ElementAccessExpression */)
&& node.expression.kind === 96 /* SuperKeyword */;
}
ts.isSuperProperty = isSuperProperty;
function getEntityNameFromTypeNode(node) {
switch (node.kind) {
- case 157 /* TypeReference */:
- case 272 /* JSDocTypeReference */:
+ case 158 /* TypeReference */:
+ case 276 /* JSDocTypeReference */:
return node.typeName;
- case 199 /* ExpressionWithTypeArguments */:
+ case 200 /* ExpressionWithTypeArguments */:
return isEntityNameExpression(node.expression)
? node.expression
: undefined;
case 70 /* Identifier */:
- case 141 /* QualifiedName */:
+ case 142 /* QualifiedName */:
return node;
}
return undefined;
@@ -7399,10 +7606,12 @@ var ts;
ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
function isCallLikeExpression(node) {
switch (node.kind) {
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
- case 181 /* TaggedTemplateExpression */:
- case 145 /* Decorator */:
+ case 250 /* JsxOpeningElement */:
+ case 249 /* JsxSelfClosingElement */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
+ case 182 /* TaggedTemplateExpression */:
+ case 146 /* Decorator */:
return true;
default:
return false;
@@ -7410,34 +7619,37 @@ var ts;
}
ts.isCallLikeExpression = isCallLikeExpression;
function getInvokedExpression(node) {
- if (node.kind === 181 /* TaggedTemplateExpression */) {
+ if (node.kind === 182 /* TaggedTemplateExpression */) {
return node.tag;
}
+ else if (isJsxOpeningLikeElement(node)) {
+ return node.tagName;
+ }
// Will either be a CallExpression, NewExpression, or Decorator.
return node.expression;
}
ts.getInvokedExpression = getInvokedExpression;
function nodeCanBeDecorated(node) {
switch (node.kind) {
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
// classes are valid targets
return true;
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
// property declarations are valid if their parent is a class declaration.
- return node.parent.kind === 226 /* ClassDeclaration */;
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 149 /* MethodDeclaration */:
+ return node.parent.kind === 228 /* ClassDeclaration */;
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 150 /* MethodDeclaration */:
// if this method has a body and its parent is a class declaration, this is a valid target.
return node.body !== undefined
- && node.parent.kind === 226 /* ClassDeclaration */;
- case 144 /* Parameter */:
+ && node.parent.kind === 228 /* ClassDeclaration */;
+ case 145 /* Parameter */:
// if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
return node.parent.body !== undefined
- && (node.parent.kind === 150 /* Constructor */
- || node.parent.kind === 149 /* MethodDeclaration */
- || node.parent.kind === 152 /* SetAccessor */)
- && node.parent.parent.kind === 226 /* ClassDeclaration */;
+ && (node.parent.kind === 151 /* Constructor */
+ || node.parent.kind === 150 /* MethodDeclaration */
+ || node.parent.kind === 153 /* SetAccessor */)
+ && node.parent.parent.kind === 228 /* ClassDeclaration */;
}
return false;
}
@@ -7453,19 +7665,19 @@ var ts;
ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
function childIsDecorated(node) {
switch (node.kind) {
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
return ts.forEach(node.members, nodeOrChildIsDecorated);
- case 149 /* MethodDeclaration */:
- case 152 /* SetAccessor */:
+ case 150 /* MethodDeclaration */:
+ case 153 /* SetAccessor */:
return ts.forEach(node.parameters, nodeIsDecorated);
}
}
ts.childIsDecorated = childIsDecorated;
function isJSXTagName(node) {
var parent = node.parent;
- if (parent.kind === 248 /* JsxOpeningElement */ ||
- parent.kind === 247 /* JsxSelfClosingElement */ ||
- parent.kind === 249 /* JsxClosingElement */) {
+ if (parent.kind === 250 /* JsxOpeningElement */ ||
+ parent.kind === 249 /* JsxSelfClosingElement */ ||
+ parent.kind === 251 /* JsxClosingElement */) {
return parent.tagName === node;
}
return false;
@@ -7479,96 +7691,97 @@ var ts;
case 100 /* TrueKeyword */:
case 85 /* FalseKeyword */:
case 11 /* RegularExpressionLiteral */:
- case 175 /* ArrayLiteralExpression */:
- case 176 /* ObjectLiteralExpression */:
- case 177 /* PropertyAccessExpression */:
- case 178 /* ElementAccessExpression */:
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
- case 181 /* TaggedTemplateExpression */:
- case 200 /* AsExpression */:
- case 182 /* TypeAssertionExpression */:
- case 201 /* NonNullExpression */:
- case 183 /* ParenthesizedExpression */:
- case 184 /* FunctionExpression */:
- case 197 /* ClassExpression */:
- case 185 /* ArrowFunction */:
- case 188 /* VoidExpression */:
- case 186 /* DeleteExpression */:
- case 187 /* TypeOfExpression */:
- case 190 /* PrefixUnaryExpression */:
- case 191 /* PostfixUnaryExpression */:
- case 192 /* BinaryExpression */:
- case 193 /* ConditionalExpression */:
- case 196 /* SpreadElement */:
- case 194 /* TemplateExpression */:
+ case 176 /* ArrayLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
+ case 178 /* PropertyAccessExpression */:
+ case 179 /* ElementAccessExpression */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
+ case 182 /* TaggedTemplateExpression */:
+ case 201 /* AsExpression */:
+ case 183 /* TypeAssertionExpression */:
+ case 202 /* NonNullExpression */:
+ case 184 /* ParenthesizedExpression */:
+ case 185 /* FunctionExpression */:
+ case 198 /* ClassExpression */:
+ case 186 /* ArrowFunction */:
+ case 189 /* VoidExpression */:
+ case 187 /* DeleteExpression */:
+ case 188 /* TypeOfExpression */:
+ case 191 /* PrefixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
+ case 193 /* BinaryExpression */:
+ case 194 /* ConditionalExpression */:
+ case 197 /* SpreadElement */:
+ case 195 /* TemplateExpression */:
case 12 /* NoSubstitutionTemplateLiteral */:
- case 198 /* OmittedExpression */:
- case 246 /* JsxElement */:
- case 247 /* JsxSelfClosingElement */:
- case 195 /* YieldExpression */:
- case 189 /* AwaitExpression */:
+ case 199 /* OmittedExpression */:
+ case 248 /* JsxElement */:
+ case 249 /* JsxSelfClosingElement */:
+ case 196 /* YieldExpression */:
+ case 190 /* AwaitExpression */:
+ case 203 /* MetaProperty */:
return true;
- case 141 /* QualifiedName */:
- while (node.parent.kind === 141 /* QualifiedName */) {
+ case 142 /* QualifiedName */:
+ while (node.parent.kind === 142 /* QualifiedName */) {
node = node.parent;
}
- return node.parent.kind === 160 /* TypeQuery */ || isJSXTagName(node);
+ return node.parent.kind === 161 /* TypeQuery */ || isJSXTagName(node);
case 70 /* Identifier */:
- if (node.parent.kind === 160 /* TypeQuery */ || isJSXTagName(node)) {
+ if (node.parent.kind === 161 /* TypeQuery */ || isJSXTagName(node)) {
return true;
}
- // fall through
+ // falls through
case 8 /* NumericLiteral */:
case 9 /* StringLiteral */:
case 98 /* ThisKeyword */:
- var parent_3 = node.parent;
- switch (parent_3.kind) {
- case 223 /* VariableDeclaration */:
- case 144 /* Parameter */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 260 /* EnumMember */:
- case 257 /* PropertyAssignment */:
- case 174 /* BindingElement */:
- return parent_3.initializer === node;
- case 207 /* ExpressionStatement */:
- case 208 /* IfStatement */:
- case 209 /* DoStatement */:
- case 210 /* WhileStatement */:
- case 216 /* ReturnStatement */:
- case 217 /* WithStatement */:
- case 218 /* SwitchStatement */:
- case 253 /* CaseClause */:
- case 220 /* ThrowStatement */:
- case 218 /* SwitchStatement */:
- return parent_3.expression === node;
- case 211 /* ForStatement */:
- var forStatement = parent_3;
- return (forStatement.initializer === node && forStatement.initializer.kind !== 224 /* VariableDeclarationList */) ||
+ var parent = node.parent;
+ switch (parent.kind) {
+ case 225 /* VariableDeclaration */:
+ case 145 /* Parameter */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 263 /* EnumMember */:
+ case 260 /* PropertyAssignment */:
+ case 175 /* BindingElement */:
+ return parent.initializer === node;
+ case 209 /* ExpressionStatement */:
+ case 210 /* IfStatement */:
+ case 211 /* DoStatement */:
+ case 212 /* WhileStatement */:
+ case 218 /* ReturnStatement */:
+ case 219 /* WithStatement */:
+ case 220 /* SwitchStatement */:
+ case 256 /* CaseClause */:
+ case 222 /* ThrowStatement */:
+ case 220 /* SwitchStatement */:
+ return parent.expression === node;
+ case 213 /* ForStatement */:
+ var forStatement = parent;
+ return (forStatement.initializer === node && forStatement.initializer.kind !== 226 /* VariableDeclarationList */) ||
forStatement.condition === node ||
forStatement.incrementor === node;
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- var forInStatement = parent_3;
- return (forInStatement.initializer === node && forInStatement.initializer.kind !== 224 /* VariableDeclarationList */) ||
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ var forInStatement = parent;
+ return (forInStatement.initializer === node && forInStatement.initializer.kind !== 226 /* VariableDeclarationList */) ||
forInStatement.expression === node;
- case 182 /* TypeAssertionExpression */:
- case 200 /* AsExpression */:
- return node === parent_3.expression;
- case 202 /* TemplateSpan */:
- return node === parent_3.expression;
- case 142 /* ComputedPropertyName */:
- return node === parent_3.expression;
- case 145 /* Decorator */:
- case 252 /* JsxExpression */:
- case 251 /* JsxSpreadAttribute */:
- case 259 /* SpreadAssignment */:
+ case 183 /* TypeAssertionExpression */:
+ case 201 /* AsExpression */:
+ return node === parent.expression;
+ case 204 /* TemplateSpan */:
+ return node === parent.expression;
+ case 143 /* ComputedPropertyName */:
+ return node === parent.expression;
+ case 146 /* Decorator */:
+ case 255 /* JsxExpression */:
+ case 254 /* JsxSpreadAttribute */:
+ case 262 /* SpreadAssignment */:
return true;
- case 199 /* ExpressionWithTypeArguments */:
- return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3);
+ case 200 /* ExpressionWithTypeArguments */:
+ return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
default:
- if (isPartOfExpression(parent_3)) {
+ if (isPartOfExpression(parent)) {
return true;
}
}
@@ -7583,7 +7796,7 @@ var ts;
}
ts.isInstantiatedModule = isInstantiatedModule;
function isExternalModuleImportEqualsDeclaration(node) {
- return node.kind === 234 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 245 /* ExternalModuleReference */;
+ return node.kind === 236 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 247 /* ExternalModuleReference */;
}
ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
function getExternalModuleImportEqualsDeclarationExpression(node) {
@@ -7592,7 +7805,7 @@ var ts;
}
ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
function isInternalModuleImportEqualsDeclaration(node) {
- return node.kind === 234 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 245 /* ExternalModuleReference */;
+ return node.kind === 236 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 247 /* ExternalModuleReference */;
}
ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
function isSourceFileJavaScript(file) {
@@ -7600,21 +7813,27 @@ var ts;
}
ts.isSourceFileJavaScript = isSourceFileJavaScript;
function isInJavaScriptFile(node) {
- return node && !!(node.flags & 2097152 /* JavaScriptFile */);
+ return node && !!(node.flags & 65536 /* JavaScriptFile */);
}
ts.isInJavaScriptFile = isInJavaScriptFile;
/**
* Returns true if the node is a CallExpression to the identifier 'require' with
- * exactly one argument.
+ * exactly one argument (of the form 'require("name")').
* This function does not test if the node is in a JavaScript file or not.
- */
- function isRequireCall(expression, checkArgumentIsStringLiteral) {
- // of the form 'require("name")'
- var isRequire = expression.kind === 179 /* CallExpression */ &&
- expression.expression.kind === 70 /* Identifier */ &&
- expression.expression.text === "require" &&
- expression.arguments.length === 1;
- return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9 /* StringLiteral */);
+ */
+ function isRequireCall(callExpression, checkArgumentIsStringLiteral) {
+ if (callExpression.kind !== 180 /* CallExpression */) {
+ return false;
+ }
+ var _a = callExpression, expression = _a.expression, args = _a.arguments;
+ if (expression.kind !== 70 /* Identifier */ || expression.text !== "require") {
+ return false;
+ }
+ if (args.length !== 1) {
+ return false;
+ }
+ var arg = args[0];
+ return !checkArgumentIsStringLiteral || arg.kind === 9 /* StringLiteral */ || arg.kind === 12 /* NoSubstitutionTemplateLiteral */;
}
ts.isRequireCall = isRequireCall;
function isSingleOrDoubleQuote(charCode) {
@@ -7625,25 +7844,37 @@ var ts;
* Returns true if the node is a variable declaration whose initializer is a function expression.
* This function does not test if the node is in a JavaScript file or not.
*/
- function isDeclarationOfFunctionExpression(s) {
- if (s.valueDeclaration && s.valueDeclaration.kind === 223 /* VariableDeclaration */) {
+ function isDeclarationOfFunctionOrClassExpression(s) {
+ if (s.valueDeclaration && s.valueDeclaration.kind === 225 /* VariableDeclaration */) {
var declaration = s.valueDeclaration;
- return declaration.initializer && declaration.initializer.kind === 184 /* FunctionExpression */;
+ return declaration.initializer && (declaration.initializer.kind === 185 /* FunctionExpression */ || declaration.initializer.kind === 198 /* ClassExpression */);
}
return false;
}
- ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression;
+ ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression;
+ function getRightMostAssignedExpression(node) {
+ while (isAssignmentExpression(node, /*excludeCompoundAssignements*/ true)) {
+ node = node.right;
+ }
+ return node;
+ }
+ ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
+ function isExportsIdentifier(node) {
+ return isIdentifier(node) && node.text === "exports";
+ }
+ ts.isExportsIdentifier = isExportsIdentifier;
+ function isModuleExportsPropertyAccessExpression(node) {
+ return isPropertyAccessExpression(node) && isIdentifier(node.expression) && node.expression.text === "module" && node.name.text === "exports";
+ }
+ ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression;
/// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
/// assignments we treat as special in the binder
function getSpecialPropertyAssignmentKind(expression) {
if (!isInJavaScriptFile(expression)) {
return 0 /* None */;
}
- if (expression.kind !== 192 /* BinaryExpression */) {
- return 0 /* None */;
- }
var expr = expression;
- if (expr.operatorToken.kind !== 57 /* EqualsToken */ || expr.left.kind !== 177 /* PropertyAccessExpression */) {
+ if (expr.operatorToken.kind !== 57 /* EqualsToken */ || expr.left.kind !== 178 /* PropertyAccessExpression */) {
return 0 /* None */;
}
var lhs = expr.left;
@@ -7657,11 +7888,15 @@ var ts;
// module.exports = expr
return 2 /* ModuleExports */;
}
+ else {
+ // F.x = expr
+ return 5 /* Property */;
+ }
}
else if (lhs.expression.kind === 98 /* ThisKeyword */) {
return 4 /* ThisProperty */;
}
- else if (lhs.expression.kind === 177 /* PropertyAccessExpression */) {
+ else if (lhs.expression.kind === 178 /* PropertyAccessExpression */) {
// chained dot, e.g. x.y.z = expr; this var is the 'x.y' part
var innerPropertyAccess = lhs.expression;
if (innerPropertyAccess.expression.kind === 70 /* Identifier */) {
@@ -7679,35 +7914,35 @@ var ts;
}
ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind;
function getExternalModuleName(node) {
- if (node.kind === 235 /* ImportDeclaration */) {
+ if (node.kind === 237 /* ImportDeclaration */) {
return node.moduleSpecifier;
}
- if (node.kind === 234 /* ImportEqualsDeclaration */) {
+ if (node.kind === 236 /* ImportEqualsDeclaration */) {
var reference = node.moduleReference;
- if (reference.kind === 245 /* ExternalModuleReference */) {
+ if (reference.kind === 247 /* ExternalModuleReference */) {
return reference.expression;
}
}
- if (node.kind === 241 /* ExportDeclaration */) {
+ if (node.kind === 243 /* ExportDeclaration */) {
return node.moduleSpecifier;
}
- if (node.kind === 230 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) {
+ if (node.kind === 232 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) {
return node.name;
}
}
ts.getExternalModuleName = getExternalModuleName;
function getNamespaceDeclarationNode(node) {
- if (node.kind === 234 /* ImportEqualsDeclaration */) {
+ if (node.kind === 236 /* ImportEqualsDeclaration */) {
return node;
}
var importClause = node.importClause;
- if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 237 /* NamespaceImport */) {
+ if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 239 /* NamespaceImport */) {
return importClause.namedBindings;
}
}
ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
function isDefaultImport(node) {
- return node.kind === 235 /* ImportDeclaration */
+ return node.kind === 237 /* ImportDeclaration */
&& node.importClause
&& !!node.importClause.name;
}
@@ -7715,13 +7950,13 @@ var ts;
function hasQuestionToken(node) {
if (node) {
switch (node.kind) {
- case 144 /* Parameter */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 258 /* ShorthandPropertyAssignment */:
- case 257 /* PropertyAssignment */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 145 /* Parameter */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 261 /* ShorthandPropertyAssignment */:
+ case 260 /* PropertyAssignment */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
return node.questionToken !== undefined;
}
}
@@ -7729,28 +7964,36 @@ var ts;
}
ts.hasQuestionToken = hasQuestionToken;
function isJSDocConstructSignature(node) {
- return node.kind === 274 /* JSDocFunctionType */ &&
+ return node.kind === 278 /* JSDocFunctionType */ &&
node.parameters.length > 0 &&
- node.parameters[0].type.kind === 276 /* JSDocConstructorType */;
+ node.parameters[0].type.kind === 280 /* JSDocConstructorType */;
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function getCommentsFromJSDoc(node) {
return ts.map(getJSDocs(node), function (doc) { return doc.comment; });
}
ts.getCommentsFromJSDoc = getCommentsFromJSDoc;
+ function hasJSDocParameterTags(node) {
+ var parameterTags = getJSDocTags(node, 285 /* JSDocParameterTag */);
+ return parameterTags && parameterTags.length > 0;
+ }
+ ts.hasJSDocParameterTags = hasJSDocParameterTags;
function getJSDocTags(node, kind) {
var docs = getJSDocs(node);
if (docs) {
var result = [];
for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) {
var doc = docs_1[_i];
- if (doc.kind === 281 /* JSDocParameterTag */) {
+ if (doc.kind === 285 /* JSDocParameterTag */) {
if (doc.kind === kind) {
result.push(doc);
}
}
else {
- result.push.apply(result, ts.filter(doc.tags, function (tag) { return tag.kind === kind; }));
+ var tags = doc.tags;
+ if (tags) {
+ result.push.apply(result, ts.filter(tags, function (tag) { return tag.kind === kind; }));
+ }
}
}
return result;
@@ -7776,9 +8019,9 @@ var ts;
// var x = function(name) { return name.length; }
var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) &&
parent.initializer === node &&
- parent.parent.parent.kind === 205 /* VariableStatement */;
+ parent.parent.parent.kind === 207 /* VariableStatement */;
var isVariableOfVariableDeclarationStatement = isVariableLike(node) &&
- parent.parent.kind === 205 /* VariableStatement */;
+ parent.parent.kind === 207 /* VariableStatement */;
var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent :
isVariableOfVariableDeclarationStatement ? parent.parent :
undefined;
@@ -7787,20 +8030,20 @@ var ts;
}
// Also recognize when the node is the RHS of an assignment expression
var isSourceOfAssignmentExpressionStatement = parent && parent.parent &&
- parent.kind === 192 /* BinaryExpression */ &&
+ parent.kind === 193 /* BinaryExpression */ &&
parent.operatorToken.kind === 57 /* EqualsToken */ &&
- parent.parent.kind === 207 /* ExpressionStatement */;
+ parent.parent.kind === 209 /* ExpressionStatement */;
if (isSourceOfAssignmentExpressionStatement) {
getJSDocsWorker(parent.parent);
}
- var isModuleDeclaration = node.kind === 230 /* ModuleDeclaration */ &&
- parent && parent.kind === 230 /* ModuleDeclaration */;
- var isPropertyAssignmentExpression = parent && parent.kind === 257 /* PropertyAssignment */;
+ var isModuleDeclaration = node.kind === 232 /* ModuleDeclaration */ &&
+ parent && parent.kind === 232 /* ModuleDeclaration */;
+ var isPropertyAssignmentExpression = parent && parent.kind === 260 /* PropertyAssignment */;
if (isModuleDeclaration || isPropertyAssignmentExpression) {
getJSDocsWorker(parent);
}
// Pull parameter comments from declaring function as well
- if (node.kind === 144 /* Parameter */) {
+ if (node.kind === 145 /* Parameter */) {
cache = ts.concatenate(cache, getJSDocParameterTags(node));
}
if (isVariableLike(node) && node.initializer) {
@@ -7809,23 +8052,24 @@ var ts;
cache = ts.concatenate(cache, node.jsDoc);
}
}
+ ts.getJSDocs = getJSDocs;
function getJSDocParameterTags(param) {
if (!isParameter(param)) {
return undefined;
}
var func = param.parent;
- var tags = getJSDocTags(func, 281 /* JSDocParameterTag */);
+ var tags = getJSDocTags(func, 285 /* JSDocParameterTag */);
if (!param.name) {
// this is an anonymous jsdoc param from a `function(type1, type2): type3` specification
var i = func.parameters.indexOf(param);
- var paramTags = ts.filter(tags, function (tag) { return tag.kind === 281 /* JSDocParameterTag */; });
+ var paramTags = ts.filter(tags, function (tag) { return tag.kind === 285 /* JSDocParameterTag */; });
if (paramTags && 0 <= i && i < paramTags.length) {
return [paramTags[i]];
}
}
else if (param.name.kind === 70 /* Identifier */) {
- var name_6 = param.name.text;
- return ts.filter(tags, function (tag) { return tag.kind === 281 /* JSDocParameterTag */ && tag.parameterName.text === name_6; });
+ var name_1 = param.name.text;
+ return ts.filter(tags, function (tag) { return tag.kind === 285 /* JSDocParameterTag */ && tag.parameterName.text === name_1; });
}
else {
// TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines
@@ -7835,8 +8079,8 @@ var ts;
}
ts.getJSDocParameterTags = getJSDocParameterTags;
function getJSDocType(node) {
- var tag = getFirstJSDocTag(node, 283 /* JSDocTypeTag */);
- if (!tag && node.kind === 144 /* Parameter */) {
+ var tag = getFirstJSDocTag(node, 287 /* JSDocTypeTag */);
+ if (!tag && node.kind === 145 /* Parameter */) {
var paramTags = getJSDocParameterTags(node);
if (paramTags) {
tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; });
@@ -7846,15 +8090,15 @@ var ts;
}
ts.getJSDocType = getJSDocType;
function getJSDocAugmentsTag(node) {
- return getFirstJSDocTag(node, 280 /* JSDocAugmentsTag */);
+ return getFirstJSDocTag(node, 284 /* JSDocAugmentsTag */);
}
ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
function getJSDocReturnTag(node) {
- return getFirstJSDocTag(node, 282 /* JSDocReturnTag */);
+ return getFirstJSDocTag(node, 286 /* JSDocReturnTag */);
}
ts.getJSDocReturnTag = getJSDocReturnTag;
function getJSDocTemplateTag(node) {
- return getFirstJSDocTag(node, 284 /* JSDocTemplateTag */);
+ return getFirstJSDocTag(node, 288 /* JSDocTemplateTag */);
}
ts.getJSDocTemplateTag = getJSDocTemplateTag;
function hasRestParameter(s) {
@@ -7866,9 +8110,9 @@ var ts;
}
ts.hasDeclaredRestParameter = hasDeclaredRestParameter;
function isRestParameter(node) {
- if (node && (node.flags & 2097152 /* JavaScriptFile */)) {
- if (node.type && node.type.kind === 275 /* JSDocVariadicType */ ||
- ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 275 /* JSDocVariadicType */; })) {
+ if (node && (node.flags & 65536 /* JavaScriptFile */)) {
+ if (node.type && node.type.kind === 279 /* JSDocVariadicType */ ||
+ ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 279 /* JSDocVariadicType */; })) {
return true;
}
}
@@ -7889,29 +8133,33 @@ var ts;
var parent = node.parent;
while (true) {
switch (parent.kind) {
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
var binaryOperator = parent.operatorToken.kind;
return isAssignmentOperator(binaryOperator) && parent.left === node ?
binaryOperator === 57 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
0 /* None */;
- case 190 /* PrefixUnaryExpression */:
- case 191 /* PostfixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
var unaryOperator = parent.operator;
return unaryOperator === 42 /* PlusPlusToken */ || unaryOperator === 43 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
- case 183 /* ParenthesizedExpression */:
- case 175 /* ArrayLiteralExpression */:
- case 196 /* SpreadElement */:
+ case 184 /* ParenthesizedExpression */:
+ case 176 /* ArrayLiteralExpression */:
+ case 197 /* SpreadElement */:
node = parent;
break;
- case 258 /* ShorthandPropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
if (parent.name !== node) {
return 0 /* None */;
}
- // Fall through
- case 257 /* PropertyAssignment */:
+ node = parent.parent;
+ break;
+ case 260 /* PropertyAssignment */:
+ if (parent.name === node) {
+ return 0 /* None */;
+ }
node = parent.parent;
break;
default:
@@ -7923,11 +8171,24 @@ var ts;
ts.getAssignmentTargetKind = getAssignmentTargetKind;
// A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
// assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
- // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'.
+ // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
+ // (Note that `p` is not a target in the above examples, only `a`.)
function isAssignmentTarget(node) {
return getAssignmentTargetKind(node) !== 0 /* None */;
}
ts.isAssignmentTarget = isAssignmentTarget;
+ // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
+ function isDeleteTarget(node) {
+ if (node.kind !== 178 /* PropertyAccessExpression */ && node.kind !== 179 /* ElementAccessExpression */) {
+ return false;
+ }
+ node = node.parent;
+ while (node && node.kind === 184 /* ParenthesizedExpression */) {
+ node = node.parent;
+ }
+ return node && node.kind === 187 /* DeleteExpression */;
+ }
+ ts.isDeleteTarget = isDeleteTarget;
function isNodeDescendantOf(node, ancestor) {
while (node) {
if (node === ancestor)
@@ -7939,7 +8200,7 @@ var ts;
ts.isNodeDescendantOf = isNodeDescendantOf;
function isInAmbientContext(node) {
while (node) {
- if (hasModifier(node, 2 /* Ambient */) || (node.kind === 261 /* SourceFile */ && node.isDeclarationFile)) {
+ if (hasModifier(node, 2 /* Ambient */) || (node.kind === 264 /* SourceFile */ && node.isDeclarationFile)) {
return true;
}
node = node.parent;
@@ -7953,7 +8214,7 @@ var ts;
return false;
}
var parent = name.parent;
- if (parent.kind === 239 /* ImportSpecifier */ || parent.kind === 243 /* ExportSpecifier */) {
+ if (parent.kind === 241 /* ImportSpecifier */ || parent.kind === 245 /* ExportSpecifier */) {
if (parent.propertyName) {
return true;
}
@@ -7966,7 +8227,7 @@ var ts;
ts.isDeclarationName = isDeclarationName;
function isLiteralComputedPropertyDeclarationName(node) {
return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) &&
- node.parent.kind === 142 /* ComputedPropertyName */ &&
+ node.parent.kind === 143 /* ComputedPropertyName */ &&
isDeclaration(node.parent.parent);
}
ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
@@ -7974,31 +8235,31 @@ var ts;
function isIdentifierName(node) {
var parent = node.parent;
switch (parent.kind) {
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 260 /* EnumMember */:
- case 257 /* PropertyAssignment */:
- case 177 /* PropertyAccessExpression */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 263 /* EnumMember */:
+ case 260 /* PropertyAssignment */:
+ case 178 /* PropertyAccessExpression */:
// Name in member declaration or property name in property access
return parent.name === node;
- case 141 /* QualifiedName */:
+ case 142 /* QualifiedName */:
// Name on right hand side of dot in a type query
if (parent.right === node) {
- while (parent.kind === 141 /* QualifiedName */) {
+ while (parent.kind === 142 /* QualifiedName */) {
parent = parent.parent;
}
- return parent.kind === 160 /* TypeQuery */;
+ return parent.kind === 161 /* TypeQuery */;
}
return false;
- case 174 /* BindingElement */:
- case 239 /* ImportSpecifier */:
+ case 175 /* BindingElement */:
+ case 241 /* ImportSpecifier */:
// Property name in binding element or import specifier
return parent.propertyName === node;
- case 243 /* ExportSpecifier */:
+ case 245 /* ExportSpecifier */:
// Any name in an export specifier
return true;
}
@@ -8014,13 +8275,13 @@ var ts;
// export = <EntityNameExpression>
// export default <EntityNameExpression>
function isAliasSymbolDeclaration(node) {
- return node.kind === 234 /* ImportEqualsDeclaration */ ||
- node.kind === 233 /* NamespaceExportDeclaration */ ||
- node.kind === 236 /* ImportClause */ && !!node.name ||
- node.kind === 237 /* NamespaceImport */ ||
- node.kind === 239 /* ImportSpecifier */ ||
- node.kind === 243 /* ExportSpecifier */ ||
- node.kind === 240 /* ExportAssignment */ && exportAssignmentIsAlias(node);
+ return node.kind === 236 /* ImportEqualsDeclaration */ ||
+ node.kind === 235 /* NamespaceExportDeclaration */ ||
+ node.kind === 238 /* ImportClause */ && !!node.name ||
+ node.kind === 239 /* NamespaceImport */ ||
+ node.kind === 241 /* ImportSpecifier */ ||
+ node.kind === 245 /* ExportSpecifier */ ||
+ node.kind === 242 /* ExportAssignment */ && exportAssignmentIsAlias(node);
}
ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
function exportAssignmentIsAlias(node) {
@@ -8106,17 +8367,62 @@ var ts;
}
ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath;
function isKeyword(token) {
- return 71 /* FirstKeyword */ <= token && token <= 140 /* LastKeyword */;
+ return 71 /* FirstKeyword */ <= token && token <= 141 /* LastKeyword */;
}
ts.isKeyword = isKeyword;
function isTrivia(token) {
return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
}
ts.isTrivia = isTrivia;
- function isAsyncFunctionLike(node) {
- return isFunctionLike(node) && hasModifier(node, 256 /* Async */) && !isAccessor(node);
+ var FunctionFlags;
+ (function (FunctionFlags) {
+ FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
+ FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
+ FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
+ FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator";
+ FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
+ FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator";
+ FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator";
+ })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
+ function getFunctionFlags(node) {
+ var flags = 0 /* Normal */;
+ switch (node.kind) {
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 150 /* MethodDeclaration */:
+ if (node.asteriskToken) {
+ flags |= 1 /* Generator */;
+ }
+ // falls through
+ case 186 /* ArrowFunction */:
+ if (hasModifier(node, 256 /* Async */)) {
+ flags |= 2 /* Async */;
+ }
+ break;
+ }
+ if (!node.body) {
+ flags |= 4 /* Invalid */;
+ }
+ return flags;
+ }
+ ts.getFunctionFlags = getFunctionFlags;
+ function isAsyncFunction(node) {
+ switch (node.kind) {
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 150 /* MethodDeclaration */:
+ return node.body !== undefined
+ && node.asteriskToken === undefined
+ && hasModifier(node, 256 /* Async */);
+ }
+ return false;
+ }
+ ts.isAsyncFunction = isAsyncFunction;
+ function isNumericLiteral(node) {
+ return node.kind === 8 /* NumericLiteral */;
}
- ts.isAsyncFunctionLike = isAsyncFunctionLike;
+ ts.isNumericLiteral = isNumericLiteral;
function isStringOrNumericLiteral(node) {
var kind = node.kind;
return kind === 9 /* StringLiteral */
@@ -8135,7 +8441,7 @@ var ts;
}
ts.hasDynamicName = hasDynamicName;
function isDynamicName(name) {
- return name.kind === 142 /* ComputedPropertyName */ &&
+ return name.kind === 143 /* ComputedPropertyName */ &&
!isStringOrNumericLiteral(name.expression) &&
!isWellKnownSymbolSyntactically(name.expression);
}
@@ -8150,10 +8456,10 @@ var ts;
}
ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
function getPropertyNameForPropertyNameNode(name) {
- if (name.kind === 70 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name.kind === 144 /* Parameter */) {
+ if (name.kind === 70 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name.kind === 145 /* Parameter */) {
return name.text;
}
- if (name.kind === 142 /* ComputedPropertyName */) {
+ if (name.kind === 143 /* ComputedPropertyName */) {
var nameExpression = name.expression;
if (isWellKnownSymbolSyntactically(nameExpression)) {
var rightHandSideName = nameExpression.name.text;
@@ -8201,11 +8507,11 @@ var ts;
ts.isModifierKind = isModifierKind;
function isParameterDeclaration(node) {
var root = getRootDeclaration(node);
- return root.kind === 144 /* Parameter */;
+ return root.kind === 145 /* Parameter */;
}
ts.isParameterDeclaration = isParameterDeclaration;
function getRootDeclaration(node) {
- while (node.kind === 174 /* BindingElement */) {
+ while (node.kind === 175 /* BindingElement */) {
node = node.parent.parent;
}
return node;
@@ -8213,15 +8519,15 @@ var ts;
ts.getRootDeclaration = getRootDeclaration;
function nodeStartsNewLexicalEnvironment(node) {
var kind = node.kind;
- return kind === 150 /* Constructor */
- || kind === 184 /* FunctionExpression */
- || kind === 225 /* FunctionDeclaration */
- || kind === 185 /* ArrowFunction */
- || kind === 149 /* MethodDeclaration */
- || kind === 151 /* GetAccessor */
- || kind === 152 /* SetAccessor */
- || kind === 230 /* ModuleDeclaration */
- || kind === 261 /* SourceFile */;
+ return kind === 151 /* Constructor */
+ || kind === 185 /* FunctionExpression */
+ || kind === 227 /* FunctionDeclaration */
+ || kind === 186 /* ArrowFunction */
+ || kind === 150 /* MethodDeclaration */
+ || kind === 152 /* GetAccessor */
+ || kind === 153 /* SetAccessor */
+ || kind === 232 /* ModuleDeclaration */
+ || kind === 264 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(node) {
@@ -8229,49 +8535,22 @@ var ts;
|| ts.positionIsSynthesized(node.end);
}
ts.nodeIsSynthesized = nodeIsSynthesized;
- function getOriginalNode(node, nodeTest) {
- if (node) {
- while (node.original !== undefined) {
- node = node.original;
- }
+ function getOriginalSourceFileOrBundle(sourceFileOrBundle) {
+ if (sourceFileOrBundle.kind === 265 /* Bundle */) {
+ return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, getOriginalSourceFile));
}
- return !nodeTest || nodeTest(node) ? node : undefined;
- }
- ts.getOriginalNode = getOriginalNode;
- /**
- * Gets a value indicating whether a node originated in the parse tree.
- *
- * @param node The node to test.
- */
- function isParseTreeNode(node) {
- return (node.flags & 8 /* Synthesized */) === 0;
+ return getOriginalSourceFile(sourceFileOrBundle);
}
- ts.isParseTreeNode = isParseTreeNode;
- function getParseTreeNode(node, nodeTest) {
- if (isParseTreeNode(node)) {
- return node;
- }
- node = getOriginalNode(node);
- if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
- return node;
- }
- return undefined;
+ ts.getOriginalSourceFileOrBundle = getOriginalSourceFileOrBundle;
+ function getOriginalSourceFile(sourceFile) {
+ return ts.getParseTreeNode(sourceFile, isSourceFile) || sourceFile;
}
- ts.getParseTreeNode = getParseTreeNode;
function getOriginalSourceFiles(sourceFiles) {
- var originalSourceFiles = [];
- for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
- var sourceFile = sourceFiles_1[_i];
- var originalSourceFile = getParseTreeNode(sourceFile, isSourceFile);
- if (originalSourceFile) {
- originalSourceFiles.push(originalSourceFile);
- }
- }
- return originalSourceFiles;
+ return ts.sameMap(sourceFiles, getOriginalSourceFile);
}
ts.getOriginalSourceFiles = getOriginalSourceFiles;
function getOriginalNodeId(node) {
- node = getOriginalNode(node);
+ node = ts.getOriginalNode(node);
return node ? ts.getNodeId(node) : 0;
}
ts.getOriginalNodeId = getOriginalNodeId;
@@ -8282,23 +8561,23 @@ var ts;
})(Associativity = ts.Associativity || (ts.Associativity = {}));
function getExpressionAssociativity(expression) {
var operator = getOperator(expression);
- var hasArguments = expression.kind === 180 /* NewExpression */ && expression.arguments !== undefined;
+ var hasArguments = expression.kind === 181 /* NewExpression */ && expression.arguments !== undefined;
return getOperatorAssociativity(expression.kind, operator, hasArguments);
}
ts.getExpressionAssociativity = getExpressionAssociativity;
function getOperatorAssociativity(kind, operator, hasArguments) {
switch (kind) {
- case 180 /* NewExpression */:
+ case 181 /* NewExpression */:
return hasArguments ? 0 /* Left */ : 1 /* Right */;
- case 190 /* PrefixUnaryExpression */:
- case 187 /* TypeOfExpression */:
- case 188 /* VoidExpression */:
- case 186 /* DeleteExpression */:
- case 189 /* AwaitExpression */:
- case 193 /* ConditionalExpression */:
- case 195 /* YieldExpression */:
+ case 191 /* PrefixUnaryExpression */:
+ case 188 /* TypeOfExpression */:
+ case 189 /* VoidExpression */:
+ case 187 /* DeleteExpression */:
+ case 190 /* AwaitExpression */:
+ case 194 /* ConditionalExpression */:
+ case 196 /* YieldExpression */:
return 1 /* Right */;
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
switch (operator) {
case 39 /* AsteriskAsteriskToken */:
case 57 /* EqualsToken */:
@@ -8322,15 +8601,15 @@ var ts;
ts.getOperatorAssociativity = getOperatorAssociativity;
function getExpressionPrecedence(expression) {
var operator = getOperator(expression);
- var hasArguments = expression.kind === 180 /* NewExpression */ && expression.arguments !== undefined;
+ var hasArguments = expression.kind === 181 /* NewExpression */ && expression.arguments !== undefined;
return getOperatorPrecedence(expression.kind, operator, hasArguments);
}
ts.getExpressionPrecedence = getExpressionPrecedence;
function getOperator(expression) {
- if (expression.kind === 192 /* BinaryExpression */) {
+ if (expression.kind === 193 /* BinaryExpression */) {
return expression.operatorToken.kind;
}
- else if (expression.kind === 190 /* PrefixUnaryExpression */ || expression.kind === 191 /* PostfixUnaryExpression */) {
+ else if (expression.kind === 191 /* PrefixUnaryExpression */ || expression.kind === 192 /* PostfixUnaryExpression */) {
return expression.operator;
}
else {
@@ -8348,37 +8627,36 @@ var ts;
case 85 /* FalseKeyword */:
case 8 /* NumericLiteral */:
case 9 /* StringLiteral */:
- case 175 /* ArrayLiteralExpression */:
- case 176 /* ObjectLiteralExpression */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 197 /* ClassExpression */:
- case 246 /* JsxElement */:
- case 247 /* JsxSelfClosingElement */:
+ case 176 /* ArrayLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 198 /* ClassExpression */:
+ case 248 /* JsxElement */:
+ case 249 /* JsxSelfClosingElement */:
case 11 /* RegularExpressionLiteral */:
case 12 /* NoSubstitutionTemplateLiteral */:
- case 194 /* TemplateExpression */:
- case 183 /* ParenthesizedExpression */:
- case 198 /* OmittedExpression */:
- case 297 /* RawExpression */:
+ case 195 /* TemplateExpression */:
+ case 184 /* ParenthesizedExpression */:
+ case 199 /* OmittedExpression */:
return 19;
- case 181 /* TaggedTemplateExpression */:
- case 177 /* PropertyAccessExpression */:
- case 178 /* ElementAccessExpression */:
+ case 182 /* TaggedTemplateExpression */:
+ case 178 /* PropertyAccessExpression */:
+ case 179 /* ElementAccessExpression */:
return 18;
- case 180 /* NewExpression */:
+ case 181 /* NewExpression */:
return hasArguments ? 18 : 17;
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
return 17;
- case 191 /* PostfixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
return 16;
- case 190 /* PrefixUnaryExpression */:
- case 187 /* TypeOfExpression */:
- case 188 /* VoidExpression */:
- case 186 /* DeleteExpression */:
- case 189 /* AwaitExpression */:
+ case 191 /* PrefixUnaryExpression */:
+ case 188 /* TypeOfExpression */:
+ case 189 /* VoidExpression */:
+ case 187 /* DeleteExpression */:
+ case 190 /* AwaitExpression */:
return 15;
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
switch (operatorKind) {
case 50 /* ExclamationToken */:
case 51 /* TildeToken */:
@@ -8436,11 +8714,11 @@ var ts;
default:
return -1;
}
- case 193 /* ConditionalExpression */:
+ case 194 /* ConditionalExpression */:
return 4;
- case 195 /* YieldExpression */:
+ case 196 /* YieldExpression */:
return 2;
- case 196 /* SpreadElement */:
+ case 197 /* SpreadElement */:
return 1;
default:
return -1;
@@ -8463,21 +8741,15 @@ var ts;
return modificationCount;
}
function reattachFileDiagnostics(newFile) {
- if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) {
- return;
- }
- for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) {
- var diagnostic = _a[_i];
- diagnostic.file = newFile;
- }
+ ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
}
function add(diagnostic) {
var diagnostics;
if (diagnostic.file) {
- diagnostics = fileDiagnostics[diagnostic.file.fileName];
+ diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
if (!diagnostics) {
diagnostics = [];
- fileDiagnostics[diagnostic.file.fileName] = diagnostics;
+ fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
}
}
else {
@@ -8494,16 +8766,16 @@ var ts;
function getDiagnostics(fileName) {
sortAndDeduplicate();
if (fileName) {
- return fileDiagnostics[fileName] || [];
+ return fileDiagnostics.get(fileName) || [];
}
var allDiagnostics = [];
function pushDiagnostic(d) {
allDiagnostics.push(d);
}
ts.forEach(nonFileDiagnostics, pushDiagnostic);
- for (var key in fileDiagnostics) {
- ts.forEach(fileDiagnostics[key], pushDiagnostic);
- }
+ fileDiagnostics.forEach(function (diagnostics) {
+ ts.forEach(diagnostics, pushDiagnostic);
+ });
return ts.sortAndDeduplicateDiagnostics(allDiagnostics);
}
function sortAndDeduplicate() {
@@ -8512,9 +8784,9 @@ var ts;
}
diagnosticsModified = false;
nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics);
- for (var key in fileDiagnostics) {
- fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]);
- }
+ fileDiagnostics.forEach(function (diagnostics, key) {
+ fileDiagnostics.set(key, ts.sortAndDeduplicateDiagnostics(diagnostics));
+ });
}
}
ts.createDiagnosticCollection = createDiagnosticCollection;
@@ -8524,7 +8796,7 @@ var ts;
// the map below must be updated. Note that this regexp *does not* include the 'delete' character.
// There is no reason for this other than that JSON.stringify does not handle it either.
var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
- var escapedCharsMap = ts.createMap({
+ var escapedCharsMap = ts.createMapFromTemplate({
"\0": "\\0",
"\t": "\\t",
"\v": "\\v",
@@ -8544,13 +8816,12 @@ var ts;
* Note that this doesn't actually wrap the input in double quotes.
*/
function escapeString(s) {
- s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s;
- return s;
- function getReplacement(c) {
- return escapedCharsMap[c] || get16BitUnicodeEscapeSequence(c.charCodeAt(0));
- }
+ return s.replace(escapedCharsRegExp, getReplacement);
}
ts.escapeString = escapeString;
+ function getReplacement(c) {
+ return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0));
+ }
function isIntrinsicJsxName(name) {
var ch = name.substr(0, 1);
return ch.toLowerCase() === ch;
@@ -8707,168 +8978,77 @@ var ts;
*/
function getSourceFilesToEmit(host, targetSourceFile) {
var options = host.getCompilerOptions();
+ var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); };
if (options.outFile || options.out) {
var moduleKind = ts.getEmitModuleKind(options);
- var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
- var sourceFiles = getAllEmittableSourceFiles();
+ var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
- return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule);
+ return ts.filter(host.getSourceFiles(), function (sourceFile) {
+ return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary);
+ });
}
else {
- var sourceFiles = targetSourceFile === undefined ? getAllEmittableSourceFiles() : [targetSourceFile];
- return filterSourceFilesInDirectory(sourceFiles, function (file) { return host.isSourceFileFromExternalLibrary(file); });
- }
- function getAllEmittableSourceFiles() {
- return options.noEmitForJsFiles ? ts.filter(host.getSourceFiles(), function (sourceFile) { return !isSourceFileJavaScript(sourceFile); }) : host.getSourceFiles();
+ var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
+ return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); });
}
}
ts.getSourceFilesToEmit = getSourceFilesToEmit;
- /** Don't call this for `--outFile`, just for `--outDir` or plain emit. */
- function filterSourceFilesInDirectory(sourceFiles, isSourceFileFromExternalLibrary) {
- return ts.filter(sourceFiles, function (file) { return shouldEmitInDirectory(file, isSourceFileFromExternalLibrary); });
- }
- ts.filterSourceFilesInDirectory = filterSourceFilesInDirectory;
- function isNonDeclarationFile(sourceFile) {
- return !isDeclarationFile(sourceFile);
- }
- /**
- * Whether a file should be emitted in a non-`--outFile` case.
- * Don't emit if source file is a declaration file, or was located under node_modules
- */
- function shouldEmitInDirectory(sourceFile, isSourceFileFromExternalLibrary) {
- return isNonDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile);
- }
- function isBundleEmitNonExternalModule(sourceFile) {
- return isNonDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile);
+ /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
+ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) {
+ return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile);
}
+ ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
/**
- * Iterates over each source file to emit. The source files are expected to have been
- * transformed for use by the pretty printer.
- *
- * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
- * transformations.
+ * Iterates over the source files that are expected to have an emit output.
*
* @param host An EmitHost.
- * @param sourceFiles The transformed source files to emit.
* @param action The action to execute.
+ * @param sourceFilesOrTargetSourceFile
+ * If an array, the full list of source files to emit.
+ * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
*/
- function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
- // Emit on each source file
if (options.outFile || options.out) {
- onBundledEmit(sourceFiles);
- }
- else {
- for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
- var sourceFile = sourceFiles_2[_i];
- // Don't emit if source file is a declaration file, or was located under node_modules
- if (!isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile)) {
- onSingleFileEmit(host, sourceFile);
- }
- }
- }
- function onSingleFileEmit(host, sourceFile) {
- // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
- // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
- // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
- var extension = ".js";
- if (options.jsx === 1 /* Preserve */) {
- if (isSourceFileJavaScript(sourceFile)) {
- if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) {
- extension = ".jsx";
- }
- }
- else if (sourceFile.languageVariant === 1 /* JSX */) {
- // TypeScript source file preserving JSX syntax
- extension = ".jsx";
- }
- }
- var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
- var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
- action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false);
- }
- function onBundledEmit(sourceFiles) {
if (sourceFiles.length) {
var jsFilePath = options.outFile || options.out;
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
- var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined;
- action(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, /*isBundledEmit*/ true);
+ var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : "";
+ action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles);
+ }
+ }
+ else {
+ for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
+ var sourceFile = sourceFiles_1[_i];
+ var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options));
+ var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
+ var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
+ action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles);
}
}
}
- ts.forEachTransformedEmitFile = forEachTransformedEmitFile;
+ ts.forEachEmittedFile = forEachEmittedFile;
function getSourceMapFilePath(jsFilePath, options) {
return options.sourceMap ? jsFilePath + ".map" : undefined;
}
- /**
- * Iterates over the source files that are expected to have an emit output. This function
- * is used by the legacy emitter and the declaration emitter and should not be used by
- * the tree transforming emitter.
- *
- * @param host An EmitHost.
- * @param action The action to execute.
- * @param targetSourceFile An optional target source file to emit.
- */
- function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) {
- var options = host.getCompilerOptions();
- // Emit on each source file
- if (options.outFile || options.out) {
- onBundledEmit(host);
- }
- else {
- var sourceFiles = targetSourceFile === undefined ? getSourceFilesToEmit(host) : [targetSourceFile];
- for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
- var sourceFile = sourceFiles_3[_i];
- if (shouldEmitInDirectory(sourceFile, function (file) { return host.isSourceFileFromExternalLibrary(file); })) {
- onSingleFileEmit(host, sourceFile);
+ // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
+ // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
+ // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
+ function getOutputExtension(sourceFile, options) {
+ if (options.jsx === 1 /* Preserve */) {
+ if (isSourceFileJavaScript(sourceFile)) {
+ if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) {
+ return ".jsx";
}
}
- }
- function onSingleFileEmit(host, sourceFile) {
- // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
- // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
- // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
- var extension = ".js";
- if (options.jsx === 1 /* Preserve */) {
- if (isSourceFileJavaScript(sourceFile)) {
- if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) {
- extension = ".jsx";
- }
- }
- else if (sourceFile.languageVariant === 1 /* JSX */) {
- // TypeScript source file preserving JSX syntax
- extension = ".jsx";
- }
- }
- var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension);
- var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
- var emitFileNames = {
- jsFilePath: jsFilePath,
- sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
- declarationFilePath: declarationFilePath
- };
- action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles);
- }
- function onBundledEmit(host) {
- // Can emit only sources that are not declaration file and are either non module code or module with
- // --module or --target es6 specified. Files included by searching under node_modules are also not emitted.
- var bundledSources = ts.filter(getSourceFilesToEmit(host), function (sourceFile) { return !isDeclarationFile(sourceFile) &&
- !host.isSourceFileFromExternalLibrary(sourceFile) &&
- (!ts.isExternalModule(sourceFile) ||
- !!ts.getEmitModuleKind(options)); });
- if (bundledSources.length) {
- var jsFilePath = options.outFile || options.out;
- var emitFileNames = {
- jsFilePath: jsFilePath,
- sourceMapFilePath: getSourceMapFilePath(jsFilePath, options),
- declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined
- };
- action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles);
+ else if (sourceFile.languageVariant === 1 /* JSX */) {
+ // TypeScript source file preserving JSX syntax
+ return ".jsx";
}
}
+ return ".js";
}
- ts.forEachExpectedEmitFile = forEachExpectedEmitFile;
function getSourceFilePathInNewDir(sourceFile, host, newDirPath) {
var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory());
var commonSourceDirectory = host.getCommonSourceDirectory();
@@ -8893,7 +9073,7 @@ var ts;
ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
function getFirstConstructorWithBody(node) {
return ts.forEach(node.members, function (member) {
- if (member.kind === 150 /* Constructor */ && nodeIsPresent(member.body)) {
+ if (member.kind === 151 /* Constructor */ && nodeIsPresent(member.body)) {
return member;
}
});
@@ -8935,10 +9115,10 @@ var ts;
var setAccessor;
if (hasDynamicName(accessor)) {
firstAccessor = accessor;
- if (accessor.kind === 151 /* GetAccessor */) {
+ if (accessor.kind === 152 /* GetAccessor */) {
getAccessor = accessor;
}
- else if (accessor.kind === 152 /* SetAccessor */) {
+ else if (accessor.kind === 153 /* SetAccessor */) {
setAccessor = accessor;
}
else {
@@ -8947,7 +9127,7 @@ var ts;
}
else {
ts.forEach(declarations, function (member) {
- if ((member.kind === 151 /* GetAccessor */ || member.kind === 152 /* SetAccessor */)
+ if ((member.kind === 152 /* GetAccessor */ || member.kind === 153 /* SetAccessor */)
&& hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
var memberName = getPropertyNameForPropertyNameNode(member.name);
var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
@@ -8958,10 +9138,10 @@ var ts;
else if (!secondAccessor) {
secondAccessor = member;
}
- if (member.kind === 151 /* GetAccessor */ && !getAccessor) {
+ if (member.kind === 152 /* GetAccessor */ && !getAccessor) {
getAccessor = member;
}
- if (member.kind === 152 /* SetAccessor */ && !setAccessor) {
+ if (member.kind === 153 /* SetAccessor */ && !setAccessor) {
setAccessor = member;
}
}
@@ -9224,7 +9404,7 @@ var ts;
ts.isAssignmentOperator = isAssignmentOperator;
/** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
function tryGetClassExtendingExpressionWithTypeArguments(node) {
- if (node.kind === 199 /* ExpressionWithTypeArguments */ &&
+ if (node.kind === 200 /* ExpressionWithTypeArguments */ &&
node.parent.token === 84 /* ExtendsKeyword */ &&
isClassLike(node.parent.parent)) {
return node.parent.parent;
@@ -9242,8 +9422,8 @@ var ts;
function isDestructuringAssignment(node) {
if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
var kind = node.left.kind;
- return kind === 176 /* ObjectLiteralExpression */
- || kind === 175 /* ArrayLiteralExpression */;
+ return kind === 177 /* ObjectLiteralExpression */
+ || kind === 176 /* ArrayLiteralExpression */;
}
return false;
}
@@ -9269,31 +9449,42 @@ var ts;
return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
}
ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
+ function isExpressionWithTypeArgumentsInClassImplementsClause(node) {
+ return node.kind === 200 /* ExpressionWithTypeArguments */
+ && isEntityNameExpression(node.expression)
+ && node.parent
+ && node.parent.token === 107 /* ImplementsKeyword */
+ && node.parent.parent
+ && isClassLike(node.parent.parent);
+ }
+ ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause;
function isEntityNameExpression(node) {
return node.kind === 70 /* Identifier */ ||
- node.kind === 177 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression);
+ node.kind === 178 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression);
}
ts.isEntityNameExpression = isEntityNameExpression;
function isRightSideOfQualifiedNameOrPropertyAccess(node) {
- return (node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node) ||
- (node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.name === node);
+ return (node.parent.kind === 142 /* QualifiedName */ && node.parent.right === node) ||
+ (node.parent.kind === 178 /* PropertyAccessExpression */ && node.parent.name === node);
}
ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
- function isEmptyObjectLiteralOrArrayLiteral(expression) {
- var kind = expression.kind;
- if (kind === 176 /* ObjectLiteralExpression */) {
- return expression.properties.length === 0;
- }
- if (kind === 175 /* ArrayLiteralExpression */) {
- return expression.elements.length === 0;
- }
- return false;
+ function isEmptyObjectLiteral(expression) {
+ return expression.kind === 177 /* ObjectLiteralExpression */ &&
+ expression.properties.length === 0;
+ }
+ ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
+ function isEmptyArrayLiteral(expression) {
+ return expression.kind === 176 /* ArrayLiteralExpression */ &&
+ expression.elements.length === 0;
}
- ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral;
+ ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
function getLocalSymbolForExportDefault(symbol) {
- return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined;
+ return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined;
}
ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
+ function isExportDefaultSymbol(symbol) {
+ return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */);
+ }
/** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
function tryExtractTypeScriptExtension(fileName) {
return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
@@ -9333,47 +9524,6 @@ var ts;
}
return output;
}
- /**
- * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph
- * as the fallback implementation does not check for circular references by default.
- */
- ts.stringify = typeof JSON !== "undefined" && JSON.stringify
- ? JSON.stringify
- : stringifyFallback;
- /**
- * Serialize an object graph into a JSON string.
- */
- function stringifyFallback(value) {
- // JSON.stringify returns `undefined` here, instead of the string "undefined".
- return value === undefined ? undefined : stringifyValue(value);
- }
- function stringifyValue(value) {
- return typeof value === "string" ? "\"" + escapeString(value) + "\""
- : typeof value === "number" ? isFinite(value) ? String(value) : "null"
- : typeof value === "boolean" ? value ? "true" : "false"
- : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value)
- : "null";
- }
- function cycleCheck(cb, value) {
- ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON");
- value.__cycle = true;
- var result = cb(value);
- delete value.__cycle;
- return result;
- }
- function stringifyArray(value) {
- return "[" + ts.reduceLeft(value, stringifyElement, "") + "]";
- }
- function stringifyElement(memo, value) {
- return (memo ? memo + "," : memo) + stringifyValue(value);
- }
- function stringifyObject(value) {
- return "{" + ts.reduceOwnProperties(value, stringifyProperty, "") + "}";
- }
- function stringifyProperty(memo, value, key) {
- return value === undefined || typeof value === "function" || key === "__cycle" ? memo
- : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value));
- }
var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/**
* Converts a string to a base-64 encoded ASCII string.
@@ -9446,39 +9596,39 @@ var ts;
|| kind === 94 /* NullKeyword */) {
return true;
}
- else if (kind === 177 /* PropertyAccessExpression */) {
+ else if (kind === 178 /* PropertyAccessExpression */) {
return isSimpleExpressionWorker(node.expression, depth + 1);
}
- else if (kind === 178 /* ElementAccessExpression */) {
+ else if (kind === 179 /* ElementAccessExpression */) {
return isSimpleExpressionWorker(node.expression, depth + 1)
&& isSimpleExpressionWorker(node.argumentExpression, depth + 1);
}
- else if (kind === 190 /* PrefixUnaryExpression */
- || kind === 191 /* PostfixUnaryExpression */) {
+ else if (kind === 191 /* PrefixUnaryExpression */
+ || kind === 192 /* PostfixUnaryExpression */) {
return isSimpleExpressionWorker(node.operand, depth + 1);
}
- else if (kind === 192 /* BinaryExpression */) {
+ else if (kind === 193 /* BinaryExpression */) {
return node.operatorToken.kind !== 39 /* AsteriskAsteriskToken */
&& isSimpleExpressionWorker(node.left, depth + 1)
&& isSimpleExpressionWorker(node.right, depth + 1);
}
- else if (kind === 193 /* ConditionalExpression */) {
+ else if (kind === 194 /* ConditionalExpression */) {
return isSimpleExpressionWorker(node.condition, depth + 1)
&& isSimpleExpressionWorker(node.whenTrue, depth + 1)
&& isSimpleExpressionWorker(node.whenFalse, depth + 1);
}
- else if (kind === 188 /* VoidExpression */
- || kind === 187 /* TypeOfExpression */
- || kind === 186 /* DeleteExpression */) {
+ else if (kind === 189 /* VoidExpression */
+ || kind === 188 /* TypeOfExpression */
+ || kind === 187 /* DeleteExpression */) {
return isSimpleExpressionWorker(node.expression, depth + 1);
}
- else if (kind === 175 /* ArrayLiteralExpression */) {
+ else if (kind === 176 /* ArrayLiteralExpression */) {
return node.elements.length === 0;
}
- else if (kind === 176 /* ObjectLiteralExpression */) {
+ else if (kind === 177 /* ObjectLiteralExpression */) {
return node.properties.length === 0;
}
- else if (kind === 179 /* CallExpression */) {
+ else if (kind === 180 /* CallExpression */) {
if (!isSimpleExpressionWorker(node.expression, depth + 1)) {
return false;
}
@@ -9493,16 +9643,19 @@ var ts;
}
return false;
}
- var syntaxKindCache = ts.createMap();
+ var syntaxKindCache = [];
function formatSyntaxKind(kind) {
var syntaxKindEnum = ts.SyntaxKind;
if (syntaxKindEnum) {
- if (syntaxKindCache[kind]) {
- return syntaxKindCache[kind];
+ var cached = syntaxKindCache[kind];
+ if (cached !== undefined) {
+ return cached;
}
- for (var name_7 in syntaxKindEnum) {
- if (syntaxKindEnum[name_7] === kind) {
- return syntaxKindCache[kind] = kind.toString() + " (" + name_7 + ")";
+ for (var name in syntaxKindEnum) {
+ if (syntaxKindEnum[name] === kind) {
+ var result = kind + " (" + name + ")";
+ syntaxKindCache[kind] = result;
+ return result;
}
}
}
@@ -9511,6 +9664,14 @@ var ts;
}
}
ts.formatSyntaxKind = formatSyntaxKind;
+ function getRangePos(range) {
+ return range ? range.pos : -1;
+ }
+ ts.getRangePos = getRangePos;
+ function getRangeEnd(range) {
+ return range ? range.end : -1;
+ }
+ ts.getRangeEnd = getRangeEnd;
/**
* Increases (or decreases) a position by the provided amount.
*
@@ -9642,11 +9803,11 @@ var ts;
* declaration.
*/
function isDeclarationNameOfEnumOrNamespace(node) {
- var parseNode = getParseTreeNode(node);
+ var parseNode = ts.getParseTreeNode(node);
if (parseNode) {
switch (parseNode.parent.kind) {
- case 229 /* EnumDeclaration */:
- case 230 /* ModuleDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 232 /* ModuleDeclaration */:
return parseNode === parseNode.parent.name;
}
}
@@ -9667,7 +9828,7 @@ var ts;
if (node.symbol) {
for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- if (declaration.kind === 226 /* ClassDeclaration */ && declaration !== node) {
+ if (declaration.kind === 228 /* ClassDeclaration */ && declaration !== node) {
return true;
}
}
@@ -9732,6 +9893,10 @@ var ts;
return node.kind === 70 /* Identifier */;
}
ts.isIdentifier = isIdentifier;
+ function isVoidExpression(node) {
+ return node.kind === 189 /* VoidExpression */;
+ }
+ ts.isVoidExpression = isVoidExpression;
function isGeneratedIdentifier(node) {
// Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`.
return isIdentifier(node) && node.autoGenerateKind > 0 /* None */;
@@ -9744,16 +9909,16 @@ var ts;
ts.isModifier = isModifier;
// Names
function isQualifiedName(node) {
- return node.kind === 141 /* QualifiedName */;
+ return node.kind === 142 /* QualifiedName */;
}
ts.isQualifiedName = isQualifiedName;
function isComputedPropertyName(node) {
- return node.kind === 142 /* ComputedPropertyName */;
+ return node.kind === 143 /* ComputedPropertyName */;
}
ts.isComputedPropertyName = isComputedPropertyName;
function isEntityName(node) {
var kind = node.kind;
- return kind === 141 /* QualifiedName */
+ return kind === 142 /* QualifiedName */
|| kind === 70 /* Identifier */;
}
ts.isEntityName = isEntityName;
@@ -9762,7 +9927,7 @@ var ts;
return kind === 70 /* Identifier */
|| kind === 9 /* StringLiteral */
|| kind === 8 /* NumericLiteral */
- || kind === 142 /* ComputedPropertyName */;
+ || kind === 143 /* ComputedPropertyName */;
}
ts.isPropertyName = isPropertyName;
function isModuleName(node) {
@@ -9774,61 +9939,65 @@ var ts;
function isBindingName(node) {
var kind = node.kind;
return kind === 70 /* Identifier */
- || kind === 172 /* ObjectBindingPattern */
- || kind === 173 /* ArrayBindingPattern */;
+ || kind === 173 /* ObjectBindingPattern */
+ || kind === 174 /* ArrayBindingPattern */;
}
ts.isBindingName = isBindingName;
// Signature elements
function isTypeParameter(node) {
- return node.kind === 143 /* TypeParameter */;
+ return node.kind === 144 /* TypeParameter */;
}
ts.isTypeParameter = isTypeParameter;
function isParameter(node) {
- return node.kind === 144 /* Parameter */;
+ return node.kind === 145 /* Parameter */;
}
ts.isParameter = isParameter;
function isDecorator(node) {
- return node.kind === 145 /* Decorator */;
+ return node.kind === 146 /* Decorator */;
}
ts.isDecorator = isDecorator;
// Type members
function isMethodDeclaration(node) {
- return node.kind === 149 /* MethodDeclaration */;
+ return node.kind === 150 /* MethodDeclaration */;
}
ts.isMethodDeclaration = isMethodDeclaration;
function isClassElement(node) {
var kind = node.kind;
- return kind === 150 /* Constructor */
- || kind === 147 /* PropertyDeclaration */
- || kind === 149 /* MethodDeclaration */
- || kind === 151 /* GetAccessor */
- || kind === 152 /* SetAccessor */
- || kind === 155 /* IndexSignature */
- || kind === 203 /* SemicolonClassElement */;
+ return kind === 151 /* Constructor */
+ || kind === 148 /* PropertyDeclaration */
+ || kind === 150 /* MethodDeclaration */
+ || kind === 152 /* GetAccessor */
+ || kind === 153 /* SetAccessor */
+ || kind === 156 /* IndexSignature */
+ || kind === 205 /* SemicolonClassElement */;
}
ts.isClassElement = isClassElement;
function isObjectLiteralElementLike(node) {
var kind = node.kind;
- return kind === 257 /* PropertyAssignment */
- || kind === 258 /* ShorthandPropertyAssignment */
- || kind === 259 /* SpreadAssignment */
- || kind === 149 /* MethodDeclaration */
- || kind === 151 /* GetAccessor */
- || kind === 152 /* SetAccessor */
- || kind === 244 /* MissingDeclaration */;
+ return kind === 260 /* PropertyAssignment */
+ || kind === 261 /* ShorthandPropertyAssignment */
+ || kind === 262 /* SpreadAssignment */
+ || kind === 150 /* MethodDeclaration */
+ || kind === 152 /* GetAccessor */
+ || kind === 153 /* SetAccessor */
+ || kind === 246 /* MissingDeclaration */;
}
ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
// Type
function isTypeNodeKind(kind) {
- return (kind >= 156 /* FirstTypeNode */ && kind <= 171 /* LastTypeNode */)
+ return (kind >= 157 /* FirstTypeNode */ && kind <= 172 /* LastTypeNode */)
|| kind === 118 /* AnyKeyword */
|| kind === 132 /* NumberKeyword */
+ || kind === 133 /* ObjectKeyword */
|| kind === 121 /* BooleanKeyword */
- || kind === 134 /* StringKeyword */
- || kind === 135 /* SymbolKeyword */
+ || kind === 135 /* StringKeyword */
+ || kind === 136 /* SymbolKeyword */
+ || kind === 98 /* ThisKeyword */
|| kind === 104 /* VoidKeyword */
+ || kind === 138 /* UndefinedKeyword */
+ || kind === 94 /* NullKeyword */
|| kind === 129 /* NeverKeyword */
- || kind === 199 /* ExpressionWithTypeArguments */;
+ || kind === 200 /* ExpressionWithTypeArguments */;
}
/**
* Node test that determines whether a node is a valid type node.
@@ -9841,36 +10010,36 @@ var ts;
ts.isTypeNode = isTypeNode;
// Binding patterns
function isArrayBindingPattern(node) {
- return node.kind === 173 /* ArrayBindingPattern */;
+ return node.kind === 174 /* ArrayBindingPattern */;
}
ts.isArrayBindingPattern = isArrayBindingPattern;
function isObjectBindingPattern(node) {
- return node.kind === 172 /* ObjectBindingPattern */;
+ return node.kind === 173 /* ObjectBindingPattern */;
}
ts.isObjectBindingPattern = isObjectBindingPattern;
function isBindingPattern(node) {
if (node) {
var kind = node.kind;
- return kind === 173 /* ArrayBindingPattern */
- || kind === 172 /* ObjectBindingPattern */;
+ return kind === 174 /* ArrayBindingPattern */
+ || kind === 173 /* ObjectBindingPattern */;
}
return false;
}
ts.isBindingPattern = isBindingPattern;
function isAssignmentPattern(node) {
var kind = node.kind;
- return kind === 175 /* ArrayLiteralExpression */
- || kind === 176 /* ObjectLiteralExpression */;
+ return kind === 176 /* ArrayLiteralExpression */
+ || kind === 177 /* ObjectLiteralExpression */;
}
ts.isAssignmentPattern = isAssignmentPattern;
function isBindingElement(node) {
- return node.kind === 174 /* BindingElement */;
+ return node.kind === 175 /* BindingElement */;
}
ts.isBindingElement = isBindingElement;
function isArrayBindingElement(node) {
var kind = node.kind;
- return kind === 174 /* BindingElement */
- || kind === 198 /* OmittedExpression */;
+ return kind === 175 /* BindingElement */
+ || kind === 199 /* OmittedExpression */;
}
ts.isArrayBindingElement = isArrayBindingElement;
/**
@@ -9878,9 +10047,9 @@ var ts;
*/
function isDeclarationBindingElement(bindingElement) {
switch (bindingElement.kind) {
- case 223 /* VariableDeclaration */:
- case 144 /* Parameter */:
- case 174 /* BindingElement */:
+ case 225 /* VariableDeclaration */:
+ case 145 /* Parameter */:
+ case 175 /* BindingElement */:
return true;
}
return false;
@@ -9899,8 +10068,8 @@ var ts;
*/
function isObjectBindingOrAssignmentPattern(node) {
switch (node.kind) {
- case 172 /* ObjectBindingPattern */:
- case 176 /* ObjectLiteralExpression */:
+ case 173 /* ObjectBindingPattern */:
+ case 177 /* ObjectLiteralExpression */:
return true;
}
return false;
@@ -9911,8 +10080,8 @@ var ts;
*/
function isArrayBindingOrAssignmentPattern(node) {
switch (node.kind) {
- case 173 /* ArrayBindingPattern */:
- case 175 /* ArrayLiteralExpression */:
+ case 174 /* ArrayBindingPattern */:
+ case 176 /* ArrayLiteralExpression */:
return true;
}
return false;
@@ -9920,86 +10089,92 @@ var ts;
ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
// Expression
function isArrayLiteralExpression(node) {
- return node.kind === 175 /* ArrayLiteralExpression */;
+ return node.kind === 176 /* ArrayLiteralExpression */;
}
ts.isArrayLiteralExpression = isArrayLiteralExpression;
function isObjectLiteralExpression(node) {
- return node.kind === 176 /* ObjectLiteralExpression */;
+ return node.kind === 177 /* ObjectLiteralExpression */;
}
ts.isObjectLiteralExpression = isObjectLiteralExpression;
function isPropertyAccessExpression(node) {
- return node.kind === 177 /* PropertyAccessExpression */;
+ return node.kind === 178 /* PropertyAccessExpression */;
}
ts.isPropertyAccessExpression = isPropertyAccessExpression;
+ function isPropertyAccessOrQualifiedName(node) {
+ var kind = node.kind;
+ return kind === 178 /* PropertyAccessExpression */
+ || kind === 142 /* QualifiedName */;
+ }
+ ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
function isElementAccessExpression(node) {
- return node.kind === 178 /* ElementAccessExpression */;
+ return node.kind === 179 /* ElementAccessExpression */;
}
ts.isElementAccessExpression = isElementAccessExpression;
function isBinaryExpression(node) {
- return node.kind === 192 /* BinaryExpression */;
+ return node.kind === 193 /* BinaryExpression */;
}
ts.isBinaryExpression = isBinaryExpression;
function isConditionalExpression(node) {
- return node.kind === 193 /* ConditionalExpression */;
+ return node.kind === 194 /* ConditionalExpression */;
}
ts.isConditionalExpression = isConditionalExpression;
function isCallExpression(node) {
- return node.kind === 179 /* CallExpression */;
+ return node.kind === 180 /* CallExpression */;
}
ts.isCallExpression = isCallExpression;
function isTemplateLiteral(node) {
var kind = node.kind;
- return kind === 194 /* TemplateExpression */
+ return kind === 195 /* TemplateExpression */
|| kind === 12 /* NoSubstitutionTemplateLiteral */;
}
ts.isTemplateLiteral = isTemplateLiteral;
function isSpreadExpression(node) {
- return node.kind === 196 /* SpreadElement */;
+ return node.kind === 197 /* SpreadElement */;
}
ts.isSpreadExpression = isSpreadExpression;
function isExpressionWithTypeArguments(node) {
- return node.kind === 199 /* ExpressionWithTypeArguments */;
+ return node.kind === 200 /* ExpressionWithTypeArguments */;
}
ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
function isLeftHandSideExpressionKind(kind) {
- return kind === 177 /* PropertyAccessExpression */
- || kind === 178 /* ElementAccessExpression */
- || kind === 180 /* NewExpression */
- || kind === 179 /* CallExpression */
- || kind === 246 /* JsxElement */
- || kind === 247 /* JsxSelfClosingElement */
- || kind === 181 /* TaggedTemplateExpression */
- || kind === 175 /* ArrayLiteralExpression */
- || kind === 183 /* ParenthesizedExpression */
- || kind === 176 /* ObjectLiteralExpression */
- || kind === 197 /* ClassExpression */
- || kind === 184 /* FunctionExpression */
+ return kind === 178 /* PropertyAccessExpression */
+ || kind === 179 /* ElementAccessExpression */
+ || kind === 181 /* NewExpression */
+ || kind === 180 /* CallExpression */
+ || kind === 248 /* JsxElement */
+ || kind === 249 /* JsxSelfClosingElement */
+ || kind === 182 /* TaggedTemplateExpression */
+ || kind === 176 /* ArrayLiteralExpression */
+ || kind === 184 /* ParenthesizedExpression */
+ || kind === 177 /* ObjectLiteralExpression */
+ || kind === 198 /* ClassExpression */
+ || kind === 185 /* FunctionExpression */
|| kind === 70 /* Identifier */
|| kind === 11 /* RegularExpressionLiteral */
|| kind === 8 /* NumericLiteral */
|| kind === 9 /* StringLiteral */
|| kind === 12 /* NoSubstitutionTemplateLiteral */
- || kind === 194 /* TemplateExpression */
+ || kind === 195 /* TemplateExpression */
|| kind === 85 /* FalseKeyword */
|| kind === 94 /* NullKeyword */
|| kind === 98 /* ThisKeyword */
|| kind === 100 /* TrueKeyword */
|| kind === 96 /* SuperKeyword */
- || kind === 201 /* NonNullExpression */
- || kind === 297 /* RawExpression */;
+ || kind === 202 /* NonNullExpression */
+ || kind === 203 /* MetaProperty */;
}
function isLeftHandSideExpression(node) {
return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind);
}
ts.isLeftHandSideExpression = isLeftHandSideExpression;
function isUnaryExpressionKind(kind) {
- return kind === 190 /* PrefixUnaryExpression */
- || kind === 191 /* PostfixUnaryExpression */
- || kind === 186 /* DeleteExpression */
- || kind === 187 /* TypeOfExpression */
- || kind === 188 /* VoidExpression */
- || kind === 189 /* AwaitExpression */
- || kind === 182 /* TypeAssertionExpression */
+ return kind === 191 /* PrefixUnaryExpression */
+ || kind === 192 /* PostfixUnaryExpression */
+ || kind === 187 /* DeleteExpression */
+ || kind === 188 /* TypeOfExpression */
+ || kind === 189 /* VoidExpression */
+ || kind === 190 /* AwaitExpression */
+ || kind === 183 /* TypeAssertionExpression */
|| isLeftHandSideExpressionKind(kind);
}
function isUnaryExpression(node) {
@@ -10007,14 +10182,13 @@ var ts;
}
ts.isUnaryExpression = isUnaryExpression;
function isExpressionKind(kind) {
- return kind === 193 /* ConditionalExpression */
- || kind === 195 /* YieldExpression */
- || kind === 185 /* ArrowFunction */
- || kind === 192 /* BinaryExpression */
- || kind === 196 /* SpreadElement */
- || kind === 200 /* AsExpression */
- || kind === 198 /* OmittedExpression */
- || kind === 297 /* RawExpression */
+ return kind === 194 /* ConditionalExpression */
+ || kind === 196 /* YieldExpression */
+ || kind === 186 /* ArrowFunction */
+ || kind === 193 /* BinaryExpression */
+ || kind === 197 /* SpreadElement */
+ || kind === 201 /* AsExpression */
+ || kind === 199 /* OmittedExpression */
|| isUnaryExpressionKind(kind);
}
function isExpression(node) {
@@ -10023,16 +10197,16 @@ var ts;
ts.isExpression = isExpression;
function isAssertionExpression(node) {
var kind = node.kind;
- return kind === 182 /* TypeAssertionExpression */
- || kind === 200 /* AsExpression */;
+ return kind === 183 /* TypeAssertionExpression */
+ || kind === 201 /* AsExpression */;
}
ts.isAssertionExpression = isAssertionExpression;
function isPartiallyEmittedExpression(node) {
- return node.kind === 294 /* PartiallyEmittedExpression */;
+ return node.kind === 295 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
function isNotEmittedStatement(node) {
- return node.kind === 293 /* NotEmittedStatement */;
+ return node.kind === 294 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
function isNotEmittedOrPartiallyEmittedNode(node) {
@@ -10041,17 +10215,17 @@ var ts;
}
ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
function isOmittedExpression(node) {
- return node.kind === 198 /* OmittedExpression */;
+ return node.kind === 199 /* OmittedExpression */;
}
ts.isOmittedExpression = isOmittedExpression;
// Misc
function isTemplateSpan(node) {
- return node.kind === 202 /* TemplateSpan */;
+ return node.kind === 204 /* TemplateSpan */;
}
ts.isTemplateSpan = isTemplateSpan;
// Element
function isBlock(node) {
- return node.kind === 204 /* Block */;
+ return node.kind === 206 /* Block */;
}
ts.isBlock = isBlock;
function isConciseBody(node) {
@@ -10069,121 +10243,135 @@ var ts;
}
ts.isForInitializer = isForInitializer;
function isVariableDeclaration(node) {
- return node.kind === 223 /* VariableDeclaration */;
+ return node.kind === 225 /* VariableDeclaration */;
}
ts.isVariableDeclaration = isVariableDeclaration;
function isVariableDeclarationList(node) {
- return node.kind === 224 /* VariableDeclarationList */;
+ return node.kind === 226 /* VariableDeclarationList */;
}
ts.isVariableDeclarationList = isVariableDeclarationList;
function isCaseBlock(node) {
- return node.kind === 232 /* CaseBlock */;
+ return node.kind === 234 /* CaseBlock */;
}
ts.isCaseBlock = isCaseBlock;
function isModuleBody(node) {
var kind = node.kind;
- return kind === 231 /* ModuleBlock */
- || kind === 230 /* ModuleDeclaration */;
+ return kind === 233 /* ModuleBlock */
+ || kind === 232 /* ModuleDeclaration */
+ || kind === 70 /* Identifier */;
}
ts.isModuleBody = isModuleBody;
+ function isNamespaceBody(node) {
+ var kind = node.kind;
+ return kind === 233 /* ModuleBlock */
+ || kind === 232 /* ModuleDeclaration */;
+ }
+ ts.isNamespaceBody = isNamespaceBody;
+ function isJSDocNamespaceBody(node) {
+ var kind = node.kind;
+ return kind === 70 /* Identifier */
+ || kind === 232 /* ModuleDeclaration */;
+ }
+ ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
function isImportEqualsDeclaration(node) {
- return node.kind === 234 /* ImportEqualsDeclaration */;
+ return node.kind === 236 /* ImportEqualsDeclaration */;
}
ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
function isImportClause(node) {
- return node.kind === 236 /* ImportClause */;
+ return node.kind === 238 /* ImportClause */;
}
ts.isImportClause = isImportClause;
function isNamedImportBindings(node) {
var kind = node.kind;
- return kind === 238 /* NamedImports */
- || kind === 237 /* NamespaceImport */;
+ return kind === 240 /* NamedImports */
+ || kind === 239 /* NamespaceImport */;
}
ts.isNamedImportBindings = isNamedImportBindings;
function isImportSpecifier(node) {
- return node.kind === 239 /* ImportSpecifier */;
+ return node.kind === 241 /* ImportSpecifier */;
}
ts.isImportSpecifier = isImportSpecifier;
function isNamedExports(node) {
- return node.kind === 242 /* NamedExports */;
+ return node.kind === 244 /* NamedExports */;
}
ts.isNamedExports = isNamedExports;
function isExportSpecifier(node) {
- return node.kind === 243 /* ExportSpecifier */;
+ return node.kind === 245 /* ExportSpecifier */;
}
ts.isExportSpecifier = isExportSpecifier;
function isModuleOrEnumDeclaration(node) {
- return node.kind === 230 /* ModuleDeclaration */ || node.kind === 229 /* EnumDeclaration */;
+ return node.kind === 232 /* ModuleDeclaration */ || node.kind === 231 /* EnumDeclaration */;
}
ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
function isDeclarationKind(kind) {
- return kind === 185 /* ArrowFunction */
- || kind === 174 /* BindingElement */
- || kind === 226 /* ClassDeclaration */
- || kind === 197 /* ClassExpression */
- || kind === 150 /* Constructor */
- || kind === 229 /* EnumDeclaration */
- || kind === 260 /* EnumMember */
- || kind === 243 /* ExportSpecifier */
- || kind === 225 /* FunctionDeclaration */
- || kind === 184 /* FunctionExpression */
- || kind === 151 /* GetAccessor */
- || kind === 236 /* ImportClause */
- || kind === 234 /* ImportEqualsDeclaration */
- || kind === 239 /* ImportSpecifier */
- || kind === 227 /* InterfaceDeclaration */
- || kind === 149 /* MethodDeclaration */
- || kind === 148 /* MethodSignature */
- || kind === 230 /* ModuleDeclaration */
- || kind === 233 /* NamespaceExportDeclaration */
- || kind === 237 /* NamespaceImport */
- || kind === 144 /* Parameter */
- || kind === 257 /* PropertyAssignment */
- || kind === 147 /* PropertyDeclaration */
- || kind === 146 /* PropertySignature */
- || kind === 152 /* SetAccessor */
- || kind === 258 /* ShorthandPropertyAssignment */
- || kind === 228 /* TypeAliasDeclaration */
- || kind === 143 /* TypeParameter */
- || kind === 223 /* VariableDeclaration */
- || kind === 285 /* JSDocTypedefTag */;
+ return kind === 186 /* ArrowFunction */
+ || kind === 175 /* BindingElement */
+ || kind === 228 /* ClassDeclaration */
+ || kind === 198 /* ClassExpression */
+ || kind === 151 /* Constructor */
+ || kind === 231 /* EnumDeclaration */
+ || kind === 263 /* EnumMember */
+ || kind === 245 /* ExportSpecifier */
+ || kind === 227 /* FunctionDeclaration */
+ || kind === 185 /* FunctionExpression */
+ || kind === 152 /* GetAccessor */
+ || kind === 238 /* ImportClause */
+ || kind === 236 /* ImportEqualsDeclaration */
+ || kind === 241 /* ImportSpecifier */
+ || kind === 229 /* InterfaceDeclaration */
+ || kind === 252 /* JsxAttribute */
+ || kind === 150 /* MethodDeclaration */
+ || kind === 149 /* MethodSignature */
+ || kind === 232 /* ModuleDeclaration */
+ || kind === 235 /* NamespaceExportDeclaration */
+ || kind === 239 /* NamespaceImport */
+ || kind === 145 /* Parameter */
+ || kind === 260 /* PropertyAssignment */
+ || kind === 148 /* PropertyDeclaration */
+ || kind === 147 /* PropertySignature */
+ || kind === 153 /* SetAccessor */
+ || kind === 261 /* ShorthandPropertyAssignment */
+ || kind === 230 /* TypeAliasDeclaration */
+ || kind === 144 /* TypeParameter */
+ || kind === 225 /* VariableDeclaration */
+ || kind === 289 /* JSDocTypedefTag */;
}
function isDeclarationStatementKind(kind) {
- return kind === 225 /* FunctionDeclaration */
- || kind === 244 /* MissingDeclaration */
- || kind === 226 /* ClassDeclaration */
- || kind === 227 /* InterfaceDeclaration */
- || kind === 228 /* TypeAliasDeclaration */
- || kind === 229 /* EnumDeclaration */
- || kind === 230 /* ModuleDeclaration */
- || kind === 235 /* ImportDeclaration */
- || kind === 234 /* ImportEqualsDeclaration */
- || kind === 241 /* ExportDeclaration */
- || kind === 240 /* ExportAssignment */
- || kind === 233 /* NamespaceExportDeclaration */;
+ return kind === 227 /* FunctionDeclaration */
+ || kind === 246 /* MissingDeclaration */
+ || kind === 228 /* ClassDeclaration */
+ || kind === 229 /* InterfaceDeclaration */
+ || kind === 230 /* TypeAliasDeclaration */
+ || kind === 231 /* EnumDeclaration */
+ || kind === 232 /* ModuleDeclaration */
+ || kind === 237 /* ImportDeclaration */
+ || kind === 236 /* ImportEqualsDeclaration */
+ || kind === 243 /* ExportDeclaration */
+ || kind === 242 /* ExportAssignment */
+ || kind === 235 /* NamespaceExportDeclaration */;
}
function isStatementKindButNotDeclarationKind(kind) {
- return kind === 215 /* BreakStatement */
- || kind === 214 /* ContinueStatement */
- || kind === 222 /* DebuggerStatement */
- || kind === 209 /* DoStatement */
- || kind === 207 /* ExpressionStatement */
- || kind === 206 /* EmptyStatement */
- || kind === 212 /* ForInStatement */
- || kind === 213 /* ForOfStatement */
- || kind === 211 /* ForStatement */
- || kind === 208 /* IfStatement */
- || kind === 219 /* LabeledStatement */
- || kind === 216 /* ReturnStatement */
- || kind === 218 /* SwitchStatement */
- || kind === 220 /* ThrowStatement */
- || kind === 221 /* TryStatement */
- || kind === 205 /* VariableStatement */
- || kind === 210 /* WhileStatement */
- || kind === 217 /* WithStatement */
- || kind === 293 /* NotEmittedStatement */
- || kind === 296 /* EndOfDeclarationMarker */
- || kind === 295 /* MergeDeclarationMarker */;
+ return kind === 217 /* BreakStatement */
+ || kind === 216 /* ContinueStatement */
+ || kind === 224 /* DebuggerStatement */
+ || kind === 211 /* DoStatement */
+ || kind === 209 /* ExpressionStatement */
+ || kind === 208 /* EmptyStatement */
+ || kind === 214 /* ForInStatement */
+ || kind === 215 /* ForOfStatement */
+ || kind === 213 /* ForStatement */
+ || kind === 210 /* IfStatement */
+ || kind === 221 /* LabeledStatement */
+ || kind === 218 /* ReturnStatement */
+ || kind === 220 /* SwitchStatement */
+ || kind === 222 /* ThrowStatement */
+ || kind === 223 /* TryStatement */
+ || kind === 207 /* VariableStatement */
+ || kind === 212 /* WhileStatement */
+ || kind === 219 /* WithStatement */
+ || kind === 294 /* NotEmittedStatement */
+ || kind === 297 /* EndOfDeclarationMarker */
+ || kind === 296 /* MergeDeclarationMarker */;
}
function isDeclaration(node) {
return isDeclarationKind(node.kind);
@@ -10204,93 +10392,104 @@ var ts;
var kind = node.kind;
return isStatementKindButNotDeclarationKind(kind)
|| isDeclarationStatementKind(kind)
- || kind === 204 /* Block */;
+ || kind === 206 /* Block */;
}
ts.isStatement = isStatement;
// Module references
function isModuleReference(node) {
var kind = node.kind;
- return kind === 245 /* ExternalModuleReference */
- || kind === 141 /* QualifiedName */
+ return kind === 247 /* ExternalModuleReference */
+ || kind === 142 /* QualifiedName */
|| kind === 70 /* Identifier */;
}
ts.isModuleReference = isModuleReference;
// JSX
function isJsxOpeningElement(node) {
- return node.kind === 248 /* JsxOpeningElement */;
+ return node.kind === 250 /* JsxOpeningElement */;
}
ts.isJsxOpeningElement = isJsxOpeningElement;
function isJsxClosingElement(node) {
- return node.kind === 249 /* JsxClosingElement */;
+ return node.kind === 251 /* JsxClosingElement */;
}
ts.isJsxClosingElement = isJsxClosingElement;
function isJsxTagNameExpression(node) {
var kind = node.kind;
return kind === 98 /* ThisKeyword */
|| kind === 70 /* Identifier */
- || kind === 177 /* PropertyAccessExpression */;
+ || kind === 178 /* PropertyAccessExpression */;
}
ts.isJsxTagNameExpression = isJsxTagNameExpression;
function isJsxChild(node) {
var kind = node.kind;
- return kind === 246 /* JsxElement */
- || kind === 252 /* JsxExpression */
- || kind === 247 /* JsxSelfClosingElement */
+ return kind === 248 /* JsxElement */
+ || kind === 255 /* JsxExpression */
+ || kind === 249 /* JsxSelfClosingElement */
|| kind === 10 /* JsxText */;
}
ts.isJsxChild = isJsxChild;
+ function isJsxAttributes(node) {
+ var kind = node.kind;
+ return kind === 253 /* JsxAttributes */;
+ }
+ ts.isJsxAttributes = isJsxAttributes;
function isJsxAttributeLike(node) {
var kind = node.kind;
- return kind === 250 /* JsxAttribute */
- || kind === 251 /* JsxSpreadAttribute */;
+ return kind === 252 /* JsxAttribute */
+ || kind === 254 /* JsxSpreadAttribute */;
}
ts.isJsxAttributeLike = isJsxAttributeLike;
function isJsxSpreadAttribute(node) {
- return node.kind === 251 /* JsxSpreadAttribute */;
+ return node.kind === 254 /* JsxSpreadAttribute */;
}
ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
function isJsxAttribute(node) {
- return node.kind === 250 /* JsxAttribute */;
+ return node.kind === 252 /* JsxAttribute */;
}
ts.isJsxAttribute = isJsxAttribute;
function isStringLiteralOrJsxExpression(node) {
var kind = node.kind;
return kind === 9 /* StringLiteral */
- || kind === 252 /* JsxExpression */;
+ || kind === 255 /* JsxExpression */;
}
ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
+ function isJsxOpeningLikeElement(node) {
+ var kind = node.kind;
+ return kind === 250 /* JsxOpeningElement */
+ || kind === 249 /* JsxSelfClosingElement */;
+ }
+ ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
// Clauses
function isCaseOrDefaultClause(node) {
var kind = node.kind;
- return kind === 253 /* CaseClause */
- || kind === 254 /* DefaultClause */;
+ return kind === 256 /* CaseClause */
+ || kind === 257 /* DefaultClause */;
}
ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
function isHeritageClause(node) {
- return node.kind === 255 /* HeritageClause */;
+ return node.kind === 258 /* HeritageClause */;
}
ts.isHeritageClause = isHeritageClause;
function isCatchClause(node) {
- return node.kind === 256 /* CatchClause */;
+ return node.kind === 259 /* CatchClause */;
}
ts.isCatchClause = isCatchClause;
// Property assignments
function isPropertyAssignment(node) {
- return node.kind === 257 /* PropertyAssignment */;
+ return node.kind === 260 /* PropertyAssignment */;
}
ts.isPropertyAssignment = isPropertyAssignment;
function isShorthandPropertyAssignment(node) {
- return node.kind === 258 /* ShorthandPropertyAssignment */;
+ return node.kind === 261 /* ShorthandPropertyAssignment */;
}
ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
// Enum
function isEnumMember(node) {
- return node.kind === 260 /* EnumMember */;
+ return node.kind === 263 /* EnumMember */;
}
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 261 /* SourceFile */;
+ return node.kind === 264 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isWatchSet(options) {
@@ -10303,12 +10502,13 @@ var ts;
function getDefaultLibFileName(options) {
switch (options.target) {
case 5 /* ESNext */:
+ return "lib.esnext.full.d.ts";
case 4 /* ES2017 */:
- return "lib.es2017.d.ts";
+ return "lib.es2017.full.d.ts";
case 3 /* ES2016 */:
- return "lib.es2016.d.ts";
+ return "lib.es2016.full.d.ts";
case 2 /* ES2015 */:
- return "lib.es6.d.ts";
+ return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
default:
return "lib.d.ts";
}
@@ -10516,13 +10716,13 @@ var ts;
oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
}
- return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength:*/ newEndN - oldStartN);
+ return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
}
ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
function getTypeParameterOwner(d) {
- if (d && d.kind === 143 /* TypeParameter */) {
+ if (d && d.kind === 144 /* TypeParameter */) {
for (var current = d; current; current = current.parent) {
- if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 227 /* InterfaceDeclaration */) {
+ if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 229 /* InterfaceDeclaration */) {
return current;
}
}
@@ -10530,11 +10730,11 @@ var ts;
}
ts.getTypeParameterOwner = getTypeParameterOwner;
function isParameterPropertyDeclaration(node) {
- return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 150 /* Constructor */ && ts.isClassLike(node.parent.parent);
+ return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 151 /* Constructor */ && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function walkUpBindingElementsAndPatterns(node) {
- while (node && (node.kind === 174 /* BindingElement */ || ts.isBindingPattern(node))) {
+ while (node && (node.kind === 175 /* BindingElement */ || ts.isBindingPattern(node))) {
node = node.parent;
}
return node;
@@ -10542,14 +10742,14 @@ var ts;
function getCombinedModifierFlags(node) {
node = walkUpBindingElementsAndPatterns(node);
var flags = ts.getModifierFlags(node);
- if (node.kind === 223 /* VariableDeclaration */) {
+ if (node.kind === 225 /* VariableDeclaration */) {
node = node.parent;
}
- if (node && node.kind === 224 /* VariableDeclarationList */) {
+ if (node && node.kind === 226 /* VariableDeclarationList */) {
flags |= ts.getModifierFlags(node);
node = node.parent;
}
- if (node && node.kind === 205 /* VariableStatement */) {
+ if (node && node.kind === 207 /* VariableStatement */) {
flags |= ts.getModifierFlags(node);
}
return flags;
@@ -10565,23 +10765,23 @@ var ts;
function getCombinedNodeFlags(node) {
node = walkUpBindingElementsAndPatterns(node);
var flags = node.flags;
- if (node.kind === 223 /* VariableDeclaration */) {
+ if (node.kind === 225 /* VariableDeclaration */) {
node = node.parent;
}
- if (node && node.kind === 224 /* VariableDeclarationList */) {
+ if (node && node.kind === 226 /* VariableDeclarationList */) {
flags |= node.flags;
node = node.parent;
}
- if (node && node.kind === 205 /* VariableStatement */) {
+ if (node && node.kind === 207 /* VariableStatement */) {
flags |= node.flags;
}
return flags;
}
ts.getCombinedNodeFlags = getCombinedNodeFlags;
/**
- * Checks to see if the locale is in the appropriate format,
- * and if it is, attempts to set the appropriate language.
- */
+ * Checks to see if the locale is in the appropriate format,
+ * and if it is, attempts to set the appropriate language.
+ */
function validateLocaleAndSetLanguage(locale, sys, errors) {
var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
@@ -10632,27 +10832,60 @@ var ts;
}
}
ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
+ function getOriginalNode(node, nodeTest) {
+ if (node) {
+ while (node.original !== undefined) {
+ node = node.original;
+ }
+ }
+ return !nodeTest || nodeTest(node) ? node : undefined;
+ }
+ ts.getOriginalNode = getOriginalNode;
+ /**
+ * Gets a value indicating whether a node originated in the parse tree.
+ *
+ * @param node The node to test.
+ */
+ function isParseTreeNode(node) {
+ return (node.flags & 8 /* Synthesized */) === 0;
+ }
+ ts.isParseTreeNode = isParseTreeNode;
+ function getParseTreeNode(node, nodeTest) {
+ if (node === undefined || isParseTreeNode(node)) {
+ return node;
+ }
+ node = getOriginalNode(node);
+ if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
+ return node;
+ }
+ return undefined;
+ }
+ ts.getParseTreeNode = getParseTreeNode;
+ /**
+ * Remove extra underscore from escaped identifier text content.
+ *
+ * @param identifier The escaped identifier text.
+ * @returns The unescaped identifier text.
+ */
+ function unescapeIdentifier(identifier) {
+ return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier;
+ }
+ ts.unescapeIdentifier = unescapeIdentifier;
})(ts || (ts = {}));
/// <reference path="core.ts"/>
/// <reference path="utilities.ts"/>
-/* @internal */
var ts;
(function (ts) {
- var NodeConstructor;
- var SourceFileConstructor;
- function createNode(kind, location, flags) {
- var ConstructorForKind = kind === 261 /* SourceFile */
- ? (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))
- : (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()));
- var node = location
- ? new ConstructorForKind(kind, location.pos, location.end)
- : new ConstructorForKind(kind, /*pos*/ -1, /*end*/ -1);
- node.flags = flags | 8 /* Synthesized */;
+ function createSynthesizedNode(kind) {
+ var node = ts.createNode(kind, -1, -1);
+ node.flags |= 8 /* Synthesized */;
return node;
}
+ /* @internal */
function updateNode(updated, original) {
if (updated !== original) {
setOriginalNode(updated, original);
+ setTextRange(updated, original);
if (original.startsOnNewLine) {
updated.startsOnNewLine = true;
}
@@ -10661,7 +10894,10 @@ var ts;
return updated;
}
ts.updateNode = updateNode;
- function createNodeArray(elements, location, hasTrailingComma) {
+ /**
+ * Make `elements` into a `NodeArray<T>`. If `elements` is `undefined`, returns an empty `NodeArray<T>`.
+ */
+ function createNodeArray(elements, hasTrailingComma) {
if (elements) {
if (ts.isNodeArray(elements)) {
return elements;
@@ -10671,38 +10907,22 @@ var ts;
elements = [];
}
var array = elements;
- if (location) {
- array.pos = location.pos;
- array.end = location.end;
- }
- else {
- array.pos = -1;
- array.end = -1;
- }
- if (hasTrailingComma) {
- array.hasTrailingComma = true;
- }
+ array.pos = -1;
+ array.end = -1;
+ array.hasTrailingComma = hasTrailingComma;
return array;
}
ts.createNodeArray = createNodeArray;
- function createSynthesizedNode(kind, startsOnNewLine) {
- var node = createNode(kind, /*location*/ undefined);
- node.startsOnNewLine = startsOnNewLine;
- return node;
- }
- ts.createSynthesizedNode = createSynthesizedNode;
- function createSynthesizedNodeArray(elements) {
- return createNodeArray(elements, /*location*/ undefined);
- }
- ts.createSynthesizedNodeArray = createSynthesizedNodeArray;
/**
* Creates a shallow, memberwise clone of a node with no source map location.
*/
+ /* @internal */
function getSynthesizedClone(node) {
// We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
// the original node. We also need to exclude specific properties and only include own-
// properties (to skip members already defined on the shared prototype).
- var clone = createNode(node.kind, /*location*/ undefined, node.flags);
+ var clone = createSynthesizedNode(node.kind);
+ clone.flags |= node.flags;
setOriginalNode(clone, node);
for (var key in node) {
if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
@@ -10713,54 +10933,50 @@ var ts;
return clone;
}
ts.getSynthesizedClone = getSynthesizedClone;
- /**
- * Creates a shallow, memberwise clone of a node for mutation.
- */
- function getMutableClone(node) {
- var clone = getSynthesizedClone(node);
- clone.pos = node.pos;
- clone.end = node.end;
- clone.parent = node.parent;
- return clone;
- }
- ts.getMutableClone = getMutableClone;
- function createLiteral(value, location) {
+ function createLiteral(value) {
if (typeof value === "number") {
- var node = createNode(8 /* NumericLiteral */, location, /*flags*/ undefined);
- node.text = value.toString();
- return node;
+ return createNumericLiteral(value + "");
}
- else if (typeof value === "boolean") {
- return createNode(value ? 100 /* TrueKeyword */ : 85 /* FalseKeyword */, location, /*flags*/ undefined);
+ if (typeof value === "boolean") {
+ return value ? createTrue() : createFalse();
}
- else if (typeof value === "string") {
- var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined);
- node.text = value;
- return node;
- }
- else if (value) {
- var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined);
- node.textSourceNode = value;
- node.text = value.text;
- return node;
+ if (typeof value === "string") {
+ return createStringLiteral(value);
}
+ return createLiteralFromNode(value);
}
ts.createLiteral = createLiteral;
+ function createNumericLiteral(value) {
+ var node = createSynthesizedNode(8 /* NumericLiteral */);
+ node.text = value;
+ node.numericLiteralFlags = 0;
+ return node;
+ }
+ ts.createNumericLiteral = createNumericLiteral;
+ function createStringLiteral(text) {
+ var node = createSynthesizedNode(9 /* StringLiteral */);
+ node.text = text;
+ return node;
+ }
+ function createLiteralFromNode(sourceNode) {
+ var node = createStringLiteral(sourceNode.text);
+ node.textSourceNode = sourceNode;
+ return node;
+ }
// Identifiers
- var nextAutoGenerateId = 0;
- function createIdentifier(text, location) {
- var node = createNode(70 /* Identifier */, location);
+ function createIdentifier(text) {
+ var node = createSynthesizedNode(70 /* Identifier */);
node.text = ts.escapeIdentifier(text);
- node.originalKeywordKind = ts.stringToToken(text);
+ node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
node.autoGenerateKind = 0 /* None */;
node.autoGenerateId = 0;
return node;
}
ts.createIdentifier = createIdentifier;
- function createTempVariable(recordTempVariable, location) {
- var name = createNode(70 /* Identifier */, location);
- name.text = "";
- name.originalKeywordKind = 0 /* Unknown */;
+ var nextAutoGenerateId = 0;
+ /** Create a unique temporary variable. */
+ function createTempVariable(recordTempVariable) {
+ var name = createIdentifier("");
name.autoGenerateKind = 1 /* Auto */;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
@@ -10770,98 +10986,399 @@ var ts;
return name;
}
ts.createTempVariable = createTempVariable;
- function createLoopVariable(location) {
- var name = createNode(70 /* Identifier */, location);
- name.text = "";
- name.originalKeywordKind = 0 /* Unknown */;
+ /** Create a unique temporary variable for use in a loop. */
+ function createLoopVariable() {
+ var name = createIdentifier("");
name.autoGenerateKind = 2 /* Loop */;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
return name;
}
ts.createLoopVariable = createLoopVariable;
- function createUniqueName(text, location) {
- var name = createNode(70 /* Identifier */, location);
- name.text = text;
- name.originalKeywordKind = 0 /* Unknown */;
+ /** Create a unique name based on the supplied text. */
+ function createUniqueName(text) {
+ var name = createIdentifier(text);
name.autoGenerateKind = 3 /* Unique */;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
return name;
}
ts.createUniqueName = createUniqueName;
- function getGeneratedNameForNode(node, location) {
- var name = createNode(70 /* Identifier */, location);
- name.original = node;
- name.text = "";
- name.originalKeywordKind = 0 /* Unknown */;
+ /** Create a unique name generated for a node. */
+ function getGeneratedNameForNode(node) {
+ var name = createIdentifier("");
name.autoGenerateKind = 4 /* Node */;
name.autoGenerateId = nextAutoGenerateId;
+ name.original = node;
nextAutoGenerateId++;
return name;
}
ts.getGeneratedNameForNode = getGeneratedNameForNode;
// Punctuation
function createToken(token) {
- return createNode(token);
+ return createSynthesizedNode(token);
}
ts.createToken = createToken;
// Reserved words
function createSuper() {
- var node = createNode(96 /* SuperKeyword */);
- return node;
+ return createSynthesizedNode(96 /* SuperKeyword */);
}
ts.createSuper = createSuper;
- function createThis(location) {
- var node = createNode(98 /* ThisKeyword */, location);
- return node;
+ function createThis() {
+ return createSynthesizedNode(98 /* ThisKeyword */);
}
ts.createThis = createThis;
function createNull() {
- var node = createNode(94 /* NullKeyword */);
- return node;
+ return createSynthesizedNode(94 /* NullKeyword */);
}
ts.createNull = createNull;
+ function createTrue() {
+ return createSynthesizedNode(100 /* TrueKeyword */);
+ }
+ ts.createTrue = createTrue;
+ function createFalse() {
+ return createSynthesizedNode(85 /* FalseKeyword */);
+ }
+ ts.createFalse = createFalse;
// Names
- function createComputedPropertyName(expression, location) {
- var node = createNode(142 /* ComputedPropertyName */, location);
+ function createQualifiedName(left, right) {
+ var node = createSynthesizedNode(142 /* QualifiedName */);
+ node.left = left;
+ node.right = asName(right);
+ return node;
+ }
+ ts.createQualifiedName = createQualifiedName;
+ function updateQualifiedName(node, left, right) {
+ return node.left !== left
+ || node.right !== right
+ ? updateNode(createQualifiedName(left, right), node)
+ : node;
+ }
+ ts.updateQualifiedName = updateQualifiedName;
+ function createComputedPropertyName(expression) {
+ var node = createSynthesizedNode(143 /* ComputedPropertyName */);
node.expression = expression;
return node;
}
ts.createComputedPropertyName = createComputedPropertyName;
function updateComputedPropertyName(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createComputedPropertyName(expression, node), node);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createComputedPropertyName(expression), node)
+ : node;
}
ts.updateComputedPropertyName = updateComputedPropertyName;
+ // Type Elements
+ function createSignatureDeclaration(kind, typeParameters, parameters, type) {
+ var signatureDeclaration = createSynthesizedNode(kind);
+ signatureDeclaration.typeParameters = asNodeArray(typeParameters);
+ signatureDeclaration.parameters = asNodeArray(parameters);
+ signatureDeclaration.type = type;
+ return signatureDeclaration;
+ }
+ ts.createSignatureDeclaration = createSignatureDeclaration;
+ function updateSignatureDeclaration(node, typeParameters, parameters, type) {
+ return node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
+ : node;
+ }
+ function createFunctionTypeNode(typeParameters, parameters, type) {
+ return createSignatureDeclaration(159 /* FunctionType */, typeParameters, parameters, type);
+ }
+ ts.createFunctionTypeNode = createFunctionTypeNode;
+ function updateFunctionTypeNode(node, typeParameters, parameters, type) {
+ return updateSignatureDeclaration(node, typeParameters, parameters, type);
+ }
+ ts.updateFunctionTypeNode = updateFunctionTypeNode;
+ function createConstructorTypeNode(typeParameters, parameters, type) {
+ return createSignatureDeclaration(160 /* ConstructorType */, typeParameters, parameters, type);
+ }
+ ts.createConstructorTypeNode = createConstructorTypeNode;
+ function updateConstructorTypeNode(node, typeParameters, parameters, type) {
+ return updateSignatureDeclaration(node, typeParameters, parameters, type);
+ }
+ ts.updateConstructorTypeNode = updateConstructorTypeNode;
+ function createCallSignatureDeclaration(typeParameters, parameters, type) {
+ return createSignatureDeclaration(154 /* CallSignature */, typeParameters, parameters, type);
+ }
+ ts.createCallSignatureDeclaration = createCallSignatureDeclaration;
+ function updateCallSignatureDeclaration(node, typeParameters, parameters, type) {
+ return updateSignatureDeclaration(node, typeParameters, parameters, type);
+ }
+ ts.updateCallSignatureDeclaration = updateCallSignatureDeclaration;
+ function createConstructSignatureDeclaration(typeParameters, parameters, type) {
+ return createSignatureDeclaration(155 /* ConstructSignature */, typeParameters, parameters, type);
+ }
+ ts.createConstructSignatureDeclaration = createConstructSignatureDeclaration;
+ function updateConstructSignatureDeclaration(node, typeParameters, parameters, type) {
+ return updateSignatureDeclaration(node, typeParameters, parameters, type);
+ }
+ ts.updateConstructSignatureDeclaration = updateConstructSignatureDeclaration;
+ function createMethodSignature(typeParameters, parameters, type, name, questionToken) {
+ var methodSignature = createSignatureDeclaration(149 /* MethodSignature */, typeParameters, parameters, type);
+ methodSignature.name = asName(name);
+ methodSignature.questionToken = questionToken;
+ return methodSignature;
+ }
+ ts.createMethodSignature = createMethodSignature;
+ function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) {
+ return node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.name !== name
+ || node.questionToken !== questionToken
+ ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
+ : node;
+ }
+ ts.updateMethodSignature = updateMethodSignature;
+ // Types
+ function createKeywordTypeNode(kind) {
+ return createSynthesizedNode(kind);
+ }
+ ts.createKeywordTypeNode = createKeywordTypeNode;
+ function createThisTypeNode() {
+ return createSynthesizedNode(168 /* ThisType */);
+ }
+ ts.createThisTypeNode = createThisTypeNode;
+ function createLiteralTypeNode(literal) {
+ var literalTypeNode = createSynthesizedNode(172 /* LiteralType */);
+ literalTypeNode.literal = literal;
+ return literalTypeNode;
+ }
+ ts.createLiteralTypeNode = createLiteralTypeNode;
+ function updateLiteralTypeNode(node, literal) {
+ return node.literal !== literal
+ ? updateNode(createLiteralTypeNode(literal), node)
+ : node;
+ }
+ ts.updateLiteralTypeNode = updateLiteralTypeNode;
+ function createTypeReferenceNode(typeName, typeArguments) {
+ var typeReference = createSynthesizedNode(158 /* TypeReference */);
+ typeReference.typeName = asName(typeName);
+ typeReference.typeArguments = asNodeArray(typeArguments);
+ return typeReference;
+ }
+ ts.createTypeReferenceNode = createTypeReferenceNode;
+ function updateTypeReferenceNode(node, typeName, typeArguments) {
+ return node.typeName !== typeName
+ || node.typeArguments !== typeArguments
+ ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
+ : node;
+ }
+ ts.updateTypeReferenceNode = updateTypeReferenceNode;
+ function createTypePredicateNode(parameterName, type) {
+ var typePredicateNode = createSynthesizedNode(157 /* TypePredicate */);
+ typePredicateNode.parameterName = asName(parameterName);
+ typePredicateNode.type = type;
+ return typePredicateNode;
+ }
+ ts.createTypePredicateNode = createTypePredicateNode;
+ function updateTypePredicateNode(node, parameterName, type) {
+ return node.parameterName !== parameterName
+ || node.type !== type
+ ? updateNode(createTypePredicateNode(parameterName, type), node)
+ : node;
+ }
+ ts.updateTypePredicateNode = updateTypePredicateNode;
+ function createTypeQueryNode(exprName) {
+ var typeQueryNode = createSynthesizedNode(161 /* TypeQuery */);
+ typeQueryNode.exprName = exprName;
+ return typeQueryNode;
+ }
+ ts.createTypeQueryNode = createTypeQueryNode;
+ function updateTypeQueryNode(node, exprName) {
+ return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node;
+ }
+ ts.updateTypeQueryNode = updateTypeQueryNode;
+ function createArrayTypeNode(elementType) {
+ var arrayTypeNode = createSynthesizedNode(163 /* ArrayType */);
+ arrayTypeNode.elementType = elementType;
+ return arrayTypeNode;
+ }
+ ts.createArrayTypeNode = createArrayTypeNode;
+ function updateArrayTypeNode(node, elementType) {
+ return node.elementType !== elementType
+ ? updateNode(createArrayTypeNode(elementType), node)
+ : node;
+ }
+ ts.updateArrayTypeNode = updateArrayTypeNode;
+ function createUnionOrIntersectionTypeNode(kind, types) {
+ var unionTypeNode = createSynthesizedNode(kind);
+ unionTypeNode.types = createNodeArray(types);
+ return unionTypeNode;
+ }
+ ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode;
+ function updateUnionOrIntersectionTypeNode(node, types) {
+ return node.types !== types
+ ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
+ : node;
+ }
+ ts.updateUnionOrIntersectionTypeNode = updateUnionOrIntersectionTypeNode;
+ function createTypeLiteralNode(members) {
+ var typeLiteralNode = createSynthesizedNode(162 /* TypeLiteral */);
+ typeLiteralNode.members = createNodeArray(members);
+ return typeLiteralNode;
+ }
+ ts.createTypeLiteralNode = createTypeLiteralNode;
+ function updateTypeLiteralNode(node, members) {
+ return node.members !== members
+ ? updateNode(createTypeLiteralNode(members), node)
+ : node;
+ }
+ ts.updateTypeLiteralNode = updateTypeLiteralNode;
+ function createTupleTypeNode(elementTypes) {
+ var tupleTypeNode = createSynthesizedNode(164 /* TupleType */);
+ tupleTypeNode.elementTypes = createNodeArray(elementTypes);
+ return tupleTypeNode;
+ }
+ ts.createTupleTypeNode = createTupleTypeNode;
+ function updateTypleTypeNode(node, elementTypes) {
+ return node.elementTypes !== elementTypes
+ ? updateNode(createTupleTypeNode(elementTypes), node)
+ : node;
+ }
+ ts.updateTypleTypeNode = updateTypleTypeNode;
+ function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
+ var mappedTypeNode = createSynthesizedNode(171 /* MappedType */);
+ mappedTypeNode.readonlyToken = readonlyToken;
+ mappedTypeNode.typeParameter = typeParameter;
+ mappedTypeNode.questionToken = questionToken;
+ mappedTypeNode.type = type;
+ return mappedTypeNode;
+ }
+ ts.createMappedTypeNode = createMappedTypeNode;
+ function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
+ return node.readonlyToken !== readonlyToken
+ || node.typeParameter !== typeParameter
+ || node.questionToken !== questionToken
+ || node.type !== type
+ ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
+ : node;
+ }
+ ts.updateMappedTypeNode = updateMappedTypeNode;
+ function createTypeOperatorNode(type) {
+ var typeOperatorNode = createSynthesizedNode(169 /* TypeOperator */);
+ typeOperatorNode.operator = 126 /* KeyOfKeyword */;
+ typeOperatorNode.type = type;
+ return typeOperatorNode;
+ }
+ ts.createTypeOperatorNode = createTypeOperatorNode;
+ function updateTypeOperatorNode(node, type) {
+ return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node;
+ }
+ ts.updateTypeOperatorNode = updateTypeOperatorNode;
+ function createIndexedAccessTypeNode(objectType, indexType) {
+ var indexedAccessTypeNode = createSynthesizedNode(170 /* IndexedAccessType */);
+ indexedAccessTypeNode.objectType = objectType;
+ indexedAccessTypeNode.indexType = indexType;
+ return indexedAccessTypeNode;
+ }
+ ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode;
+ function updateIndexedAccessTypeNode(node, objectType, indexType) {
+ return node.objectType !== objectType
+ || node.indexType !== indexType
+ ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
+ : node;
+ }
+ ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode;
+ // Type Declarations
+ function createTypeParameterDeclaration(name, constraint, defaultType) {
+ var typeParameter = createSynthesizedNode(144 /* TypeParameter */);
+ typeParameter.name = asName(name);
+ typeParameter.constraint = constraint;
+ typeParameter.default = defaultType;
+ return typeParameter;
+ }
+ ts.createTypeParameterDeclaration = createTypeParameterDeclaration;
+ function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
+ return node.name !== name
+ || node.constraint !== constraint
+ || node.default !== defaultType
+ ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
+ : node;
+ }
+ ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration;
+ // Signature elements
+ function createPropertySignature(name, questionToken, type, initializer) {
+ var propertySignature = createSynthesizedNode(147 /* PropertySignature */);
+ propertySignature.name = asName(name);
+ propertySignature.questionToken = questionToken;
+ propertySignature.type = type;
+ propertySignature.initializer = initializer;
+ return propertySignature;
+ }
+ ts.createPropertySignature = createPropertySignature;
+ function updatePropertySignature(node, name, questionToken, type, initializer) {
+ return node.name !== name
+ || node.questionToken !== questionToken
+ || node.type !== type
+ || node.initializer !== initializer
+ ? updateNode(createPropertySignature(name, questionToken, type, initializer), node)
+ : node;
+ }
+ ts.updatePropertySignature = updatePropertySignature;
+ function createIndexSignatureDeclaration(decorators, modifiers, parameters, type) {
+ var indexSignature = createSynthesizedNode(156 /* IndexSignature */);
+ indexSignature.decorators = asNodeArray(decorators);
+ indexSignature.modifiers = asNodeArray(modifiers);
+ indexSignature.parameters = createNodeArray(parameters);
+ indexSignature.type = type;
+ return indexSignature;
+ }
+ ts.createIndexSignatureDeclaration = createIndexSignatureDeclaration;
+ function updateIndexSignatureDeclaration(node, decorators, modifiers, parameters, type) {
+ return node.parameters !== parameters
+ || node.type !== type
+ || node.decorators !== decorators
+ || node.modifiers !== modifiers
+ ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node)
+ : node;
+ }
+ ts.updateIndexSignatureDeclaration = updateIndexSignatureDeclaration;
// Signature elements
- function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer, location, flags) {
- var node = createNode(144 /* Parameter */, location, flags);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
+ function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
+ var node = createSynthesizedNode(145 /* Parameter */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
node.dotDotDotToken = dotDotDotToken;
- node.name = typeof name === "string" ? createIdentifier(name) : name;
+ node.name = asName(name);
node.questionToken = questionToken;
node.type = type;
- node.initializer = initializer ? parenthesizeExpressionForList(initializer) : undefined;
+ node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
return node;
}
ts.createParameter = createParameter;
- function updateParameter(node, decorators, modifiers, dotDotDotToken, name, type, initializer) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.type !== type || node.initializer !== initializer) {
- return updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node);
- }
- return node;
+ function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.dotDotDotToken !== dotDotDotToken
+ || node.name !== name
+ || node.questionToken !== questionToken
+ || node.type !== type
+ || node.initializer !== initializer
+ ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer), node)
+ : node;
}
ts.updateParameter = updateParameter;
+ function createDecorator(expression) {
+ var node = createSynthesizedNode(146 /* Decorator */);
+ node.expression = ts.parenthesizeForAccess(expression);
+ return node;
+ }
+ ts.createDecorator = createDecorator;
+ function updateDecorator(node, expression) {
+ return node.expression !== expression
+ ? updateNode(createDecorator(expression), node)
+ : node;
+ }
+ ts.updateDecorator = updateDecorator;
// Type members
- function createProperty(decorators, modifiers, name, questionToken, type, initializer, location) {
- var node = createNode(147 /* PropertyDeclaration */, location);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
- node.name = typeof name === "string" ? createIdentifier(name) : name;
+ function createProperty(decorators, modifiers, name, questionToken, type, initializer) {
+ var node = createSynthesizedNode(148 /* PropertyDeclaration */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
+ node.name = asName(name);
node.questionToken = questionToken;
node.type = type;
node.initializer = initializer;
@@ -10869,36 +11386,46 @@ var ts;
}
ts.createProperty = createProperty;
function updateProperty(node, decorators, modifiers, name, type, initializer) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) {
- return updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer, node), node);
- }
- return node;
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.type !== type
+ || node.initializer !== initializer
+ ? updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer), node)
+ : node;
}
ts.updateProperty = updateProperty;
- function createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) {
- var node = createNode(149 /* MethodDeclaration */, location, flags);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
+ function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
+ var node = createSynthesizedNode(150 /* MethodDeclaration */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
node.asteriskToken = asteriskToken;
- node.name = typeof name === "string" ? createIdentifier(name) : name;
- node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined;
+ node.name = asName(name);
+ node.questionToken = questionToken;
+ node.typeParameters = asNodeArray(typeParameters);
node.parameters = createNodeArray(parameters);
node.type = type;
node.body = body;
return node;
}
- ts.createMethod = createMethod;
- function updateMethod(node, decorators, modifiers, name, typeParameters, parameters, type, body) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) {
- return updateNode(createMethod(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node);
- }
- return node;
+ ts.createMethodDeclaration = createMethodDeclaration;
+ function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.asteriskToken !== asteriskToken
+ || node.name !== name
+ || node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.body !== body
+ ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
+ : node;
}
ts.updateMethod = updateMethod;
- function createConstructor(decorators, modifiers, parameters, body, location, flags) {
- var node = createNode(150 /* Constructor */, location, flags);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
+ function createConstructor(decorators, modifiers, parameters, body) {
+ var node = createSynthesizedNode(151 /* Constructor */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
node.typeParameters = undefined;
node.parameters = createNodeArray(parameters);
node.type = undefined;
@@ -10907,17 +11434,19 @@ var ts;
}
ts.createConstructor = createConstructor;
function updateConstructor(node, decorators, modifiers, parameters, body) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.parameters !== parameters || node.body !== body) {
- return updateNode(createConstructor(decorators, modifiers, parameters, body, /*location*/ node, node.flags), node);
- }
- return node;
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.parameters !== parameters
+ || node.body !== body
+ ? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
+ : node;
}
ts.updateConstructor = updateConstructor;
- function createGetAccessor(decorators, modifiers, name, parameters, type, body, location, flags) {
- var node = createNode(151 /* GetAccessor */, location, flags);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
- node.name = typeof name === "string" ? createIdentifier(name) : name;
+ function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
+ var node = createSynthesizedNode(152 /* GetAccessor */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
+ node.name = asName(name);
node.typeParameters = undefined;
node.parameters = createNodeArray(parameters);
node.type = type;
@@ -10926,17 +11455,21 @@ var ts;
}
ts.createGetAccessor = createGetAccessor;
function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.type !== type || node.body !== body) {
- return updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body, /*location*/ node, node.flags), node);
- }
- return node;
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.body !== body
+ ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
+ : node;
}
ts.updateGetAccessor = updateGetAccessor;
- function createSetAccessor(decorators, modifiers, name, parameters, body, location, flags) {
- var node = createNode(152 /* SetAccessor */, location, flags);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
- node.name = typeof name === "string" ? createIdentifier(name) : name;
+ function createSetAccessor(decorators, modifiers, name, parameters, body) {
+ var node = createSynthesizedNode(153 /* SetAccessor */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
+ node.name = asName(name);
node.typeParameters = undefined;
node.parameters = createNodeArray(parameters);
node.body = body;
@@ -10944,59 +11477,62 @@ var ts;
}
ts.createSetAccessor = createSetAccessor;
function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.parameters !== parameters || node.body !== body) {
- return updateNode(createSetAccessor(decorators, modifiers, name, parameters, body, /*location*/ node, node.flags), node);
- }
- return node;
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.parameters !== parameters
+ || node.body !== body
+ ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
+ : node;
}
ts.updateSetAccessor = updateSetAccessor;
// Binding Patterns
- function createObjectBindingPattern(elements, location) {
- var node = createNode(172 /* ObjectBindingPattern */, location);
+ function createObjectBindingPattern(elements) {
+ var node = createSynthesizedNode(173 /* ObjectBindingPattern */);
node.elements = createNodeArray(elements);
return node;
}
ts.createObjectBindingPattern = createObjectBindingPattern;
function updateObjectBindingPattern(node, elements) {
- if (node.elements !== elements) {
- return updateNode(createObjectBindingPattern(elements, node), node);
- }
- return node;
+ return node.elements !== elements
+ ? updateNode(createObjectBindingPattern(elements), node)
+ : node;
}
ts.updateObjectBindingPattern = updateObjectBindingPattern;
- function createArrayBindingPattern(elements, location) {
- var node = createNode(173 /* ArrayBindingPattern */, location);
+ function createArrayBindingPattern(elements) {
+ var node = createSynthesizedNode(174 /* ArrayBindingPattern */);
node.elements = createNodeArray(elements);
return node;
}
ts.createArrayBindingPattern = createArrayBindingPattern;
function updateArrayBindingPattern(node, elements) {
- if (node.elements !== elements) {
- return updateNode(createArrayBindingPattern(elements, node), node);
- }
- return node;
+ return node.elements !== elements
+ ? updateNode(createArrayBindingPattern(elements), node)
+ : node;
}
ts.updateArrayBindingPattern = updateArrayBindingPattern;
- function createBindingElement(propertyName, dotDotDotToken, name, initializer, location) {
- var node = createNode(174 /* BindingElement */, location);
- node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName;
+ function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
+ var node = createSynthesizedNode(175 /* BindingElement */);
node.dotDotDotToken = dotDotDotToken;
- node.name = typeof name === "string" ? createIdentifier(name) : name;
+ node.propertyName = asName(propertyName);
+ node.name = asName(name);
node.initializer = initializer;
return node;
}
ts.createBindingElement = createBindingElement;
function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
- if (node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer) {
- return updateNode(createBindingElement(propertyName, dotDotDotToken, name, initializer, node), node);
- }
- return node;
+ return node.propertyName !== propertyName
+ || node.dotDotDotToken !== dotDotDotToken
+ || node.name !== name
+ || node.initializer !== initializer
+ ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
+ : node;
}
ts.updateBindingElement = updateBindingElement;
// Expression
- function createArrayLiteral(elements, location, multiLine) {
- var node = createNode(175 /* ArrayLiteralExpression */, location);
- node.elements = parenthesizeListElements(createNodeArray(elements));
+ function createArrayLiteral(elements, multiLine) {
+ var node = createSynthesizedNode(176 /* ArrayLiteralExpression */);
+ node.elements = ts.parenthesizeListElements(createNodeArray(elements));
if (multiLine) {
node.multiLine = true;
}
@@ -11004,14 +11540,13 @@ var ts;
}
ts.createArrayLiteral = createArrayLiteral;
function updateArrayLiteral(node, elements) {
- if (node.elements !== elements) {
- return updateNode(createArrayLiteral(elements, node, node.multiLine), node);
- }
- return node;
+ return node.elements !== elements
+ ? updateNode(createArrayLiteral(elements, node.multiLine), node)
+ : node;
}
ts.updateArrayLiteral = updateArrayLiteral;
- function createObjectLiteral(properties, location, multiLine) {
- var node = createNode(176 /* ObjectLiteralExpression */, location);
+ function createObjectLiteral(properties, multiLine) {
+ var node = createSynthesizedNode(177 /* ObjectLiteralExpression */);
node.properties = createNodeArray(properties);
if (multiLine) {
node.multiLine = true;
@@ -11020,436 +11555,465 @@ var ts;
}
ts.createObjectLiteral = createObjectLiteral;
function updateObjectLiteral(node, properties) {
- if (node.properties !== properties) {
- return updateNode(createObjectLiteral(properties, node, node.multiLine), node);
- }
- return node;
+ return node.properties !== properties
+ ? updateNode(createObjectLiteral(properties, node.multiLine), node)
+ : node;
}
ts.updateObjectLiteral = updateObjectLiteral;
- function createPropertyAccess(expression, name, location, flags) {
- var node = createNode(177 /* PropertyAccessExpression */, location, flags);
- node.expression = parenthesizeForAccess(expression);
- (node.emitNode || (node.emitNode = {})).flags |= 65536 /* NoIndentation */;
- node.name = typeof name === "string" ? createIdentifier(name) : name;
+ function createPropertyAccess(expression, name) {
+ var node = createSynthesizedNode(178 /* PropertyAccessExpression */);
+ node.expression = ts.parenthesizeForAccess(expression);
+ node.name = asName(name);
+ setEmitFlags(node, 65536 /* NoIndentation */);
return node;
}
ts.createPropertyAccess = createPropertyAccess;
function updatePropertyAccess(node, expression, name) {
- if (node.expression !== expression || node.name !== name) {
- var propertyAccess = createPropertyAccess(expression, name, /*location*/ node, node.flags);
- // Because we are updating existed propertyAccess we want to inherit its emitFlags instead of using default from createPropertyAccess
- (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node);
- return updateNode(propertyAccess, node);
- }
- return node;
+ // Because we are updating existed propertyAccess we want to inherit its emitFlags
+ // instead of using the default from createPropertyAccess
+ return node.expression !== expression
+ || node.name !== name
+ ? updateNode(setEmitFlags(createPropertyAccess(expression, name), getEmitFlags(node)), node)
+ : node;
}
ts.updatePropertyAccess = updatePropertyAccess;
- function createElementAccess(expression, index, location) {
- var node = createNode(178 /* ElementAccessExpression */, location);
- node.expression = parenthesizeForAccess(expression);
- node.argumentExpression = typeof index === "number" ? createLiteral(index) : index;
+ function createElementAccess(expression, index) {
+ var node = createSynthesizedNode(179 /* ElementAccessExpression */);
+ node.expression = ts.parenthesizeForAccess(expression);
+ node.argumentExpression = asExpression(index);
return node;
}
ts.createElementAccess = createElementAccess;
function updateElementAccess(node, expression, argumentExpression) {
- if (node.expression !== expression || node.argumentExpression !== argumentExpression) {
- return updateNode(createElementAccess(expression, argumentExpression, node), node);
- }
- return node;
+ return node.expression !== expression
+ || node.argumentExpression !== argumentExpression
+ ? updateNode(createElementAccess(expression, argumentExpression), node)
+ : node;
}
ts.updateElementAccess = updateElementAccess;
- function createCall(expression, typeArguments, argumentsArray, location, flags) {
- var node = createNode(179 /* CallExpression */, location, flags);
- node.expression = parenthesizeForAccess(expression);
- if (typeArguments) {
- node.typeArguments = createNodeArray(typeArguments);
- }
- node.arguments = parenthesizeListElements(createNodeArray(argumentsArray));
+ function createCall(expression, typeArguments, argumentsArray) {
+ var node = createSynthesizedNode(180 /* CallExpression */);
+ node.expression = ts.parenthesizeForAccess(expression);
+ node.typeArguments = asNodeArray(typeArguments);
+ node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
return node;
}
ts.createCall = createCall;
function updateCall(node, expression, typeArguments, argumentsArray) {
- if (expression !== node.expression || typeArguments !== node.typeArguments || argumentsArray !== node.arguments) {
- return updateNode(createCall(expression, typeArguments, argumentsArray, /*location*/ node, node.flags), node);
- }
- return node;
+ return expression !== node.expression
+ || typeArguments !== node.typeArguments
+ || argumentsArray !== node.arguments
+ ? updateNode(createCall(expression, typeArguments, argumentsArray), node)
+ : node;
}
ts.updateCall = updateCall;
- function createNew(expression, typeArguments, argumentsArray, location, flags) {
- var node = createNode(180 /* NewExpression */, location, flags);
- node.expression = parenthesizeForNew(expression);
- node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined;
- node.arguments = argumentsArray ? parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
+ function createNew(expression, typeArguments, argumentsArray) {
+ var node = createSynthesizedNode(181 /* NewExpression */);
+ node.expression = ts.parenthesizeForNew(expression);
+ node.typeArguments = asNodeArray(typeArguments);
+ node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
return node;
}
ts.createNew = createNew;
function updateNew(node, expression, typeArguments, argumentsArray) {
- if (node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray) {
- return updateNode(createNew(expression, typeArguments, argumentsArray, /*location*/ node, node.flags), node);
- }
- return node;
+ return node.expression !== expression
+ || node.typeArguments !== typeArguments
+ || node.arguments !== argumentsArray
+ ? updateNode(createNew(expression, typeArguments, argumentsArray), node)
+ : node;
}
ts.updateNew = updateNew;
- function createTaggedTemplate(tag, template, location) {
- var node = createNode(181 /* TaggedTemplateExpression */, location);
- node.tag = parenthesizeForAccess(tag);
+ function createTaggedTemplate(tag, template) {
+ var node = createSynthesizedNode(182 /* TaggedTemplateExpression */);
+ node.tag = ts.parenthesizeForAccess(tag);
node.template = template;
return node;
}
ts.createTaggedTemplate = createTaggedTemplate;
function updateTaggedTemplate(node, tag, template) {
- if (node.tag !== tag || node.template !== template) {
- return updateNode(createTaggedTemplate(tag, template, node), node);
- }
- return node;
+ return node.tag !== tag
+ || node.template !== template
+ ? updateNode(createTaggedTemplate(tag, template), node)
+ : node;
}
ts.updateTaggedTemplate = updateTaggedTemplate;
- function createParen(expression, location) {
- var node = createNode(183 /* ParenthesizedExpression */, location);
+ function createTypeAssertion(type, expression) {
+ var node = createSynthesizedNode(183 /* TypeAssertionExpression */);
+ node.type = type;
+ node.expression = ts.parenthesizePrefixOperand(expression);
+ return node;
+ }
+ ts.createTypeAssertion = createTypeAssertion;
+ function updateTypeAssertion(node, type, expression) {
+ return node.type !== type
+ || node.expression !== expression
+ ? updateNode(createTypeAssertion(type, expression), node)
+ : node;
+ }
+ ts.updateTypeAssertion = updateTypeAssertion;
+ function createParen(expression) {
+ var node = createSynthesizedNode(184 /* ParenthesizedExpression */);
node.expression = expression;
return node;
}
ts.createParen = createParen;
function updateParen(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createParen(expression, node), node);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createParen(expression), node)
+ : node;
}
ts.updateParen = updateParen;
- function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) {
- var node = createNode(184 /* FunctionExpression */, location, flags);
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
+ function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
+ var node = createSynthesizedNode(185 /* FunctionExpression */);
+ node.modifiers = asNodeArray(modifiers);
node.asteriskToken = asteriskToken;
- node.name = typeof name === "string" ? createIdentifier(name) : name;
- node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined;
+ node.name = asName(name);
+ node.typeParameters = asNodeArray(typeParameters);
node.parameters = createNodeArray(parameters);
node.type = type;
node.body = body;
return node;
}
ts.createFunctionExpression = createFunctionExpression;
- function updateFunctionExpression(node, modifiers, name, typeParameters, parameters, type, body) {
- if (node.name !== name || node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) {
- return updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node);
- }
- return node;
+ function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
+ return node.name !== name
+ || node.modifiers !== modifiers
+ || node.asteriskToken !== asteriskToken
+ || node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.body !== body
+ ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
+ : node;
}
ts.updateFunctionExpression = updateFunctionExpression;
- function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body, location, flags) {
- var node = createNode(185 /* ArrowFunction */, location, flags);
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
- node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined;
+ function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
+ var node = createSynthesizedNode(186 /* ArrowFunction */);
+ node.modifiers = asNodeArray(modifiers);
+ node.typeParameters = asNodeArray(typeParameters);
node.parameters = createNodeArray(parameters);
node.type = type;
node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(35 /* EqualsGreaterThanToken */);
- node.body = parenthesizeConciseBody(body);
+ node.body = ts.parenthesizeConciseBody(body);
return node;
}
ts.createArrowFunction = createArrowFunction;
function updateArrowFunction(node, modifiers, typeParameters, parameters, type, body) {
- if (node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) {
- return updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body, /*location*/ node, node.flags), node);
- }
- return node;
+ return node.modifiers !== modifiers
+ || node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.body !== body
+ ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, node.equalsGreaterThanToken, body), node)
+ : node;
}
ts.updateArrowFunction = updateArrowFunction;
- function createDelete(expression, location) {
- var node = createNode(186 /* DeleteExpression */, location);
- node.expression = parenthesizePrefixOperand(expression);
+ function createDelete(expression) {
+ var node = createSynthesizedNode(187 /* DeleteExpression */);
+ node.expression = ts.parenthesizePrefixOperand(expression);
return node;
}
ts.createDelete = createDelete;
function updateDelete(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createDelete(expression, node), expression);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createDelete(expression), node)
+ : node;
}
ts.updateDelete = updateDelete;
- function createTypeOf(expression, location) {
- var node = createNode(187 /* TypeOfExpression */, location);
- node.expression = parenthesizePrefixOperand(expression);
+ function createTypeOf(expression) {
+ var node = createSynthesizedNode(188 /* TypeOfExpression */);
+ node.expression = ts.parenthesizePrefixOperand(expression);
return node;
}
ts.createTypeOf = createTypeOf;
function updateTypeOf(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createTypeOf(expression, node), expression);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createTypeOf(expression), node)
+ : node;
}
ts.updateTypeOf = updateTypeOf;
- function createVoid(expression, location) {
- var node = createNode(188 /* VoidExpression */, location);
- node.expression = parenthesizePrefixOperand(expression);
+ function createVoid(expression) {
+ var node = createSynthesizedNode(189 /* VoidExpression */);
+ node.expression = ts.parenthesizePrefixOperand(expression);
return node;
}
ts.createVoid = createVoid;
function updateVoid(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createVoid(expression, node), node);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createVoid(expression), node)
+ : node;
}
ts.updateVoid = updateVoid;
- function createAwait(expression, location) {
- var node = createNode(189 /* AwaitExpression */, location);
- node.expression = parenthesizePrefixOperand(expression);
+ function createAwait(expression) {
+ var node = createSynthesizedNode(190 /* AwaitExpression */);
+ node.expression = ts.parenthesizePrefixOperand(expression);
return node;
}
ts.createAwait = createAwait;
function updateAwait(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createAwait(expression, node), node);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createAwait(expression), node)
+ : node;
}
ts.updateAwait = updateAwait;
- function createPrefix(operator, operand, location) {
- var node = createNode(190 /* PrefixUnaryExpression */, location);
+ function createPrefix(operator, operand) {
+ var node = createSynthesizedNode(191 /* PrefixUnaryExpression */);
node.operator = operator;
- node.operand = parenthesizePrefixOperand(operand);
+ node.operand = ts.parenthesizePrefixOperand(operand);
return node;
}
ts.createPrefix = createPrefix;
function updatePrefix(node, operand) {
- if (node.operand !== operand) {
- return updateNode(createPrefix(node.operator, operand, node), node);
- }
- return node;
+ return node.operand !== operand
+ ? updateNode(createPrefix(node.operator, operand), node)
+ : node;
}
ts.updatePrefix = updatePrefix;
- function createPostfix(operand, operator, location) {
- var node = createNode(191 /* PostfixUnaryExpression */, location);
- node.operand = parenthesizePostfixOperand(operand);
+ function createPostfix(operand, operator) {
+ var node = createSynthesizedNode(192 /* PostfixUnaryExpression */);
+ node.operand = ts.parenthesizePostfixOperand(operand);
node.operator = operator;
return node;
}
ts.createPostfix = createPostfix;
function updatePostfix(node, operand) {
- if (node.operand !== operand) {
- return updateNode(createPostfix(operand, node.operator, node), node);
- }
- return node;
+ return node.operand !== operand
+ ? updateNode(createPostfix(operand, node.operator), node)
+ : node;
}
ts.updatePostfix = updatePostfix;
- function createBinary(left, operator, right, location) {
- var operatorToken = typeof operator === "number" ? createToken(operator) : operator;
+ function createBinary(left, operator, right) {
+ var node = createSynthesizedNode(193 /* BinaryExpression */);
+ var operatorToken = asToken(operator);
var operatorKind = operatorToken.kind;
- var node = createNode(192 /* BinaryExpression */, location);
- node.left = parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
+ node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
node.operatorToken = operatorToken;
- node.right = parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
+ node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
return node;
}
ts.createBinary = createBinary;
function updateBinary(node, left, right) {
- if (node.left !== left || node.right !== right) {
- return updateNode(createBinary(left, node.operatorToken, right, /*location*/ node), node);
- }
- return node;
+ return node.left !== left
+ || node.right !== right
+ ? updateNode(createBinary(left, node.operatorToken, right), node)
+ : node;
}
ts.updateBinary = updateBinary;
- function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonTokenOrLocation, whenFalse, location) {
- var node = createNode(193 /* ConditionalExpression */, whenFalse ? location : colonTokenOrLocation);
- node.condition = parenthesizeForConditionalHead(condition);
- if (whenFalse) {
- // second overload
- node.questionToken = questionTokenOrWhenTrue;
- node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse);
- node.colonToken = colonTokenOrLocation;
- node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenFalse);
- }
- else {
- // first overload
- node.questionToken = createToken(54 /* QuestionToken */);
- node.whenTrue = parenthesizeSubexpressionOfConditionalExpression(questionTokenOrWhenTrue);
- node.colonToken = createToken(55 /* ColonToken */);
- node.whenFalse = parenthesizeSubexpressionOfConditionalExpression(whenTrueOrWhenFalse);
- }
+ function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
+ var node = createSynthesizedNode(194 /* ConditionalExpression */);
+ node.condition = ts.parenthesizeForConditionalHead(condition);
+ node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(54 /* QuestionToken */);
+ node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue);
+ node.colonToken = whenFalse ? colonToken : createToken(55 /* ColonToken */);
+ node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
return node;
}
ts.createConditional = createConditional;
function updateConditional(node, condition, whenTrue, whenFalse) {
- if (node.condition !== condition || node.whenTrue !== whenTrue || node.whenFalse !== whenFalse) {
- return updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse, node), node);
- }
- return node;
+ return node.condition !== condition
+ || node.whenTrue !== whenTrue
+ || node.whenFalse !== whenFalse
+ ? updateNode(createConditional(condition, node.questionToken, whenTrue, node.colonToken, whenFalse), node)
+ : node;
}
ts.updateConditional = updateConditional;
- function createTemplateExpression(head, templateSpans, location) {
- var node = createNode(194 /* TemplateExpression */, location);
+ function createTemplateExpression(head, templateSpans) {
+ var node = createSynthesizedNode(195 /* TemplateExpression */);
node.head = head;
node.templateSpans = createNodeArray(templateSpans);
return node;
}
ts.createTemplateExpression = createTemplateExpression;
function updateTemplateExpression(node, head, templateSpans) {
- if (node.head !== head || node.templateSpans !== templateSpans) {
- return updateNode(createTemplateExpression(head, templateSpans, node), node);
- }
- return node;
+ return node.head !== head
+ || node.templateSpans !== templateSpans
+ ? updateNode(createTemplateExpression(head, templateSpans), node)
+ : node;
}
ts.updateTemplateExpression = updateTemplateExpression;
- function createYield(asteriskToken, expression, location) {
- var node = createNode(195 /* YieldExpression */, location);
- node.asteriskToken = asteriskToken;
- node.expression = expression;
+ function createYield(asteriskTokenOrExpression, expression) {
+ var node = createSynthesizedNode(196 /* YieldExpression */);
+ node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 38 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined;
+ node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 38 /* AsteriskToken */ ? asteriskTokenOrExpression : expression;
return node;
}
ts.createYield = createYield;
- function updateYield(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createYield(node.asteriskToken, expression, node), node);
- }
- return node;
+ function updateYield(node, asteriskToken, expression) {
+ return node.expression !== expression
+ || node.asteriskToken !== asteriskToken
+ ? updateNode(createYield(asteriskToken, expression), node)
+ : node;
}
ts.updateYield = updateYield;
- function createSpread(expression, location) {
- var node = createNode(196 /* SpreadElement */, location);
- node.expression = parenthesizeExpressionForList(expression);
+ function createSpread(expression) {
+ var node = createSynthesizedNode(197 /* SpreadElement */);
+ node.expression = ts.parenthesizeExpressionForList(expression);
return node;
}
ts.createSpread = createSpread;
function updateSpread(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createSpread(expression, node), node);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createSpread(expression), node)
+ : node;
}
ts.updateSpread = updateSpread;
- function createClassExpression(modifiers, name, typeParameters, heritageClauses, members, location) {
- var node = createNode(197 /* ClassExpression */, location);
+ function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
+ var node = createSynthesizedNode(198 /* ClassExpression */);
node.decorators = undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
- node.name = name;
- node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined;
- node.heritageClauses = createNodeArray(heritageClauses);
+ node.modifiers = asNodeArray(modifiers);
+ node.name = asName(name);
+ node.typeParameters = asNodeArray(typeParameters);
+ node.heritageClauses = asNodeArray(heritageClauses);
node.members = createNodeArray(members);
return node;
}
ts.createClassExpression = createClassExpression;
function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
- if (node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) {
- return updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members, node), node);
- }
- return node;
+ return node.modifiers !== modifiers
+ || node.name !== name
+ || node.typeParameters !== typeParameters
+ || node.heritageClauses !== heritageClauses
+ || node.members !== members
+ ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
+ : node;
}
ts.updateClassExpression = updateClassExpression;
- function createOmittedExpression(location) {
- var node = createNode(198 /* OmittedExpression */, location);
- return node;
+ function createOmittedExpression() {
+ return createSynthesizedNode(199 /* OmittedExpression */);
}
ts.createOmittedExpression = createOmittedExpression;
- function createExpressionWithTypeArguments(typeArguments, expression, location) {
- var node = createNode(199 /* ExpressionWithTypeArguments */, location);
- node.typeArguments = typeArguments ? createNodeArray(typeArguments) : undefined;
- node.expression = parenthesizeForAccess(expression);
+ function createExpressionWithTypeArguments(typeArguments, expression) {
+ var node = createSynthesizedNode(200 /* ExpressionWithTypeArguments */);
+ node.expression = ts.parenthesizeForAccess(expression);
+ node.typeArguments = asNodeArray(typeArguments);
return node;
}
ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments;
function updateExpressionWithTypeArguments(node, typeArguments, expression) {
- if (node.typeArguments !== typeArguments || node.expression !== expression) {
- return updateNode(createExpressionWithTypeArguments(typeArguments, expression, node), node);
- }
- return node;
+ return node.typeArguments !== typeArguments
+ || node.expression !== expression
+ ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
+ : node;
}
ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments;
+ function createAsExpression(expression, type) {
+ var node = createSynthesizedNode(201 /* AsExpression */);
+ node.expression = expression;
+ node.type = type;
+ return node;
+ }
+ ts.createAsExpression = createAsExpression;
+ function updateAsExpression(node, expression, type) {
+ return node.expression !== expression
+ || node.type !== type
+ ? updateNode(createAsExpression(expression, type), node)
+ : node;
+ }
+ ts.updateAsExpression = updateAsExpression;
+ function createNonNullExpression(expression) {
+ var node = createSynthesizedNode(202 /* NonNullExpression */);
+ node.expression = ts.parenthesizeForAccess(expression);
+ return node;
+ }
+ ts.createNonNullExpression = createNonNullExpression;
+ function updateNonNullExpression(node, expression) {
+ return node.expression !== expression
+ ? updateNode(createNonNullExpression(expression), node)
+ : node;
+ }
+ ts.updateNonNullExpression = updateNonNullExpression;
// Misc
- function createTemplateSpan(expression, literal, location) {
- var node = createNode(202 /* TemplateSpan */, location);
+ function createTemplateSpan(expression, literal) {
+ var node = createSynthesizedNode(204 /* TemplateSpan */);
node.expression = expression;
node.literal = literal;
return node;
}
ts.createTemplateSpan = createTemplateSpan;
function updateTemplateSpan(node, expression, literal) {
- if (node.expression !== expression || node.literal !== literal) {
- return updateNode(createTemplateSpan(expression, literal, node), node);
- }
- return node;
+ return node.expression !== expression
+ || node.literal !== literal
+ ? updateNode(createTemplateSpan(expression, literal), node)
+ : node;
}
ts.updateTemplateSpan = updateTemplateSpan;
// Element
- function createBlock(statements, location, multiLine, flags) {
- var block = createNode(204 /* Block */, location, flags);
+ function createBlock(statements, multiLine) {
+ var block = createSynthesizedNode(206 /* Block */);
block.statements = createNodeArray(statements);
- if (multiLine) {
- block.multiLine = true;
- }
+ if (multiLine)
+ block.multiLine = multiLine;
return block;
}
ts.createBlock = createBlock;
function updateBlock(node, statements) {
- if (statements !== node.statements) {
- return updateNode(createBlock(statements, /*location*/ node, node.multiLine, node.flags), node);
- }
- return node;
+ return statements !== node.statements
+ ? updateNode(createBlock(statements, node.multiLine), node)
+ : node;
}
ts.updateBlock = updateBlock;
- function createVariableStatement(modifiers, declarationList, location, flags) {
- var node = createNode(205 /* VariableStatement */, location, flags);
+ function createVariableStatement(modifiers, declarationList) {
+ var node = createSynthesizedNode(207 /* VariableStatement */);
node.decorators = undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
+ node.modifiers = asNodeArray(modifiers);
node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
return node;
}
ts.createVariableStatement = createVariableStatement;
function updateVariableStatement(node, modifiers, declarationList) {
- if (node.modifiers !== modifiers || node.declarationList !== declarationList) {
- return updateNode(createVariableStatement(modifiers, declarationList, /*location*/ node, node.flags), node);
- }
- return node;
+ return node.modifiers !== modifiers
+ || node.declarationList !== declarationList
+ ? updateNode(createVariableStatement(modifiers, declarationList), node)
+ : node;
}
ts.updateVariableStatement = updateVariableStatement;
- function createVariableDeclarationList(declarations, location, flags) {
- var node = createNode(224 /* VariableDeclarationList */, location, flags);
+ function createVariableDeclarationList(declarations, flags) {
+ var node = createSynthesizedNode(226 /* VariableDeclarationList */);
+ node.flags |= flags;
node.declarations = createNodeArray(declarations);
return node;
}
ts.createVariableDeclarationList = createVariableDeclarationList;
function updateVariableDeclarationList(node, declarations) {
- if (node.declarations !== declarations) {
- return updateNode(createVariableDeclarationList(declarations, /*location*/ node, node.flags), node);
- }
- return node;
+ return node.declarations !== declarations
+ ? updateNode(createVariableDeclarationList(declarations, node.flags), node)
+ : node;
}
ts.updateVariableDeclarationList = updateVariableDeclarationList;
- function createVariableDeclaration(name, type, initializer, location, flags) {
- var node = createNode(223 /* VariableDeclaration */, location, flags);
- node.name = typeof name === "string" ? createIdentifier(name) : name;
+ function createVariableDeclaration(name, type, initializer) {
+ var node = createSynthesizedNode(225 /* VariableDeclaration */);
+ node.name = asName(name);
node.type = type;
- node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined;
+ node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
return node;
}
ts.createVariableDeclaration = createVariableDeclaration;
function updateVariableDeclaration(node, name, type, initializer) {
- if (node.name !== name || node.type !== type || node.initializer !== initializer) {
- return updateNode(createVariableDeclaration(name, type, initializer, /*location*/ node, node.flags), node);
- }
- return node;
+ return node.name !== name
+ || node.type !== type
+ || node.initializer !== initializer
+ ? updateNode(createVariableDeclaration(name, type, initializer), node)
+ : node;
}
ts.updateVariableDeclaration = updateVariableDeclaration;
- function createEmptyStatement(location) {
- return createNode(206 /* EmptyStatement */, location);
+ function createEmptyStatement() {
+ return createSynthesizedNode(208 /* EmptyStatement */);
}
ts.createEmptyStatement = createEmptyStatement;
- function createStatement(expression, location, flags) {
- var node = createNode(207 /* ExpressionStatement */, location, flags);
- node.expression = parenthesizeExpressionForExpressionStatement(expression);
+ function createStatement(expression) {
+ var node = createSynthesizedNode(209 /* ExpressionStatement */);
+ node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
return node;
}
ts.createStatement = createStatement;
function updateStatement(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createStatement(expression, /*location*/ node, node.flags), node);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createStatement(expression), node)
+ : node;
}
ts.updateStatement = updateStatement;
- function createIf(expression, thenStatement, elseStatement, location) {
- var node = createNode(208 /* IfStatement */, location);
+ function createIf(expression, thenStatement, elseStatement) {
+ var node = createSynthesizedNode(210 /* IfStatement */);
node.expression = expression;
node.thenStatement = thenStatement;
node.elseStatement = elseStatement;
@@ -11457,42 +12021,43 @@ var ts;
}
ts.createIf = createIf;
function updateIf(node, expression, thenStatement, elseStatement) {
- if (node.expression !== expression || node.thenStatement !== thenStatement || node.elseStatement !== elseStatement) {
- return updateNode(createIf(expression, thenStatement, elseStatement, /*location*/ node), node);
- }
- return node;
+ return node.expression !== expression
+ || node.thenStatement !== thenStatement
+ || node.elseStatement !== elseStatement
+ ? updateNode(createIf(expression, thenStatement, elseStatement), node)
+ : node;
}
ts.updateIf = updateIf;
- function createDo(statement, expression, location) {
- var node = createNode(209 /* DoStatement */, location);
+ function createDo(statement, expression) {
+ var node = createSynthesizedNode(211 /* DoStatement */);
node.statement = statement;
node.expression = expression;
return node;
}
ts.createDo = createDo;
function updateDo(node, statement, expression) {
- if (node.statement !== statement || node.expression !== expression) {
- return updateNode(createDo(statement, expression, node), node);
- }
- return node;
+ return node.statement !== statement
+ || node.expression !== expression
+ ? updateNode(createDo(statement, expression), node)
+ : node;
}
ts.updateDo = updateDo;
- function createWhile(expression, statement, location) {
- var node = createNode(210 /* WhileStatement */, location);
+ function createWhile(expression, statement) {
+ var node = createSynthesizedNode(212 /* WhileStatement */);
node.expression = expression;
node.statement = statement;
return node;
}
ts.createWhile = createWhile;
function updateWhile(node, expression, statement) {
- if (node.expression !== expression || node.statement !== statement) {
- return updateNode(createWhile(expression, statement, node), node);
- }
- return node;
+ return node.expression !== expression
+ || node.statement !== statement
+ ? updateNode(createWhile(expression, statement), node)
+ : node;
}
ts.updateWhile = updateWhile;
- function createFor(initializer, condition, incrementor, statement, location) {
- var node = createNode(211 /* ForStatement */, location, /*flags*/ undefined);
+ function createFor(initializer, condition, incrementor, statement) {
+ var node = createSynthesizedNode(213 /* ForStatement */);
node.initializer = initializer;
node.condition = condition;
node.incrementor = incrementor;
@@ -11501,14 +12066,16 @@ var ts;
}
ts.createFor = createFor;
function updateFor(node, initializer, condition, incrementor, statement) {
- if (node.initializer !== initializer || node.condition !== condition || node.incrementor !== incrementor || node.statement !== statement) {
- return updateNode(createFor(initializer, condition, incrementor, statement, node), node);
- }
- return node;
+ return node.initializer !== initializer
+ || node.condition !== condition
+ || node.incrementor !== incrementor
+ || node.statement !== statement
+ ? updateNode(createFor(initializer, condition, incrementor, statement), node)
+ : node;
}
ts.updateFor = updateFor;
- function createForIn(initializer, expression, statement, location) {
- var node = createNode(212 /* ForInStatement */, location);
+ function createForIn(initializer, expression, statement) {
+ var node = createSynthesizedNode(214 /* ForInStatement */);
node.initializer = initializer;
node.expression = expression;
node.statement = statement;
@@ -11516,127 +12083,123 @@ var ts;
}
ts.createForIn = createForIn;
function updateForIn(node, initializer, expression, statement) {
- if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) {
- return updateNode(createForIn(initializer, expression, statement, node), node);
- }
- return node;
+ return node.initializer !== initializer
+ || node.expression !== expression
+ || node.statement !== statement
+ ? updateNode(createForIn(initializer, expression, statement), node)
+ : node;
}
ts.updateForIn = updateForIn;
- function createForOf(initializer, expression, statement, location) {
- var node = createNode(213 /* ForOfStatement */, location);
+ function createForOf(awaitModifier, initializer, expression, statement) {
+ var node = createSynthesizedNode(215 /* ForOfStatement */);
+ node.awaitModifier = awaitModifier;
node.initializer = initializer;
node.expression = expression;
node.statement = statement;
return node;
}
ts.createForOf = createForOf;
- function updateForOf(node, initializer, expression, statement) {
- if (node.initializer !== initializer || node.expression !== expression || node.statement !== statement) {
- return updateNode(createForOf(initializer, expression, statement, node), node);
- }
- return node;
+ function updateForOf(node, awaitModifier, initializer, expression, statement) {
+ return node.awaitModifier !== awaitModifier
+ || node.initializer !== initializer
+ || node.expression !== expression
+ || node.statement !== statement
+ ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node)
+ : node;
}
ts.updateForOf = updateForOf;
- function createContinue(label, location) {
- var node = createNode(214 /* ContinueStatement */, location);
- if (label) {
- node.label = label;
- }
+ function createContinue(label) {
+ var node = createSynthesizedNode(216 /* ContinueStatement */);
+ node.label = asName(label);
return node;
}
ts.createContinue = createContinue;
function updateContinue(node, label) {
- if (node.label !== label) {
- return updateNode(createContinue(label, node), node);
- }
- return node;
+ return node.label !== label
+ ? updateNode(createContinue(label), node)
+ : node;
}
ts.updateContinue = updateContinue;
- function createBreak(label, location) {
- var node = createNode(215 /* BreakStatement */, location);
- if (label) {
- node.label = label;
- }
+ function createBreak(label) {
+ var node = createSynthesizedNode(217 /* BreakStatement */);
+ node.label = asName(label);
return node;
}
ts.createBreak = createBreak;
function updateBreak(node, label) {
- if (node.label !== label) {
- return updateNode(createBreak(label, node), node);
- }
- return node;
+ return node.label !== label
+ ? updateNode(createBreak(label), node)
+ : node;
}
ts.updateBreak = updateBreak;
- function createReturn(expression, location) {
- var node = createNode(216 /* ReturnStatement */, location);
+ function createReturn(expression) {
+ var node = createSynthesizedNode(218 /* ReturnStatement */);
node.expression = expression;
return node;
}
ts.createReturn = createReturn;
function updateReturn(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createReturn(expression, /*location*/ node), node);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createReturn(expression), node)
+ : node;
}
ts.updateReturn = updateReturn;
- function createWith(expression, statement, location) {
- var node = createNode(217 /* WithStatement */, location);
+ function createWith(expression, statement) {
+ var node = createSynthesizedNode(219 /* WithStatement */);
node.expression = expression;
node.statement = statement;
return node;
}
ts.createWith = createWith;
function updateWith(node, expression, statement) {
- if (node.expression !== expression || node.statement !== statement) {
- return updateNode(createWith(expression, statement, node), node);
- }
- return node;
+ return node.expression !== expression
+ || node.statement !== statement
+ ? updateNode(createWith(expression, statement), node)
+ : node;
}
ts.updateWith = updateWith;
- function createSwitch(expression, caseBlock, location) {
- var node = createNode(218 /* SwitchStatement */, location);
- node.expression = parenthesizeExpressionForList(expression);
+ function createSwitch(expression, caseBlock) {
+ var node = createSynthesizedNode(220 /* SwitchStatement */);
+ node.expression = ts.parenthesizeExpressionForList(expression);
node.caseBlock = caseBlock;
return node;
}
ts.createSwitch = createSwitch;
function updateSwitch(node, expression, caseBlock) {
- if (node.expression !== expression || node.caseBlock !== caseBlock) {
- return updateNode(createSwitch(expression, caseBlock, node), node);
- }
- return node;
+ return node.expression !== expression
+ || node.caseBlock !== caseBlock
+ ? updateNode(createSwitch(expression, caseBlock), node)
+ : node;
}
ts.updateSwitch = updateSwitch;
- function createLabel(label, statement, location) {
- var node = createNode(219 /* LabeledStatement */, location);
- node.label = typeof label === "string" ? createIdentifier(label) : label;
+ function createLabel(label, statement) {
+ var node = createSynthesizedNode(221 /* LabeledStatement */);
+ node.label = asName(label);
node.statement = statement;
return node;
}
ts.createLabel = createLabel;
function updateLabel(node, label, statement) {
- if (node.label !== label || node.statement !== statement) {
- return updateNode(createLabel(label, statement, node), node);
- }
- return node;
+ return node.label !== label
+ || node.statement !== statement
+ ? updateNode(createLabel(label, statement), node)
+ : node;
}
ts.updateLabel = updateLabel;
- function createThrow(expression, location) {
- var node = createNode(220 /* ThrowStatement */, location);
+ function createThrow(expression) {
+ var node = createSynthesizedNode(222 /* ThrowStatement */);
node.expression = expression;
return node;
}
ts.createThrow = createThrow;
function updateThrow(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createThrow(expression, node), node);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createThrow(expression), node)
+ : node;
}
ts.updateThrow = updateThrow;
- function createTry(tryBlock, catchClause, finallyBlock, location) {
- var node = createNode(221 /* TryStatement */, location);
+ function createTry(tryBlock, catchClause, finallyBlock) {
+ var node = createSynthesizedNode(223 /* TryStatement */);
node.tryBlock = tryBlock;
node.catchClause = catchClause;
node.finallyBlock = finallyBlock;
@@ -11644,195 +12207,286 @@ var ts;
}
ts.createTry = createTry;
function updateTry(node, tryBlock, catchClause, finallyBlock) {
- if (node.tryBlock !== tryBlock || node.catchClause !== catchClause || node.finallyBlock !== finallyBlock) {
- return updateNode(createTry(tryBlock, catchClause, finallyBlock, node), node);
- }
- return node;
+ return node.tryBlock !== tryBlock
+ || node.catchClause !== catchClause
+ || node.finallyBlock !== finallyBlock
+ ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
+ : node;
}
ts.updateTry = updateTry;
- function createCaseBlock(clauses, location) {
- var node = createNode(232 /* CaseBlock */, location);
- node.clauses = createNodeArray(clauses);
- return node;
- }
- ts.createCaseBlock = createCaseBlock;
- function updateCaseBlock(node, clauses) {
- if (node.clauses !== clauses) {
- return updateNode(createCaseBlock(clauses, node), node);
- }
- return node;
- }
- ts.updateCaseBlock = updateCaseBlock;
- function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body, location, flags) {
- var node = createNode(225 /* FunctionDeclaration */, location, flags);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
+ function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
+ var node = createSynthesizedNode(227 /* FunctionDeclaration */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
node.asteriskToken = asteriskToken;
- node.name = typeof name === "string" ? createIdentifier(name) : name;
- node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined;
+ node.name = asName(name);
+ node.typeParameters = asNodeArray(typeParameters);
node.parameters = createNodeArray(parameters);
node.type = type;
node.body = body;
return node;
}
ts.createFunctionDeclaration = createFunctionDeclaration;
- function updateFunctionDeclaration(node, decorators, modifiers, name, typeParameters, parameters, type, body) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) {
- return updateNode(createFunctionDeclaration(decorators, modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node);
- }
- return node;
+ function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.asteriskToken !== asteriskToken
+ || node.name !== name
+ || node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.body !== body
+ ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
+ : node;
}
ts.updateFunctionDeclaration = updateFunctionDeclaration;
- function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, location) {
- var node = createNode(226 /* ClassDeclaration */, location);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
- node.name = name;
- node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined;
- node.heritageClauses = createNodeArray(heritageClauses);
+ function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
+ var node = createSynthesizedNode(228 /* ClassDeclaration */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
+ node.name = asName(name);
+ node.typeParameters = asNodeArray(typeParameters);
+ node.heritageClauses = asNodeArray(heritageClauses);
node.members = createNodeArray(members);
return node;
}
ts.createClassDeclaration = createClassDeclaration;
function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.typeParameters !== typeParameters || node.heritageClauses !== heritageClauses || node.members !== members) {
- return updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members, node), node);
- }
- return node;
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.typeParameters !== typeParameters
+ || node.heritageClauses !== heritageClauses
+ || node.members !== members
+ ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
+ : node;
}
ts.updateClassDeclaration = updateClassDeclaration;
- function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, location) {
- var node = createNode(235 /* ImportDeclaration */, location);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
+ function createEnumDeclaration(decorators, modifiers, name, members) {
+ var node = createSynthesizedNode(231 /* EnumDeclaration */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
+ node.name = asName(name);
+ node.members = createNodeArray(members);
+ return node;
+ }
+ ts.createEnumDeclaration = createEnumDeclaration;
+ function updateEnumDeclaration(node, decorators, modifiers, name, members) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.members !== members
+ ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
+ : node;
+ }
+ ts.updateEnumDeclaration = updateEnumDeclaration;
+ function createModuleDeclaration(decorators, modifiers, name, body, flags) {
+ var node = createSynthesizedNode(232 /* ModuleDeclaration */);
+ node.flags |= flags;
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
+ node.name = name;
+ node.body = body;
+ return node;
+ }
+ ts.createModuleDeclaration = createModuleDeclaration;
+ function updateModuleDeclaration(node, decorators, modifiers, name, body) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.body !== body
+ ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
+ : node;
+ }
+ ts.updateModuleDeclaration = updateModuleDeclaration;
+ function createModuleBlock(statements) {
+ var node = createSynthesizedNode(233 /* ModuleBlock */);
+ node.statements = createNodeArray(statements);
+ return node;
+ }
+ ts.createModuleBlock = createModuleBlock;
+ function updateModuleBlock(node, statements) {
+ return node.statements !== statements
+ ? updateNode(createModuleBlock(statements), node)
+ : node;
+ }
+ ts.updateModuleBlock = updateModuleBlock;
+ function createCaseBlock(clauses) {
+ var node = createSynthesizedNode(234 /* CaseBlock */);
+ node.clauses = createNodeArray(clauses);
+ return node;
+ }
+ ts.createCaseBlock = createCaseBlock;
+ function updateCaseBlock(node, clauses) {
+ return node.clauses !== clauses
+ ? updateNode(createCaseBlock(clauses), node)
+ : node;
+ }
+ ts.updateCaseBlock = updateCaseBlock;
+ function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
+ var node = createSynthesizedNode(236 /* ImportEqualsDeclaration */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
+ node.name = asName(name);
+ node.moduleReference = moduleReference;
+ return node;
+ }
+ ts.createImportEqualsDeclaration = createImportEqualsDeclaration;
+ function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.name !== name
+ || node.moduleReference !== moduleReference
+ ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
+ : node;
+ }
+ ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration;
+ function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
+ var node = createSynthesizedNode(237 /* ImportDeclaration */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
node.importClause = importClause;
node.moduleSpecifier = moduleSpecifier;
return node;
}
ts.createImportDeclaration = createImportDeclaration;
function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier) {
- return updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, node), node);
- }
- return node;
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.importClause !== importClause || node.moduleSpecifier !== moduleSpecifier
+ ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
+ : node;
}
ts.updateImportDeclaration = updateImportDeclaration;
- function createImportClause(name, namedBindings, location) {
- var node = createNode(236 /* ImportClause */, location);
+ function createImportClause(name, namedBindings) {
+ var node = createSynthesizedNode(238 /* ImportClause */);
node.name = name;
node.namedBindings = namedBindings;
return node;
}
ts.createImportClause = createImportClause;
function updateImportClause(node, name, namedBindings) {
- if (node.name !== name || node.namedBindings !== namedBindings) {
- return updateNode(createImportClause(name, namedBindings, node), node);
- }
- return node;
+ return node.name !== name
+ || node.namedBindings !== namedBindings
+ ? updateNode(createImportClause(name, namedBindings), node)
+ : node;
}
ts.updateImportClause = updateImportClause;
- function createNamespaceImport(name, location) {
- var node = createNode(237 /* NamespaceImport */, location);
+ function createNamespaceImport(name) {
+ var node = createSynthesizedNode(239 /* NamespaceImport */);
node.name = name;
return node;
}
ts.createNamespaceImport = createNamespaceImport;
function updateNamespaceImport(node, name) {
- if (node.name !== name) {
- return updateNode(createNamespaceImport(name, node), node);
- }
- return node;
+ return node.name !== name
+ ? updateNode(createNamespaceImport(name), node)
+ : node;
}
ts.updateNamespaceImport = updateNamespaceImport;
- function createNamedImports(elements, location) {
- var node = createNode(238 /* NamedImports */, location);
+ function createNamedImports(elements) {
+ var node = createSynthesizedNode(240 /* NamedImports */);
node.elements = createNodeArray(elements);
return node;
}
ts.createNamedImports = createNamedImports;
function updateNamedImports(node, elements) {
- if (node.elements !== elements) {
- return updateNode(createNamedImports(elements, node), node);
- }
- return node;
+ return node.elements !== elements
+ ? updateNode(createNamedImports(elements), node)
+ : node;
}
ts.updateNamedImports = updateNamedImports;
- function createImportSpecifier(propertyName, name, location) {
- var node = createNode(239 /* ImportSpecifier */, location);
+ function createImportSpecifier(propertyName, name) {
+ var node = createSynthesizedNode(241 /* ImportSpecifier */);
node.propertyName = propertyName;
node.name = name;
return node;
}
ts.createImportSpecifier = createImportSpecifier;
function updateImportSpecifier(node, propertyName, name) {
- if (node.propertyName !== propertyName || node.name !== name) {
- return updateNode(createImportSpecifier(propertyName, name, node), node);
- }
- return node;
+ return node.propertyName !== propertyName
+ || node.name !== name
+ ? updateNode(createImportSpecifier(propertyName, name), node)
+ : node;
}
ts.updateImportSpecifier = updateImportSpecifier;
- function createExportAssignment(decorators, modifiers, isExportEquals, expression, location) {
- var node = createNode(240 /* ExportAssignment */, location);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
+ function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
+ var node = createSynthesizedNode(242 /* ExportAssignment */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
node.isExportEquals = isExportEquals;
node.expression = expression;
return node;
}
ts.createExportAssignment = createExportAssignment;
function updateExportAssignment(node, decorators, modifiers, expression) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.expression !== expression) {
- return updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression, node), node);
- }
- return node;
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.expression !== expression
+ ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
+ : node;
}
ts.updateExportAssignment = updateExportAssignment;
- function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, location) {
- var node = createNode(241 /* ExportDeclaration */, location);
- node.decorators = decorators ? createNodeArray(decorators) : undefined;
- node.modifiers = modifiers ? createNodeArray(modifiers) : undefined;
+ function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) {
+ var node = createSynthesizedNode(243 /* ExportDeclaration */);
+ node.decorators = asNodeArray(decorators);
+ node.modifiers = asNodeArray(modifiers);
node.exportClause = exportClause;
node.moduleSpecifier = moduleSpecifier;
return node;
}
ts.createExportDeclaration = createExportDeclaration;
function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier) {
- if (node.decorators !== decorators || node.modifiers !== modifiers || node.exportClause !== exportClause || node.moduleSpecifier !== moduleSpecifier) {
- return updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, node), node);
- }
- return node;
+ return node.decorators !== decorators
+ || node.modifiers !== modifiers
+ || node.exportClause !== exportClause
+ || node.moduleSpecifier !== moduleSpecifier
+ ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier), node)
+ : node;
}
ts.updateExportDeclaration = updateExportDeclaration;
- function createNamedExports(elements, location) {
- var node = createNode(242 /* NamedExports */, location);
+ function createNamedExports(elements) {
+ var node = createSynthesizedNode(244 /* NamedExports */);
node.elements = createNodeArray(elements);
return node;
}
ts.createNamedExports = createNamedExports;
function updateNamedExports(node, elements) {
- if (node.elements !== elements) {
- return updateNode(createNamedExports(elements, node), node);
- }
- return node;
+ return node.elements !== elements
+ ? updateNode(createNamedExports(elements), node)
+ : node;
}
ts.updateNamedExports = updateNamedExports;
- function createExportSpecifier(name, propertyName, location) {
- var node = createNode(243 /* ExportSpecifier */, location);
- node.name = typeof name === "string" ? createIdentifier(name) : name;
- node.propertyName = typeof propertyName === "string" ? createIdentifier(propertyName) : propertyName;
+ function createExportSpecifier(propertyName, name) {
+ var node = createSynthesizedNode(245 /* ExportSpecifier */);
+ node.propertyName = asName(propertyName);
+ node.name = asName(name);
return node;
}
ts.createExportSpecifier = createExportSpecifier;
- function updateExportSpecifier(node, name, propertyName) {
- if (node.name !== name || node.propertyName !== propertyName) {
- return updateNode(createExportSpecifier(name, propertyName, node), node);
- }
- return node;
+ function updateExportSpecifier(node, propertyName, name) {
+ return node.propertyName !== propertyName
+ || node.name !== name
+ ? updateNode(createExportSpecifier(propertyName, name), node)
+ : node;
}
ts.updateExportSpecifier = updateExportSpecifier;
+ // Module references
+ function createExternalModuleReference(expression) {
+ var node = createSynthesizedNode(247 /* ExternalModuleReference */);
+ node.expression = expression;
+ return node;
+ }
+ ts.createExternalModuleReference = createExternalModuleReference;
+ function updateExternalModuleReference(node, expression) {
+ return node.expression !== expression
+ ? updateNode(createExternalModuleReference(expression), node)
+ : node;
+ }
+ ts.updateExternalModuleReference = updateExternalModuleReference;
// JSX
- function createJsxElement(openingElement, children, closingElement, location) {
- var node = createNode(246 /* JsxElement */, location);
+ function createJsxElement(openingElement, children, closingElement) {
+ var node = createSynthesizedNode(248 /* JsxElement */);
node.openingElement = openingElement;
node.children = createNodeArray(children);
node.closingElement = closingElement;
@@ -11840,96 +12494,108 @@ var ts;
}
ts.createJsxElement = createJsxElement;
function updateJsxElement(node, openingElement, children, closingElement) {
- if (node.openingElement !== openingElement || node.children !== children || node.closingElement !== closingElement) {
- return updateNode(createJsxElement(openingElement, children, closingElement, node), node);
- }
- return node;
+ return node.openingElement !== openingElement
+ || node.children !== children
+ || node.closingElement !== closingElement
+ ? updateNode(createJsxElement(openingElement, children, closingElement), node)
+ : node;
}
ts.updateJsxElement = updateJsxElement;
- function createJsxSelfClosingElement(tagName, attributes, location) {
- var node = createNode(247 /* JsxSelfClosingElement */, location);
+ function createJsxSelfClosingElement(tagName, attributes) {
+ var node = createSynthesizedNode(249 /* JsxSelfClosingElement */);
node.tagName = tagName;
- node.attributes = createNodeArray(attributes);
+ node.attributes = attributes;
return node;
}
ts.createJsxSelfClosingElement = createJsxSelfClosingElement;
function updateJsxSelfClosingElement(node, tagName, attributes) {
- if (node.tagName !== tagName || node.attributes !== attributes) {
- return updateNode(createJsxSelfClosingElement(tagName, attributes, node), node);
- }
- return node;
+ return node.tagName !== tagName
+ || node.attributes !== attributes
+ ? updateNode(createJsxSelfClosingElement(tagName, attributes), node)
+ : node;
}
ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement;
- function createJsxOpeningElement(tagName, attributes, location) {
- var node = createNode(248 /* JsxOpeningElement */, location);
+ function createJsxOpeningElement(tagName, attributes) {
+ var node = createSynthesizedNode(250 /* JsxOpeningElement */);
node.tagName = tagName;
- node.attributes = createNodeArray(attributes);
+ node.attributes = attributes;
return node;
}
ts.createJsxOpeningElement = createJsxOpeningElement;
function updateJsxOpeningElement(node, tagName, attributes) {
- if (node.tagName !== tagName || node.attributes !== attributes) {
- return updateNode(createJsxOpeningElement(tagName, attributes, node), node);
- }
- return node;
+ return node.tagName !== tagName
+ || node.attributes !== attributes
+ ? updateNode(createJsxOpeningElement(tagName, attributes), node)
+ : node;
}
ts.updateJsxOpeningElement = updateJsxOpeningElement;
- function createJsxClosingElement(tagName, location) {
- var node = createNode(249 /* JsxClosingElement */, location);
+ function createJsxClosingElement(tagName) {
+ var node = createSynthesizedNode(251 /* JsxClosingElement */);
node.tagName = tagName;
return node;
}
ts.createJsxClosingElement = createJsxClosingElement;
function updateJsxClosingElement(node, tagName) {
- if (node.tagName !== tagName) {
- return updateNode(createJsxClosingElement(tagName, node), node);
- }
- return node;
+ return node.tagName !== tagName
+ ? updateNode(createJsxClosingElement(tagName), node)
+ : node;
}
ts.updateJsxClosingElement = updateJsxClosingElement;
- function createJsxAttribute(name, initializer, location) {
- var node = createNode(250 /* JsxAttribute */, location);
+ function createJsxAttributes(properties) {
+ var jsxAttributes = createSynthesizedNode(253 /* JsxAttributes */);
+ jsxAttributes.properties = createNodeArray(properties);
+ return jsxAttributes;
+ }
+ ts.createJsxAttributes = createJsxAttributes;
+ function updateJsxAttributes(jsxAttributes, properties) {
+ if (jsxAttributes.properties !== properties) {
+ return updateNode(createJsxAttributes(properties), jsxAttributes);
+ }
+ return jsxAttributes;
+ }
+ ts.updateJsxAttributes = updateJsxAttributes;
+ function createJsxAttribute(name, initializer) {
+ var node = createSynthesizedNode(252 /* JsxAttribute */);
node.name = name;
node.initializer = initializer;
return node;
}
ts.createJsxAttribute = createJsxAttribute;
function updateJsxAttribute(node, name, initializer) {
- if (node.name !== name || node.initializer !== initializer) {
- return updateNode(createJsxAttribute(name, initializer, node), node);
- }
- return node;
+ return node.name !== name
+ || node.initializer !== initializer
+ ? updateNode(createJsxAttribute(name, initializer), node)
+ : node;
}
ts.updateJsxAttribute = updateJsxAttribute;
- function createJsxSpreadAttribute(expression, location) {
- var node = createNode(251 /* JsxSpreadAttribute */, location);
+ function createJsxSpreadAttribute(expression) {
+ var node = createSynthesizedNode(254 /* JsxSpreadAttribute */);
node.expression = expression;
return node;
}
ts.createJsxSpreadAttribute = createJsxSpreadAttribute;
function updateJsxSpreadAttribute(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createJsxSpreadAttribute(expression, node), node);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createJsxSpreadAttribute(expression), node)
+ : node;
}
ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute;
- function createJsxExpression(expression, location) {
- var node = createNode(252 /* JsxExpression */, location);
+ function createJsxExpression(dotDotDotToken, expression) {
+ var node = createSynthesizedNode(255 /* JsxExpression */);
+ node.dotDotDotToken = dotDotDotToken;
node.expression = expression;
return node;
}
ts.createJsxExpression = createJsxExpression;
function updateJsxExpression(node, expression) {
- if (node.expression !== expression) {
- return updateNode(createJsxExpression(expression, node), node);
- }
- return node;
+ return node.expression !== expression
+ ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node)
+ : node;
}
ts.updateJsxExpression = updateJsxExpression;
// Clauses
- function createHeritageClause(token, types, location) {
- var node = createNode(255 /* HeritageClause */, location);
+ function createHeritageClause(token, types) {
+ var node = createSynthesizedNode(258 /* HeritageClause */);
node.token = token;
node.types = createNodeArray(types);
return node;
@@ -11937,40 +12603,40 @@ var ts;
ts.createHeritageClause = createHeritageClause;
function updateHeritageClause(node, types) {
if (node.types !== types) {
- return updateNode(createHeritageClause(node.token, types, node), node);
+ return updateNode(createHeritageClause(node.token, types), node);
}
return node;
}
ts.updateHeritageClause = updateHeritageClause;
- function createCaseClause(expression, statements, location) {
- var node = createNode(253 /* CaseClause */, location);
- node.expression = parenthesizeExpressionForList(expression);
+ function createCaseClause(expression, statements) {
+ var node = createSynthesizedNode(256 /* CaseClause */);
+ node.expression = ts.parenthesizeExpressionForList(expression);
node.statements = createNodeArray(statements);
return node;
}
ts.createCaseClause = createCaseClause;
function updateCaseClause(node, expression, statements) {
if (node.expression !== expression || node.statements !== statements) {
- return updateNode(createCaseClause(expression, statements, node), node);
+ return updateNode(createCaseClause(expression, statements), node);
}
return node;
}
ts.updateCaseClause = updateCaseClause;
- function createDefaultClause(statements, location) {
- var node = createNode(254 /* DefaultClause */, location);
+ function createDefaultClause(statements) {
+ var node = createSynthesizedNode(257 /* DefaultClause */);
node.statements = createNodeArray(statements);
return node;
}
ts.createDefaultClause = createDefaultClause;
function updateDefaultClause(node, statements) {
if (node.statements !== statements) {
- return updateNode(createDefaultClause(statements, node), node);
+ return updateNode(createDefaultClause(statements), node);
}
return node;
}
ts.updateDefaultClause = updateDefaultClause;
- function createCatchClause(variableDeclaration, block, location) {
- var node = createNode(256 /* CatchClause */, location);
+ function createCatchClause(variableDeclaration, block) {
+ var node = createSynthesizedNode(259 /* CatchClause */);
node.variableDeclaration = typeof variableDeclaration === "string" ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
node.block = block;
return node;
@@ -11978,58 +12644,74 @@ var ts;
ts.createCatchClause = createCatchClause;
function updateCatchClause(node, variableDeclaration, block) {
if (node.variableDeclaration !== variableDeclaration || node.block !== block) {
- return updateNode(createCatchClause(variableDeclaration, block, node), node);
+ return updateNode(createCatchClause(variableDeclaration, block), node);
}
return node;
}
ts.updateCatchClause = updateCatchClause;
// Property assignments
- function createPropertyAssignment(name, initializer, location) {
- var node = createNode(257 /* PropertyAssignment */, location);
- node.name = typeof name === "string" ? createIdentifier(name) : name;
+ function createPropertyAssignment(name, initializer) {
+ var node = createSynthesizedNode(260 /* PropertyAssignment */);
+ node.name = asName(name);
node.questionToken = undefined;
- node.initializer = initializer !== undefined ? parenthesizeExpressionForList(initializer) : undefined;
+ node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
return node;
}
ts.createPropertyAssignment = createPropertyAssignment;
function updatePropertyAssignment(node, name, initializer) {
if (node.name !== name || node.initializer !== initializer) {
- return updateNode(createPropertyAssignment(name, initializer, node), node);
+ return updateNode(createPropertyAssignment(name, initializer), node);
}
return node;
}
ts.updatePropertyAssignment = updatePropertyAssignment;
- function createShorthandPropertyAssignment(name, objectAssignmentInitializer, location) {
- var node = createNode(258 /* ShorthandPropertyAssignment */, location);
- node.name = typeof name === "string" ? createIdentifier(name) : name;
- node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
+ function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
+ var node = createSynthesizedNode(261 /* ShorthandPropertyAssignment */);
+ node.name = asName(name);
+ node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
return node;
}
ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment;
- function createSpreadAssignment(expression, location) {
- var node = createNode(259 /* SpreadAssignment */, location);
- node.expression = expression !== undefined ? parenthesizeExpressionForList(expression) : undefined;
- return node;
- }
- ts.createSpreadAssignment = createSpreadAssignment;
function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) {
- return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node);
+ return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node);
}
return node;
}
ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment;
+ function createSpreadAssignment(expression) {
+ var node = createSynthesizedNode(262 /* SpreadAssignment */);
+ node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined;
+ return node;
+ }
+ ts.createSpreadAssignment = createSpreadAssignment;
function updateSpreadAssignment(node, expression) {
if (node.expression !== expression) {
- return updateNode(createSpreadAssignment(expression, node), node);
+ return updateNode(createSpreadAssignment(expression), node);
}
return node;
}
ts.updateSpreadAssignment = updateSpreadAssignment;
+ // Enum
+ function createEnumMember(name, initializer) {
+ var node = createSynthesizedNode(263 /* EnumMember */);
+ node.name = asName(name);
+ node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
+ return node;
+ }
+ ts.createEnumMember = createEnumMember;
+ function updateEnumMember(node, name, initializer) {
+ return node.name !== name
+ || node.initializer !== initializer
+ ? updateNode(createEnumMember(name, initializer), node)
+ : node;
+ }
+ ts.updateEnumMember = updateEnumMember;
// Top-level nodes
function updateSourceFileNode(node, statements) {
if (node.statements !== statements) {
- var updated = createNode(261 /* SourceFile */, /*location*/ node, node.flags);
+ var updated = createSynthesizedNode(264 /* SourceFile */);
+ updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
updated.fileName = node.fileName;
@@ -12088,6 +12770,17 @@ var ts;
return node;
}
ts.updateSourceFileNode = updateSourceFileNode;
+ /**
+ * Creates a shallow, memberwise clone of a node for mutation.
+ */
+ function getMutableClone(node) {
+ var clone = getSynthesizedClone(node);
+ clone.pos = node.pos;
+ clone.end = node.end;
+ clone.parent = node.parent;
+ return clone;
+ }
+ ts.getMutableClone = getMutableClone;
// Transformation nodes
/**
* Creates a synthetic statement to act as a placeholder for a not-emitted statement in
@@ -12096,8 +12789,9 @@ var ts;
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createNode(293 /* NotEmittedStatement */, /*location*/ original);
+ var node = createSynthesizedNode(294 /* NotEmittedStatement */);
node.original = original;
+ setTextRange(node, original);
return node;
}
ts.createNotEmittedStatement = createNotEmittedStatement;
@@ -12105,8 +12799,9 @@ var ts;
* Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
* order to properly emit exports.
*/
+ /* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createNode(296 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(297 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -12116,8 +12811,9 @@ var ts;
* Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
* order to properly emit exports.
*/
+ /* @internal */
function createMergeDeclarationMarker(original) {
- var node = createNode(295 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(296 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -12131,44 +12827,45 @@ var ts;
* @param original The original outer expression.
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
- function createPartiallyEmittedExpression(expression, original, location) {
- var node = createNode(294 /* PartiallyEmittedExpression */, /*location*/ location || original);
+ function createPartiallyEmittedExpression(expression, original) {
+ var node = createSynthesizedNode(295 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
+ setTextRange(node, original);
return node;
}
ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression;
function updatePartiallyEmittedExpression(node, expression) {
if (node.expression !== expression) {
- return updateNode(createPartiallyEmittedExpression(expression, node.original, node), node);
+ return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
}
return node;
}
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
- /**
- * Creates a node that emits a string of raw text in an expression position. Raw text is never
- * transformed, should be ES3 compliant, and should have the same precedence as
- * PrimaryExpression.
- *
- * @param text The raw text of the node.
- */
- function createRawExpression(text) {
- var node = createNode(297 /* RawExpression */);
- node.text = text;
+ function createBundle(sourceFiles) {
+ var node = ts.createNode(265 /* Bundle */);
+ node.sourceFiles = sourceFiles;
+ return node;
+ }
+ ts.createBundle = createBundle;
+ function updateBundle(node, sourceFiles) {
+ if (node.sourceFiles !== sourceFiles) {
+ return createBundle(sourceFiles);
+ }
return node;
}
- ts.createRawExpression = createRawExpression;
+ ts.updateBundle = updateBundle;
// Compound nodes
function createComma(left, right) {
return createBinary(left, 25 /* CommaToken */, right);
}
ts.createComma = createComma;
- function createLessThan(left, right, location) {
- return createBinary(left, 26 /* LessThanToken */, right, location);
+ function createLessThan(left, right) {
+ return createBinary(left, 26 /* LessThanToken */, right);
}
ts.createLessThan = createLessThan;
- function createAssignment(left, right, location) {
- return createBinary(left, 57 /* EqualsToken */, right, location);
+ function createAssignment(left, right) {
+ return createBinary(left, 57 /* EqualsToken */, right);
}
ts.createAssignment = createAssignment;
function createStrictEquality(left, right) {
@@ -12187,8 +12884,8 @@ var ts;
return createBinary(left, 37 /* MinusToken */, right);
}
ts.createSubtract = createSubtract;
- function createPostfixIncrement(operand, location) {
- return createPostfix(operand, 42 /* PlusPlusToken */, location);
+ function createPostfixIncrement(operand) {
+ return createPostfix(operand, 42 /* PlusPlusToken */);
}
ts.createPostfixIncrement = createPostfixIncrement;
function createLogicalAnd(left, right) {
@@ -12207,61 +12904,378 @@ var ts;
return createVoid(createLiteral(0));
}
ts.createVoidZero = createVoidZero;
+ function createExportDefault(expression) {
+ return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
+ }
+ ts.createExportDefault = createExportDefault;
+ function createExternalModuleExport(exportName) {
+ return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)]));
+ }
+ ts.createExternalModuleExport = createExternalModuleExport;
+ function asName(name) {
+ return typeof name === "string" ? createIdentifier(name) : name;
+ }
+ function asExpression(value) {
+ return typeof value === "string" || typeof value === "number" ? createLiteral(value) : value;
+ }
+ function asNodeArray(array) {
+ return array ? createNodeArray(array) : undefined;
+ }
+ function asToken(value) {
+ return typeof value === "number" ? createToken(value) : value;
+ }
+ /**
+ * Clears any EmitNode entries from parse-tree nodes.
+ * @param sourceFile A source file.
+ */
+ function disposeEmitNodes(sourceFile) {
+ // During transformation we may need to annotate a parse tree node with transient
+ // transformation properties. As parse tree nodes live longer than transformation
+ // nodes, we need to make sure we reclaim any memory allocated for custom ranges
+ // from these nodes to ensure we do not hold onto entire subtrees just for position
+ // information. We also need to reset these nodes to a pre-transformation state
+ // for incremental parsing scenarios so that we do not impact later emit.
+ sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
+ var emitNode = sourceFile && sourceFile.emitNode;
+ var annotatedNodes = emitNode && emitNode.annotatedNodes;
+ if (annotatedNodes) {
+ for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
+ var node = annotatedNodes_1[_i];
+ node.emitNode = undefined;
+ }
+ }
+ }
+ ts.disposeEmitNodes = disposeEmitNodes;
+ /**
+ * Associates a node with the current transformation, initializing
+ * various transient transformation properties.
+ */
+ /* @internal */
+ function getOrCreateEmitNode(node) {
+ if (!node.emitNode) {
+ if (ts.isParseTreeNode(node)) {
+ // To avoid holding onto transformation artifacts, we keep track of any
+ // parse tree node we are annotating. This allows us to clean them up after
+ // all transformations have completed.
+ if (node.kind === 264 /* SourceFile */) {
+ return node.emitNode = { annotatedNodes: [node] };
+ }
+ var sourceFile = ts.getSourceFileOfNode(node);
+ getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
+ }
+ node.emitNode = {};
+ }
+ return node.emitNode;
+ }
+ ts.getOrCreateEmitNode = getOrCreateEmitNode;
+ function setTextRange(range, location) {
+ if (location) {
+ range.pos = location.pos;
+ range.end = location.end;
+ }
+ return range;
+ }
+ ts.setTextRange = setTextRange;
+ /**
+ * Gets flags that control emit behavior of a node.
+ */
+ function getEmitFlags(node) {
+ var emitNode = node.emitNode;
+ return emitNode && emitNode.flags;
+ }
+ ts.getEmitFlags = getEmitFlags;
+ /**
+ * Sets flags that control emit behavior of a node.
+ */
+ function setEmitFlags(node, emitFlags) {
+ getOrCreateEmitNode(node).flags = emitFlags;
+ return node;
+ }
+ ts.setEmitFlags = setEmitFlags;
+ /**
+ * Gets a custom text range to use when emitting source maps.
+ */
+ function getSourceMapRange(node) {
+ var emitNode = node.emitNode;
+ return (emitNode && emitNode.sourceMapRange) || node;
+ }
+ ts.getSourceMapRange = getSourceMapRange;
+ /**
+ * Sets a custom text range to use when emitting source maps.
+ */
+ function setSourceMapRange(node, range) {
+ getOrCreateEmitNode(node).sourceMapRange = range;
+ return node;
+ }
+ ts.setSourceMapRange = setSourceMapRange;
+ /**
+ * Gets the TextRange to use for source maps for a token of a node.
+ */
+ function getTokenSourceMapRange(node, token) {
+ var emitNode = node.emitNode;
+ var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
+ return tokenSourceMapRanges && tokenSourceMapRanges[token];
+ }
+ ts.getTokenSourceMapRange = getTokenSourceMapRange;
+ /**
+ * Sets the TextRange to use for source maps for a token of a node.
+ */
+ function setTokenSourceMapRange(node, token, range) {
+ var emitNode = getOrCreateEmitNode(node);
+ var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
+ tokenSourceMapRanges[token] = range;
+ return node;
+ }
+ ts.setTokenSourceMapRange = setTokenSourceMapRange;
+ /**
+ * Gets a custom text range to use when emitting comments.
+ */
+ function getCommentRange(node) {
+ var emitNode = node.emitNode;
+ return (emitNode && emitNode.commentRange) || node;
+ }
+ ts.getCommentRange = getCommentRange;
+ /**
+ * Sets a custom text range to use when emitting comments.
+ */
+ function setCommentRange(node, range) {
+ getOrCreateEmitNode(node).commentRange = range;
+ return node;
+ }
+ ts.setCommentRange = setCommentRange;
+ function getSyntheticLeadingComments(node) {
+ var emitNode = node.emitNode;
+ return emitNode && emitNode.leadingComments;
+ }
+ ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
+ function setSyntheticLeadingComments(node, comments) {
+ getOrCreateEmitNode(node).leadingComments = comments;
+ return node;
+ }
+ ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
+ function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
+ return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
+ }
+ ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
+ function getSyntheticTrailingComments(node) {
+ var emitNode = node.emitNode;
+ return emitNode && emitNode.trailingComments;
+ }
+ ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
+ function setSyntheticTrailingComments(node, comments) {
+ getOrCreateEmitNode(node).trailingComments = comments;
+ return node;
+ }
+ ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
+ function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
+ return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
+ }
+ ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
+ /**
+ * Gets the constant value to emit for an expression.
+ */
+ function getConstantValue(node) {
+ var emitNode = node.emitNode;
+ return emitNode && emitNode.constantValue;
+ }
+ ts.getConstantValue = getConstantValue;
+ /**
+ * Sets the constant value to emit for an expression.
+ */
+ function setConstantValue(node, value) {
+ var emitNode = getOrCreateEmitNode(node);
+ emitNode.constantValue = value;
+ return node;
+ }
+ ts.setConstantValue = setConstantValue;
+ /**
+ * Adds an EmitHelper to a node.
+ */
+ function addEmitHelper(node, helper) {
+ var emitNode = getOrCreateEmitNode(node);
+ emitNode.helpers = ts.append(emitNode.helpers, helper);
+ return node;
+ }
+ ts.addEmitHelper = addEmitHelper;
+ /**
+ * Add EmitHelpers to a node.
+ */
+ function addEmitHelpers(node, helpers) {
+ if (ts.some(helpers)) {
+ var emitNode = getOrCreateEmitNode(node);
+ for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
+ var helper = helpers_1[_i];
+ if (!ts.contains(emitNode.helpers, helper)) {
+ emitNode.helpers = ts.append(emitNode.helpers, helper);
+ }
+ }
+ }
+ return node;
+ }
+ ts.addEmitHelpers = addEmitHelpers;
+ /**
+ * Removes an EmitHelper from a node.
+ */
+ function removeEmitHelper(node, helper) {
+ var emitNode = node.emitNode;
+ if (emitNode) {
+ var helpers = emitNode.helpers;
+ if (helpers) {
+ return ts.orderedRemoveItem(helpers, helper);
+ }
+ }
+ return false;
+ }
+ ts.removeEmitHelper = removeEmitHelper;
+ /**
+ * Gets the EmitHelpers of a node.
+ */
+ function getEmitHelpers(node) {
+ var emitNode = node.emitNode;
+ return emitNode && emitNode.helpers;
+ }
+ ts.getEmitHelpers = getEmitHelpers;
+ /**
+ * Moves matching emit helpers from a source node to a target node.
+ */
+ function moveEmitHelpers(source, target, predicate) {
+ var sourceEmitNode = source.emitNode;
+ var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
+ if (!ts.some(sourceEmitHelpers))
+ return;
+ var targetEmitNode = getOrCreateEmitNode(target);
+ var helpersRemoved = 0;
+ for (var i = 0; i < sourceEmitHelpers.length; i++) {
+ var helper = sourceEmitHelpers[i];
+ if (predicate(helper)) {
+ helpersRemoved++;
+ if (!ts.contains(targetEmitNode.helpers, helper)) {
+ targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper);
+ }
+ }
+ else if (helpersRemoved > 0) {
+ sourceEmitHelpers[i - helpersRemoved] = helper;
+ }
+ }
+ if (helpersRemoved > 0) {
+ sourceEmitHelpers.length -= helpersRemoved;
+ }
+ }
+ ts.moveEmitHelpers = moveEmitHelpers;
+ /* @internal */
+ function compareEmitHelpers(x, y) {
+ if (x === y)
+ return 0 /* EqualTo */;
+ if (x.priority === y.priority)
+ return 0 /* EqualTo */;
+ if (x.priority === undefined)
+ return 1 /* GreaterThan */;
+ if (y.priority === undefined)
+ return -1 /* LessThan */;
+ return ts.compareValues(x.priority, y.priority);
+ }
+ ts.compareEmitHelpers = compareEmitHelpers;
+ function setOriginalNode(node, original) {
+ node.original = original;
+ if (original) {
+ var emitNode = original.emitNode;
+ if (emitNode)
+ node.emitNode = mergeEmitNode(emitNode, node.emitNode);
+ }
+ return node;
+ }
+ ts.setOriginalNode = setOriginalNode;
+ function mergeEmitNode(sourceEmitNode, destEmitNode) {
+ var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers;
+ if (!destEmitNode)
+ destEmitNode = {};
+ if (leadingComments)
+ destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
+ if (trailingComments)
+ destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
+ if (flags)
+ destEmitNode.flags = flags;
+ if (commentRange)
+ destEmitNode.commentRange = commentRange;
+ if (sourceMapRange)
+ destEmitNode.sourceMapRange = sourceMapRange;
+ if (tokenSourceMapRanges)
+ destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
+ if (constantValue !== undefined)
+ destEmitNode.constantValue = constantValue;
+ if (helpers)
+ destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
+ return destEmitNode;
+ }
+ function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
+ if (!destRanges)
+ destRanges = [];
+ for (var key in sourceRanges) {
+ destRanges[key] = sourceRanges[key];
+ }
+ return destRanges;
+ }
+})(ts || (ts = {}));
+/* @internal */
+(function (ts) {
+ // Compound nodes
function createTypeCheck(value, tag) {
return tag === "undefined"
- ? createStrictEquality(value, createVoidZero())
- : createStrictEquality(createTypeOf(value), createLiteral(tag));
+ ? ts.createStrictEquality(value, ts.createVoidZero())
+ : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
}
ts.createTypeCheck = createTypeCheck;
function createMemberAccessForPropertyName(target, memberName, location) {
if (ts.isComputedPropertyName(memberName)) {
- return createElementAccess(target, memberName.expression, location);
+ return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
}
else {
- var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location);
- (expression.emitNode || (expression.emitNode = {})).flags |= 64 /* NoNestedSourceMaps */;
+ var expression = ts.setTextRange(ts.isIdentifier(memberName)
+ ? ts.createPropertyAccess(target, memberName)
+ : ts.createElementAccess(target, memberName), memberName);
+ ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
return expression;
}
}
ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
function createFunctionCall(func, thisArg, argumentsList, location) {
- return createCall(createPropertyAccess(func, "call"),
+ return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"),
/*typeArguments*/ undefined, [
thisArg
- ].concat(argumentsList), location);
+ ].concat(argumentsList)), location);
}
ts.createFunctionCall = createFunctionCall;
function createFunctionApply(func, thisArg, argumentsExpression, location) {
- return createCall(createPropertyAccess(func, "apply"),
+ return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"),
/*typeArguments*/ undefined, [
thisArg,
argumentsExpression
- ], location);
+ ]), location);
}
ts.createFunctionApply = createFunctionApply;
function createArraySlice(array, start) {
var argumentsList = [];
if (start !== undefined) {
- argumentsList.push(typeof start === "number" ? createLiteral(start) : start);
+ argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
}
- return createCall(createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
+ return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
}
ts.createArraySlice = createArraySlice;
function createArrayConcat(array, values) {
- return createCall(createPropertyAccess(array, "concat"),
+ return ts.createCall(ts.createPropertyAccess(array, "concat"),
/*typeArguments*/ undefined, values);
}
ts.createArrayConcat = createArrayConcat;
function createMathPow(left, right, location) {
- return createCall(createPropertyAccess(createIdentifier("Math"), "pow"),
- /*typeArguments*/ undefined, [left, right], location);
+ return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"),
+ /*typeArguments*/ undefined, [left, right]), location);
}
ts.createMathPow = createMathPow;
function createReactNamespace(reactNamespace, parent) {
// To ensure the emit resolver can properly resolve the namespace, we need to
// treat this identifier as if it were a source tree node by clearing the `Synthesized`
// flag and setting a parent node.
- var react = createIdentifier(reactNamespace || "React");
+ var react = ts.createIdentifier(reactNamespace || "React");
react.flags &= ~8 /* Synthesized */;
// Set the parent that is in parse tree
// this makes sure that parent chain is intact for checker to traverse complete scope tree
@@ -12271,9 +13285,9 @@ var ts;
function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) {
if (ts.isQualifiedName(jsxFactory)) {
var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
- var right = createSynthesizedNode(70 /* Identifier */);
+ var right = ts.createIdentifier(jsxFactory.right.text);
right.text = jsxFactory.right.text;
- return createPropertyAccess(left, right);
+ return ts.createPropertyAccess(left, right);
}
else {
return createReactNamespace(jsxFactory.text, parent);
@@ -12282,7 +13296,7 @@ var ts;
function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) {
return jsxFactoryEntity ?
createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
- createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
+ ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
}
function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
var argumentsList = [tagName];
@@ -12291,7 +13305,7 @@ var ts;
}
if (children && children.length > 0) {
if (!props) {
- argumentsList.push(createNull());
+ argumentsList.push(ts.createNull());
}
if (children.length > 1) {
for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
@@ -12304,35 +13318,89 @@ var ts;
argumentsList.push(children[0]);
}
}
- return createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement),
- /*typeArguments*/ undefined, argumentsList, location);
+ return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement),
+ /*typeArguments*/ undefined, argumentsList), location);
}
ts.createExpressionForJsxElement = createExpressionForJsxElement;
- function createExportDefault(expression) {
- return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
- }
- ts.createExportDefault = createExportDefault;
- function createExternalModuleExport(exportName) {
- return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(exportName)]));
- }
- ts.createExternalModuleExport = createExternalModuleExport;
- function createLetStatement(name, initializer, location) {
- return createVariableStatement(/*modifiers*/ undefined, createLetDeclarationList([createVariableDeclaration(name, /*type*/ undefined, initializer)]), location);
- }
- ts.createLetStatement = createLetStatement;
- function createLetDeclarationList(declarations, location) {
- return createVariableDeclarationList(declarations, location, 1 /* Let */);
- }
- ts.createLetDeclarationList = createLetDeclarationList;
- function createConstDeclarationList(declarations, location) {
- return createVariableDeclarationList(declarations, location, 2 /* Const */);
- }
- ts.createConstDeclarationList = createConstDeclarationList;
// Helpers
function getHelperName(name) {
- return setEmitFlags(createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
+ return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
+ var valuesHelper = {
+ name: "typescript:values",
+ scoped: false,
+ text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };\n "
+ };
+ function createValuesHelper(context, expression, location) {
+ context.requestEmitHelper(valuesHelper);
+ return ts.setTextRange(ts.createCall(getHelperName("__values"),
+ /*typeArguments*/ undefined, [expression]), location);
+ }
+ ts.createValuesHelper = createValuesHelper;
+ var readHelper = {
+ name: "typescript:read",
+ scoped: false,
+ text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };\n "
+ };
+ function createReadHelper(context, iteratorRecord, count, location) {
+ context.requestEmitHelper(readHelper);
+ return ts.setTextRange(ts.createCall(getHelperName("__read"),
+ /*typeArguments*/ undefined, count !== undefined
+ ? [iteratorRecord, ts.createLiteral(count)]
+ : [iteratorRecord]), location);
+ }
+ ts.createReadHelper = createReadHelper;
+ var spreadHelper = {
+ name: "typescript:spread",
+ scoped: false,
+ text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
+ };
+ function createSpreadHelper(context, argumentList, location) {
+ context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(spreadHelper);
+ return ts.setTextRange(ts.createCall(getHelperName("__spread"),
+ /*typeArguments*/ undefined, argumentList), location);
+ }
+ ts.createSpreadHelper = createSpreadHelper;
+ // Utilities
+ function createForOfBindingStatement(node, boundValue) {
+ if (ts.isVariableDeclarationList(node)) {
+ var firstDeclaration = ts.firstOrUndefined(node.declarations);
+ var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name,
+ /*typeNode*/ undefined, boundValue);
+ return ts.setTextRange(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])),
+ /*location*/ node);
+ }
+ else {
+ var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node);
+ return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node);
+ }
+ }
+ ts.createForOfBindingStatement = createForOfBindingStatement;
+ function insertLeadingStatement(dest, source) {
+ if (ts.isBlock(dest)) {
+ return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray([source].concat(dest.statements)), dest.statements));
+ }
+ else {
+ return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true);
+ }
+ }
+ ts.insertLeadingStatement = insertLeadingStatement;
+ function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
+ if (!outermostLabeledStatement) {
+ return node;
+ }
+ var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 221 /* LabeledStatement */
+ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
+ : node);
+ if (afterRestoreLabelCallback) {
+ afterRestoreLabelCallback(outermostLabeledStatement);
+ }
+ return updated;
+ }
+ ts.restoreEnclosingLabel = restoreEnclosingLabel;
function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
var target = skipParentheses(node);
switch (target.kind) {
@@ -12342,13 +13410,13 @@ var ts;
case 8 /* NumericLiteral */:
case 9 /* StringLiteral */:
return false;
- case 175 /* ArrayLiteralExpression */:
+ case 176 /* ArrayLiteralExpression */:
var elements = target.elements;
if (elements.length === 0) {
return false;
}
return true;
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
return target.properties.length > 0;
default:
return true;
@@ -12359,22 +13427,27 @@ var ts;
var thisArg;
var target;
if (ts.isSuperProperty(callee)) {
- thisArg = createThis();
+ thisArg = ts.createThis();
target = callee;
}
else if (callee.kind === 96 /* SuperKeyword */) {
- thisArg = createThis();
- target = languageVersion < 2 /* ES2015 */ ? createIdentifier("_super", /*location*/ callee) : callee;
+ thisArg = ts.createThis();
+ target = languageVersion < 2 /* ES2015 */
+ ? ts.setTextRange(ts.createIdentifier("_super"), callee)
+ : callee;
+ }
+ else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
+ thisArg = ts.createVoidZero();
+ target = parenthesizeForAccess(callee);
}
else {
switch (callee.kind) {
- case 177 /* PropertyAccessExpression */: {
+ case 178 /* PropertyAccessExpression */: {
if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
// for `a.b()` target is `(_a = a).b` and thisArg is `_a`
- thisArg = createTempVariable(recordTempVariable);
- target = createPropertyAccess(createAssignment(thisArg, callee.expression,
- /*location*/ callee.expression), callee.name,
- /*location*/ callee);
+ thisArg = ts.createTempVariable(recordTempVariable);
+ target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
+ ts.setTextRange(target, callee);
}
else {
thisArg = callee.expression;
@@ -12382,13 +13455,12 @@ var ts;
}
break;
}
- case 178 /* ElementAccessExpression */: {
+ case 179 /* ElementAccessExpression */: {
if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
// for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
- thisArg = createTempVariable(recordTempVariable);
- target = createElementAccess(createAssignment(thisArg, callee.expression,
- /*location*/ callee.expression), callee.argumentExpression,
- /*location*/ callee);
+ thisArg = ts.createTempVariable(recordTempVariable);
+ target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
+ ts.setTextRange(target, callee);
}
else {
thisArg = callee.expression;
@@ -12398,7 +13470,7 @@ var ts;
}
default: {
// for `a()` target is `a` and thisArg is `void 0`
- thisArg = createVoidZero();
+ thisArg = ts.createVoidZero();
target = parenthesizeForAccess(expression);
break;
}
@@ -12408,42 +13480,42 @@ var ts;
}
ts.createCallBinding = createCallBinding;
function inlineExpressions(expressions) {
- return ts.reduceLeft(expressions, createComma);
+ return ts.reduceLeft(expressions, ts.createComma);
}
ts.inlineExpressions = inlineExpressions;
function createExpressionFromEntityName(node) {
if (ts.isQualifiedName(node)) {
var left = createExpressionFromEntityName(node.left);
- var right = getMutableClone(node.right);
- return createPropertyAccess(left, right, /*location*/ node);
+ var right = ts.getMutableClone(node.right);
+ return ts.setTextRange(ts.createPropertyAccess(left, right), node);
}
else {
- return getMutableClone(node);
+ return ts.getMutableClone(node);
}
}
ts.createExpressionFromEntityName = createExpressionFromEntityName;
function createExpressionForPropertyName(memberName) {
if (ts.isIdentifier(memberName)) {
- return createLiteral(memberName, /*location*/ undefined);
+ return ts.createLiteral(memberName);
}
else if (ts.isComputedPropertyName(memberName)) {
- return getMutableClone(memberName.expression);
+ return ts.getMutableClone(memberName.expression);
}
else {
- return getMutableClone(memberName);
+ return ts.getMutableClone(memberName);
}
}
ts.createExpressionForPropertyName = createExpressionForPropertyName;
function createExpressionForObjectLiteralElementLike(node, property, receiver) {
switch (property.kind) {
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine);
- case 257 /* PropertyAssignment */:
+ case 260 /* PropertyAssignment */:
return createExpressionForPropertyAssignment(property, receiver);
- case 258 /* ShorthandPropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
return createExpressionForShorthandPropertyAssignment(property, receiver);
- case 149 /* MethodDeclaration */:
+ case 150 /* MethodDeclaration */:
return createExpressionForMethodDeclaration(property, receiver);
}
}
@@ -12453,57 +13525,55 @@ var ts;
if (property === firstAccessor) {
var properties_1 = [];
if (getAccessor) {
- var getterFunction = createFunctionExpression(getAccessor.modifiers,
+ var getterFunction = ts.createFunctionExpression(getAccessor.modifiers,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined, getAccessor.parameters,
- /*type*/ undefined, getAccessor.body,
- /*location*/ getAccessor);
- setOriginalNode(getterFunction, getAccessor);
- var getter = createPropertyAssignment("get", getterFunction);
+ /*type*/ undefined, getAccessor.body);
+ ts.setTextRange(getterFunction, getAccessor);
+ ts.setOriginalNode(getterFunction, getAccessor);
+ var getter = ts.createPropertyAssignment("get", getterFunction);
properties_1.push(getter);
}
if (setAccessor) {
- var setterFunction = createFunctionExpression(setAccessor.modifiers,
+ var setterFunction = ts.createFunctionExpression(setAccessor.modifiers,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined, setAccessor.parameters,
- /*type*/ undefined, setAccessor.body,
- /*location*/ setAccessor);
- setOriginalNode(setterFunction, setAccessor);
- var setter = createPropertyAssignment("set", setterFunction);
+ /*type*/ undefined, setAccessor.body);
+ ts.setTextRange(setterFunction, setAccessor);
+ ts.setOriginalNode(setterFunction, setAccessor);
+ var setter = ts.createPropertyAssignment("set", setterFunction);
properties_1.push(setter);
}
- properties_1.push(createPropertyAssignment("enumerable", createLiteral(true)));
- properties_1.push(createPropertyAssignment("configurable", createLiteral(true)));
- var expression = createCall(createPropertyAccess(createIdentifier("Object"), "defineProperty"),
+ properties_1.push(ts.createPropertyAssignment("enumerable", ts.createTrue()));
+ properties_1.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
+ var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
/*typeArguments*/ undefined, [
receiver,
createExpressionForPropertyName(property.name),
- createObjectLiteral(properties_1, /*location*/ undefined, multiLine)
- ],
+ ts.createObjectLiteral(properties_1, multiLine)
+ ]),
/*location*/ firstAccessor);
return ts.aggregateTransformFlags(expression);
}
return undefined;
}
function createExpressionForPropertyAssignment(property, receiver) {
- return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer,
- /*location*/ property),
- /*original*/ property));
+ return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property));
}
function createExpressionForShorthandPropertyAssignment(property, receiver) {
- return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), getSynthesizedClone(property.name),
+ return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)),
/*location*/ property),
/*original*/ property));
}
function createExpressionForMethodDeclaration(method, receiver) {
- return ts.aggregateTransformFlags(setOriginalNode(createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), setOriginalNode(createFunctionExpression(method.modifiers, method.asteriskToken,
+ return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken,
/*name*/ undefined,
/*typeParameters*/ undefined, method.parameters,
- /*type*/ undefined, method.body,
+ /*type*/ undefined, method.body),
/*location*/ method),
- /*original*/ method),
+ /*original*/ method)),
/*location*/ method),
/*original*/ method));
}
@@ -12525,7 +13595,7 @@ var ts;
* Gets whether an identifier should only be referred to by its local name.
*/
function isLocalName(node) {
- return (getEmitFlags(node) & 16384 /* LocalName */) !== 0;
+ return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
}
ts.isLocalName = isLocalName;
/**
@@ -12547,7 +13617,7 @@ var ts;
* name points to an exported symbol.
*/
function isExportName(node) {
- return (getEmitFlags(node) & 8192 /* ExportName */) !== 0;
+ return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
}
ts.isExportName = isExportName;
/**
@@ -12563,17 +13633,17 @@ var ts;
ts.getDeclarationName = getDeclarationName;
function getName(node, allowComments, allowSourceMaps, emitFlags) {
if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) {
- var name_8 = getMutableClone(node.name);
- emitFlags |= getEmitFlags(node.name);
+ var name = ts.getMutableClone(node.name);
+ emitFlags |= ts.getEmitFlags(node.name);
if (!allowSourceMaps)
emitFlags |= 48 /* NoSourceMap */;
if (!allowComments)
emitFlags |= 1536 /* NoComments */;
if (emitFlags)
- setEmitFlags(name_8, emitFlags);
- return name_8;
+ ts.setEmitFlags(name, emitFlags);
+ return name;
}
- return getGeneratedNameForNode(node);
+ return ts.getGeneratedNameForNode(node);
}
/**
* Gets the exported name of a declaration for use in expressions.
@@ -12602,19 +13672,20 @@ var ts;
* @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
*/
function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
- var qualifiedName = createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : getSynthesizedClone(name), /*location*/ name);
+ var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
+ ts.setTextRange(qualifiedName, name);
var emitFlags;
if (!allowSourceMaps)
emitFlags |= 48 /* NoSourceMap */;
if (!allowComments)
emitFlags |= 1536 /* NoComments */;
if (emitFlags)
- setEmitFlags(qualifiedName, emitFlags);
+ ts.setEmitFlags(qualifiedName, emitFlags);
return qualifiedName;
}
ts.getNamespaceMemberName = getNamespaceMemberName;
function convertToFunctionBody(node, multiLine) {
- return ts.isBlock(node) ? node : createBlock([createReturn(node, /*location*/ node)], /*location*/ node, multiLine);
+ return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node);
}
ts.convertToFunctionBody = convertToFunctionBody;
function isUseStrictPrologue(node) {
@@ -12631,7 +13702,18 @@ var ts;
* @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
* @param visitor: Optional callback used to visit any custom prologue directives.
*/
- function addPrologueDirectives(target, source, ensureUseStrict, visitor) {
+ function addPrologue(target, source, ensureUseStrict, visitor) {
+ var offset = addStandardPrologue(target, source, ensureUseStrict);
+ return addCustomPrologue(target, source, offset, visitor);
+ }
+ ts.addPrologue = addPrologue;
+ /**
+ * Add just the standard (string-expression) prologue-directives into target statement-array.
+ * The function needs to be called during each transformation step.
+ * This function needs to be called whenever we transform the statement
+ * list of a source file, namespace, or function-like body.
+ */
+ function addStandardPrologue(target, source, ensureUseStrict) {
ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
var foundUseStrict = false;
var statementOffset = 0;
@@ -12650,11 +13732,22 @@ var ts;
statementOffset++;
}
if (ensureUseStrict && !foundUseStrict) {
- target.push(startOnNewLine(createStatement(createLiteral("use strict"))));
+ target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
}
+ return statementOffset;
+ }
+ ts.addStandardPrologue = addStandardPrologue;
+ /**
+ * Add just the custom prologue-directives into target statement-array.
+ * The function needs to be called during each transformation step.
+ * This function needs to be called whenever we transform the statement
+ * list of a source file, namespace, or function-like body.
+ */
+ function addCustomPrologue(target, source, statementOffset, visitor) {
+ var numStatements = source.length;
while (statementOffset < numStatements) {
var statement = source[statementOffset];
- if (getEmitFlags(statement) & 524288 /* CustomPrologue */) {
+ if (ts.getEmitFlags(statement) & 524288 /* CustomPrologue */) {
target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
}
else {
@@ -12664,7 +13757,7 @@ var ts;
}
return statementOffset;
}
- ts.addPrologueDirectives = addPrologueDirectives;
+ ts.addCustomPrologue = addCustomPrologue;
function startsWithUseStrict(statements) {
var firstStatement = ts.firstOrUndefined(statements);
return firstStatement !== undefined
@@ -12692,13 +13785,23 @@ var ts;
}
}
if (!foundUseStrict) {
- return createNodeArray([
- startOnNewLine(createStatement(createLiteral("use strict")))
- ].concat(statements), statements);
+ return ts.setTextRange(ts.createNodeArray([
+ startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
+ ].concat(statements)), statements);
}
return statements;
}
ts.ensureUseStrict = ensureUseStrict;
+ function parenthesizeConditionalHead(condition) {
+ var conditionalPrecedence = ts.getOperatorPrecedence(194 /* ConditionalExpression */, 54 /* QuestionToken */);
+ var emittedCondition = skipPartiallyEmittedExpressions(condition);
+ var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
+ if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) {
+ return ts.createParen(condition);
+ }
+ return condition;
+ }
+ ts.parenthesizeConditionalHead = parenthesizeConditionalHead;
/**
* Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
* order of operations.
@@ -12711,11 +13814,11 @@ var ts;
function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
var skipped = skipPartiallyEmittedExpressions(operand);
// If the resulting expression is already parenthesized, we do not need to do any further processing.
- if (skipped.kind === 183 /* ParenthesizedExpression */) {
+ if (skipped.kind === 184 /* ParenthesizedExpression */) {
return operand;
}
return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
- ? createParen(operand)
+ ? ts.createParen(operand)
: operand;
}
ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand;
@@ -12745,8 +13848,8 @@ var ts;
//
// If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
// the intended order of operations: `(a ** b) ** c`
- var binaryOperatorPrecedence = ts.getOperatorPrecedence(192 /* BinaryExpression */, binaryOperator);
- var binaryOperatorAssociativity = ts.getOperatorAssociativity(192 /* BinaryExpression */, binaryOperator);
+ var binaryOperatorPrecedence = ts.getOperatorPrecedence(193 /* BinaryExpression */, binaryOperator);
+ var binaryOperatorAssociativity = ts.getOperatorAssociativity(193 /* BinaryExpression */, binaryOperator);
var emittedOperand = skipPartiallyEmittedExpressions(operand);
var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
@@ -12755,7 +13858,7 @@ var ts;
// and is a yield expression, then we do not need parentheses.
if (!isLeftSideOfBinary
&& binaryOperatorAssociativity === 1 /* Right */
- && operand.kind === 195 /* YieldExpression */) {
+ && operand.kind === 196 /* YieldExpression */) {
return false;
}
return true;
@@ -12843,7 +13946,7 @@ var ts;
if (ts.isLiteralKind(node.kind)) {
return node.kind;
}
- if (node.kind === 192 /* BinaryExpression */ && node.operatorToken.kind === 36 /* PlusToken */) {
+ if (node.kind === 193 /* BinaryExpression */ && node.operatorToken.kind === 36 /* PlusToken */) {
if (node.cachedLiteralKind !== undefined) {
return node.cachedLiteralKind;
}
@@ -12858,11 +13961,11 @@ var ts;
return 0 /* Unknown */;
}
function parenthesizeForConditionalHead(condition) {
- var conditionalPrecedence = ts.getOperatorPrecedence(193 /* ConditionalExpression */, 54 /* QuestionToken */);
+ var conditionalPrecedence = ts.getOperatorPrecedence(194 /* ConditionalExpression */, 54 /* QuestionToken */);
var emittedCondition = skipPartiallyEmittedExpressions(condition);
var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) {
- return createParen(condition);
+ return ts.createParen(condition);
}
return condition;
}
@@ -12871,10 +13974,11 @@ var ts;
// per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
// so in case when comma expression is introduced as a part of previous transformations
// if should be wrapped in parens since comma operator has the lowest precedence
- return e.kind === 192 /* BinaryExpression */ && e.operatorToken.kind === 25 /* CommaToken */
- ? createParen(e)
+ return e.kind === 193 /* BinaryExpression */ && e.operatorToken.kind === 25 /* CommaToken */
+ ? ts.createParen(e)
: e;
}
+ ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression;
/**
* Wraps an expression in parentheses if it is needed in order to use the expression
* as the expression of a NewExpression node.
@@ -12884,12 +13988,12 @@ var ts;
function parenthesizeForNew(expression) {
var emittedExpression = skipPartiallyEmittedExpressions(expression);
switch (emittedExpression.kind) {
- case 179 /* CallExpression */:
- return createParen(expression);
- case 180 /* NewExpression */:
+ case 180 /* CallExpression */:
+ return ts.createParen(expression);
+ case 181 /* NewExpression */:
return emittedExpression.arguments
? expression
- : createParen(expression);
+ : ts.createParen(expression);
}
return parenthesizeForAccess(expression);
}
@@ -12902,32 +14006,29 @@ var ts;
*/
function parenthesizeForAccess(expression) {
// isLeftHandSideExpression is almost the correct criterion for when it is not necessary
- // to parenthesize the expression before a dot. The known exceptions are:
+ // to parenthesize the expression before a dot. The known exception is:
//
// NewExpression:
// new C.x -> not the same as (new C).x
- // NumericLiteral
- // 1.x -> not the same as (1).x
//
var emittedExpression = skipPartiallyEmittedExpressions(expression);
if (ts.isLeftHandSideExpression(emittedExpression)
- && (emittedExpression.kind !== 180 /* NewExpression */ || emittedExpression.arguments)
- && emittedExpression.kind !== 8 /* NumericLiteral */) {
+ && (emittedExpression.kind !== 181 /* NewExpression */ || emittedExpression.arguments)) {
return expression;
}
- return createParen(expression, /*location*/ expression);
+ return ts.setTextRange(ts.createParen(expression), expression);
}
ts.parenthesizeForAccess = parenthesizeForAccess;
function parenthesizePostfixOperand(operand) {
return ts.isLeftHandSideExpression(operand)
? operand
- : createParen(operand, /*location*/ operand);
+ : ts.setTextRange(ts.createParen(operand), operand);
}
ts.parenthesizePostfixOperand = parenthesizePostfixOperand;
function parenthesizePrefixOperand(operand) {
return ts.isUnaryExpression(operand)
? operand
- : createParen(operand, /*location*/ operand);
+ : ts.setTextRange(ts.createParen(operand), operand);
}
ts.parenthesizePrefixOperand = parenthesizePrefixOperand;
function parenthesizeListElements(elements) {
@@ -12942,17 +14043,18 @@ var ts;
}
}
if (result !== undefined) {
- return createNodeArray(result, elements, elements.hasTrailingComma);
+ return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
}
return elements;
}
+ ts.parenthesizeListElements = parenthesizeListElements;
function parenthesizeExpressionForList(expression) {
var emittedExpression = skipPartiallyEmittedExpressions(expression);
var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
- var commaPrecedence = ts.getOperatorPrecedence(192 /* BinaryExpression */, 25 /* CommaToken */);
+ var commaPrecedence = ts.getOperatorPrecedence(193 /* BinaryExpression */, 25 /* CommaToken */);
return expressionPrecedence > commaPrecedence
? expression
- : createParen(expression, /*location*/ expression);
+ : ts.setTextRange(ts.createParen(expression), expression);
}
ts.parenthesizeExpressionForList = parenthesizeExpressionForList;
function parenthesizeExpressionForExpressionStatement(expression) {
@@ -12960,16 +14062,16 @@ var ts;
if (ts.isCallExpression(emittedExpression)) {
var callee = emittedExpression.expression;
var kind = skipPartiallyEmittedExpressions(callee).kind;
- if (kind === 184 /* FunctionExpression */ || kind === 185 /* ArrowFunction */) {
- var mutableCall = getMutableClone(emittedExpression);
- mutableCall.expression = createParen(callee, /*location*/ callee);
+ if (kind === 185 /* FunctionExpression */ || kind === 186 /* ArrowFunction */) {
+ var mutableCall = ts.getMutableClone(emittedExpression);
+ mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
return recreatePartiallyEmittedExpressions(expression, mutableCall);
}
}
else {
var leftmostExpressionKind = getLeftmostExpression(emittedExpression).kind;
- if (leftmostExpressionKind === 176 /* ObjectLiteralExpression */ || leftmostExpressionKind === 184 /* FunctionExpression */) {
- return createParen(expression, /*location*/ expression);
+ if (leftmostExpressionKind === 177 /* ObjectLiteralExpression */ || leftmostExpressionKind === 185 /* FunctionExpression */) {
+ return ts.setTextRange(ts.createParen(expression), expression);
}
}
return expression;
@@ -12983,7 +14085,7 @@ var ts;
*/
function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) {
if (ts.isPartiallyEmittedExpression(originalOuterExpression)) {
- var clone_1 = getMutableClone(originalOuterExpression);
+ var clone_1 = ts.getMutableClone(originalOuterExpression);
clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression);
return clone_1;
}
@@ -12992,21 +14094,21 @@ var ts;
function getLeftmostExpression(node) {
while (true) {
switch (node.kind) {
- case 191 /* PostfixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
node = node.operand;
continue;
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
node = node.left;
continue;
- case 193 /* ConditionalExpression */:
+ case 194 /* ConditionalExpression */:
node = node.condition;
continue;
- case 179 /* CallExpression */:
- case 178 /* ElementAccessExpression */:
- case 177 /* PropertyAccessExpression */:
+ case 180 /* CallExpression */:
+ case 179 /* ElementAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
node = node.expression;
continue;
- case 294 /* PartiallyEmittedExpression */:
+ case 295 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -13014,9 +14116,8 @@ var ts;
}
}
function parenthesizeConciseBody(body) {
- var emittedBody = skipPartiallyEmittedExpressions(body);
- if (emittedBody.kind === 176 /* ObjectLiteralExpression */) {
- return createParen(body, /*location*/ body);
+ if (!ts.isBlock(body) && getLeftmostExpression(body).kind === 177 /* ObjectLiteralExpression */) {
+ return ts.setTextRange(ts.createParen(body), body);
}
return body;
}
@@ -13047,7 +14148,7 @@ var ts;
}
ts.skipOuterExpressions = skipOuterExpressions;
function skipParentheses(node) {
- while (node.kind === 183 /* ParenthesizedExpression */) {
+ while (node.kind === 184 /* ParenthesizedExpression */) {
node = node.expression;
}
return node;
@@ -13061,7 +14162,7 @@ var ts;
}
ts.skipAssertions = skipAssertions;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 294 /* PartiallyEmittedExpression */) {
+ while (node.kind === 295 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13072,188 +14173,6 @@ var ts;
return node;
}
ts.startOnNewLine = startOnNewLine;
- function setOriginalNode(node, original) {
- node.original = original;
- if (original) {
- var emitNode = original.emitNode;
- if (emitNode)
- node.emitNode = mergeEmitNode(emitNode, node.emitNode);
- }
- return node;
- }
- ts.setOriginalNode = setOriginalNode;
- function mergeEmitNode(sourceEmitNode, destEmitNode) {
- var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers;
- if (!destEmitNode)
- destEmitNode = {};
- if (flags)
- destEmitNode.flags = flags;
- if (commentRange)
- destEmitNode.commentRange = commentRange;
- if (sourceMapRange)
- destEmitNode.sourceMapRange = sourceMapRange;
- if (tokenSourceMapRanges)
- destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
- if (constantValue !== undefined)
- destEmitNode.constantValue = constantValue;
- if (helpers)
- destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
- return destEmitNode;
- }
- function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
- if (!destRanges)
- destRanges = ts.createMap();
- ts.copyProperties(sourceRanges, destRanges);
- return destRanges;
- }
- /**
- * Clears any EmitNode entries from parse-tree nodes.
- * @param sourceFile A source file.
- */
- function disposeEmitNodes(sourceFile) {
- // During transformation we may need to annotate a parse tree node with transient
- // transformation properties. As parse tree nodes live longer than transformation
- // nodes, we need to make sure we reclaim any memory allocated for custom ranges
- // from these nodes to ensure we do not hold onto entire subtrees just for position
- // information. We also need to reset these nodes to a pre-transformation state
- // for incremental parsing scenarios so that we do not impact later emit.
- sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
- var emitNode = sourceFile && sourceFile.emitNode;
- var annotatedNodes = emitNode && emitNode.annotatedNodes;
- if (annotatedNodes) {
- for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
- var node = annotatedNodes_1[_i];
- node.emitNode = undefined;
- }
- }
- }
- ts.disposeEmitNodes = disposeEmitNodes;
- /**
- * Associates a node with the current transformation, initializing
- * various transient transformation properties.
- *
- * @param node The node.
- */
- function getOrCreateEmitNode(node) {
- if (!node.emitNode) {
- if (ts.isParseTreeNode(node)) {
- // To avoid holding onto transformation artifacts, we keep track of any
- // parse tree node we are annotating. This allows us to clean them up after
- // all transformations have completed.
- if (node.kind === 261 /* SourceFile */) {
- return node.emitNode = { annotatedNodes: [node] };
- }
- var sourceFile = ts.getSourceFileOfNode(node);
- getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
- }
- node.emitNode = {};
- }
- return node.emitNode;
- }
- ts.getOrCreateEmitNode = getOrCreateEmitNode;
- /**
- * Gets flags that control emit behavior of a node.
- *
- * @param node The node.
- */
- function getEmitFlags(node) {
- var emitNode = node.emitNode;
- return emitNode && emitNode.flags;
- }
- ts.getEmitFlags = getEmitFlags;
- /**
- * Sets flags that control emit behavior of a node.
- *
- * @param node The node.
- * @param emitFlags The NodeEmitFlags for the node.
- */
- function setEmitFlags(node, emitFlags) {
- getOrCreateEmitNode(node).flags = emitFlags;
- return node;
- }
- ts.setEmitFlags = setEmitFlags;
- /**
- * Gets a custom text range to use when emitting source maps.
- *
- * @param node The node.
- */
- function getSourceMapRange(node) {
- var emitNode = node.emitNode;
- return (emitNode && emitNode.sourceMapRange) || node;
- }
- ts.getSourceMapRange = getSourceMapRange;
- /**
- * Sets a custom text range to use when emitting source maps.
- *
- * @param node The node.
- * @param range The text range.
- */
- function setSourceMapRange(node, range) {
- getOrCreateEmitNode(node).sourceMapRange = range;
- return node;
- }
- ts.setSourceMapRange = setSourceMapRange;
- /**
- * Gets the TextRange to use for source maps for a token of a node.
- *
- * @param node The node.
- * @param token The token.
- */
- function getTokenSourceMapRange(node, token) {
- var emitNode = node.emitNode;
- var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
- return tokenSourceMapRanges && tokenSourceMapRanges[token];
- }
- ts.getTokenSourceMapRange = getTokenSourceMapRange;
- /**
- * Sets the TextRange to use for source maps for a token of a node.
- *
- * @param node The node.
- * @param token The token.
- * @param range The text range.
- */
- function setTokenSourceMapRange(node, token, range) {
- var emitNode = getOrCreateEmitNode(node);
- var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap());
- tokenSourceMapRanges[token] = range;
- return node;
- }
- ts.setTokenSourceMapRange = setTokenSourceMapRange;
- /**
- * Gets a custom text range to use when emitting comments.
- *
- * @param node The node.
- */
- function getCommentRange(node) {
- var emitNode = node.emitNode;
- return (emitNode && emitNode.commentRange) || node;
- }
- ts.getCommentRange = getCommentRange;
- /**
- * Sets a custom text range to use when emitting comments.
- */
- function setCommentRange(node, range) {
- getOrCreateEmitNode(node).commentRange = range;
- return node;
- }
- ts.setCommentRange = setCommentRange;
- /**
- * Gets the constant value to emit for an expression.
- */
- function getConstantValue(node) {
- var emitNode = node.emitNode;
- return emitNode && emitNode.constantValue;
- }
- ts.getConstantValue = getConstantValue;
- /**
- * Sets the constant value to emit for an expression.
- */
- function setConstantValue(node, value) {
- var emitNode = getOrCreateEmitNode(node);
- emitNode.constantValue = value;
- return node;
- }
- ts.setConstantValue = setConstantValue;
function getExternalHelpersModuleName(node) {
var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
var emitNode = parseNode && parseNode.emitNode;
@@ -13266,14 +14185,14 @@ var ts;
if (externalHelpersModuleName) {
return externalHelpersModuleName;
}
- var helpers = getEmitHelpers(node);
+ var helpers = ts.getEmitHelpers(node);
if (helpers) {
- for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
- var helper = helpers_1[_i];
+ for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
+ var helper = helpers_2[_i];
if (!helper.scoped) {
var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
- var emitNode = getOrCreateEmitNode(parseNode);
- return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = createUniqueName(ts.externalHelpersModuleNameText));
+ var emitNode = ts.getOrCreateEmitNode(parseNode);
+ return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText));
}
}
}
@@ -13281,128 +14200,19 @@ var ts;
}
ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
/**
- * Adds an EmitHelper to a node.
- */
- function addEmitHelper(node, helper) {
- var emitNode = getOrCreateEmitNode(node);
- emitNode.helpers = ts.append(emitNode.helpers, helper);
- return node;
- }
- ts.addEmitHelper = addEmitHelper;
- /**
- * Adds an EmitHelper to a node.
- */
- function addEmitHelpers(node, helpers) {
- if (ts.some(helpers)) {
- var emitNode = getOrCreateEmitNode(node);
- for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
- var helper = helpers_2[_i];
- if (!ts.contains(emitNode.helpers, helper)) {
- emitNode.helpers = ts.append(emitNode.helpers, helper);
- }
- }
- }
- return node;
- }
- ts.addEmitHelpers = addEmitHelpers;
- /**
- * Removes an EmitHelper from a node.
- */
- function removeEmitHelper(node, helper) {
- var emitNode = node.emitNode;
- if (emitNode) {
- var helpers = emitNode.helpers;
- if (helpers) {
- return ts.orderedRemoveItem(helpers, helper);
- }
- }
- return false;
- }
- ts.removeEmitHelper = removeEmitHelper;
- /**
- * Gets the EmitHelpers of a node.
- */
- function getEmitHelpers(node) {
- var emitNode = node.emitNode;
- return emitNode && emitNode.helpers;
- }
- ts.getEmitHelpers = getEmitHelpers;
- /**
- * Moves matching emit helpers from a source node to a target node.
- */
- function moveEmitHelpers(source, target, predicate) {
- var sourceEmitNode = source.emitNode;
- var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
- if (!ts.some(sourceEmitHelpers))
- return;
- var targetEmitNode = getOrCreateEmitNode(target);
- var helpersRemoved = 0;
- for (var i = 0; i < sourceEmitHelpers.length; i++) {
- var helper = sourceEmitHelpers[i];
- if (predicate(helper)) {
- helpersRemoved++;
- if (!ts.contains(targetEmitNode.helpers, helper)) {
- targetEmitNode.helpers = ts.append(targetEmitNode.helpers, helper);
- }
- }
- else if (helpersRemoved > 0) {
- sourceEmitHelpers[i - helpersRemoved] = helper;
- }
- }
- if (helpersRemoved > 0) {
- sourceEmitHelpers.length -= helpersRemoved;
- }
- }
- ts.moveEmitHelpers = moveEmitHelpers;
- function compareEmitHelpers(x, y) {
- if (x === y)
- return 0 /* EqualTo */;
- if (x.priority === y.priority)
- return 0 /* EqualTo */;
- if (x.priority === undefined)
- return 1 /* GreaterThan */;
- if (y.priority === undefined)
- return -1 /* LessThan */;
- return ts.compareValues(x.priority, y.priority);
- }
- ts.compareEmitHelpers = compareEmitHelpers;
- function setTextRange(node, location) {
- if (location) {
- node.pos = location.pos;
- node.end = location.end;
- }
- return node;
- }
- ts.setTextRange = setTextRange;
- function setNodeFlags(node, flags) {
- node.flags = flags;
- return node;
- }
- ts.setNodeFlags = setNodeFlags;
- function setMultiLine(node, multiLine) {
- node.multiLine = multiLine;
- return node;
- }
- ts.setMultiLine = setMultiLine;
- function setHasTrailingComma(nodes, hasTrailingComma) {
- nodes.hasTrailingComma = hasTrailingComma;
- return nodes;
- }
- ts.setHasTrailingComma = setHasTrailingComma;
- /**
* Get the name of that target module from an import or export declaration
*/
function getLocalNameForExternalImport(node, sourceFile) {
var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !ts.isDefaultImport(node)) {
- var name_9 = namespaceDeclaration.name;
- return ts.isGeneratedIdentifier(name_9) ? name_9 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name));
+ var name = namespaceDeclaration.name;
+ return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name));
}
- if (node.kind === 235 /* ImportDeclaration */ && node.importClause) {
- return getGeneratedNameForNode(node);
+ if (node.kind === 237 /* ImportDeclaration */ && node.importClause) {
+ return ts.getGeneratedNameForNode(node);
}
- if (node.kind === 241 /* ExportDeclaration */ && node.moduleSpecifier) {
- return getGeneratedNameForNode(node);
+ if (node.kind === 243 /* ExportDeclaration */ && node.moduleSpecifier) {
+ return ts.getGeneratedNameForNode(node);
}
return undefined;
}
@@ -13420,7 +14230,7 @@ var ts;
if (moduleName.kind === 9 /* StringLiteral */) {
return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
|| tryRenameExternalModule(moduleName, sourceFile)
- || getSynthesizedClone(moduleName);
+ || ts.getSynthesizedClone(moduleName);
}
return undefined;
}
@@ -13430,10 +14240,8 @@ var ts;
* Here we check if alternative name was provided for a given moduleName and return it if possible.
*/
function tryRenameExternalModule(moduleName, sourceFile) {
- if (sourceFile.renamedDependencies && ts.hasProperty(sourceFile.renamedDependencies, moduleName.text)) {
- return createLiteral(sourceFile.renamedDependencies[moduleName.text]);
- }
- return undefined;
+ var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
+ return rename && ts.createLiteral(rename);
}
/**
* Get the name of a module as should be written in the emitted output.
@@ -13447,10 +14255,10 @@ var ts;
return undefined;
}
if (file.moduleName) {
- return createLiteral(file.moduleName);
+ return ts.createLiteral(file.moduleName);
}
if (!ts.isDeclarationFile(file) && (options.out || options.outFile)) {
- return createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
+ return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
}
return undefined;
}
@@ -13521,7 +14329,7 @@ var ts;
}
if (ts.isObjectLiteralElementLike(bindingElement)) {
switch (bindingElement.kind) {
- case 257 /* PropertyAssignment */:
+ case 260 /* PropertyAssignment */:
// `b` in `({ a: b } = ...)`
// `b` in `({ a: b = 1 } = ...)`
// `{b}` in `({ a: {b} } = ...)`
@@ -13533,11 +14341,11 @@ var ts;
// `b[0]` in `({ a: b[0] } = ...)`
// `b[0]` in `({ a: b[0] = 1 } = ...)`
return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
- case 258 /* ShorthandPropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
// `a` in `({ a } = ...)`
// `a` in `({ a = 1 } = ...)`
return bindingElement.name;
- case 259 /* SpreadAssignment */:
+ case 262 /* SpreadAssignment */:
// `a` in `({ ...a } = ...)`
return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
}
@@ -13569,12 +14377,12 @@ var ts;
*/
function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
switch (bindingElement.kind) {
- case 144 /* Parameter */:
- case 174 /* BindingElement */:
+ case 145 /* Parameter */:
+ case 175 /* BindingElement */:
// `...` in `let [...a] = ...`
return bindingElement.dotDotDotToken;
- case 196 /* SpreadElement */:
- case 259 /* SpreadAssignment */:
+ case 197 /* SpreadElement */:
+ case 262 /* SpreadAssignment */:
// `...` in `[...a] = ...`
return bindingElement;
}
@@ -13586,7 +14394,7 @@ var ts;
*/
function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
switch (bindingElement.kind) {
- case 174 /* BindingElement */:
+ case 175 /* BindingElement */:
// `a` in `let { a: b } = ...`
// `[a]` in `let { [a]: b } = ...`
// `"a"` in `let { "a": b } = ...`
@@ -13598,7 +14406,7 @@ var ts;
: propertyName;
}
break;
- case 257 /* PropertyAssignment */:
+ case 260 /* PropertyAssignment */:
// `a` in `({ a: b } = ...)`
// `[a]` in `({ [a]: b } = ...)`
// `"a"` in `({ "a": b } = ...)`
@@ -13610,7 +14418,7 @@ var ts;
: propertyName;
}
break;
- case 259 /* SpreadAssignment */:
+ case 262 /* SpreadAssignment */:
// `a` in `({ ...a } = ...)`
return bindingElement.name;
}
@@ -13628,13 +14436,13 @@ var ts;
*/
function getElementsOfBindingOrAssignmentPattern(name) {
switch (name.kind) {
- case 172 /* ObjectBindingPattern */:
- case 173 /* ArrayBindingPattern */:
- case 175 /* ArrayLiteralExpression */:
+ case 173 /* ObjectBindingPattern */:
+ case 174 /* ArrayBindingPattern */:
+ case 176 /* ArrayLiteralExpression */:
// `a` in `{a}`
// `a` in `[a]`
return name.elements;
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
// `a` in `{a}`
return name.properties;
}
@@ -13644,10 +14452,12 @@ var ts;
if (ts.isBindingElement(element)) {
if (element.dotDotDotToken) {
ts.Debug.assertNode(element.name, ts.isIdentifier);
- return setOriginalNode(createSpread(element.name, element), element);
+ return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
}
var expression = convertToAssignmentElementTarget(element.name);
- return element.initializer ? setOriginalNode(createAssignment(expression, element.initializer, element), element) : expression;
+ return element.initializer
+ ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
+ : expression;
}
ts.Debug.assertNode(element, ts.isExpression);
return element;
@@ -13657,14 +14467,14 @@ var ts;
if (ts.isBindingElement(element)) {
if (element.dotDotDotToken) {
ts.Debug.assertNode(element.name, ts.isIdentifier);
- return setOriginalNode(createSpreadAssignment(element.name, element), element);
+ return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
}
if (element.propertyName) {
var expression = convertToAssignmentElementTarget(element.name);
- return setOriginalNode(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression, element), element);
+ return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element);
}
ts.Debug.assertNode(element.name, ts.isIdentifier);
- return setOriginalNode(createShorthandPropertyAssignment(element.name, element.initializer, element), element);
+ return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
}
ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
return element;
@@ -13672,18 +14482,18 @@ var ts;
ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement;
function convertToAssignmentPattern(node) {
switch (node.kind) {
- case 173 /* ArrayBindingPattern */:
- case 175 /* ArrayLiteralExpression */:
+ case 174 /* ArrayBindingPattern */:
+ case 176 /* ArrayLiteralExpression */:
return convertToArrayAssignmentPattern(node);
- case 172 /* ObjectBindingPattern */:
- case 176 /* ObjectLiteralExpression */:
+ case 173 /* ObjectBindingPattern */:
+ case 177 /* ObjectLiteralExpression */:
return convertToObjectAssignmentPattern(node);
}
}
ts.convertToAssignmentPattern = convertToAssignmentPattern;
function convertToObjectAssignmentPattern(node) {
if (ts.isObjectBindingPattern(node)) {
- return setOriginalNode(createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement), node), node);
+ return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
}
ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
return node;
@@ -13691,7 +14501,7 @@ var ts;
ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern;
function convertToArrayAssignmentPattern(node) {
if (ts.isArrayBindingPattern(node)) {
- return setOriginalNode(createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement), node), node);
+ return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
}
ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
return node;
@@ -13707,37 +14517,37 @@ var ts;
ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget;
function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
var externalImports = [];
- var exportSpecifiers = ts.createMap();
- var exportedBindings = ts.createMap();
+ var exportSpecifiers = ts.createMultiMap();
+ var exportedBindings = [];
var uniqueExports = ts.createMap();
var exportedNames;
var hasExportDefault = false;
var exportEquals = undefined;
var hasExportStarsToExportValues = false;
var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions);
- var externalHelpersImportDeclaration = externalHelpersModuleName && createImportDeclaration(
+ var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(
/*decorators*/ undefined,
- /*modifiers*/ undefined, createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)), createLiteral(ts.externalHelpersModuleNameText));
+ /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText));
if (externalHelpersImportDeclaration) {
externalImports.push(externalHelpersImportDeclaration);
}
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var node = _a[_i];
switch (node.kind) {
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
// import "mod"
// import x from "mod"
// import * as x from "mod"
// import { x, y } from "mod"
externalImports.push(node);
break;
- case 234 /* ImportEqualsDeclaration */:
- if (node.moduleReference.kind === 245 /* ExternalModuleReference */) {
+ case 236 /* ImportEqualsDeclaration */:
+ if (node.moduleReference.kind === 247 /* ExternalModuleReference */) {
// import x = require("mod")
externalImports.push(node);
}
break;
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
if (node.moduleSpecifier) {
if (!node.exportClause) {
// export * from "mod"
@@ -13753,27 +14563,27 @@ var ts;
// export { x, y }
for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) {
var specifier = _c[_b];
- if (!uniqueExports[specifier.name.text]) {
- var name_10 = specifier.propertyName || specifier.name;
- ts.multiMapAdd(exportSpecifiers, name_10.text, specifier);
- var decl = resolver.getReferencedImportDeclaration(name_10)
- || resolver.getReferencedValueDeclaration(name_10);
+ if (!uniqueExports.get(specifier.name.text)) {
+ var name = specifier.propertyName || specifier.name;
+ exportSpecifiers.add(name.text, specifier);
+ var decl = resolver.getReferencedImportDeclaration(name)
+ || resolver.getReferencedValueDeclaration(name);
if (decl) {
- ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name);
+ multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name);
}
- uniqueExports[specifier.name.text] = true;
+ uniqueExports.set(specifier.name.text, true);
exportedNames = ts.append(exportedNames, specifier.name);
}
}
}
break;
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
if (node.isExportEquals && !exportEquals) {
// export = x
exportEquals = node;
}
break;
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
if (ts.hasModifier(node, 1 /* Export */)) {
for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
var decl = _e[_d];
@@ -13781,42 +14591,42 @@ var ts;
}
}
break;
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
if (ts.hasModifier(node, 1 /* Export */)) {
if (ts.hasModifier(node, 512 /* Default */)) {
// export default function() { }
if (!hasExportDefault) {
- ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node));
+ multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node));
hasExportDefault = true;
}
}
else {
// export function x() { }
- var name_11 = node.name;
- if (!uniqueExports[name_11.text]) {
- ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_11);
- uniqueExports[name_11.text] = true;
- exportedNames = ts.append(exportedNames, name_11);
+ var name = node.name;
+ if (!uniqueExports.get(name.text)) {
+ multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name);
+ uniqueExports.set(name.text, true);
+ exportedNames = ts.append(exportedNames, name);
}
}
}
break;
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
if (ts.hasModifier(node, 1 /* Export */)) {
if (ts.hasModifier(node, 512 /* Default */)) {
// export default class { }
if (!hasExportDefault) {
- ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node));
+ multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node));
hasExportDefault = true;
}
}
else {
// export class x { }
- var name_12 = node.name;
- if (!uniqueExports[name_12.text]) {
- ts.multiMapAdd(exportedBindings, ts.getOriginalNodeId(node), name_12);
- uniqueExports[name_12.text] = true;
- exportedNames = ts.append(exportedNames, name_12);
+ var name = node.name;
+ if (!uniqueExports.get(name.text)) {
+ multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name);
+ uniqueExports.set(name.text, true);
+ exportedNames = ts.append(exportedNames, name);
}
}
}
@@ -13836,13 +14646,24 @@ var ts;
}
}
else if (!ts.isGeneratedIdentifier(decl.name)) {
- if (!uniqueExports[decl.name.text]) {
- uniqueExports[decl.name.text] = true;
+ if (!uniqueExports.get(decl.name.text)) {
+ uniqueExports.set(decl.name.text, true);
exportedNames = ts.append(exportedNames, decl.name);
}
}
return exportedNames;
}
+ /** Use a sparse array as a multi-map. */
+ function multiMapSparseArrayAdd(map, key, value) {
+ var values = map[key];
+ if (values) {
+ values.push(value);
+ }
+ else {
+ map[key] = values = [value];
+ }
+ return values;
+ }
})(ts || (ts = {}));
/// <reference path="utilities.ts"/>
/// <reference path="scanner.ts"/>
@@ -13854,13 +14675,13 @@ var ts;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
- if (kind === 261 /* SourceFile */) {
+ if (kind === 264 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 70 /* Identifier */) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
- else if (kind < 141 /* FirstNode */) {
+ else if (kind < 142 /* FirstNode */) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
@@ -13903,28 +14724,29 @@ var ts;
var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode;
var cbNodes = cbNodeArray || cbNode;
switch (node.kind) {
- case 141 /* QualifiedName */:
+ case 142 /* QualifiedName */:
return visitNode(cbNode, node.left) ||
visitNode(cbNode, node.right);
- case 143 /* TypeParameter */:
+ case 144 /* TypeParameter */:
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.constraint) ||
+ visitNode(cbNode, node.default) ||
visitNode(cbNode, node.expression);
- case 258 /* ShorthandPropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.equalsToken) ||
visitNode(cbNode, node.objectAssignmentInitializer);
- case 259 /* SpreadAssignment */:
+ case 262 /* SpreadAssignment */:
return visitNode(cbNode, node.expression);
- case 144 /* Parameter */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 257 /* PropertyAssignment */:
- case 223 /* VariableDeclaration */:
- case 174 /* BindingElement */:
+ case 145 /* Parameter */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 260 /* PropertyAssignment */:
+ case 225 /* VariableDeclaration */:
+ case 175 /* BindingElement */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.propertyName) ||
@@ -13933,24 +14755,24 @@ var ts;
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.type) ||
visitNode(cbNode, node.initializer);
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNodes(cbNodes, node.typeParameters) ||
visitNodes(cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 184 /* FunctionExpression */:
- case 225 /* FunctionDeclaration */:
- case 185 /* ArrowFunction */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 185 /* FunctionExpression */:
+ case 227 /* FunctionDeclaration */:
+ case 186 /* ArrowFunction */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.asteriskToken) ||
@@ -13961,320 +14783,326 @@ var ts;
visitNode(cbNode, node.type) ||
visitNode(cbNode, node.equalsGreaterThanToken) ||
visitNode(cbNode, node.body);
- case 157 /* TypeReference */:
+ case 158 /* TypeReference */:
return visitNode(cbNode, node.typeName) ||
visitNodes(cbNodes, node.typeArguments);
- case 156 /* TypePredicate */:
+ case 157 /* TypePredicate */:
return visitNode(cbNode, node.parameterName) ||
visitNode(cbNode, node.type);
- case 160 /* TypeQuery */:
+ case 161 /* TypeQuery */:
return visitNode(cbNode, node.exprName);
- case 161 /* TypeLiteral */:
+ case 162 /* TypeLiteral */:
return visitNodes(cbNodes, node.members);
- case 162 /* ArrayType */:
+ case 163 /* ArrayType */:
return visitNode(cbNode, node.elementType);
- case 163 /* TupleType */:
+ case 164 /* TupleType */:
return visitNodes(cbNodes, node.elementTypes);
- case 164 /* UnionType */:
- case 165 /* IntersectionType */:
+ case 165 /* UnionType */:
+ case 166 /* IntersectionType */:
return visitNodes(cbNodes, node.types);
- case 166 /* ParenthesizedType */:
- case 168 /* TypeOperator */:
+ case 167 /* ParenthesizedType */:
+ case 169 /* TypeOperator */:
return visitNode(cbNode, node.type);
- case 169 /* IndexedAccessType */:
+ case 170 /* IndexedAccessType */:
return visitNode(cbNode, node.objectType) ||
visitNode(cbNode, node.indexType);
- case 170 /* MappedType */:
+ case 171 /* MappedType */:
return visitNode(cbNode, node.readonlyToken) ||
visitNode(cbNode, node.typeParameter) ||
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.type);
- case 171 /* LiteralType */:
+ case 172 /* LiteralType */:
return visitNode(cbNode, node.literal);
- case 172 /* ObjectBindingPattern */:
- case 173 /* ArrayBindingPattern */:
+ case 173 /* ObjectBindingPattern */:
+ case 174 /* ArrayBindingPattern */:
return visitNodes(cbNodes, node.elements);
- case 175 /* ArrayLiteralExpression */:
+ case 176 /* ArrayLiteralExpression */:
return visitNodes(cbNodes, node.elements);
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
return visitNodes(cbNodes, node.properties);
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.name);
- case 178 /* ElementAccessExpression */:
+ case 179 /* ElementAccessExpression */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.argumentExpression);
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
return visitNode(cbNode, node.expression) ||
visitNodes(cbNodes, node.typeArguments) ||
visitNodes(cbNodes, node.arguments);
- case 181 /* TaggedTemplateExpression */:
+ case 182 /* TaggedTemplateExpression */:
return visitNode(cbNode, node.tag) ||
visitNode(cbNode, node.template);
- case 182 /* TypeAssertionExpression */:
+ case 183 /* TypeAssertionExpression */:
return visitNode(cbNode, node.type) ||
visitNode(cbNode, node.expression);
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return visitNode(cbNode, node.expression);
- case 186 /* DeleteExpression */:
+ case 187 /* DeleteExpression */:
return visitNode(cbNode, node.expression);
- case 187 /* TypeOfExpression */:
+ case 188 /* TypeOfExpression */:
return visitNode(cbNode, node.expression);
- case 188 /* VoidExpression */:
+ case 189 /* VoidExpression */:
return visitNode(cbNode, node.expression);
- case 190 /* PrefixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
return visitNode(cbNode, node.operand);
- case 195 /* YieldExpression */:
+ case 196 /* YieldExpression */:
return visitNode(cbNode, node.asteriskToken) ||
visitNode(cbNode, node.expression);
- case 189 /* AwaitExpression */:
+ case 190 /* AwaitExpression */:
return visitNode(cbNode, node.expression);
- case 191 /* PostfixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
return visitNode(cbNode, node.operand);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return visitNode(cbNode, node.left) ||
visitNode(cbNode, node.operatorToken) ||
visitNode(cbNode, node.right);
- case 200 /* AsExpression */:
+ case 201 /* AsExpression */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.type);
- case 201 /* NonNullExpression */:
+ case 202 /* NonNullExpression */:
return visitNode(cbNode, node.expression);
- case 193 /* ConditionalExpression */:
+ case 203 /* MetaProperty */:
+ return visitNode(cbNode, node.name);
+ case 194 /* ConditionalExpression */:
return visitNode(cbNode, node.condition) ||
visitNode(cbNode, node.questionToken) ||
visitNode(cbNode, node.whenTrue) ||
visitNode(cbNode, node.colonToken) ||
visitNode(cbNode, node.whenFalse);
- case 196 /* SpreadElement */:
+ case 197 /* SpreadElement */:
return visitNode(cbNode, node.expression);
- case 204 /* Block */:
- case 231 /* ModuleBlock */:
+ case 206 /* Block */:
+ case 233 /* ModuleBlock */:
return visitNodes(cbNodes, node.statements);
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
return visitNodes(cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.declarationList);
- case 224 /* VariableDeclarationList */:
+ case 226 /* VariableDeclarationList */:
return visitNodes(cbNodes, node.declarations);
- case 207 /* ExpressionStatement */:
+ case 209 /* ExpressionStatement */:
return visitNode(cbNode, node.expression);
- case 208 /* IfStatement */:
+ case 210 /* IfStatement */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.thenStatement) ||
visitNode(cbNode, node.elseStatement);
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
return visitNode(cbNode, node.statement) ||
visitNode(cbNode, node.expression);
- case 210 /* WhileStatement */:
+ case 212 /* WhileStatement */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.statement);
- case 211 /* ForStatement */:
+ case 213 /* ForStatement */:
return visitNode(cbNode, node.initializer) ||
visitNode(cbNode, node.condition) ||
visitNode(cbNode, node.incrementor) ||
visitNode(cbNode, node.statement);
- case 212 /* ForInStatement */:
+ case 214 /* ForInStatement */:
return visitNode(cbNode, node.initializer) ||
visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.statement);
- case 213 /* ForOfStatement */:
- return visitNode(cbNode, node.initializer) ||
+ case 215 /* ForOfStatement */:
+ return visitNode(cbNode, node.awaitModifier) ||
+ visitNode(cbNode, node.initializer) ||
visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.statement);
- case 214 /* ContinueStatement */:
- case 215 /* BreakStatement */:
+ case 216 /* ContinueStatement */:
+ case 217 /* BreakStatement */:
return visitNode(cbNode, node.label);
- case 216 /* ReturnStatement */:
+ case 218 /* ReturnStatement */:
return visitNode(cbNode, node.expression);
- case 217 /* WithStatement */:
+ case 219 /* WithStatement */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.statement);
- case 218 /* SwitchStatement */:
+ case 220 /* SwitchStatement */:
return visitNode(cbNode, node.expression) ||
visitNode(cbNode, node.caseBlock);
- case 232 /* CaseBlock */:
+ case 234 /* CaseBlock */:
return visitNodes(cbNodes, node.clauses);
- case 253 /* CaseClause */:
+ case 256 /* CaseClause */:
return visitNode(cbNode, node.expression) ||
visitNodes(cbNodes, node.statements);
- case 254 /* DefaultClause */:
+ case 257 /* DefaultClause */:
return visitNodes(cbNodes, node.statements);
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
return visitNode(cbNode, node.label) ||
visitNode(cbNode, node.statement);
- case 220 /* ThrowStatement */:
+ case 222 /* ThrowStatement */:
return visitNode(cbNode, node.expression);
- case 221 /* TryStatement */:
+ case 223 /* TryStatement */:
return visitNode(cbNode, node.tryBlock) ||
visitNode(cbNode, node.catchClause) ||
visitNode(cbNode, node.finallyBlock);
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return visitNode(cbNode, node.variableDeclaration) ||
visitNode(cbNode, node.block);
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
return visitNode(cbNode, node.expression);
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNodes(cbNodes, node.typeParameters) ||
visitNodes(cbNodes, node.heritageClauses) ||
visitNodes(cbNodes, node.members);
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNodes(cbNodes, node.typeParameters) ||
visitNodes(cbNodes, node.heritageClauses) ||
visitNodes(cbNodes, node.members);
- case 228 /* TypeAliasDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNodes(cbNodes, node.typeParameters) ||
visitNode(cbNode, node.type);
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNodes(cbNodes, node.members);
- case 260 /* EnumMember */:
+ case 263 /* EnumMember */:
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.initializer);
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.body);
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.moduleReference);
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.importClause) ||
visitNode(cbNode, node.moduleSpecifier);
- case 236 /* ImportClause */:
+ case 238 /* ImportClause */:
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.namedBindings);
- case 233 /* NamespaceExportDeclaration */:
+ case 235 /* NamespaceExportDeclaration */:
return visitNode(cbNode, node.name);
- case 237 /* NamespaceImport */:
+ case 239 /* NamespaceImport */:
return visitNode(cbNode, node.name);
- case 238 /* NamedImports */:
- case 242 /* NamedExports */:
+ case 240 /* NamedImports */:
+ case 244 /* NamedExports */:
return visitNodes(cbNodes, node.elements);
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.exportClause) ||
visitNode(cbNode, node.moduleSpecifier);
- case 239 /* ImportSpecifier */:
- case 243 /* ExportSpecifier */:
+ case 241 /* ImportSpecifier */:
+ case 245 /* ExportSpecifier */:
return visitNode(cbNode, node.propertyName) ||
visitNode(cbNode, node.name);
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
return visitNodes(cbNodes, node.decorators) ||
visitNodes(cbNodes, node.modifiers) ||
visitNode(cbNode, node.expression);
- case 194 /* TemplateExpression */:
+ case 195 /* TemplateExpression */:
return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans);
- case 202 /* TemplateSpan */:
+ case 204 /* TemplateSpan */:
return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
- case 142 /* ComputedPropertyName */:
+ case 143 /* ComputedPropertyName */:
return visitNode(cbNode, node.expression);
- case 255 /* HeritageClause */:
+ case 258 /* HeritageClause */:
return visitNodes(cbNodes, node.types);
- case 199 /* ExpressionWithTypeArguments */:
+ case 200 /* ExpressionWithTypeArguments */:
return visitNode(cbNode, node.expression) ||
visitNodes(cbNodes, node.typeArguments);
- case 245 /* ExternalModuleReference */:
+ case 247 /* ExternalModuleReference */:
return visitNode(cbNode, node.expression);
- case 244 /* MissingDeclaration */:
+ case 246 /* MissingDeclaration */:
return visitNodes(cbNodes, node.decorators);
- case 246 /* JsxElement */:
+ case 248 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
visitNodes(cbNodes, node.children) ||
visitNode(cbNode, node.closingElement);
- case 247 /* JsxSelfClosingElement */:
- case 248 /* JsxOpeningElement */:
+ case 249 /* JsxSelfClosingElement */:
+ case 250 /* JsxOpeningElement */:
return visitNode(cbNode, node.tagName) ||
- visitNodes(cbNodes, node.attributes);
- case 250 /* JsxAttribute */:
+ visitNode(cbNode, node.attributes);
+ case 253 /* JsxAttributes */:
+ return visitNodes(cbNodes, node.properties);
+ case 252 /* JsxAttribute */:
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.initializer);
- case 251 /* JsxSpreadAttribute */:
- return visitNode(cbNode, node.expression);
- case 252 /* JsxExpression */:
+ case 254 /* JsxSpreadAttribute */:
return visitNode(cbNode, node.expression);
- case 249 /* JsxClosingElement */:
+ case 255 /* JsxExpression */:
+ return visitNode(cbNode, node.dotDotDotToken) ||
+ visitNode(cbNode, node.expression);
+ case 251 /* JsxClosingElement */:
return visitNode(cbNode, node.tagName);
- case 262 /* JSDocTypeExpression */:
+ case 266 /* JSDocTypeExpression */:
return visitNode(cbNode, node.type);
- case 266 /* JSDocUnionType */:
+ case 270 /* JSDocUnionType */:
return visitNodes(cbNodes, node.types);
- case 267 /* JSDocTupleType */:
+ case 271 /* JSDocTupleType */:
return visitNodes(cbNodes, node.types);
- case 265 /* JSDocArrayType */:
+ case 269 /* JSDocArrayType */:
return visitNode(cbNode, node.elementType);
- case 269 /* JSDocNonNullableType */:
+ case 273 /* JSDocNonNullableType */:
return visitNode(cbNode, node.type);
- case 268 /* JSDocNullableType */:
+ case 272 /* JSDocNullableType */:
return visitNode(cbNode, node.type);
- case 270 /* JSDocRecordType */:
+ case 274 /* JSDocRecordType */:
return visitNode(cbNode, node.literal);
- case 272 /* JSDocTypeReference */:
+ case 276 /* JSDocTypeReference */:
return visitNode(cbNode, node.name) ||
visitNodes(cbNodes, node.typeArguments);
- case 273 /* JSDocOptionalType */:
+ case 277 /* JSDocOptionalType */:
return visitNode(cbNode, node.type);
- case 274 /* JSDocFunctionType */:
+ case 278 /* JSDocFunctionType */:
return visitNodes(cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 275 /* JSDocVariadicType */:
+ case 279 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 276 /* JSDocConstructorType */:
+ case 280 /* JSDocConstructorType */:
return visitNode(cbNode, node.type);
- case 277 /* JSDocThisType */:
+ case 281 /* JSDocThisType */:
return visitNode(cbNode, node.type);
- case 271 /* JSDocRecordMember */:
+ case 275 /* JSDocRecordMember */:
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.type);
- case 278 /* JSDocComment */:
+ case 282 /* JSDocComment */:
return visitNodes(cbNodes, node.tags);
- case 281 /* JSDocParameterTag */:
+ case 285 /* JSDocParameterTag */:
return visitNode(cbNode, node.preParameterName) ||
visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.postParameterName);
- case 282 /* JSDocReturnTag */:
+ case 286 /* JSDocReturnTag */:
return visitNode(cbNode, node.typeExpression);
- case 283 /* JSDocTypeTag */:
+ case 287 /* JSDocTypeTag */:
return visitNode(cbNode, node.typeExpression);
- case 280 /* JSDocAugmentsTag */:
+ case 284 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.typeExpression);
- case 284 /* JSDocTemplateTag */:
+ case 288 /* JSDocTemplateTag */:
return visitNodes(cbNodes, node.typeParameters);
- case 285 /* JSDocTypedefTag */:
+ case 289 /* JSDocTypedefTag */:
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.name) ||
visitNode(cbNode, node.jsDocTypeLiteral);
- case 287 /* JSDocTypeLiteral */:
+ case 291 /* JSDocTypeLiteral */:
return visitNodes(cbNodes, node.jsDocPropertyTags);
- case 286 /* JSDocPropertyTag */:
+ case 290 /* JSDocPropertyTag */:
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name);
- case 294 /* PartiallyEmittedExpression */:
+ case 295 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
- case 288 /* JSDocLiteralType */:
+ case 292 /* JSDocLiteralType */:
return visitNode(cbNode, node.literal);
}
}
@@ -14292,6 +15120,7 @@ var ts;
return Parser.parseIsolatedEntityName(text, languageVersion);
}
ts.parseIsolatedEntityName = parseIsolatedEntityName;
+ // See also `isExternalOrCommonJsModule` in utilities.ts
function isExternalModule(file) {
return file.externalModuleIndicator !== undefined;
}
@@ -14334,7 +15163,7 @@ var ts;
// Share a single scanner across all calls to parse a source file. This helps speed things
// up by avoiding the cost of creating/compiling scanners over and over again.
var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true);
- var disallowInAndDecoratorContext = 65536 /* DisallowInContext */ | 262144 /* DecoratorContext */;
+ var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
var NodeConstructor;
var TokenConstructor;
@@ -14458,7 +15287,7 @@ var ts;
identifiers = ts.createMap();
identifierCount = 0;
nodeCount = 0;
- contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 2097152 /* JavaScriptFile */ : 0 /* None */;
+ contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 65536 /* JavaScriptFile */ : 0 /* None */;
parseErrorBeforeNextFinishedNode = false;
// Initialize and prime the scanner before parsing the source elements.
scanner.setText(sourceText);
@@ -14546,7 +15375,7 @@ var ts;
function createSourceFile(fileName, languageVersion, scriptKind) {
// code from createNode is inlined here so createNode won't have to deal with special case of creating source files
// this is quite rare comparing to other nodes and createNode should be as fast as possible
- var sourceFile = new SourceFileConstructor(261 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(264 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -14566,16 +15395,16 @@ var ts;
}
}
function setDisallowInContext(val) {
- setContextFlag(val, 65536 /* DisallowInContext */);
+ setContextFlag(val, 2048 /* DisallowInContext */);
}
function setYieldContext(val) {
- setContextFlag(val, 131072 /* YieldContext */);
+ setContextFlag(val, 4096 /* YieldContext */);
}
function setDecoratorContext(val) {
- setContextFlag(val, 262144 /* DecoratorContext */);
+ setContextFlag(val, 8192 /* DecoratorContext */);
}
function setAwaitContext(val) {
- setContextFlag(val, 524288 /* AwaitContext */);
+ setContextFlag(val, 16384 /* AwaitContext */);
}
function doOutsideOfContext(context, func) {
// contextFlagsToClear will contain only the context flags that are
@@ -14616,40 +15445,40 @@ var ts;
return func();
}
function allowInAnd(func) {
- return doOutsideOfContext(65536 /* DisallowInContext */, func);
+ return doOutsideOfContext(2048 /* DisallowInContext */, func);
}
function disallowInAnd(func) {
- return doInsideOfContext(65536 /* DisallowInContext */, func);
+ return doInsideOfContext(2048 /* DisallowInContext */, func);
}
function doInYieldContext(func) {
- return doInsideOfContext(131072 /* YieldContext */, func);
+ return doInsideOfContext(4096 /* YieldContext */, func);
}
function doInDecoratorContext(func) {
- return doInsideOfContext(262144 /* DecoratorContext */, func);
+ return doInsideOfContext(8192 /* DecoratorContext */, func);
}
function doInAwaitContext(func) {
- return doInsideOfContext(524288 /* AwaitContext */, func);
+ return doInsideOfContext(16384 /* AwaitContext */, func);
}
function doOutsideOfAwaitContext(func) {
- return doOutsideOfContext(524288 /* AwaitContext */, func);
+ return doOutsideOfContext(16384 /* AwaitContext */, func);
}
function doInYieldAndAwaitContext(func) {
- return doInsideOfContext(131072 /* YieldContext */ | 524288 /* AwaitContext */, func);
+ return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func);
}
function inContext(flags) {
return (contextFlags & flags) !== 0;
}
function inYieldContext() {
- return inContext(131072 /* YieldContext */);
+ return inContext(4096 /* YieldContext */);
}
function inDisallowInContext() {
- return inContext(65536 /* DisallowInContext */);
+ return inContext(2048 /* DisallowInContext */);
}
function inDecoratorContext() {
- return inContext(262144 /* DecoratorContext */);
+ return inContext(8192 /* DecoratorContext */);
}
function inAwaitContext() {
- return inContext(524288 /* AwaitContext */);
+ return inContext(16384 /* AwaitContext */);
}
function parseErrorAtCurrentToken(message, arg0) {
var start = scanner.getTokenPos();
@@ -14830,7 +15659,7 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
- return kind >= 141 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) :
+ return kind >= 142 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) :
kind === 70 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
@@ -14853,7 +15682,7 @@ var ts;
// flag so that we don't mark any subsequent nodes.
if (parseErrorBeforeNextFinishedNode) {
parseErrorBeforeNextFinishedNode = false;
- node.flags |= 1048576 /* ThisNodeHasError */;
+ node.flags |= 32768 /* ThisNodeHasError */;
}
return node;
}
@@ -14870,7 +15699,11 @@ var ts;
}
function internIdentifier(text) {
text = ts.escapeIdentifier(text);
- return identifiers[text] || (identifiers[text] = text);
+ var identifier = identifiers.get(text);
+ if (identifier === undefined) {
+ identifiers.set(text, identifier = text);
+ }
+ return identifier;
}
// An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
// with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
@@ -14922,7 +15755,7 @@ var ts;
// PropertyName [Yield]:
// LiteralPropertyName
// ComputedPropertyName[?Yield]
- var node = createNode(142 /* ComputedPropertyName */);
+ var node = createNode(143 /* ComputedPropertyName */);
parseExpected(20 /* OpenBracketToken */);
// We parse any expression (including a comma expression). But the grammar
// says that only an assignment expression is allowed, so the grammar checker
@@ -14975,6 +15808,7 @@ var ts;
function nextTokenIsClassOrFunctionOrAsync() {
nextToken();
return token() === 74 /* ClassKeyword */ || token() === 88 /* FunctionKeyword */ ||
+ (token() === 116 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
(token() === 119 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
}
// True if positioned at the start of a list element
@@ -15015,7 +15849,7 @@ var ts;
case 9 /* ObjectBindingElements */:
return token() === 20 /* OpenBracketToken */ || token() === 23 /* DotDotDotToken */ || isLiteralPropertyName();
case 7 /* HeritageClauseElement */:
- // If we see { } then only consume it as an expression if it is followed by , or {
+ // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
// That way we won't consume the body of a class in its heritage clause.
if (token() === 16 /* OpenBraceToken */) {
return lookAhead(isValidHeritageClauseObjectLiteral);
@@ -15247,7 +16081,7 @@ var ts;
// differently depending on what mode it is in.
//
// This also applies to all our other context flags as well.
- var nodeContextFlags = node.flags & 3080192 /* ContextFlags */;
+ var nodeContextFlags = node.flags & 96256 /* ContextFlags */;
if (nodeContextFlags !== contextFlags) {
return undefined;
}
@@ -15329,14 +16163,14 @@ var ts;
function isReusableClassMember(node) {
if (node) {
switch (node.kind) {
- case 150 /* Constructor */:
- case 155 /* IndexSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 147 /* PropertyDeclaration */:
- case 203 /* SemicolonClassElement */:
+ case 151 /* Constructor */:
+ case 156 /* IndexSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 148 /* PropertyDeclaration */:
+ case 205 /* SemicolonClassElement */:
return true;
- case 149 /* MethodDeclaration */:
+ case 150 /* MethodDeclaration */:
// Method declarations are not necessarily reusable. An object-literal
// may have a method calls "constructor(...)" and we must reparse that
// into an actual .ConstructorDeclaration.
@@ -15351,8 +16185,8 @@ var ts;
function isReusableSwitchClause(node) {
if (node) {
switch (node.kind) {
- case 253 /* CaseClause */:
- case 254 /* DefaultClause */:
+ case 256 /* CaseClause */:
+ case 257 /* DefaultClause */:
return true;
}
}
@@ -15361,58 +16195,58 @@ var ts;
function isReusableStatement(node) {
if (node) {
switch (node.kind) {
- case 225 /* FunctionDeclaration */:
- case 205 /* VariableStatement */:
- case 204 /* Block */:
- case 208 /* IfStatement */:
- case 207 /* ExpressionStatement */:
- case 220 /* ThrowStatement */:
- case 216 /* ReturnStatement */:
- case 218 /* SwitchStatement */:
- case 215 /* BreakStatement */:
- case 214 /* ContinueStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- case 211 /* ForStatement */:
- case 210 /* WhileStatement */:
- case 217 /* WithStatement */:
- case 206 /* EmptyStatement */:
- case 221 /* TryStatement */:
- case 219 /* LabeledStatement */:
- case 209 /* DoStatement */:
- case 222 /* DebuggerStatement */:
- case 235 /* ImportDeclaration */:
- case 234 /* ImportEqualsDeclaration */:
- case 241 /* ExportDeclaration */:
- case 240 /* ExportAssignment */:
- case 230 /* ModuleDeclaration */:
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 229 /* EnumDeclaration */:
- case 228 /* TypeAliasDeclaration */:
+ case 227 /* FunctionDeclaration */:
+ case 207 /* VariableStatement */:
+ case 206 /* Block */:
+ case 210 /* IfStatement */:
+ case 209 /* ExpressionStatement */:
+ case 222 /* ThrowStatement */:
+ case 218 /* ReturnStatement */:
+ case 220 /* SwitchStatement */:
+ case 217 /* BreakStatement */:
+ case 216 /* ContinueStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ case 213 /* ForStatement */:
+ case 212 /* WhileStatement */:
+ case 219 /* WithStatement */:
+ case 208 /* EmptyStatement */:
+ case 223 /* TryStatement */:
+ case 221 /* LabeledStatement */:
+ case 211 /* DoStatement */:
+ case 224 /* DebuggerStatement */:
+ case 237 /* ImportDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 243 /* ExportDeclaration */:
+ case 242 /* ExportAssignment */:
+ case 232 /* ModuleDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
return true;
}
}
return false;
}
function isReusableEnumMember(node) {
- return node.kind === 260 /* EnumMember */;
+ return node.kind === 263 /* EnumMember */;
}
function isReusableTypeMember(node) {
if (node) {
switch (node.kind) {
- case 154 /* ConstructSignature */:
- case 148 /* MethodSignature */:
- case 155 /* IndexSignature */:
- case 146 /* PropertySignature */:
- case 153 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 149 /* MethodSignature */:
+ case 156 /* IndexSignature */:
+ case 147 /* PropertySignature */:
+ case 154 /* CallSignature */:
return true;
}
}
return false;
}
function isReusableVariableDeclaration(node) {
- if (node.kind !== 223 /* VariableDeclaration */) {
+ if (node.kind !== 225 /* VariableDeclaration */) {
return false;
}
// Very subtle incremental parsing bug. Consider the following code:
@@ -15433,7 +16267,7 @@ var ts;
return variableDeclarator.initializer === undefined;
}
function isReusableParameter(node) {
- if (node.kind !== 144 /* Parameter */) {
+ if (node.kind !== 145 /* Parameter */) {
return false;
}
// See the comment in isReusableVariableDeclaration for why we do this.
@@ -15480,7 +16314,6 @@ var ts;
case 25 /* JSDocRecordMembers */: return ts.Diagnostics.Property_assignment_expected;
}
}
- ;
// Parses a comma-delimited list of elements
function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
var saveParsingContext = parsingContext;
@@ -15546,7 +16379,7 @@ var ts;
function parseEntityName(allowReservedWords, diagnosticMessage) {
var entity = parseIdentifier(diagnosticMessage);
while (parseOptional(22 /* DotToken */)) {
- var node = createNode(141 /* QualifiedName */, entity.pos); // !!!
+ var node = createNode(142 /* QualifiedName */, entity.pos); // !!!
node.left = entity;
node.right = parseRightSideOfDot(allowReservedWords);
entity = finishNode(node);
@@ -15585,7 +16418,7 @@ var ts;
return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
}
function parseTemplateExpression() {
- var template = createNode(194 /* TemplateExpression */);
+ var template = createNode(195 /* TemplateExpression */);
template.head = parseTemplateHead();
ts.Debug.assert(template.head.kind === 13 /* TemplateHead */, "Template head has wrong token kind");
var templateSpans = createNodeArray();
@@ -15597,7 +16430,7 @@ var ts;
return finishNode(template);
}
function parseTemplateSpan() {
- var span = createNode(202 /* TemplateSpan */);
+ var span = createNode(204 /* TemplateSpan */);
span.expression = allowInAnd(parseExpression);
var literal;
if (token() === 17 /* CloseBraceToken */) {
@@ -15633,27 +16466,23 @@ var ts;
if (scanner.isUnterminated()) {
node.isUnterminated = true;
}
- var tokenPos = scanner.getTokenPos();
- nextToken();
- finishNode(node);
// Octal literals are not allowed in strict mode or ES5
// Note that theoretically the following condition would hold true literals like 009,
// which is not octal.But because of how the scanner separates the tokens, we would
// never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
// We also do not need to check for negatives because any prefix operator would be part of a
// parent unary expression.
- if (node.kind === 8 /* NumericLiteral */
- && sourceText.charCodeAt(tokenPos) === 48 /* _0 */
- && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) {
- node.isOctalLiteral = true;
+ if (node.kind === 8 /* NumericLiteral */) {
+ node.numericLiteralFlags = scanner.getNumericLiteralFlags();
}
+ nextToken();
+ finishNode(node);
return node;
}
// TYPES
function parseTypeReference() {
- var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected);
- var node = createNode(157 /* TypeReference */, typeName.pos);
- node.typeName = typeName;
+ var node = createNode(158 /* TypeReference */);
+ node.typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected);
if (!scanner.hasPrecedingLineBreak() && token() === 26 /* LessThanToken */) {
node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 26 /* LessThanToken */, 28 /* GreaterThanToken */);
}
@@ -15661,24 +16490,24 @@ var ts;
}
function parseThisTypePredicate(lhs) {
nextToken();
- var node = createNode(156 /* TypePredicate */, lhs.pos);
+ var node = createNode(157 /* TypePredicate */, lhs.pos);
node.parameterName = lhs;
node.type = parseType();
return finishNode(node);
}
function parseThisTypeNode() {
- var node = createNode(167 /* ThisType */);
+ var node = createNode(168 /* ThisType */);
nextToken();
return finishNode(node);
}
function parseTypeQuery() {
- var node = createNode(160 /* TypeQuery */);
+ var node = createNode(161 /* TypeQuery */);
parseExpected(102 /* TypeOfKeyword */);
node.exprName = parseEntityName(/*allowReservedWords*/ true);
return finishNode(node);
}
function parseTypeParameter() {
- var node = createNode(143 /* TypeParameter */);
+ var node = createNode(144 /* TypeParameter */);
node.name = parseIdentifier();
if (parseOptional(84 /* ExtendsKeyword */)) {
// It's not uncommon for people to write improper constraints to a generic. If the
@@ -15699,6 +16528,9 @@ var ts;
node.expression = parseUnaryExpressionOrHigher();
}
}
+ if (parseOptional(57 /* EqualsToken */)) {
+ node.default = parseType();
+ }
return finishNode(node);
}
function parseTypeParameters() {
@@ -15716,9 +16548,9 @@ var ts;
return token() === 23 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 56 /* AtToken */ || token() === 98 /* ThisKeyword */;
}
function parseParameter() {
- var node = createNode(144 /* Parameter */);
+ var node = createNode(145 /* Parameter */);
if (token() === 98 /* ThisKeyword */) {
- node.name = createIdentifier(/*isIdentifier*/ true, undefined);
+ node.name = createIdentifier(/*isIdentifier*/ true);
node.type = parseParameterType();
return finishNode(node);
}
@@ -15815,7 +16647,7 @@ var ts;
}
function parseSignatureMember(kind) {
var node = createNode(kind);
- if (kind === 154 /* ConstructSignature */) {
+ if (kind === 155 /* ConstructSignature */) {
parseExpected(93 /* NewKeyword */);
}
fillSignature(55 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node);
@@ -15879,7 +16711,7 @@ var ts;
return token() === 55 /* ColonToken */ || token() === 25 /* CommaToken */ || token() === 21 /* CloseBracketToken */;
}
function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) {
- var node = createNode(155 /* IndexSignature */, fullStart);
+ var node = createNode(156 /* IndexSignature */, fullStart);
node.decorators = decorators;
node.modifiers = modifiers;
node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 20 /* OpenBracketToken */, 21 /* CloseBracketToken */);
@@ -15891,7 +16723,7 @@ var ts;
var name = parsePropertyName();
var questionToken = parseOptionalToken(54 /* QuestionToken */);
if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) {
- var method = createNode(148 /* MethodSignature */, fullStart);
+ var method = createNode(149 /* MethodSignature */, fullStart);
method.modifiers = modifiers;
method.name = name;
method.questionToken = questionToken;
@@ -15902,7 +16734,7 @@ var ts;
return addJSDocComment(finishNode(method));
}
else {
- var property = createNode(146 /* PropertySignature */, fullStart);
+ var property = createNode(147 /* PropertySignature */, fullStart);
property.modifiers = modifiers;
property.name = name;
property.questionToken = questionToken;
@@ -15918,14 +16750,14 @@ var ts;
}
}
function isTypeMemberStart() {
- var idToken;
// Return true if we have the start of a signature member
if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) {
return true;
}
+ var idToken;
// Eat up all modifiers, but hold on to the last one in case it is actually an identifier
while (ts.isModifierKind(token())) {
- idToken = token();
+ idToken = true;
nextToken();
}
// Index signatures and computed property names are type members
@@ -15934,7 +16766,7 @@ var ts;
}
// Try to get the first property-like token following all modifiers
if (isLiteralPropertyName()) {
- idToken = token();
+ idToken = true;
nextToken();
}
// If we were able to get any potential identifier, check that it is
@@ -15951,10 +16783,10 @@ var ts;
}
function parseTypeMember() {
if (token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */) {
- return parseSignatureMember(153 /* CallSignature */);
+ return parseSignatureMember(154 /* CallSignature */);
}
if (token() === 93 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) {
- return parseSignatureMember(154 /* ConstructSignature */);
+ return parseSignatureMember(155 /* ConstructSignature */);
}
var fullStart = getNodePos();
var modifiers = parseModifiers();
@@ -15968,7 +16800,7 @@ var ts;
return token() === 18 /* OpenParenToken */ || token() === 26 /* LessThanToken */;
}
function parseTypeLiteral() {
- var node = createNode(161 /* TypeLiteral */);
+ var node = createNode(162 /* TypeLiteral */);
node.members = parseObjectTypeMembers();
return finishNode(node);
}
@@ -15991,14 +16823,14 @@ var ts;
return token() === 20 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 91 /* InKeyword */;
}
function parseMappedTypeParameter() {
- var node = createNode(143 /* TypeParameter */);
+ var node = createNode(144 /* TypeParameter */);
node.name = parseIdentifier();
parseExpected(91 /* InKeyword */);
node.constraint = parseType();
return finishNode(node);
}
function parseMappedType() {
- var node = createNode(170 /* MappedType */);
+ var node = createNode(171 /* MappedType */);
parseExpected(16 /* OpenBraceToken */);
node.readonlyToken = parseOptionalToken(130 /* ReadonlyKeyword */);
parseExpected(20 /* OpenBracketToken */);
@@ -16011,12 +16843,12 @@ var ts;
return finishNode(node);
}
function parseTupleType() {
- var node = createNode(163 /* TupleType */);
+ var node = createNode(164 /* TupleType */);
node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 20 /* OpenBracketToken */, 21 /* CloseBracketToken */);
return finishNode(node);
}
function parseParenthesizedType() {
- var node = createNode(166 /* ParenthesizedType */);
+ var node = createNode(167 /* ParenthesizedType */);
parseExpected(18 /* OpenParenToken */);
node.type = parseType();
parseExpected(19 /* CloseParenToken */);
@@ -16024,7 +16856,7 @@ var ts;
}
function parseFunctionOrConstructorType(kind) {
var node = createNode(kind);
- if (kind === 159 /* ConstructorType */) {
+ if (kind === 160 /* ConstructorType */) {
parseExpected(93 /* NewKeyword */);
}
fillSignature(35 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node);
@@ -16035,7 +16867,7 @@ var ts;
return token() === 22 /* DotToken */ ? undefined : node;
}
function parseLiteralTypeNode() {
- var node = createNode(171 /* LiteralType */);
+ var node = createNode(172 /* LiteralType */);
node.literal = parseSimpleUnaryExpression();
finishNode(node);
return node;
@@ -16046,12 +16878,13 @@ var ts;
function parseNonArrayType() {
switch (token()) {
case 118 /* AnyKeyword */:
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
case 132 /* NumberKeyword */:
case 121 /* BooleanKeyword */:
- case 135 /* SymbolKeyword */:
- case 137 /* UndefinedKeyword */:
+ case 136 /* SymbolKeyword */:
+ case 138 /* UndefinedKeyword */:
case 129 /* NeverKeyword */:
+ case 133 /* ObjectKeyword */:
// If these are followed by a dot, then parse these out as a dotted type reference instead.
var node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReference();
@@ -16089,12 +16922,12 @@ var ts;
function isStartOfType() {
switch (token()) {
case 118 /* AnyKeyword */:
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
case 132 /* NumberKeyword */:
case 121 /* BooleanKeyword */:
- case 135 /* SymbolKeyword */:
+ case 136 /* SymbolKeyword */:
case 104 /* VoidKeyword */:
- case 137 /* UndefinedKeyword */:
+ case 138 /* UndefinedKeyword */:
case 94 /* NullKeyword */:
case 98 /* ThisKeyword */:
case 102 /* TypeOfKeyword */:
@@ -16102,11 +16935,14 @@ var ts;
case 16 /* OpenBraceToken */:
case 20 /* OpenBracketToken */:
case 26 /* LessThanToken */:
+ case 48 /* BarToken */:
+ case 47 /* AmpersandToken */:
case 93 /* NewKeyword */:
case 9 /* StringLiteral */:
case 8 /* NumericLiteral */:
case 100 /* TrueKeyword */:
case 85 /* FalseKeyword */:
+ case 133 /* ObjectKeyword */:
return true;
case 37 /* MinusToken */:
return lookAhead(nextTokenIsNumericLiteral);
@@ -16126,14 +16962,14 @@ var ts;
var type = parseNonArrayType();
while (!scanner.hasPrecedingLineBreak() && parseOptional(20 /* OpenBracketToken */)) {
if (isStartOfType()) {
- var node = createNode(169 /* IndexedAccessType */, type.pos);
+ var node = createNode(170 /* IndexedAccessType */, type.pos);
node.objectType = type;
node.indexType = parseType();
parseExpected(21 /* CloseBracketToken */);
type = finishNode(node);
}
else {
- var node = createNode(162 /* ArrayType */, type.pos);
+ var node = createNode(163 /* ArrayType */, type.pos);
node.elementType = type;
parseExpected(21 /* CloseBracketToken */);
type = finishNode(node);
@@ -16142,7 +16978,7 @@ var ts;
return type;
}
function parseTypeOperator(operator) {
- var node = createNode(168 /* TypeOperator */);
+ var node = createNode(169 /* TypeOperator */);
parseExpected(operator);
node.operator = operator;
node.type = parseTypeOperatorOrHigher();
@@ -16156,6 +16992,7 @@ var ts;
return parseArrayTypeOrHigher();
}
function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
+ parseOptional(operator);
var type = parseConstituentType();
if (token() === operator) {
var types = createNodeArray([type], type.pos);
@@ -16170,10 +17007,10 @@ var ts;
return type;
}
function parseIntersectionTypeOrHigher() {
- return parseUnionOrIntersectionType(165 /* IntersectionType */, parseTypeOperatorOrHigher, 47 /* AmpersandToken */);
+ return parseUnionOrIntersectionType(166 /* IntersectionType */, parseTypeOperatorOrHigher, 47 /* AmpersandToken */);
}
function parseUnionTypeOrHigher() {
- return parseUnionOrIntersectionType(164 /* UnionType */, parseIntersectionTypeOrHigher, 48 /* BarToken */);
+ return parseUnionOrIntersectionType(165 /* UnionType */, parseIntersectionTypeOrHigher, 48 /* BarToken */);
}
function isStartOfFunctionType() {
if (token() === 26 /* LessThanToken */) {
@@ -16230,7 +17067,7 @@ var ts;
var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
var type = parseType();
if (typePredicateVariable) {
- var node = createNode(156 /* TypePredicate */, typePredicateVariable.pos);
+ var node = createNode(157 /* TypePredicate */, typePredicateVariable.pos);
node.parameterName = typePredicateVariable;
node.type = type;
return finishNode(node);
@@ -16249,14 +17086,14 @@ var ts;
function parseType() {
// The rules about 'yield' only apply to actual code/expression contexts. They don't
// apply to 'type' contexts. So we disable these parameters here before moving on.
- return doOutsideOfContext(655360 /* TypeExcludesFlags */, parseTypeWorker);
+ return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker);
}
function parseTypeWorker() {
if (isStartOfFunctionType()) {
- return parseFunctionOrConstructorType(158 /* FunctionType */);
+ return parseFunctionOrConstructorType(159 /* FunctionType */);
}
if (token() === 93 /* NewKeyword */) {
- return parseFunctionOrConstructorType(159 /* ConstructorType */);
+ return parseFunctionOrConstructorType(160 /* ConstructorType */);
}
return parseUnionTypeOrHigher();
}
@@ -16457,7 +17294,7 @@ var ts;
return !scanner.hasPrecedingLineBreak() && isIdentifier();
}
function parseYieldExpression() {
- var node = createNode(195 /* YieldExpression */);
+ var node = createNode(196 /* YieldExpression */);
// YieldExpression[In] :
// yield
// yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
@@ -16479,13 +17316,13 @@ var ts;
ts.Debug.assert(token() === 35 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
var node;
if (asyncModifier) {
- node = createNode(185 /* ArrowFunction */, asyncModifier.pos);
+ node = createNode(186 /* ArrowFunction */, asyncModifier.pos);
node.modifiers = asyncModifier;
}
else {
- node = createNode(185 /* ArrowFunction */, identifier.pos);
+ node = createNode(186 /* ArrowFunction */, identifier.pos);
}
- var parameter = createNode(144 /* Parameter */, identifier.pos);
+ var parameter = createNode(145 /* Parameter */, identifier.pos);
parameter.name = identifier;
finishNode(parameter);
node.parameters = createNodeArray([parameter], parameter.pos);
@@ -16667,7 +17504,7 @@ var ts;
return 0 /* False */;
}
function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
- var node = createNode(185 /* ArrowFunction */);
+ var node = createNode(186 /* ArrowFunction */);
node.modifiers = parseModifiersForArrowFunction();
var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */);
// Arrow functions are never generators.
@@ -16733,7 +17570,7 @@ var ts;
}
// Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
// we do not that for the 'whenFalse' part.
- var node = createNode(193 /* ConditionalExpression */, leftOperand.pos);
+ var node = createNode(194 /* ConditionalExpression */, leftOperand.pos);
node.condition = leftOperand;
node.questionToken = questionToken;
node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
@@ -16746,7 +17583,7 @@ var ts;
return parseBinaryExpressionRest(precedence, leftOperand);
}
function isInOrOfKeyword(t) {
- return t === 91 /* InKeyword */ || t === 140 /* OfKeyword */;
+ return t === 91 /* InKeyword */ || t === 141 /* OfKeyword */;
}
function parseBinaryExpressionRest(precedence, leftOperand) {
while (true) {
@@ -16854,39 +17691,39 @@ var ts;
return -1;
}
function makeBinaryExpression(left, operatorToken, right) {
- var node = createNode(192 /* BinaryExpression */, left.pos);
+ var node = createNode(193 /* BinaryExpression */, left.pos);
node.left = left;
node.operatorToken = operatorToken;
node.right = right;
return finishNode(node);
}
function makeAsExpression(left, right) {
- var node = createNode(200 /* AsExpression */, left.pos);
+ var node = createNode(201 /* AsExpression */, left.pos);
node.expression = left;
node.type = right;
return finishNode(node);
}
function parsePrefixUnaryExpression() {
- var node = createNode(190 /* PrefixUnaryExpression */);
+ var node = createNode(191 /* PrefixUnaryExpression */);
node.operator = token();
nextToken();
node.operand = parseSimpleUnaryExpression();
return finishNode(node);
}
function parseDeleteExpression() {
- var node = createNode(186 /* DeleteExpression */);
+ var node = createNode(187 /* DeleteExpression */);
nextToken();
node.expression = parseSimpleUnaryExpression();
return finishNode(node);
}
function parseTypeOfExpression() {
- var node = createNode(187 /* TypeOfExpression */);
+ var node = createNode(188 /* TypeOfExpression */);
nextToken();
node.expression = parseSimpleUnaryExpression();
return finishNode(node);
}
function parseVoidExpression() {
- var node = createNode(188 /* VoidExpression */);
+ var node = createNode(189 /* VoidExpression */);
nextToken();
node.expression = parseSimpleUnaryExpression();
return finishNode(node);
@@ -16902,7 +17739,7 @@ var ts;
return false;
}
function parseAwaitExpression() {
- var node = createNode(189 /* AwaitExpression */);
+ var node = createNode(190 /* AwaitExpression */);
nextToken();
node.expression = parseSimpleUnaryExpression();
return finishNode(node);
@@ -16945,7 +17782,7 @@ var ts;
var simpleUnaryExpression = parseSimpleUnaryExpression();
if (token() === 39 /* AsteriskAsteriskToken */) {
var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
- if (simpleUnaryExpression.kind === 182 /* TypeAssertionExpression */) {
+ if (simpleUnaryExpression.kind === 183 /* TypeAssertionExpression */) {
parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses);
}
else {
@@ -16990,6 +17827,7 @@ var ts;
if (isAwaitExpression()) {
return parseAwaitExpression();
}
+ // falls through
default:
return parseIncrementExpression();
}
@@ -17023,7 +17861,7 @@ var ts;
return false;
}
// We are in JSX context and the token is part of JSXElement.
- // Fall through
+ // falls through
default:
return true;
}
@@ -17041,7 +17879,7 @@ var ts;
*/
function parseIncrementExpression() {
if (token() === 42 /* PlusPlusToken */ || token() === 43 /* MinusMinusToken */) {
- var node = createNode(190 /* PrefixUnaryExpression */);
+ var node = createNode(191 /* PrefixUnaryExpression */);
node.operator = token();
nextToken();
node.operand = parseLeftHandSideExpressionOrHigher();
@@ -17054,7 +17892,7 @@ var ts;
var expression = parseLeftHandSideExpressionOrHigher();
ts.Debug.assert(ts.isLeftHandSideExpression(expression));
if ((token() === 42 /* PlusPlusToken */ || token() === 43 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
- var node = createNode(191 /* PostfixUnaryExpression */, expression.pos);
+ var node = createNode(192 /* PostfixUnaryExpression */, expression.pos);
node.operand = expression;
node.operator = token();
nextToken();
@@ -17158,7 +17996,7 @@ var ts;
}
// If we have seen "super" it must be followed by '(' or '.'.
// If it wasn't then just try to parse out a '.' and report an error.
- var node = createNode(177 /* PropertyAccessExpression */, expression.pos);
+ var node = createNode(178 /* PropertyAccessExpression */, expression.pos);
node.expression = expression;
parseExpectedToken(22 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
@@ -17183,8 +18021,8 @@ var ts;
function parseJsxElementOrSelfClosingElement(inExpressionContext) {
var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext);
var result;
- if (opening.kind === 248 /* JsxOpeningElement */) {
- var node = createNode(246 /* JsxElement */, opening.pos);
+ if (opening.kind === 250 /* JsxOpeningElement */) {
+ var node = createNode(248 /* JsxElement */, opening.pos);
node.openingElement = opening;
node.children = parseJsxChildren(node.openingElement.tagName);
node.closingElement = parseJsxClosingElement(inExpressionContext);
@@ -17194,7 +18032,7 @@ var ts;
result = finishNode(node);
}
else {
- ts.Debug.assert(opening.kind === 247 /* JsxSelfClosingElement */);
+ ts.Debug.assert(opening.kind === 249 /* JsxSelfClosingElement */);
// Nothing else to do for self-closing elements
result = opening;
}
@@ -17209,7 +18047,7 @@ var ts;
var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); });
if (invalidElement) {
parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
- var badNode = createNode(192 /* BinaryExpression */, result.pos);
+ var badNode = createNode(193 /* BinaryExpression */, result.pos);
badNode.end = invalidElement.end;
badNode.left = result;
badNode.right = invalidElement;
@@ -17252,23 +18090,31 @@ var ts;
parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName));
break;
}
+ else if (token() === 7 /* ConflictMarkerTrivia */) {
+ break;
+ }
result.push(parseJsxChild());
}
result.end = scanner.getTokenPos();
parsingContext = saveParsingContext;
return result;
}
+ function parseJsxAttributes() {
+ var jsxAttributes = createNode(253 /* JsxAttributes */);
+ jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
+ return finishNode(jsxAttributes);
+ }
function parseJsxOpeningOrSelfClosingElement(inExpressionContext) {
var fullStart = scanner.getStartPos();
parseExpected(26 /* LessThanToken */);
var tagName = parseJsxElementName();
- var attributes = parseList(13 /* JsxAttributes */, parseJsxAttribute);
+ var attributes = parseJsxAttributes();
var node;
if (token() === 28 /* GreaterThanToken */) {
// Closing tag, so scan the immediately-following text with the JSX scanning instead
// of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
// scanning errors
- node = createNode(248 /* JsxOpeningElement */, fullStart);
+ node = createNode(250 /* JsxOpeningElement */, fullStart);
scanJsxText();
}
else {
@@ -17280,7 +18126,7 @@ var ts;
parseExpected(28 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
scanJsxText();
}
- node = createNode(247 /* JsxSelfClosingElement */, fullStart);
+ node = createNode(249 /* JsxSelfClosingElement */, fullStart);
}
node.tagName = tagName;
node.attributes = attributes;
@@ -17296,7 +18142,7 @@ var ts;
var expression = token() === 98 /* ThisKeyword */ ?
parseTokenNode() : parseIdentifierName();
while (parseOptional(22 /* DotToken */)) {
- var propertyAccess = createNode(177 /* PropertyAccessExpression */, expression.pos);
+ var propertyAccess = createNode(178 /* PropertyAccessExpression */, expression.pos);
propertyAccess.expression = expression;
propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
expression = finishNode(propertyAccess);
@@ -17304,9 +18150,10 @@ var ts;
return expression;
}
function parseJsxExpression(inExpressionContext) {
- var node = createNode(252 /* JsxExpression */);
+ var node = createNode(255 /* JsxExpression */);
parseExpected(16 /* OpenBraceToken */);
if (token() !== 17 /* CloseBraceToken */) {
+ node.dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */);
node.expression = parseAssignmentExpressionOrHigher();
}
if (inExpressionContext) {
@@ -17323,7 +18170,7 @@ var ts;
return parseJsxSpreadAttribute();
}
scanJsxIdentifier();
- var node = createNode(250 /* JsxAttribute */);
+ var node = createNode(252 /* JsxAttribute */);
node.name = parseIdentifierName();
if (token() === 57 /* EqualsToken */) {
switch (scanJsxAttributeValue()) {
@@ -17338,7 +18185,7 @@ var ts;
return finishNode(node);
}
function parseJsxSpreadAttribute() {
- var node = createNode(251 /* JsxSpreadAttribute */);
+ var node = createNode(254 /* JsxSpreadAttribute */);
parseExpected(16 /* OpenBraceToken */);
parseExpected(23 /* DotDotDotToken */);
node.expression = parseExpression();
@@ -17346,7 +18193,7 @@ var ts;
return finishNode(node);
}
function parseJsxClosingElement(inExpressionContext) {
- var node = createNode(249 /* JsxClosingElement */);
+ var node = createNode(251 /* JsxClosingElement */);
parseExpected(27 /* LessThanSlashToken */);
node.tagName = parseJsxElementName();
if (inExpressionContext) {
@@ -17359,7 +18206,7 @@ var ts;
return finishNode(node);
}
function parseTypeAssertion() {
- var node = createNode(182 /* TypeAssertionExpression */);
+ var node = createNode(183 /* TypeAssertionExpression */);
parseExpected(26 /* LessThanToken */);
node.type = parseType();
parseExpected(28 /* GreaterThanToken */);
@@ -17370,7 +18217,7 @@ var ts;
while (true) {
var dotToken = parseOptionalToken(22 /* DotToken */);
if (dotToken) {
- var propertyAccess = createNode(177 /* PropertyAccessExpression */, expression.pos);
+ var propertyAccess = createNode(178 /* PropertyAccessExpression */, expression.pos);
propertyAccess.expression = expression;
propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
expression = finishNode(propertyAccess);
@@ -17378,14 +18225,14 @@ var ts;
}
if (token() === 50 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
nextToken();
- var nonNullExpression = createNode(201 /* NonNullExpression */, expression.pos);
+ var nonNullExpression = createNode(202 /* NonNullExpression */, expression.pos);
nonNullExpression.expression = expression;
expression = finishNode(nonNullExpression);
continue;
}
// when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
if (!inDecoratorContext() && parseOptional(20 /* OpenBracketToken */)) {
- var indexedAccess = createNode(178 /* ElementAccessExpression */, expression.pos);
+ var indexedAccess = createNode(179 /* ElementAccessExpression */, expression.pos);
indexedAccess.expression = expression;
// It's not uncommon for a user to write: "new Type[]".
// Check for that common pattern and report a better error message.
@@ -17401,7 +18248,7 @@ var ts;
continue;
}
if (token() === 12 /* NoSubstitutionTemplateLiteral */ || token() === 13 /* TemplateHead */) {
- var tagExpression = createNode(181 /* TaggedTemplateExpression */, expression.pos);
+ var tagExpression = createNode(182 /* TaggedTemplateExpression */, expression.pos);
tagExpression.tag = expression;
tagExpression.template = token() === 12 /* NoSubstitutionTemplateLiteral */
? parseLiteralNode()
@@ -17424,7 +18271,7 @@ var ts;
if (!typeArguments) {
return expression;
}
- var callExpr = createNode(179 /* CallExpression */, expression.pos);
+ var callExpr = createNode(180 /* CallExpression */, expression.pos);
callExpr.expression = expression;
callExpr.typeArguments = typeArguments;
callExpr.arguments = parseArgumentList();
@@ -17432,7 +18279,7 @@ var ts;
continue;
}
else if (token() === 18 /* OpenParenToken */) {
- var callExpr = createNode(179 /* CallExpression */, expression.pos);
+ var callExpr = createNode(180 /* CallExpression */, expression.pos);
callExpr.expression = expression;
callExpr.arguments = parseArgumentList();
expression = finishNode(callExpr);
@@ -17542,28 +18389,28 @@ var ts;
return parseIdentifier(ts.Diagnostics.Expression_expected);
}
function parseParenthesizedExpression() {
- var node = createNode(183 /* ParenthesizedExpression */);
+ var node = createNode(184 /* ParenthesizedExpression */);
parseExpected(18 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
parseExpected(19 /* CloseParenToken */);
return finishNode(node);
}
function parseSpreadElement() {
- var node = createNode(196 /* SpreadElement */);
+ var node = createNode(197 /* SpreadElement */);
parseExpected(23 /* DotDotDotToken */);
node.expression = parseAssignmentExpressionOrHigher();
return finishNode(node);
}
function parseArgumentOrArrayLiteralElement() {
return token() === 23 /* DotDotDotToken */ ? parseSpreadElement() :
- token() === 25 /* CommaToken */ ? createNode(198 /* OmittedExpression */) :
+ token() === 25 /* CommaToken */ ? createNode(199 /* OmittedExpression */) :
parseAssignmentExpressionOrHigher();
}
function parseArgumentExpression() {
return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
}
function parseArrayLiteralExpression() {
- var node = createNode(175 /* ArrayLiteralExpression */);
+ var node = createNode(176 /* ArrayLiteralExpression */);
parseExpected(20 /* OpenBracketToken */);
if (scanner.hasPrecedingLineBreak()) {
node.multiLine = true;
@@ -17574,10 +18421,10 @@ var ts;
}
function tryParseAccessorDeclaration(fullStart, decorators, modifiers) {
if (parseContextualModifier(124 /* GetKeyword */)) {
- return parseAccessorDeclaration(151 /* GetAccessor */, fullStart, decorators, modifiers);
+ return parseAccessorDeclaration(152 /* GetAccessor */, fullStart, decorators, modifiers);
}
- else if (parseContextualModifier(133 /* SetKeyword */)) {
- return parseAccessorDeclaration(152 /* SetAccessor */, fullStart, decorators, modifiers);
+ else if (parseContextualModifier(134 /* SetKeyword */)) {
+ return parseAccessorDeclaration(153 /* SetAccessor */, fullStart, decorators, modifiers);
}
return undefined;
}
@@ -17585,7 +18432,7 @@ var ts;
var fullStart = scanner.getStartPos();
var dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */);
if (dotDotDotToken) {
- var spreadElement = createNode(259 /* SpreadAssignment */, fullStart);
+ var spreadElement = createNode(262 /* SpreadAssignment */, fullStart);
spreadElement.expression = parseAssignmentExpressionOrHigher();
return addJSDocComment(finishNode(spreadElement));
}
@@ -17610,7 +18457,7 @@ var ts;
// this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 25 /* CommaToken */ || token() === 17 /* CloseBraceToken */ || token() === 57 /* EqualsToken */);
if (isShorthandPropertyAssignment) {
- var shorthandDeclaration = createNode(258 /* ShorthandPropertyAssignment */, fullStart);
+ var shorthandDeclaration = createNode(261 /* ShorthandPropertyAssignment */, fullStart);
shorthandDeclaration.name = propertyName;
shorthandDeclaration.questionToken = questionToken;
var equalsToken = parseOptionalToken(57 /* EqualsToken */);
@@ -17621,7 +18468,7 @@ var ts;
return addJSDocComment(finishNode(shorthandDeclaration));
}
else {
- var propertyAssignment = createNode(257 /* PropertyAssignment */, fullStart);
+ var propertyAssignment = createNode(260 /* PropertyAssignment */, fullStart);
propertyAssignment.modifiers = modifiers;
propertyAssignment.name = propertyName;
propertyAssignment.questionToken = questionToken;
@@ -17631,7 +18478,7 @@ var ts;
}
}
function parseObjectLiteralExpression() {
- var node = createNode(176 /* ObjectLiteralExpression */);
+ var node = createNode(177 /* ObjectLiteralExpression */);
parseExpected(16 /* OpenBraceToken */);
if (scanner.hasPrecedingLineBreak()) {
node.multiLine = true;
@@ -17650,7 +18497,7 @@ var ts;
if (saveDecoratorContext) {
setDecoratorContext(/*val*/ false);
}
- var node = createNode(184 /* FunctionExpression */);
+ var node = createNode(185 /* FunctionExpression */);
node.modifiers = parseModifiers();
parseExpected(88 /* FunctionKeyword */);
node.asteriskToken = parseOptionalToken(38 /* AsteriskToken */);
@@ -17672,8 +18519,15 @@ var ts;
return isIdentifier() ? parseIdentifier() : undefined;
}
function parseNewExpression() {
- var node = createNode(180 /* NewExpression */);
+ var fullStart = scanner.getStartPos();
parseExpected(93 /* NewKeyword */);
+ if (parseOptional(22 /* DotToken */)) {
+ var node_1 = createNode(203 /* MetaProperty */, fullStart);
+ node_1.keywordToken = 93 /* NewKeyword */;
+ node_1.name = parseIdentifierName();
+ return finishNode(node_1);
+ }
+ var node = createNode(181 /* NewExpression */, fullStart);
node.expression = parseMemberExpressionOrHigher();
node.typeArguments = tryParse(parseTypeArgumentsInExpression);
if (node.typeArguments || token() === 18 /* OpenParenToken */) {
@@ -17683,7 +18537,7 @@ var ts;
}
// STATEMENTS
function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
- var node = createNode(204 /* Block */);
+ var node = createNode(206 /* Block */);
if (parseExpected(16 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
if (scanner.hasPrecedingLineBreak()) {
node.multiLine = true;
@@ -17716,12 +18570,12 @@ var ts;
return block;
}
function parseEmptyStatement() {
- var node = createNode(206 /* EmptyStatement */);
+ var node = createNode(208 /* EmptyStatement */);
parseExpected(24 /* SemicolonToken */);
return finishNode(node);
}
function parseIfStatement() {
- var node = createNode(208 /* IfStatement */);
+ var node = createNode(210 /* IfStatement */);
parseExpected(89 /* IfKeyword */);
parseExpected(18 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
@@ -17731,7 +18585,7 @@ var ts;
return finishNode(node);
}
function parseDoStatement() {
- var node = createNode(209 /* DoStatement */);
+ var node = createNode(211 /* DoStatement */);
parseExpected(80 /* DoKeyword */);
node.statement = parseStatement();
parseExpected(105 /* WhileKeyword */);
@@ -17746,7 +18600,7 @@ var ts;
return finishNode(node);
}
function parseWhileStatement() {
- var node = createNode(210 /* WhileStatement */);
+ var node = createNode(212 /* WhileStatement */);
parseExpected(105 /* WhileKeyword */);
parseExpected(18 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
@@ -17757,6 +18611,7 @@ var ts;
function parseForOrForInOrForOfStatement() {
var pos = getNodePos();
parseExpected(87 /* ForKeyword */);
+ var awaitToken = parseOptionalToken(120 /* AwaitKeyword */);
parseExpected(18 /* OpenParenToken */);
var initializer = undefined;
if (token() !== 24 /* SemicolonToken */) {
@@ -17768,22 +18623,23 @@ var ts;
}
}
var forOrForInOrForOfStatement;
- if (parseOptional(91 /* InKeyword */)) {
- var forInStatement = createNode(212 /* ForInStatement */, pos);
- forInStatement.initializer = initializer;
- forInStatement.expression = allowInAnd(parseExpression);
- parseExpected(19 /* CloseParenToken */);
- forOrForInOrForOfStatement = forInStatement;
- }
- else if (parseOptional(140 /* OfKeyword */)) {
- var forOfStatement = createNode(213 /* ForOfStatement */, pos);
+ if (awaitToken ? parseExpected(141 /* OfKeyword */) : parseOptional(141 /* OfKeyword */)) {
+ var forOfStatement = createNode(215 /* ForOfStatement */, pos);
+ forOfStatement.awaitModifier = awaitToken;
forOfStatement.initializer = initializer;
forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
parseExpected(19 /* CloseParenToken */);
forOrForInOrForOfStatement = forOfStatement;
}
+ else if (parseOptional(91 /* InKeyword */)) {
+ var forInStatement = createNode(214 /* ForInStatement */, pos);
+ forInStatement.initializer = initializer;
+ forInStatement.expression = allowInAnd(parseExpression);
+ parseExpected(19 /* CloseParenToken */);
+ forOrForInOrForOfStatement = forInStatement;
+ }
else {
- var forStatement = createNode(211 /* ForStatement */, pos);
+ var forStatement = createNode(213 /* ForStatement */, pos);
forStatement.initializer = initializer;
parseExpected(24 /* SemicolonToken */);
if (token() !== 24 /* SemicolonToken */ && token() !== 19 /* CloseParenToken */) {
@@ -17801,7 +18657,7 @@ var ts;
}
function parseBreakOrContinueStatement(kind) {
var node = createNode(kind);
- parseExpected(kind === 215 /* BreakStatement */ ? 71 /* BreakKeyword */ : 76 /* ContinueKeyword */);
+ parseExpected(kind === 217 /* BreakStatement */ ? 71 /* BreakKeyword */ : 76 /* ContinueKeyword */);
if (!canParseSemicolon()) {
node.label = parseIdentifier();
}
@@ -17809,7 +18665,7 @@ var ts;
return finishNode(node);
}
function parseReturnStatement() {
- var node = createNode(216 /* ReturnStatement */);
+ var node = createNode(218 /* ReturnStatement */);
parseExpected(95 /* ReturnKeyword */);
if (!canParseSemicolon()) {
node.expression = allowInAnd(parseExpression);
@@ -17818,7 +18674,7 @@ var ts;
return finishNode(node);
}
function parseWithStatement() {
- var node = createNode(217 /* WithStatement */);
+ var node = createNode(219 /* WithStatement */);
parseExpected(106 /* WithKeyword */);
parseExpected(18 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
@@ -17827,7 +18683,7 @@ var ts;
return finishNode(node);
}
function parseCaseClause() {
- var node = createNode(253 /* CaseClause */);
+ var node = createNode(256 /* CaseClause */);
parseExpected(72 /* CaseKeyword */);
node.expression = allowInAnd(parseExpression);
parseExpected(55 /* ColonToken */);
@@ -17835,7 +18691,7 @@ var ts;
return finishNode(node);
}
function parseDefaultClause() {
- var node = createNode(254 /* DefaultClause */);
+ var node = createNode(257 /* DefaultClause */);
parseExpected(78 /* DefaultKeyword */);
parseExpected(55 /* ColonToken */);
node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
@@ -17845,12 +18701,12 @@ var ts;
return token() === 72 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
}
function parseSwitchStatement() {
- var node = createNode(218 /* SwitchStatement */);
+ var node = createNode(220 /* SwitchStatement */);
parseExpected(97 /* SwitchKeyword */);
parseExpected(18 /* OpenParenToken */);
node.expression = allowInAnd(parseExpression);
parseExpected(19 /* CloseParenToken */);
- var caseBlock = createNode(232 /* CaseBlock */, scanner.getStartPos());
+ var caseBlock = createNode(234 /* CaseBlock */, scanner.getStartPos());
parseExpected(16 /* OpenBraceToken */);
caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
parseExpected(17 /* CloseBraceToken */);
@@ -17865,7 +18721,7 @@ var ts;
// directly as that might consume an expression on the following line.
// We just return 'undefined' in that case. The actual error will be reported in the
// grammar walker.
- var node = createNode(220 /* ThrowStatement */);
+ var node = createNode(222 /* ThrowStatement */);
parseExpected(99 /* ThrowKeyword */);
node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
parseSemicolon();
@@ -17873,7 +18729,7 @@ var ts;
}
// TODO: Review for error recovery
function parseTryStatement() {
- var node = createNode(221 /* TryStatement */);
+ var node = createNode(223 /* TryStatement */);
parseExpected(101 /* TryKeyword */);
node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
node.catchClause = token() === 73 /* CatchKeyword */ ? parseCatchClause() : undefined;
@@ -17886,7 +18742,7 @@ var ts;
return finishNode(node);
}
function parseCatchClause() {
- var result = createNode(256 /* CatchClause */);
+ var result = createNode(259 /* CatchClause */);
parseExpected(73 /* CatchKeyword */);
if (parseExpected(18 /* OpenParenToken */)) {
result.variableDeclaration = parseVariableDeclaration();
@@ -17896,7 +18752,7 @@ var ts;
return finishNode(result);
}
function parseDebuggerStatement() {
- var node = createNode(222 /* DebuggerStatement */);
+ var node = createNode(224 /* DebuggerStatement */);
parseExpected(77 /* DebuggerKeyword */);
parseSemicolon();
return finishNode(node);
@@ -17908,13 +18764,13 @@ var ts;
var fullStart = scanner.getStartPos();
var expression = allowInAnd(parseExpression);
if (expression.kind === 70 /* Identifier */ && parseOptional(55 /* ColonToken */)) {
- var labeledStatement = createNode(219 /* LabeledStatement */, fullStart);
+ var labeledStatement = createNode(221 /* LabeledStatement */, fullStart);
labeledStatement.label = expression;
labeledStatement.statement = parseStatement();
return addJSDocComment(finishNode(labeledStatement));
}
else {
- var expressionStatement = createNode(207 /* ExpressionStatement */, fullStart);
+ var expressionStatement = createNode(209 /* ExpressionStatement */, fullStart);
expressionStatement.expression = expression;
parseSemicolon();
return addJSDocComment(finishNode(expressionStatement));
@@ -17924,6 +18780,10 @@ var ts;
nextToken();
return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
}
+ function nextTokenIsClassKeywordOnSameLine() {
+ nextToken();
+ return token() === 74 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
+ }
function nextTokenIsFunctionKeywordOnSameLine() {
nextToken();
return token() === 88 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
@@ -17964,7 +18824,7 @@ var ts;
//
// could be legal, it would add complexity for very little gain.
case 108 /* InterfaceKeyword */:
- case 136 /* TypeKeyword */:
+ case 137 /* TypeKeyword */:
return nextTokenIsIdentifierOnSameLine();
case 127 /* ModuleKeyword */:
case 128 /* NamespaceKeyword */:
@@ -17982,7 +18842,7 @@ var ts;
return false;
}
continue;
- case 139 /* GlobalKeyword */:
+ case 140 /* GlobalKeyword */:
nextToken();
return token() === 16 /* OpenBraceToken */ || token() === 70 /* Identifier */ || token() === 83 /* ExportKeyword */;
case 90 /* ImportKeyword */:
@@ -18044,8 +18904,8 @@ var ts;
case 108 /* InterfaceKeyword */:
case 127 /* ModuleKeyword */:
case 128 /* NamespaceKeyword */:
- case 136 /* TypeKeyword */:
- case 139 /* GlobalKeyword */:
+ case 137 /* TypeKeyword */:
+ case 140 /* GlobalKeyword */:
// When these don't start a declaration, they're an identifier in an expression statement
return true;
case 113 /* PublicKeyword */:
@@ -18095,9 +18955,9 @@ var ts;
case 87 /* ForKeyword */:
return parseForOrForInOrForOfStatement();
case 76 /* ContinueKeyword */:
- return parseBreakOrContinueStatement(214 /* ContinueStatement */);
+ return parseBreakOrContinueStatement(216 /* ContinueStatement */);
case 71 /* BreakKeyword */:
- return parseBreakOrContinueStatement(215 /* BreakStatement */);
+ return parseBreakOrContinueStatement(217 /* BreakStatement */);
case 95 /* ReturnKeyword */:
return parseReturnStatement();
case 106 /* WithKeyword */:
@@ -18117,7 +18977,7 @@ var ts;
return parseDeclaration();
case 119 /* AsyncKeyword */:
case 108 /* InterfaceKeyword */:
- case 136 /* TypeKeyword */:
+ case 137 /* TypeKeyword */:
case 127 /* ModuleKeyword */:
case 128 /* NamespaceKeyword */:
case 123 /* DeclareKeyword */:
@@ -18131,7 +18991,7 @@ var ts;
case 116 /* AbstractKeyword */:
case 114 /* StaticKeyword */:
case 130 /* ReadonlyKeyword */:
- case 139 /* GlobalKeyword */:
+ case 140 /* GlobalKeyword */:
if (isStartOfDeclaration()) {
return parseDeclaration();
}
@@ -18154,11 +19014,11 @@ var ts;
return parseClassDeclaration(fullStart, decorators, modifiers);
case 108 /* InterfaceKeyword */:
return parseInterfaceDeclaration(fullStart, decorators, modifiers);
- case 136 /* TypeKeyword */:
+ case 137 /* TypeKeyword */:
return parseTypeAliasDeclaration(fullStart, decorators, modifiers);
case 82 /* EnumKeyword */:
return parseEnumDeclaration(fullStart, decorators, modifiers);
- case 139 /* GlobalKeyword */:
+ case 140 /* GlobalKeyword */:
case 127 /* ModuleKeyword */:
case 128 /* NamespaceKeyword */:
return parseModuleDeclaration(fullStart, decorators, modifiers);
@@ -18179,7 +19039,7 @@ var ts;
if (decorators || modifiers) {
// We reached this point because we encountered decorators and/or modifiers and assumed a declaration
// would follow. For recovery and error reporting purposes, return an incomplete declaration.
- var node = createMissingNode(244 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
+ var node = createMissingNode(246 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
node.pos = fullStart;
node.decorators = decorators;
node.modifiers = modifiers;
@@ -18201,16 +19061,16 @@ var ts;
// DECLARATIONS
function parseArrayBindingElement() {
if (token() === 25 /* CommaToken */) {
- return createNode(198 /* OmittedExpression */);
+ return createNode(199 /* OmittedExpression */);
}
- var node = createNode(174 /* BindingElement */);
+ var node = createNode(175 /* BindingElement */);
node.dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */);
node.name = parseIdentifierOrPattern();
node.initializer = parseBindingElementInitializer(/*inParameter*/ false);
return finishNode(node);
}
function parseObjectBindingElement() {
- var node = createNode(174 /* BindingElement */);
+ var node = createNode(175 /* BindingElement */);
node.dotDotDotToken = parseOptionalToken(23 /* DotDotDotToken */);
var tokenIsIdentifier = isIdentifier();
var propertyName = parsePropertyName();
@@ -18226,14 +19086,14 @@ var ts;
return finishNode(node);
}
function parseObjectBindingPattern() {
- var node = createNode(172 /* ObjectBindingPattern */);
+ var node = createNode(173 /* ObjectBindingPattern */);
parseExpected(16 /* OpenBraceToken */);
node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
parseExpected(17 /* CloseBraceToken */);
return finishNode(node);
}
function parseArrayBindingPattern() {
- var node = createNode(173 /* ArrayBindingPattern */);
+ var node = createNode(174 /* ArrayBindingPattern */);
parseExpected(20 /* OpenBracketToken */);
node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
parseExpected(21 /* CloseBracketToken */);
@@ -18252,7 +19112,7 @@ var ts;
return parseIdentifier();
}
function parseVariableDeclaration() {
- var node = createNode(223 /* VariableDeclaration */);
+ var node = createNode(225 /* VariableDeclaration */);
node.name = parseIdentifierOrPattern();
node.type = parseTypeAnnotation();
if (!isInOrOfKeyword(token())) {
@@ -18261,7 +19121,7 @@ var ts;
return finishNode(node);
}
function parseVariableDeclarationList(inForStatementInitializer) {
- var node = createNode(224 /* VariableDeclarationList */);
+ var node = createNode(226 /* VariableDeclarationList */);
switch (token()) {
case 103 /* VarKeyword */:
break;
@@ -18284,7 +19144,7 @@ var ts;
// So we need to look ahead to determine if 'of' should be treated as a keyword in
// this context.
// The checker will then give an error that there is an empty declaration list.
- if (token() === 140 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
+ if (token() === 141 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
node.declarations = createMissingList();
}
else {
@@ -18299,7 +19159,7 @@ var ts;
return nextTokenIsIdentifier() && nextToken() === 19 /* CloseParenToken */;
}
function parseVariableStatement(fullStart, decorators, modifiers) {
- var node = createNode(205 /* VariableStatement */, fullStart);
+ var node = createNode(207 /* VariableStatement */, fullStart);
node.decorators = decorators;
node.modifiers = modifiers;
node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
@@ -18307,7 +19167,7 @@ var ts;
return addJSDocComment(finishNode(node));
}
function parseFunctionDeclaration(fullStart, decorators, modifiers) {
- var node = createNode(225 /* FunctionDeclaration */, fullStart);
+ var node = createNode(227 /* FunctionDeclaration */, fullStart);
node.decorators = decorators;
node.modifiers = modifiers;
parseExpected(88 /* FunctionKeyword */);
@@ -18320,7 +19180,7 @@ var ts;
return addJSDocComment(finishNode(node));
}
function parseConstructorDeclaration(pos, decorators, modifiers) {
- var node = createNode(150 /* Constructor */, pos);
+ var node = createNode(151 /* Constructor */, pos);
node.decorators = decorators;
node.modifiers = modifiers;
parseExpected(122 /* ConstructorKeyword */);
@@ -18329,7 +19189,7 @@ var ts;
return addJSDocComment(finishNode(node));
}
function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) {
- var method = createNode(149 /* MethodDeclaration */, fullStart);
+ var method = createNode(150 /* MethodDeclaration */, fullStart);
method.decorators = decorators;
method.modifiers = modifiers;
method.asteriskToken = asteriskToken;
@@ -18342,7 +19202,7 @@ var ts;
return addJSDocComment(finishNode(method));
}
function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) {
- var property = createNode(147 /* PropertyDeclaration */, fullStart);
+ var property = createNode(148 /* PropertyDeclaration */, fullStart);
property.decorators = decorators;
property.modifiers = modifiers;
property.name = name;
@@ -18359,7 +19219,7 @@ var ts;
// The checker may still error in the static case to explicitly disallow the yield expression.
property.initializer = ts.hasModifier(property, 32 /* Static */)
? allowInAnd(parseNonParameterInitializer)
- : doOutsideOfContext(131072 /* YieldContext */ | 65536 /* DisallowInContext */, parseNonParameterInitializer);
+ : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseNonParameterInitializer);
parseSemicolon();
return addJSDocComment(finishNode(property));
}
@@ -18435,7 +19295,7 @@ var ts;
// If we were able to get any potential identifier...
if (idToken !== undefined) {
// If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
- if (!ts.isKeyword(idToken) || idToken === 133 /* SetKeyword */ || idToken === 124 /* GetKeyword */) {
+ if (!ts.isKeyword(idToken) || idToken === 134 /* SetKeyword */ || idToken === 124 /* GetKeyword */) {
return true;
}
// If it *is* a keyword, but not an accessor, check a little farther along
@@ -18465,7 +19325,7 @@ var ts;
if (!parseOptional(56 /* AtToken */)) {
break;
}
- var decorator = createNode(145 /* Decorator */, decoratorStart);
+ var decorator = createNode(146 /* Decorator */, decoratorStart);
decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
finishNode(decorator);
if (!decorators) {
@@ -18531,7 +19391,7 @@ var ts;
}
function parseClassElement() {
if (token() === 24 /* SemicolonToken */) {
- var result = createNode(203 /* SemicolonClassElement */);
+ var result = createNode(205 /* SemicolonClassElement */);
nextToken();
return finishNode(result);
}
@@ -18559,8 +19419,8 @@ var ts;
}
if (decorators || modifiers) {
// treat this as a property declaration with a missing name.
- var name_13 = createMissingNode(70 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
- return parsePropertyDeclaration(fullStart, decorators, modifiers, name_13, /*questionToken*/ undefined);
+ var name = createMissingNode(70 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
+ return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined);
}
// 'isClassMemberStart' should have hinted not to attempt parsing.
ts.Debug.fail("Should not have attempted to parse class member declaration.");
@@ -18569,10 +19429,10 @@ var ts;
return parseClassDeclarationOrExpression(
/*fullStart*/ scanner.getStartPos(),
/*decorators*/ undefined,
- /*modifiers*/ undefined, 197 /* ClassExpression */);
+ /*modifiers*/ undefined, 198 /* ClassExpression */);
}
function parseClassDeclaration(fullStart, decorators, modifiers) {
- return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 226 /* ClassDeclaration */);
+ return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 228 /* ClassDeclaration */);
}
function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) {
var node = createNode(kind, fullStart);
@@ -18615,9 +19475,10 @@ var ts;
return undefined;
}
function parseHeritageClause() {
- if (token() === 84 /* ExtendsKeyword */ || token() === 107 /* ImplementsKeyword */) {
- var node = createNode(255 /* HeritageClause */);
- node.token = token();
+ var tok = token();
+ if (tok === 84 /* ExtendsKeyword */ || tok === 107 /* ImplementsKeyword */) {
+ var node = createNode(258 /* HeritageClause */);
+ node.token = tok;
nextToken();
node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
return finishNode(node);
@@ -18625,7 +19486,7 @@ var ts;
return undefined;
}
function parseExpressionWithTypeArguments() {
- var node = createNode(199 /* ExpressionWithTypeArguments */);
+ var node = createNode(200 /* ExpressionWithTypeArguments */);
node.expression = parseLeftHandSideExpressionOrHigher();
if (token() === 26 /* LessThanToken */) {
node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 26 /* LessThanToken */, 28 /* GreaterThanToken */);
@@ -18639,7 +19500,7 @@ var ts;
return parseList(5 /* ClassMembers */, parseClassElement);
}
function parseInterfaceDeclaration(fullStart, decorators, modifiers) {
- var node = createNode(227 /* InterfaceDeclaration */, fullStart);
+ var node = createNode(229 /* InterfaceDeclaration */, fullStart);
node.decorators = decorators;
node.modifiers = modifiers;
parseExpected(108 /* InterfaceKeyword */);
@@ -18650,10 +19511,10 @@ var ts;
return addJSDocComment(finishNode(node));
}
function parseTypeAliasDeclaration(fullStart, decorators, modifiers) {
- var node = createNode(228 /* TypeAliasDeclaration */, fullStart);
+ var node = createNode(230 /* TypeAliasDeclaration */, fullStart);
node.decorators = decorators;
node.modifiers = modifiers;
- parseExpected(136 /* TypeKeyword */);
+ parseExpected(137 /* TypeKeyword */);
node.name = parseIdentifier();
node.typeParameters = parseTypeParameters();
parseExpected(57 /* EqualsToken */);
@@ -18666,13 +19527,13 @@ var ts;
// ConstantEnumMemberSection, which starts at the beginning of an enum declaration
// or any time an integer literal initializer is encountered.
function parseEnumMember() {
- var node = createNode(260 /* EnumMember */, scanner.getStartPos());
+ var node = createNode(263 /* EnumMember */, scanner.getStartPos());
node.name = parsePropertyName();
node.initializer = allowInAnd(parseNonParameterInitializer);
return addJSDocComment(finishNode(node));
}
function parseEnumDeclaration(fullStart, decorators, modifiers) {
- var node = createNode(229 /* EnumDeclaration */, fullStart);
+ var node = createNode(231 /* EnumDeclaration */, fullStart);
node.decorators = decorators;
node.modifiers = modifiers;
parseExpected(82 /* EnumKeyword */);
@@ -18687,7 +19548,7 @@ var ts;
return addJSDocComment(finishNode(node));
}
function parseModuleBlock() {
- var node = createNode(231 /* ModuleBlock */, scanner.getStartPos());
+ var node = createNode(233 /* ModuleBlock */, scanner.getStartPos());
if (parseExpected(16 /* OpenBraceToken */)) {
node.statements = parseList(1 /* BlockStatements */, parseStatement);
parseExpected(17 /* CloseBraceToken */);
@@ -18698,7 +19559,7 @@ var ts;
return finishNode(node);
}
function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) {
- var node = createNode(230 /* ModuleDeclaration */, fullStart);
+ var node = createNode(232 /* ModuleDeclaration */, fullStart);
// If we are parsing a dotted namespace name, we want to
// propagate the 'Namespace' flag across the names if set.
var namespaceFlag = flags & 16 /* Namespace */;
@@ -18712,10 +19573,10 @@ var ts;
return addJSDocComment(finishNode(node));
}
function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) {
- var node = createNode(230 /* ModuleDeclaration */, fullStart);
+ var node = createNode(232 /* ModuleDeclaration */, fullStart);
node.decorators = decorators;
node.modifiers = modifiers;
- if (token() === 139 /* GlobalKeyword */) {
+ if (token() === 140 /* GlobalKeyword */) {
// parse 'global' as name of global scope augmentation
node.name = parseIdentifier();
node.flags |= 512 /* GlobalAugmentation */;
@@ -18733,7 +19594,7 @@ var ts;
}
function parseModuleDeclaration(fullStart, decorators, modifiers) {
var flags = 0;
- if (token() === 139 /* GlobalKeyword */) {
+ if (token() === 140 /* GlobalKeyword */) {
// global augmentation
return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers);
}
@@ -18759,7 +19620,7 @@ var ts;
return nextToken() === 40 /* SlashToken */;
}
function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) {
- var exportDeclaration = createNode(233 /* NamespaceExportDeclaration */, fullStart);
+ var exportDeclaration = createNode(235 /* NamespaceExportDeclaration */, fullStart);
exportDeclaration.decorators = decorators;
exportDeclaration.modifiers = modifiers;
parseExpected(117 /* AsKeyword */);
@@ -18774,22 +19635,12 @@ var ts;
var identifier;
if (isIdentifier()) {
identifier = parseIdentifier();
- if (token() !== 25 /* CommaToken */ && token() !== 138 /* FromKeyword */) {
- // ImportEquals declaration of type:
- // import x = require("mod"); or
- // import x = M.x;
- var importEqualsDeclaration = createNode(234 /* ImportEqualsDeclaration */, fullStart);
- importEqualsDeclaration.decorators = decorators;
- importEqualsDeclaration.modifiers = modifiers;
- importEqualsDeclaration.name = identifier;
- parseExpected(57 /* EqualsToken */);
- importEqualsDeclaration.moduleReference = parseModuleReference();
- parseSemicolon();
- return addJSDocComment(finishNode(importEqualsDeclaration));
+ if (token() !== 25 /* CommaToken */ && token() !== 139 /* FromKeyword */) {
+ return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier);
}
}
// Import statement
- var importDeclaration = createNode(235 /* ImportDeclaration */, fullStart);
+ var importDeclaration = createNode(237 /* ImportDeclaration */, fullStart);
importDeclaration.decorators = decorators;
importDeclaration.modifiers = modifiers;
// ImportDeclaration:
@@ -18799,12 +19650,22 @@ var ts;
token() === 38 /* AsteriskToken */ ||
token() === 16 /* OpenBraceToken */) {
importDeclaration.importClause = parseImportClause(identifier, afterImportPos);
- parseExpected(138 /* FromKeyword */);
+ parseExpected(139 /* FromKeyword */);
}
importDeclaration.moduleSpecifier = parseModuleSpecifier();
parseSemicolon();
return finishNode(importDeclaration);
}
+ function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) {
+ var importEqualsDeclaration = createNode(236 /* ImportEqualsDeclaration */, fullStart);
+ importEqualsDeclaration.decorators = decorators;
+ importEqualsDeclaration.modifiers = modifiers;
+ importEqualsDeclaration.name = identifier;
+ parseExpected(57 /* EqualsToken */);
+ importEqualsDeclaration.moduleReference = parseModuleReference();
+ parseSemicolon();
+ return addJSDocComment(finishNode(importEqualsDeclaration));
+ }
function parseImportClause(identifier, fullStart) {
// ImportClause:
// ImportedDefaultBinding
@@ -18812,7 +19673,7 @@ var ts;
// NamedImports
// ImportedDefaultBinding, NameSpaceImport
// ImportedDefaultBinding, NamedImports
- var importClause = createNode(236 /* ImportClause */, fullStart);
+ var importClause = createNode(238 /* ImportClause */, fullStart);
if (identifier) {
// ImportedDefaultBinding:
// ImportedBinding
@@ -18822,7 +19683,7 @@ var ts;
// parse namespace or named imports
if (!importClause.name ||
parseOptional(25 /* CommaToken */)) {
- importClause.namedBindings = token() === 38 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(238 /* NamedImports */);
+ importClause.namedBindings = token() === 38 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(240 /* NamedImports */);
}
return finishNode(importClause);
}
@@ -18832,7 +19693,7 @@ var ts;
: parseEntityName(/*allowReservedWords*/ false);
}
function parseExternalModuleReference() {
- var node = createNode(245 /* ExternalModuleReference */);
+ var node = createNode(247 /* ExternalModuleReference */);
parseExpected(131 /* RequireKeyword */);
parseExpected(18 /* OpenParenToken */);
node.expression = parseModuleSpecifier();
@@ -18855,7 +19716,7 @@ var ts;
function parseNamespaceImport() {
// NameSpaceImport:
// * as ImportedBinding
- var namespaceImport = createNode(237 /* NamespaceImport */);
+ var namespaceImport = createNode(239 /* NamespaceImport */);
parseExpected(38 /* AsteriskToken */);
parseExpected(117 /* AsKeyword */);
namespaceImport.name = parseIdentifier();
@@ -18870,14 +19731,14 @@ var ts;
// ImportsList:
// ImportSpecifier
// ImportsList, ImportSpecifier
- node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 238 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 16 /* OpenBraceToken */, 17 /* CloseBraceToken */);
+ node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 240 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 16 /* OpenBraceToken */, 17 /* CloseBraceToken */);
return finishNode(node);
}
function parseExportSpecifier() {
- return parseImportOrExportSpecifier(243 /* ExportSpecifier */);
+ return parseImportOrExportSpecifier(245 /* ExportSpecifier */);
}
function parseImportSpecifier() {
- return parseImportOrExportSpecifier(239 /* ImportSpecifier */);
+ return parseImportOrExportSpecifier(241 /* ImportSpecifier */);
}
function parseImportOrExportSpecifier(kind) {
var node = createNode(kind);
@@ -18902,27 +19763,27 @@ var ts;
else {
node.name = identifierName;
}
- if (kind === 239 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
+ if (kind === 241 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
// Report error identifier expected
parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected);
}
return finishNode(node);
}
function parseExportDeclaration(fullStart, decorators, modifiers) {
- var node = createNode(241 /* ExportDeclaration */, fullStart);
+ var node = createNode(243 /* ExportDeclaration */, fullStart);
node.decorators = decorators;
node.modifiers = modifiers;
if (parseOptional(38 /* AsteriskToken */)) {
- parseExpected(138 /* FromKeyword */);
+ parseExpected(139 /* FromKeyword */);
node.moduleSpecifier = parseModuleSpecifier();
}
else {
- node.exportClause = parseNamedImportsOrExports(242 /* NamedExports */);
+ node.exportClause = parseNamedImportsOrExports(244 /* NamedExports */);
// It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
// the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
// If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
- if (token() === 138 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
- parseExpected(138 /* FromKeyword */);
+ if (token() === 139 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
+ parseExpected(139 /* FromKeyword */);
node.moduleSpecifier = parseModuleSpecifier();
}
}
@@ -18930,7 +19791,7 @@ var ts;
return finishNode(node);
}
function parseExportAssignment(fullStart, decorators, modifiers) {
- var node = createNode(240 /* ExportAssignment */, fullStart);
+ var node = createNode(242 /* ExportAssignment */, fullStart);
node.decorators = decorators;
node.modifiers = modifiers;
if (parseOptional(57 /* EqualsToken */)) {
@@ -18949,6 +19810,7 @@ var ts;
var typeReferenceDirectives = [];
var amdDependencies = [];
var amdModuleName;
+ var checkJsDirective = undefined;
// Keep scanning all the leading trivia in the file until we get to something that
// isn't trivia. Any single line comment will be analyzed to see if it is a
// reference comment.
@@ -18962,7 +19824,11 @@ var ts;
break;
}
}
- var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() };
+ var range = {
+ kind: triviaScanner.getToken(),
+ pos: triviaScanner.getTokenPos(),
+ end: triviaScanner.getTextPos(),
+ };
var comment = sourceText.substring(range.pos, range.end);
var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range);
if (referencePathMatchResult) {
@@ -19002,20 +19868,30 @@ var ts;
amdDependencies.push(amdDependency);
}
}
+ var checkJsDirectiveRegEx = /^\/\/\/?\s*(@ts-check|@ts-nocheck)\s*$/gim;
+ var checkJsDirectiveMatchResult = checkJsDirectiveRegEx.exec(comment);
+ if (checkJsDirectiveMatchResult) {
+ checkJsDirective = {
+ enabled: ts.compareStrings(checkJsDirectiveMatchResult[1], "@ts-check", /*ignoreCase*/ true) === 0 /* EqualTo */,
+ end: range.end,
+ pos: range.pos
+ };
+ }
}
}
sourceFile.referencedFiles = referencedFiles;
sourceFile.typeReferenceDirectives = typeReferenceDirectives;
sourceFile.amdDependencies = amdDependencies;
sourceFile.moduleName = amdModuleName;
+ sourceFile.checkJsDirective = checkJsDirective;
}
function setExternalModuleIndicator(sourceFile) {
sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) {
return ts.hasModifier(node, 1 /* Export */)
- || node.kind === 234 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 245 /* ExternalModuleReference */
- || node.kind === 235 /* ImportDeclaration */
- || node.kind === 240 /* ExportAssignment */
- || node.kind === 241 /* ExportDeclaration */
+ || node.kind === 236 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 247 /* ExternalModuleReference */
+ || node.kind === 237 /* ImportDeclaration */
+ || node.kind === 242 /* ExportAssignment */
+ || node.kind === 243 /* ExportDeclaration */
? node
: undefined;
});
@@ -19090,7 +19966,7 @@ var ts;
// Parses out a JSDoc type expression.
/* @internal */
function parseJSDocTypeExpression() {
- var result = createNode(262 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var result = createNode(266 /* JSDocTypeExpression */, scanner.getTokenPos());
parseExpected(16 /* OpenBraceToken */);
result.type = parseJSDocTopLevelType();
parseExpected(17 /* CloseBraceToken */);
@@ -19101,12 +19977,12 @@ var ts;
function parseJSDocTopLevelType() {
var type = parseJSDocType();
if (token() === 48 /* BarToken */) {
- var unionType = createNode(266 /* JSDocUnionType */, type.pos);
+ var unionType = createNode(270 /* JSDocUnionType */, type.pos);
unionType.types = parseJSDocTypeList(type);
type = finishNode(unionType);
}
if (token() === 57 /* EqualsToken */) {
- var optionalType = createNode(273 /* JSDocOptionalType */, type.pos);
+ var optionalType = createNode(277 /* JSDocOptionalType */, type.pos);
nextToken();
optionalType.type = type;
type = finishNode(optionalType);
@@ -19117,20 +19993,20 @@ var ts;
var type = parseBasicTypeExpression();
while (true) {
if (token() === 20 /* OpenBracketToken */) {
- var arrayType = createNode(265 /* JSDocArrayType */, type.pos);
+ var arrayType = createNode(269 /* JSDocArrayType */, type.pos);
arrayType.elementType = type;
nextToken();
parseExpected(21 /* CloseBracketToken */);
type = finishNode(arrayType);
}
else if (token() === 54 /* QuestionToken */) {
- var nullableType = createNode(268 /* JSDocNullableType */, type.pos);
+ var nullableType = createNode(272 /* JSDocNullableType */, type.pos);
nullableType.type = type;
nextToken();
type = finishNode(nullableType);
}
else if (token() === 50 /* ExclamationToken */) {
- var nonNullableType = createNode(269 /* JSDocNonNullableType */, type.pos);
+ var nonNullableType = createNode(273 /* JSDocNonNullableType */, type.pos);
nonNullableType.type = type;
nextToken();
type = finishNode(nonNullableType);
@@ -19164,14 +20040,15 @@ var ts;
case 98 /* ThisKeyword */:
return parseJSDocThisType();
case 118 /* AnyKeyword */:
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
case 132 /* NumberKeyword */:
case 121 /* BooleanKeyword */:
- case 135 /* SymbolKeyword */:
+ case 136 /* SymbolKeyword */:
case 104 /* VoidKeyword */:
case 94 /* NullKeyword */:
- case 137 /* UndefinedKeyword */:
+ case 138 /* UndefinedKeyword */:
case 129 /* NeverKeyword */:
+ case 133 /* ObjectKeyword */:
return parseTokenNode();
case 9 /* StringLiteral */:
case 8 /* NumericLiteral */:
@@ -19182,27 +20059,27 @@ var ts;
return parseJSDocTypeReference();
}
function parseJSDocThisType() {
- var result = createNode(277 /* JSDocThisType */);
+ var result = createNode(281 /* JSDocThisType */);
nextToken();
parseExpected(55 /* ColonToken */);
result.type = parseJSDocType();
return finishNode(result);
}
function parseJSDocConstructorType() {
- var result = createNode(276 /* JSDocConstructorType */);
+ var result = createNode(280 /* JSDocConstructorType */);
nextToken();
parseExpected(55 /* ColonToken */);
result.type = parseJSDocType();
return finishNode(result);
}
function parseJSDocVariadicType() {
- var result = createNode(275 /* JSDocVariadicType */);
+ var result = createNode(279 /* JSDocVariadicType */);
nextToken();
result.type = parseJSDocType();
return finishNode(result);
}
function parseJSDocFunctionType() {
- var result = createNode(274 /* JSDocFunctionType */);
+ var result = createNode(278 /* JSDocFunctionType */);
nextToken();
parseExpected(18 /* OpenParenToken */);
result.parameters = parseDelimitedList(23 /* JSDocFunctionParameters */, parseJSDocParameter);
@@ -19215,7 +20092,7 @@ var ts;
return finishNode(result);
}
function parseJSDocParameter() {
- var parameter = createNode(144 /* Parameter */);
+ var parameter = createNode(145 /* Parameter */);
parameter.type = parseJSDocType();
if (parseOptional(57 /* EqualsToken */)) {
// TODO(rbuckton): Can this be changed to SyntaxKind.QuestionToken?
@@ -19224,7 +20101,7 @@ var ts;
return finishNode(parameter);
}
function parseJSDocTypeReference() {
- var result = createNode(272 /* JSDocTypeReference */);
+ var result = createNode(276 /* JSDocTypeReference */);
result.name = parseSimplePropertyName();
if (token() === 26 /* LessThanToken */) {
result.typeArguments = parseTypeArguments();
@@ -19259,24 +20136,24 @@ var ts;
}
}
function parseQualifiedName(left) {
- var result = createNode(141 /* QualifiedName */, left.pos);
+ var result = createNode(142 /* QualifiedName */, left.pos);
result.left = left;
result.right = parseIdentifierName();
return finishNode(result);
}
function parseJSDocRecordType() {
- var result = createNode(270 /* JSDocRecordType */);
+ var result = createNode(274 /* JSDocRecordType */);
result.literal = parseTypeLiteral();
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(269 /* JSDocNonNullableType */);
+ var result = createNode(273 /* JSDocNonNullableType */);
nextToken();
result.type = parseJSDocType();
return finishNode(result);
}
function parseJSDocTupleType() {
- var result = createNode(267 /* JSDocTupleType */);
+ var result = createNode(271 /* JSDocTupleType */);
nextToken();
result.types = parseDelimitedList(26 /* JSDocTupleTypes */, parseJSDocType);
checkForTrailingComma(result.types);
@@ -19290,7 +20167,7 @@ var ts;
}
}
function parseJSDocUnionType() {
- var result = createNode(266 /* JSDocUnionType */);
+ var result = createNode(270 /* JSDocUnionType */);
nextToken();
result.types = parseJSDocTypeList(parseJSDocType());
parseExpected(19 /* CloseParenToken */);
@@ -19306,12 +20183,12 @@ var ts;
return types;
}
function parseJSDocAllType() {
- var result = createNode(263 /* JSDocAllType */);
+ var result = createNode(267 /* JSDocAllType */);
nextToken();
return finishNode(result);
}
function parseJSDocLiteralType() {
- var result = createNode(288 /* JSDocLiteralType */);
+ var result = createNode(292 /* JSDocLiteralType */);
result.literal = parseLiteralTypeNode();
return finishNode(result);
}
@@ -19334,11 +20211,11 @@ var ts;
token() === 28 /* GreaterThanToken */ ||
token() === 57 /* EqualsToken */ ||
token() === 48 /* BarToken */) {
- var result = createNode(264 /* JSDocUnknownType */, pos);
+ var result = createNode(268 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(268 /* JSDocNullableType */, pos);
+ var result = createNode(272 /* JSDocNullableType */, pos);
result.type = parseJSDocType();
return finishNode(result);
}
@@ -19437,7 +20314,7 @@ var ts;
break;
case 38 /* AsteriskToken */:
var asterisk = scanner.getTokenText();
- if (state === 1 /* SawAsterisk */) {
+ if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
// If we've already seen an asterisk, then we can no longer parse a tag on this line
state = 2 /* SavingComments */;
pushComment(asterisk);
@@ -19458,7 +20335,10 @@ var ts;
case 5 /* WhitespaceTrivia */:
// only collect whitespace if we're already saving comments or have just crossed the comment indent margin
var whitespace = scanner.getTokenText();
- if (state === 2 /* SavingComments */ || margin !== undefined && indent + whitespace.length > margin) {
+ if (state === 2 /* SavingComments */) {
+ comments.push(whitespace);
+ }
+ else if (margin !== undefined && indent + whitespace.length > margin) {
comments.push(whitespace.slice(margin - indent - 1));
}
indent += whitespace.length;
@@ -19466,6 +20346,8 @@ var ts;
case 1 /* EndOfFileToken */:
break;
default:
+ // anything other than whitespace or asterisk at the beginning of the line starts the comment text
+ state = 2 /* SavingComments */;
pushComment(scanner.getTokenText());
break;
}
@@ -19498,7 +20380,7 @@ var ts;
content.charCodeAt(start + 3) !== 42 /* asterisk */;
}
function createJSDocComment() {
- var result = createNode(278 /* JSDocComment */, start);
+ var result = createNode(282 /* JSDocComment */, start);
result.tags = tags;
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -19556,7 +20438,7 @@ var ts;
}
function parseTagComments(indent) {
var comments = [];
- var state = 1 /* SawAsterisk */;
+ var state = 0 /* BeginningOfLine */;
var margin;
function pushComment(text) {
if (!margin) {
@@ -19597,7 +20479,8 @@ var ts;
indent += scanner.getTokenText().length;
break;
}
- // FALLTHROUGH otherwise to record the * as a comment
+ // record the * as a comment
+ // falls through
default:
state = 2 /* SavingComments */; // leading identifiers start recording as well
pushComment(scanner.getTokenText());
@@ -19614,7 +20497,7 @@ var ts;
return comments;
}
function parseUnknownTag(atToken, tagName) {
- var result = createNode(279 /* JSDocTag */, atToken.pos);
+ var result = createNode(283 /* JSDocTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
return finishNode(result);
@@ -19671,7 +20554,7 @@ var ts;
if (!typeExpression) {
typeExpression = tryParseTypeExpression();
}
- var result = createNode(281 /* JSDocParameterTag */, atToken.pos);
+ var result = createNode(285 /* JSDocParameterTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.preParameterName = preName;
@@ -19682,20 +20565,20 @@ var ts;
return finishNode(result);
}
function parseReturnTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 282 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 286 /* JSDocReturnTag */; })) {
parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text);
}
- var result = createNode(282 /* JSDocReturnTag */, atToken.pos);
+ var result = createNode(286 /* JSDocReturnTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 283 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocTypeTag */; })) {
parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text);
}
- var result = createNode(283 /* JSDocTypeTag */, atToken.pos);
+ var result = createNode(287 /* JSDocTypeTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
@@ -19710,7 +20593,7 @@ var ts;
parseErrorAtPosition(scanner.getStartPos(), /*length*/ 0, ts.Diagnostics.Identifier_expected);
return undefined;
}
- var result = createNode(286 /* JSDocPropertyTag */, atToken.pos);
+ var result = createNode(290 /* JSDocPropertyTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.name = name;
@@ -19719,7 +20602,7 @@ var ts;
}
function parseAugmentsTag(atToken, tagName) {
var typeExpression = tryParseTypeExpression();
- var result = createNode(280 /* JSDocAugmentsTag */, atToken.pos);
+ var result = createNode(284 /* JSDocAugmentsTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = typeExpression;
@@ -19728,25 +20611,30 @@ var ts;
function parseTypedefTag(atToken, tagName) {
var typeExpression = tryParseTypeExpression();
skipWhitespace();
- var typedefTag = createNode(285 /* JSDocTypedefTag */, atToken.pos);
+ var typedefTag = createNode(289 /* JSDocTypedefTag */, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0);
if (typedefTag.fullName) {
var rightNode = typedefTag.fullName;
- while (rightNode.kind !== 70 /* Identifier */) {
+ while (true) {
+ if (rightNode.kind === 70 /* Identifier */ || !rightNode.body) {
+ // if node is identifier - use it as name
+ // otherwise use name of the rightmost part that we were able to parse
+ typedefTag.name = rightNode.kind === 70 /* Identifier */ ? rightNode : rightNode.name;
+ break;
+ }
rightNode = rightNode.body;
}
- typedefTag.name = rightNode;
}
typedefTag.typeExpression = typeExpression;
skipWhitespace();
if (typeExpression) {
- if (typeExpression.type.kind === 272 /* JSDocTypeReference */) {
+ if (typeExpression.type.kind === 276 /* JSDocTypeReference */) {
var jsDocTypeReference = typeExpression.type;
if (jsDocTypeReference.name.kind === 70 /* Identifier */) {
- var name_14 = jsDocTypeReference.name;
- if (name_14.text === "Object") {
+ var name = jsDocTypeReference.name;
+ if (name.text === "Object") {
typedefTag.jsDocTypeLiteral = scanChildTags();
}
}
@@ -19760,7 +20648,7 @@ var ts;
}
return finishNode(typedefTag);
function scanChildTags() {
- var jsDocTypeLiteral = createNode(287 /* JSDocTypeLiteral */, scanner.getStartPos());
+ var jsDocTypeLiteral = createNode(291 /* JSDocTypeLiteral */, scanner.getStartPos());
var resumePos = scanner.getStartPos();
var canParseTag = true;
var seenAsterisk = false;
@@ -19790,6 +20678,7 @@ var ts;
break;
case 70 /* Identifier */:
canParseTag = false;
+ break;
case 1 /* EndOfFileToken */:
break;
}
@@ -19801,7 +20690,7 @@ var ts;
var pos = scanner.getTokenPos();
var typeNameOrNamespaceName = parseJSDocIdentifierName();
if (typeNameOrNamespaceName && parseOptional(22 /* DotToken */)) {
- var jsDocNamespaceNode = createNode(230 /* ModuleDeclaration */, pos);
+ var jsDocNamespaceNode = createNode(232 /* ModuleDeclaration */, pos);
jsDocNamespaceNode.flags |= flags;
jsDocNamespaceNode.name = typeNameOrNamespaceName;
jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */);
@@ -19847,20 +20736,20 @@ var ts;
return false;
}
function parseTemplateTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 284 /* JSDocTemplateTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 288 /* JSDocTemplateTag */; })) {
parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text);
}
// Type parameter list looks like '@template T,U,V'
var typeParameters = createNodeArray();
while (true) {
- var name_15 = parseJSDocIdentifierName();
+ var name = parseJSDocIdentifierName();
skipWhitespace();
- if (!name_15) {
+ if (!name) {
parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected);
return undefined;
}
- var typeParameter = createNode(143 /* TypeParameter */, name_15.pos);
- typeParameter.name = name_15;
+ var typeParameter = createNode(144 /* TypeParameter */, name.pos);
+ typeParameter.name = name;
finishNode(typeParameter);
typeParameters.push(typeParameter);
if (token() === 25 /* CommaToken */) {
@@ -19871,7 +20760,7 @@ var ts;
break;
}
}
- var result = createNode(284 /* JSDocTemplateTag */, atToken.pos);
+ var result = createNode(288 /* JSDocTemplateTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeParameters = typeParameters;
@@ -20345,7 +21234,7 @@ var ts;
if (position >= array.pos && position < array.end) {
// position was in this array. Search through this array to see if we find a
// viable element.
- for (var i = 0, n = array.length; i < n; i++) {
+ for (var i = 0; i < array.length; i++) {
var child = array[i];
if (child) {
if (child.pos === position) {
@@ -20391,16 +21280,16 @@ var ts;
function getModuleInstanceState(node) {
// A module is uninstantiated if it contains only
// 1. interface declarations, type alias declarations
- if (node.kind === 227 /* InterfaceDeclaration */ || node.kind === 228 /* TypeAliasDeclaration */) {
+ if (node.kind === 229 /* InterfaceDeclaration */ || node.kind === 230 /* TypeAliasDeclaration */) {
return 0 /* NonInstantiated */;
}
else if (ts.isConstEnumDeclaration(node)) {
return 2 /* ConstEnumOnly */;
}
- else if ((node.kind === 235 /* ImportDeclaration */ || node.kind === 234 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) {
+ else if ((node.kind === 237 /* ImportDeclaration */ || node.kind === 236 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) {
return 0 /* NonInstantiated */;
}
- else if (node.kind === 231 /* ModuleBlock */) {
+ else if (node.kind === 233 /* ModuleBlock */) {
var state_1 = 0 /* NonInstantiated */;
ts.forEachChild(node, function (n) {
switch (getModuleInstanceState(n)) {
@@ -20419,7 +21308,7 @@ var ts;
});
return state_1;
}
- else if (node.kind === 230 /* ModuleDeclaration */) {
+ else if (node.kind === 232 /* ModuleDeclaration */) {
var body = node.body;
return body ? getModuleInstanceState(body) : 1 /* Instantiated */;
}
@@ -20532,7 +21421,7 @@ var ts;
}
return bindSourceFile;
function bindInStrictMode(file, opts) {
- if (opts.alwaysStrict && !ts.isDeclarationFile(file)) {
+ if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !ts.isDeclarationFile(file)) {
// bind in strict mode source files with alwaysStrict option
return true;
}
@@ -20560,7 +21449,7 @@ var ts;
if (symbolFlags & 107455 /* Value */) {
var valueDeclaration = symbol.valueDeclaration;
if (!valueDeclaration ||
- (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 230 /* ModuleDeclaration */)) {
+ (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 232 /* ModuleDeclaration */)) {
// other kinds of value declarations take precedence over modules
symbol.valueDeclaration = node;
}
@@ -20573,7 +21462,7 @@ var ts;
if (ts.isAmbientModule(node)) {
return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\"";
}
- if (node.name.kind === 142 /* ComputedPropertyName */) {
+ if (node.name.kind === 143 /* ComputedPropertyName */) {
var nameExpression = node.name.expression;
// treat computed property names where expression is string/numeric literal as just string/numeric literal
if (ts.isStringOrNumericLiteral(nameExpression)) {
@@ -20585,27 +21474,28 @@ var ts;
return node.name.text;
}
switch (node.kind) {
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
return "__constructor";
- case 158 /* FunctionType */:
- case 153 /* CallSignature */:
+ case 159 /* FunctionType */:
+ case 154 /* CallSignature */:
return "__call";
- case 159 /* ConstructorType */:
- case 154 /* ConstructSignature */:
+ case 160 /* ConstructorType */:
+ case 155 /* ConstructSignature */:
return "__new";
- case 155 /* IndexSignature */:
+ case 156 /* IndexSignature */:
return "__index";
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
return "__export";
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
return node.isExportEquals ? "export=" : "default";
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
switch (ts.getSpecialPropertyAssignmentKind(node)) {
case 2 /* ModuleExports */:
// module.exports = ...
return "export=";
case 1 /* ExportsProperty */:
case 4 /* ThisProperty */:
+ case 5 /* Property */:
// exports.x = ... or this.y = ...
return node.left.name.text;
case 3 /* PrototypeProperty */:
@@ -20614,22 +21504,22 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 225 /* FunctionDeclaration */:
- case 226 /* ClassDeclaration */:
+ case 227 /* FunctionDeclaration */:
+ case 228 /* ClassDeclaration */:
return ts.hasModifier(node, 512 /* Default */) ? "default" : undefined;
- case 274 /* JSDocFunctionType */:
+ case 278 /* JSDocFunctionType */:
return ts.isJSDocConstructSignature(node) ? "__new" : "__call";
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
- ts.Debug.assert(node.parent.kind === 274 /* JSDocFunctionType */);
+ ts.Debug.assert(node.parent.kind === 278 /* JSDocFunctionType */);
var functionType = node.parent;
var index = ts.indexOf(functionType.parameters, node);
return "arg" + index;
- case 285 /* JSDocTypedefTag */:
+ case 289 /* JSDocTypedefTag */:
var parentNode = node.parent && node.parent.parent;
var nameFromParentNode = void 0;
- if (parentNode && parentNode.kind === 205 /* VariableStatement */) {
+ if (parentNode && parentNode.kind === 207 /* VariableStatement */) {
if (parentNode.declarationList.declarations.length > 0) {
var nameIdentifier = parentNode.declarationList.declarations[0].name;
if (nameIdentifier.kind === 70 /* Identifier */) {
@@ -20684,15 +21574,18 @@ var ts;
// Otherwise, we'll be merging into a compatible existing symbol (for example when
// you have multiple 'vars' with the same name in the same container). In this case
// just add this node into the declarations list of the symbol.
- symbol = symbolTable[name] || (symbolTable[name] = createSymbol(0 /* None */, name));
+ symbol = symbolTable.get(name);
+ if (!symbol) {
+ symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
+ }
if (name && (includes & 788448 /* Classifiable */)) {
- classifiableNames[name] = name;
+ classifiableNames.set(name, name);
}
if (symbol.flags & excludes) {
if (symbol.isReplaceableByMethod) {
// Javascript constructor-declared symbols can be discarded in favor of
// prototype symbols like methods.
- symbol = symbolTable[name] = createSymbol(0 /* None */, name);
+ symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
}
else {
if (node.name) {
@@ -20716,7 +21609,7 @@ var 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 &&
- (isDefaultExport || (node.kind === 240 /* ExportAssignment */ && !node.isExportEquals))) {
+ (isDefaultExport || (node.kind === 242 /* ExportAssignment */ && !node.isExportEquals))) {
message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
}
}
@@ -20736,11 +21629,11 @@ var ts;
function declareModuleMember(node, symbolFlags, symbolExcludes) {
var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
if (symbolFlags & 8388608 /* Alias */) {
- if (node.kind === 243 /* ExportSpecifier */ || (node.kind === 234 /* ImportEqualsDeclaration */ && hasExportModifier)) {
+ if (node.kind === 245 /* ExportSpecifier */ || (node.kind === 236 /* ImportEqualsDeclaration */ && hasExportModifier)) {
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
}
else {
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
else {
@@ -20759,7 +21652,7 @@ var ts;
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
- var isJSDocTypedefInJSDocNamespace = node.kind === 285 /* JSDocTypedefTag */ &&
+ var isJSDocTypedefInJSDocNamespace = node.kind === 289 /* JSDocTypedefTag */ &&
node.name &&
node.name.kind === 70 /* Identifier */ &&
node.name.isInJSDocNamespace;
@@ -20767,13 +21660,13 @@ var ts;
var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) |
(symbolFlags & 793064 /* Type */ ? 2097152 /* ExportType */ : 0) |
(symbolFlags & 1920 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0);
- var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes);
+ var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
node.localSymbol = local;
return local;
}
else {
- return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
+ return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
}
@@ -20840,14 +21733,13 @@ var ts;
hasExplicitReturn = false;
bindChildren(node);
// Reset all reachability check related flags on node (for incremental scenarios)
- // Reset all emit helper flags on node (for incremental scenarios)
- node.flags &= ~64896 /* ReachabilityAndEmitFlags */;
+ node.flags &= ~1408 /* ReachabilityAndEmitFlags */;
if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
node.flags |= 128 /* HasImplicitReturn */;
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 261 /* SourceFile */) {
+ if (node.kind === 264 /* SourceFile */) {
node.flags |= emitFlags;
}
if (isIIFE) {
@@ -20926,66 +21818,72 @@ var ts;
return;
}
switch (node.kind) {
- case 210 /* WhileStatement */:
+ case 212 /* WhileStatement */:
bindWhileStatement(node);
break;
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
bindDoStatement(node);
break;
- case 211 /* ForStatement */:
+ case 213 /* ForStatement */:
bindForStatement(node);
break;
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
bindForInOrForOfStatement(node);
break;
- case 208 /* IfStatement */:
+ case 210 /* IfStatement */:
bindIfStatement(node);
break;
- case 216 /* ReturnStatement */:
- case 220 /* ThrowStatement */:
+ case 218 /* ReturnStatement */:
+ case 222 /* ThrowStatement */:
bindReturnOrThrow(node);
break;
- case 215 /* BreakStatement */:
- case 214 /* ContinueStatement */:
+ case 217 /* BreakStatement */:
+ case 216 /* ContinueStatement */:
bindBreakOrContinueStatement(node);
break;
- case 221 /* TryStatement */:
+ case 223 /* TryStatement */:
bindTryStatement(node);
break;
- case 218 /* SwitchStatement */:
+ case 220 /* SwitchStatement */:
bindSwitchStatement(node);
break;
- case 232 /* CaseBlock */:
+ case 234 /* CaseBlock */:
bindCaseBlock(node);
break;
- case 253 /* CaseClause */:
+ case 256 /* CaseClause */:
bindCaseClause(node);
break;
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
bindLabeledStatement(node);
break;
- case 190 /* PrefixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
bindPrefixUnaryExpressionFlow(node);
break;
- case 191 /* PostfixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
bindPostfixUnaryExpressionFlow(node);
break;
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
bindBinaryExpressionFlow(node);
break;
- case 186 /* DeleteExpression */:
+ case 187 /* DeleteExpression */:
bindDeleteExpressionFlow(node);
break;
- case 193 /* ConditionalExpression */:
+ case 194 /* ConditionalExpression */:
bindConditionalExpressionFlow(node);
break;
- case 223 /* VariableDeclaration */:
+ case 225 /* VariableDeclaration */:
bindVariableDeclarationFlow(node);
break;
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
bindCallExpressionFlow(node);
break;
+ case 282 /* JSDocComment */:
+ bindJSDocComment(node);
+ break;
+ case 289 /* JSDocTypedefTag */:
+ bindJSDocTypedefTag(node);
+ break;
default:
bindEachChild(node);
break;
@@ -20995,15 +21893,15 @@ var ts;
switch (expr.kind) {
case 70 /* Identifier */:
case 98 /* ThisKeyword */:
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
return isNarrowableReference(expr);
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
return hasNarrowableArgument(expr);
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return isNarrowingExpression(expr.expression);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return isNarrowingBinaryExpression(expr);
- case 190 /* PrefixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
return expr.operator === 50 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
}
return false;
@@ -21011,7 +21909,8 @@ var ts;
function isNarrowableReference(expr) {
return expr.kind === 70 /* Identifier */ ||
expr.kind === 98 /* ThisKeyword */ ||
- expr.kind === 177 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression);
+ expr.kind === 96 /* SuperKeyword */ ||
+ expr.kind === 178 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression);
}
function hasNarrowableArgument(expr) {
if (expr.arguments) {
@@ -21022,14 +21921,14 @@ var ts;
}
}
}
- if (expr.expression.kind === 177 /* PropertyAccessExpression */ &&
+ if (expr.expression.kind === 178 /* PropertyAccessExpression */ &&
isNarrowableReference(expr.expression.expression)) {
return true;
}
return false;
}
function isNarrowingTypeofOperands(expr1, expr2) {
- return expr1.kind === 187 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */;
+ return expr1.kind === 188 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */;
}
function isNarrowingBinaryExpression(expr) {
switch (expr.operatorToken.kind) {
@@ -21050,9 +21949,9 @@ var ts;
}
function isNarrowableOperand(expr) {
switch (expr.kind) {
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return isNarrowableOperand(expr.expression);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
switch (expr.operatorToken.kind) {
case 57 /* EqualsToken */:
return isNarrowableOperand(expr.left);
@@ -21147,33 +22046,33 @@ var ts;
function isStatementCondition(node) {
var parent = node.parent;
switch (parent.kind) {
- case 208 /* IfStatement */:
- case 210 /* WhileStatement */:
- case 209 /* DoStatement */:
+ case 210 /* IfStatement */:
+ case 212 /* WhileStatement */:
+ case 211 /* DoStatement */:
return parent.expression === node;
- case 211 /* ForStatement */:
- case 193 /* ConditionalExpression */:
+ case 213 /* ForStatement */:
+ case 194 /* ConditionalExpression */:
return parent.condition === node;
}
return false;
}
function isLogicalExpression(node) {
while (true) {
- if (node.kind === 183 /* ParenthesizedExpression */) {
+ if (node.kind === 184 /* ParenthesizedExpression */) {
node = node.expression;
}
- else if (node.kind === 190 /* PrefixUnaryExpression */ && node.operator === 50 /* ExclamationToken */) {
+ else if (node.kind === 191 /* PrefixUnaryExpression */ && node.operator === 50 /* ExclamationToken */) {
node = node.operand;
}
else {
- return node.kind === 192 /* BinaryExpression */ && (node.operatorToken.kind === 52 /* AmpersandAmpersandToken */ ||
+ return node.kind === 193 /* BinaryExpression */ && (node.operatorToken.kind === 52 /* AmpersandAmpersandToken */ ||
node.operatorToken.kind === 53 /* BarBarToken */);
}
}
}
function isTopLevelLogicalExpression(node) {
- while (node.parent.kind === 183 /* ParenthesizedExpression */ ||
- node.parent.kind === 190 /* PrefixUnaryExpression */ &&
+ while (node.parent.kind === 184 /* ParenthesizedExpression */ ||
+ node.parent.kind === 191 /* PrefixUnaryExpression */ &&
node.parent.operator === 50 /* ExclamationToken */) {
node = node.parent;
}
@@ -21215,7 +22114,7 @@ var ts;
}
function bindDoStatement(node) {
var preDoLabel = createLoopLabel();
- var enclosingLabeledStatement = node.parent.kind === 219 /* LabeledStatement */
+ var enclosingLabeledStatement = node.parent.kind === 221 /* LabeledStatement */
? ts.lastOrUndefined(activeLabels)
: undefined;
// if do statement is wrapped in labeled statement then target labels for break/continue with or without
@@ -21249,10 +22148,13 @@ var ts;
var postLoopLabel = createBranchLabel();
addAntecedent(preLoopLabel, currentFlow);
currentFlow = preLoopLabel;
+ if (node.kind === 215 /* ForOfStatement */) {
+ bind(node.awaitModifier);
+ }
bind(node.expression);
addAntecedent(postLoopLabel, currentFlow);
bind(node.initializer);
- if (node.initializer.kind !== 224 /* VariableDeclarationList */) {
+ if (node.initializer.kind !== 226 /* VariableDeclarationList */) {
bindAssignmentTargetFlow(node.initializer);
}
bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
@@ -21274,7 +22176,7 @@ var ts;
}
function bindReturnOrThrow(node) {
bind(node.expression);
- if (node.kind === 216 /* ReturnStatement */) {
+ if (node.kind === 218 /* ReturnStatement */) {
hasExplicitReturn = true;
if (currentReturnTarget) {
addAntecedent(currentReturnTarget, currentFlow);
@@ -21294,7 +22196,7 @@ var ts;
return undefined;
}
function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
- var flowLabel = node.kind === 215 /* BreakStatement */ ? breakTarget : continueTarget;
+ var flowLabel = node.kind === 217 /* BreakStatement */ ? breakTarget : continueTarget;
if (flowLabel) {
addAntecedent(flowLabel, currentFlow);
currentFlow = unreachableFlow;
@@ -21330,7 +22232,32 @@ var ts;
if (node.finallyBlock) {
// in finally flow is combined from pre-try/flow from try/flow from catch
// pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable
- addAntecedent(preFinallyLabel, preTryFlow);
+ // also for finally blocks we inject two extra edges into the flow graph.
+ // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it
+ // second -> edge that represents post-finally flow.
+ // these edges are used in following scenario:
+ // let a; (1)
+ // try { a = someOperation(); (2)}
+ // finally { (3) console.log(a) } (4)
+ // (5) a
+ // flow graph for this case looks roughly like this (arrows show ):
+ // (1-pre-try-flow) <--.. <-- (2-post-try-flow)
+ // ^ ^
+ // |*****(3-pre-finally-label) -----|
+ // ^
+ // |-- ... <-- (4-post-finally-label) <--- (5)
+ // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account
+ // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5)
+ // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable
+ // Simply speaking code inside finally block is treated as reachable as pre-try-flow
+ // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally.
+ // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from
+ // final flows of these blocks without taking pre-try flow into account.
+ //
+ // extra edges that we inject allows to control this behavior
+ // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped.
+ var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} };
+ addAntecedent(preFinallyLabel, preFinallyFlow);
currentFlow = finishFlowLabel(preFinallyLabel);
bind(node.finallyBlock);
// if flow after finally is unreachable - keep it
@@ -21346,6 +22273,11 @@ var ts;
: unreachableFlow;
}
}
+ if (!(currentFlow.flags & 1 /* Unreachable */)) {
+ var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow };
+ preFinallyFlow.lock = afterFinallyFlow;
+ currentFlow = afterFinallyFlow;
+ }
}
else {
currentFlow = finishFlowLabel(preFinallyLabel);
@@ -21360,7 +22292,7 @@ var ts;
preSwitchCaseFlow = currentFlow;
bind(node.caseBlock);
addAntecedent(postSwitchLabel, currentFlow);
- var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 254 /* DefaultClause */; });
+ var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 257 /* DefaultClause */; });
// We mark a switch statement as possibly exhaustive if it has no default clause and if all
// case clauses have unreachable end points (e.g. they all return).
node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
@@ -21427,14 +22359,14 @@ var ts;
if (!activeLabel.referenced && !options.allowUnusedLabels) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label));
}
- if (!node.statement || node.statement.kind !== 209 /* DoStatement */) {
+ if (!node.statement || node.statement.kind !== 211 /* DoStatement */) {
// do statement sets current flow inside bindDoStatement
addAntecedent(postStatementLabel, currentFlow);
currentFlow = finishFlowLabel(postStatementLabel);
}
}
function bindDestructuringTargetFlow(node) {
- if (node.kind === 192 /* BinaryExpression */ && node.operatorToken.kind === 57 /* EqualsToken */) {
+ if (node.kind === 193 /* BinaryExpression */ && node.operatorToken.kind === 57 /* EqualsToken */) {
bindAssignmentTargetFlow(node.left);
}
else {
@@ -21445,10 +22377,10 @@ var ts;
if (isNarrowableReference(node)) {
currentFlow = createFlowAssignment(currentFlow, node);
}
- else if (node.kind === 175 /* ArrayLiteralExpression */) {
+ else if (node.kind === 176 /* ArrayLiteralExpression */) {
for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
var e = _a[_i];
- if (e.kind === 196 /* SpreadElement */) {
+ if (e.kind === 197 /* SpreadElement */) {
bindAssignmentTargetFlow(e.expression);
}
else {
@@ -21456,16 +22388,16 @@ var ts;
}
}
}
- else if (node.kind === 176 /* ObjectLiteralExpression */) {
+ else if (node.kind === 177 /* ObjectLiteralExpression */) {
for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
var p = _c[_b];
- if (p.kind === 257 /* PropertyAssignment */) {
+ if (p.kind === 260 /* PropertyAssignment */) {
bindDestructuringTargetFlow(p.initializer);
}
- else if (p.kind === 258 /* ShorthandPropertyAssignment */) {
+ else if (p.kind === 261 /* ShorthandPropertyAssignment */) {
bindAssignmentTargetFlow(p.name);
}
- else if (p.kind === 259 /* SpreadAssignment */) {
+ else if (p.kind === 262 /* SpreadAssignment */) {
bindAssignmentTargetFlow(p.expression);
}
}
@@ -21521,7 +22453,7 @@ var ts;
bindEachChild(node);
if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
bindAssignmentTargetFlow(node.left);
- if (operator === 57 /* EqualsToken */ && node.left.kind === 178 /* ElementAccessExpression */) {
+ if (operator === 57 /* EqualsToken */ && node.left.kind === 179 /* ElementAccessExpression */) {
var elementAccess = node.left;
if (isNarrowableOperand(elementAccess.expression)) {
currentFlow = createFlowArrayMutation(currentFlow, node);
@@ -21532,7 +22464,7 @@ var ts;
}
function bindDeleteExpressionFlow(node) {
bindEachChild(node);
- if (node.expression.kind === 177 /* PropertyAccessExpression */) {
+ if (node.expression.kind === 178 /* PropertyAccessExpression */) {
bindAssignmentTargetFlow(node.expression);
}
}
@@ -21565,19 +22497,37 @@ var ts;
}
function bindVariableDeclarationFlow(node) {
bindEachChild(node);
- if (node.initializer || node.parent.parent.kind === 212 /* ForInStatement */ || node.parent.parent.kind === 213 /* ForOfStatement */) {
+ if (node.initializer || node.parent.parent.kind === 214 /* ForInStatement */ || node.parent.parent.kind === 215 /* ForOfStatement */) {
bindInitializedVariableFlow(node);
}
}
+ function bindJSDocComment(node) {
+ ts.forEachChild(node, function (n) {
+ if (n.kind !== 289 /* JSDocTypedefTag */) {
+ bind(n);
+ }
+ });
+ }
+ function bindJSDocTypedefTag(node) {
+ ts.forEachChild(node, function (n) {
+ // if the node has a fullName "A.B.C", that means symbol "C" was already bound
+ // when we visit "fullName"; so when we visit the name "C" as the next child of
+ // the jsDocTypedefTag, we should skip binding it.
+ if (node.fullName && n === node.name && node.fullName.kind !== 70 /* Identifier */) {
+ return;
+ }
+ bind(n);
+ });
+ }
function bindCallExpressionFlow(node) {
// If the target of the call expression is a function expression or arrow function we have
// an immediately invoked function expression (IIFE). Initialize the flowNode property to
// the current control flow (which includes evaluation of the IIFE arguments).
var expr = node.expression;
- while (expr.kind === 183 /* ParenthesizedExpression */) {
+ while (expr.kind === 184 /* ParenthesizedExpression */) {
expr = expr.expression;
}
- if (expr.kind === 184 /* FunctionExpression */ || expr.kind === 185 /* ArrowFunction */) {
+ if (expr.kind === 185 /* FunctionExpression */ || expr.kind === 186 /* ArrowFunction */) {
bindEach(node.typeArguments);
bindEach(node.arguments);
bind(node.expression);
@@ -21585,7 +22535,7 @@ var ts;
else {
bindEachChild(node);
}
- if (node.expression.kind === 177 /* PropertyAccessExpression */) {
+ if (node.expression.kind === 178 /* PropertyAccessExpression */) {
var propertyAccess = node.expression;
if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
currentFlow = createFlowArrayMutation(currentFlow, node);
@@ -21594,52 +22544,54 @@ var ts;
}
function getContainerFlags(node) {
switch (node.kind) {
- case 197 /* ClassExpression */:
- case 226 /* ClassDeclaration */:
- case 229 /* EnumDeclaration */:
- case 176 /* ObjectLiteralExpression */:
- case 161 /* TypeLiteral */:
- case 287 /* JSDocTypeLiteral */:
- case 270 /* JSDocRecordType */:
+ case 198 /* ClassExpression */:
+ case 228 /* ClassDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 177 /* ObjectLiteralExpression */:
+ case 162 /* TypeLiteral */:
+ case 291 /* JSDocTypeLiteral */:
+ case 274 /* JSDocRecordType */:
+ case 253 /* JsxAttributes */:
return 1 /* IsContainer */;
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
return 1 /* IsContainer */ | 64 /* IsInterface */;
- case 274 /* JSDocFunctionType */:
- case 230 /* ModuleDeclaration */:
- case 228 /* TypeAliasDeclaration */:
- case 170 /* MappedType */:
+ case 278 /* JSDocFunctionType */:
+ case 232 /* ModuleDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
+ case 171 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
- case 149 /* MethodDeclaration */:
+ case 150 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
}
- case 150 /* Constructor */:
- case 225 /* FunctionDeclaration */:
- case 148 /* MethodSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
+ // falls through
+ case 151 /* Constructor */:
+ case 227 /* FunctionDeclaration */:
+ case 149 /* MethodSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
- case 231 /* ModuleBlock */:
+ case 233 /* ModuleBlock */:
return 4 /* IsControlFlowContainer */;
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
- case 256 /* CatchClause */:
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- case 232 /* CaseBlock */:
+ case 259 /* CatchClause */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ case 234 /* CaseBlock */:
return 2 /* IsBlockScopedContainer */;
- case 204 /* Block */:
+ case 206 /* Block */:
// do not treat blocks directly inside a function as a block-scoped-container.
// Locals that reside in this block should go to the function locals. Otherwise 'x'
// would not appear to be a redeclaration of a block scoped local in the following
@@ -21676,42 +22628,43 @@ var ts;
// members are declared (for example, a member of a class will go into a specific
// symbol table depending on if it is static or not). We defer to specialized
// handlers to take care of declaring these child members.
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
- case 197 /* ClassExpression */:
- case 226 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 228 /* ClassDeclaration */:
return declareClassMember(node, symbolFlags, symbolExcludes);
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
- case 161 /* TypeLiteral */:
- case 176 /* ObjectLiteralExpression */:
- case 227 /* InterfaceDeclaration */:
- case 270 /* JSDocRecordType */:
- case 287 /* JSDocTypeLiteral */:
+ case 162 /* TypeLiteral */:
+ case 177 /* ObjectLiteralExpression */:
+ case 229 /* InterfaceDeclaration */:
+ case 274 /* JSDocRecordType */:
+ case 291 /* JSDocTypeLiteral */:
+ case 253 /* JsxAttributes */:
// Interface/Object-types always have their children added to the 'members' of
// their container. They are only accessible through an instance of their
// container, and are never in scope otherwise (even inside the body of the
// object / type / interface declaring them). An exception is type parameters,
// which are in scope without qualification (similar to 'locals').
return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 274 /* JSDocFunctionType */:
- case 228 /* TypeAliasDeclaration */:
- case 170 /* MappedType */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 278 /* JSDocFunctionType */:
+ case 230 /* TypeAliasDeclaration */:
+ case 171 /* MappedType */:
// All the children of these container types are never visible through another
// symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
// they're only accessed 'lexically' (i.e. from code that exists underneath
@@ -21729,14 +22682,14 @@ var ts;
function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
return ts.isExternalModule(file)
? declareModuleMember(node, symbolFlags, symbolExcludes)
- : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes);
+ : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 261 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 261 /* SourceFile */ || body.kind === 231 /* ModuleBlock */)) {
+ var body = node.kind === 264 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 264 /* SourceFile */ || body.kind === 233 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
- if (stat.kind === 241 /* ExportDeclaration */ || stat.kind === 240 /* ExportAssignment */) {
+ if (stat.kind === 243 /* ExportDeclaration */ || stat.kind === 242 /* ExportAssignment */) {
return true;
}
}
@@ -21760,7 +22713,7 @@ var ts;
errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
}
if (ts.isExternalModuleAugmentation(node)) {
- declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */);
+ declareModuleSymbol(node);
}
else {
var pattern = void 0;
@@ -21780,12 +22733,8 @@ var ts;
}
}
else {
- var state = getModuleInstanceState(node);
- if (state === 0 /* NonInstantiated */) {
- declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */);
- }
- else {
- declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */);
+ var state = declareModuleSymbol(node);
+ if (state !== 0 /* NonInstantiated */) {
if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) {
// if module was already merged with some function, class or non-const enum
// treat is a non-const-enum-only
@@ -21805,6 +22754,12 @@ var ts;
}
}
}
+ function declareModuleSymbol(node) {
+ var state = getModuleInstanceState(node);
+ var instantiated = state !== 0 /* NonInstantiated */;
+ declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 106639 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
+ return state;
+ }
function bindFunctionOrConstructorType(node) {
// For a given function symbol "<...>(...) => T" we want to generate a symbol identical
// to the one we would get for: { <...>(...): T }
@@ -21817,7 +22772,7 @@ var ts;
var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type");
addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
typeLiteralSymbol.members = ts.createMap();
- typeLiteralSymbol.members[symbol.name] = symbol;
+ typeLiteralSymbol.members.set(symbol.name, symbol);
}
function bindObjectLiteralExpression(node) {
var ElementKind;
@@ -21829,7 +22784,7 @@ var ts;
var seen = ts.createMap();
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var prop = _a[_i];
- if (prop.kind === 259 /* SpreadAssignment */ || prop.name.kind !== 70 /* Identifier */) {
+ if (prop.kind === 262 /* SpreadAssignment */ || prop.name.kind !== 70 /* Identifier */) {
continue;
}
var identifier = prop.name;
@@ -21841,12 +22796,12 @@ var ts;
// c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
// d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
// and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
- var currentKind = prop.kind === 257 /* PropertyAssignment */ || prop.kind === 258 /* ShorthandPropertyAssignment */ || prop.kind === 149 /* MethodDeclaration */
+ var currentKind = prop.kind === 260 /* PropertyAssignment */ || prop.kind === 261 /* ShorthandPropertyAssignment */ || prop.kind === 150 /* MethodDeclaration */
? 1 /* Property */
: 2 /* Accessor */;
- var existingKind = seen[identifier.text];
+ var existingKind = seen.get(identifier.text);
if (!existingKind) {
- seen[identifier.text] = currentKind;
+ seen.set(identifier.text, currentKind);
continue;
}
if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
@@ -21857,27 +22812,33 @@ var ts;
}
return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object");
}
+ function bindJsxAttributes(node) {
+ return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes");
+ }
+ function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
+ return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
+ }
function bindAnonymousDeclaration(node, symbolFlags, name) {
var symbol = createSymbol(symbolFlags, name);
addDeclarationToSymbol(symbol, node, symbolFlags);
}
function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
switch (blockScopeContainer.kind) {
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
if (ts.isExternalModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
}
- // fall through.
+ // falls through
default:
if (!blockScopeContainer.locals) {
blockScopeContainer.locals = ts.createMap();
addToContainerChain(blockScopeContainer);
}
- declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
+ declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
function bindBlockScopedVariableDeclaration(node) {
@@ -21977,8 +22938,8 @@ var ts;
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 261 /* SourceFile */ &&
- blockScopeContainer.kind !== 230 /* ModuleDeclaration */ &&
+ if (blockScopeContainer.kind !== 264 /* SourceFile */ &&
+ blockScopeContainer.kind !== 232 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
// otherwise report generic error message.
@@ -21988,7 +22949,7 @@ var ts;
}
}
function checkStrictModeNumericLiteral(node) {
- if (inStrictMode && node.isOctalLiteral) {
+ if (inStrictMode && node.numericLiteralFlags & 4 /* Octal */) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
}
}
@@ -22028,6 +22989,18 @@ var ts;
}
node.parent = parent;
var saveInStrictMode = inStrictMode;
+ // Even though in the AST the jsdoc @typedef node belongs to the current node,
+ // its symbol might be in the same scope with the current node's symbol. Consider:
+ //
+ // /** @typedef {string | number} MyType */
+ // function foo();
+ //
+ // Here the current node is "foo", which is a container, but the scope of "MyType" should
+ // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
+ // and skip binding this tag later when binding all the other jsdoc tags.
+ if (ts.isInJavaScriptFile(node)) {
+ bindJSDocTypedefTagIfAny(node);
+ }
// First we bind declaration nodes to a symbol if possible. We'll both create a symbol
// and then potentially add the symbol to an appropriate symbol table. Possible
// destination symbol tables are:
@@ -22044,7 +23017,7 @@ var ts;
// the current 'container' node when it changes. This helps us know which symbol table
// a local should go into for example. Since terminal nodes are known not to have
// children, as an optimization we don't process those.
- if (node.kind > 140 /* LastToken */) {
+ if (node.kind > 141 /* LastToken */) {
var saveParent = parent;
parent = node;
var containerFlags = getContainerFlags(node);
@@ -22061,6 +23034,26 @@ var ts;
}
inStrictMode = saveInStrictMode;
}
+ function bindJSDocTypedefTagIfAny(node) {
+ if (!node.jsDoc) {
+ return;
+ }
+ for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
+ var jsDoc = _a[_i];
+ if (!jsDoc.tags) {
+ continue;
+ }
+ for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) {
+ var tag = _c[_b];
+ if (tag.kind === 289 /* JSDocTypedefTag */) {
+ var savedParent = parent;
+ parent = jsDoc;
+ bind(tag);
+ parent = savedParent;
+ }
+ }
+ }
+ }
function updateStrictModeStatementList(statements) {
if (!inStrictMode) {
for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
@@ -22091,91 +23084,90 @@ var ts;
// current "blockScopeContainer" needs to be set to its immediate namespace parent.
if (node.isInJSDocNamespace) {
var parentNode = node.parent;
- while (parentNode && parentNode.kind !== 285 /* JSDocTypedefTag */) {
+ while (parentNode && parentNode.kind !== 289 /* JSDocTypedefTag */) {
parentNode = parentNode.parent;
}
bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */);
break;
}
+ // falls through
case 98 /* ThisKeyword */:
- if (currentFlow && (ts.isExpression(node) || parent.kind === 258 /* ShorthandPropertyAssignment */)) {
+ if (currentFlow && (ts.isExpression(node) || parent.kind === 261 /* ShorthandPropertyAssignment */)) {
node.flowNode = currentFlow;
}
return checkStrictModeIdentifier(node);
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
if (currentFlow && isNarrowableReference(node)) {
node.flowNode = currentFlow;
}
break;
- case 192 /* BinaryExpression */:
- if (ts.isInJavaScriptFile(node)) {
- var specialKind = ts.getSpecialPropertyAssignmentKind(node);
- switch (specialKind) {
- case 1 /* ExportsProperty */:
- bindExportsPropertyAssignment(node);
- break;
- case 2 /* ModuleExports */:
- bindModuleExportsAssignment(node);
- break;
- case 3 /* PrototypeProperty */:
- bindPrototypePropertyAssignment(node);
- break;
- case 4 /* ThisProperty */:
- bindThisPropertyAssignment(node);
- break;
- case 0 /* None */:
- // Nothing to do
- break;
- default:
- ts.Debug.fail("Unknown special property assignment kind");
- }
+ case 193 /* BinaryExpression */:
+ var specialKind = ts.getSpecialPropertyAssignmentKind(node);
+ switch (specialKind) {
+ case 1 /* ExportsProperty */:
+ bindExportsPropertyAssignment(node);
+ break;
+ case 2 /* ModuleExports */:
+ bindModuleExportsAssignment(node);
+ break;
+ case 3 /* PrototypeProperty */:
+ bindPrototypePropertyAssignment(node);
+ break;
+ case 4 /* ThisProperty */:
+ bindThisPropertyAssignment(node);
+ break;
+ case 5 /* Property */:
+ bindStaticPropertyAssignment(node);
+ break;
+ case 0 /* None */:
+ // Nothing to do
+ break;
+ default:
+ ts.Debug.fail("Unknown special property assignment kind");
}
return checkStrictModeBinaryExpression(node);
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return checkStrictModeCatchClause(node);
- case 186 /* DeleteExpression */:
+ case 187 /* DeleteExpression */:
return checkStrictModeDeleteExpression(node);
case 8 /* NumericLiteral */:
return checkStrictModeNumericLiteral(node);
- case 191 /* PostfixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
return checkStrictModePostfixUnaryExpression(node);
- case 190 /* PrefixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
return checkStrictModePrefixUnaryExpression(node);
- case 217 /* WithStatement */:
+ case 219 /* WithStatement */:
return checkStrictModeWithStatement(node);
- case 167 /* ThisType */:
+ case 168 /* ThisType */:
seenThisKeyword = true;
return;
- case 156 /* TypePredicate */:
+ case 157 /* TypePredicate */:
return checkTypePredicate(node);
- case 143 /* TypeParameter */:
+ case 144 /* TypeParameter */:
return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */);
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
return bindParameter(node);
- case 223 /* VariableDeclaration */:
- case 174 /* BindingElement */:
- if (node.dotDotDotToken && node.parent.kind === 172 /* ObjectBindingPattern */) {
- emitFlags |= 32768 /* HasRestAttribute */;
- }
+ case 225 /* VariableDeclaration */:
+ case 175 /* BindingElement */:
return bindVariableDeclarationOrBindingElement(node);
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 271 /* JSDocRecordMember */:
- return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
- case 286 /* JSDocPropertyTag */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 275 /* JSDocRecordMember */:
+ return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
+ case 290 /* JSDocPropertyTag */:
return bindJSDocProperty(node);
- case 257 /* PropertyAssignment */:
- case 258 /* ShorthandPropertyAssignment */:
+ case 260 /* PropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
- case 260 /* EnumMember */:
+ case 263 /* EnumMember */:
return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
- case 259 /* SpreadAssignment */:
- case 251 /* JsxSpreadAttribute */:
+ case 262 /* SpreadAssignment */:
+ case 254 /* JsxSpreadAttribute */:
var root = container;
var hasRest = false;
while (root.parent) {
- if (root.kind === 176 /* ObjectLiteralExpression */ &&
- root.parent.kind === 192 /* BinaryExpression */ &&
+ if (root.kind === 177 /* ObjectLiteralExpression */ &&
+ root.parent.kind === 193 /* BinaryExpression */ &&
root.parent.operatorToken.kind === 57 /* EqualsToken */ &&
root.parent.left === root) {
hasRest = true;
@@ -22183,88 +23175,92 @@ var ts;
}
root = root.parent;
}
- emitFlags |= hasRest ? 32768 /* HasRestAttribute */ : 16384 /* HasSpreadAttribute */;
return;
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* 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(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */);
- case 225 /* FunctionDeclaration */:
+ return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */);
+ case 227 /* FunctionDeclaration */:
return bindFunctionDeclaration(node);
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
- case 151 /* GetAccessor */:
+ case 152 /* GetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */);
- case 152 /* SetAccessor */:
+ case 153 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */);
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
- case 274 /* JSDocFunctionType */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
+ case 278 /* JSDocFunctionType */:
return bindFunctionOrConstructorType(node);
- case 161 /* TypeLiteral */:
- case 170 /* MappedType */:
- case 287 /* JSDocTypeLiteral */:
- case 270 /* JSDocRecordType */:
+ case 162 /* TypeLiteral */:
+ case 171 /* MappedType */:
+ case 291 /* JSDocTypeLiteral */:
+ case 274 /* JSDocRecordType */:
return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type");
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
return bindObjectLiteralExpression(node);
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
return bindFunctionExpression(node);
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
if (ts.isInJavaScriptFile(node)) {
bindCallExpression(node);
}
break;
// Members of classes, interfaces, and modules
- case 197 /* ClassExpression */:
- case 226 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 228 /* ClassDeclaration */:
// All classes are automatically in strict mode in ES6.
inStrictMode = true;
return bindClassLikeDeclaration(node);
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */);
- case 285 /* JSDocTypedefTag */:
+ case 289 /* JSDocTypedefTag */:
if (!node.fullName || node.fullName.kind === 70 /* Identifier */) {
return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */);
}
break;
- case 228 /* TypeAliasDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */);
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
return bindEnumDeclaration(node);
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return bindModuleDeclaration(node);
+ // Jsx-attributes
+ case 253 /* JsxAttributes */:
+ return bindJsxAttributes(node);
+ case 252 /* JsxAttribute */:
+ return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
// Imports and exports
- case 234 /* ImportEqualsDeclaration */:
- case 237 /* NamespaceImport */:
- case 239 /* ImportSpecifier */:
- case 243 /* ExportSpecifier */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 239 /* NamespaceImport */:
+ case 241 /* ImportSpecifier */:
+ case 245 /* ExportSpecifier */:
return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */);
- case 233 /* NamespaceExportDeclaration */:
+ case 235 /* NamespaceExportDeclaration */:
return bindNamespaceExportDeclaration(node);
- case 236 /* ImportClause */:
+ case 238 /* ImportClause */:
return bindImportClause(node);
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
return bindExportDeclaration(node);
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
return bindExportAssignment(node);
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
- case 204 /* Block */:
+ case 206 /* Block */:
if (!ts.isFunctionLike(node.parent)) {
return;
}
- // Fall through
- case 231 /* ModuleBlock */:
+ // falls through
+ case 233 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
}
}
@@ -22273,7 +23269,7 @@ var ts;
if (parameterName && parameterName.kind === 70 /* Identifier */) {
checkStrictModeIdentifier(parameterName);
}
- if (parameterName && parameterName.kind === 167 /* ThisType */) {
+ if (parameterName && parameterName.kind === 168 /* ThisType */) {
seenThisKeyword = true;
}
bind(type);
@@ -22296,7 +23292,7 @@ var ts;
// An export default clause with an expression exports a value
// We want to exclude both class and function here, this is necessary to issue an error when there are both
// default export-assignment and default export function and class declaration.
- var flags = node.kind === 240 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node)
+ var flags = node.kind === 242 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node)
? 8388608 /* Alias */
: 4 /* Property */;
declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 8388608 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */);
@@ -22306,17 +23302,17 @@ var ts;
if (node.modifiers && node.modifiers.length) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
}
- if (node.parent.kind !== 261 /* SourceFile */) {
+ if (node.parent.kind !== 264 /* SourceFile */) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level));
return;
}
else {
- var parent_4 = node.parent;
- if (!ts.isExternalModule(parent_4)) {
+ var parent_1 = node.parent;
+ if (!ts.isExternalModule(parent_1)) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files));
return;
}
- if (!parent_4.isDeclarationFile) {
+ if (!parent_1.isDeclarationFile) {
file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files));
return;
}
@@ -22327,11 +23323,11 @@ var ts;
function bindExportDeclaration(node) {
if (!container.symbol || !container.symbol.exports) {
// Export * in some sort of block construct
- bindAnonymousDeclaration(node, 1073741824 /* ExportStar */, getDeclarationName(node));
+ bindAnonymousDeclaration(node, 33554432 /* ExportStar */, getDeclarationName(node));
}
else if (!node.exportClause) {
// All export * declarations are collected in an __export symbol
- declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0 /* None */);
+ declareSymbol(container.symbol.exports, container.symbol, node, 33554432 /* ExportStar */, 0 /* None */);
}
}
function bindImportClause(node) {
@@ -22353,30 +23349,67 @@ var ts;
setCommonJsModuleIndicator(node);
declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 7340032 /* Export */, 0 /* None */);
}
+ function isExportsOrModuleExportsOrAlias(node) {
+ return ts.isExportsIdentifier(node) ||
+ ts.isModuleExportsPropertyAccessExpression(node) ||
+ isNameOfExportsOrModuleExportsAliasDeclaration(node);
+ }
+ function isNameOfExportsOrModuleExportsAliasDeclaration(node) {
+ if (node.kind === 70 /* Identifier */) {
+ var symbol = lookupSymbolForName(node.text);
+ if (symbol && symbol.valueDeclaration && symbol.valueDeclaration.kind === 225 /* VariableDeclaration */) {
+ var declaration = symbol.valueDeclaration;
+ if (declaration.initializer) {
+ return isExportsOrModuleExportsOrAliasOrAssignemnt(declaration.initializer);
+ }
+ }
+ }
+ return false;
+ }
+ function isExportsOrModuleExportsOrAliasOrAssignemnt(node) {
+ return isExportsOrModuleExportsOrAlias(node) ||
+ (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignemnt(node.left) || isExportsOrModuleExportsOrAliasOrAssignemnt(node.right)));
+ }
function bindModuleExportsAssignment(node) {
+ // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
+ // is still pointing to 'module.exports'.
+ // We do not want to consider this as 'export=' since a module can have only one of these.
+ // Similarlly we do not want to treat 'module.exports = exports' as an 'export='.
+ var assignedExpression = ts.getRightMostAssignedExpression(node.right);
+ if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) {
+ // Mark it as a module in case there are no other exports in the file
+ setCommonJsModuleIndicator(node);
+ return;
+ }
// 'module.exports = expr' assignment
setCommonJsModuleIndicator(node);
declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 7340032 /* Export */ | 512 /* ValueModule */, 0 /* None */);
}
function bindThisPropertyAssignment(node) {
ts.Debug.assert(ts.isInJavaScriptFile(node));
- // Declare a 'member' if the container is an ES5 class or ES6 constructor
- if (container.kind === 225 /* FunctionDeclaration */ || container.kind === 184 /* FunctionExpression */) {
- container.symbol.members = container.symbol.members || ts.createMap();
- // It's acceptable for multiple 'this' assignments of the same identifier to occur
- declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */);
- }
- else if (container.kind === 150 /* Constructor */) {
- // this.foo assignment in a JavaScript class
- // Bind this property to the containing class
- var saveContainer = container;
- container = container.parent;
- var symbol = bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* None */);
- if (symbol) {
- // constructor-declared symbols can be overwritten by subsequent method declarations
- symbol.isReplaceableByMethod = true;
- }
- container = saveContainer;
+ var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
+ switch (container.kind) {
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ // Declare a 'member' if the container is an ES5 class or ES6 constructor
+ container.symbol.members = container.symbol.members || ts.createMap();
+ // It's acceptable for multiple 'this' assignments of the same identifier to occur
+ declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */);
+ break;
+ case 151 /* Constructor */:
+ case 148 /* PropertyDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ // this.foo assignment in a JavaScript class
+ // Bind this property to the containing class
+ var containingClass = container.parent;
+ var symbol = declareSymbol(ts.hasModifier(container, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members, containingClass.symbol, node, 4 /* Property */, 0 /* None */);
+ if (symbol) {
+ // symbols declared through 'this' property assignements can be overwritten by subsequent method declarations
+ symbol.isReplaceableByMethod = true;
+ }
+ break;
}
}
function bindPrototypePropertyAssignment(node) {
@@ -22390,16 +23423,44 @@ var ts;
leftSideOfAssignment.parent = node;
constructorFunction.parent = classPrototype;
classPrototype.parent = leftSideOfAssignment;
- var funcSymbol = container.locals[constructorFunction.text];
- if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) {
+ bindPropertyAssignment(constructorFunction.text, leftSideOfAssignment, /*isPrototypeProperty*/ true);
+ }
+ function bindStaticPropertyAssignment(node) {
+ // We saw a node of the form 'x.y = z'. Declare a 'member' y on x if x was a function.
+ // Look up the function in the local scope, since prototype assignments should
+ // follow the function declaration
+ var leftSideOfAssignment = node.left;
+ var target = leftSideOfAssignment.expression;
+ // Fix up parent pointers since we're going to use these nodes before we bind into them
+ leftSideOfAssignment.parent = node;
+ target.parent = leftSideOfAssignment;
+ if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) {
+ // This can be an alias for the 'exports' or 'module.exports' names, e.g.
+ // var util = module.exports;
+ // util.property = function ...
+ bindExportsPropertyAssignment(node);
+ }
+ else {
+ bindPropertyAssignment(target.text, leftSideOfAssignment, /*isPrototypeProperty*/ false);
+ }
+ }
+ function lookupSymbolForName(name) {
+ return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name));
+ }
+ function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) {
+ var targetSymbol = lookupSymbolForName(functionName);
+ if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) {
+ targetSymbol = targetSymbol.valueDeclaration.initializer.symbol;
+ }
+ if (!targetSymbol || !(targetSymbol.flags & (16 /* Function */ | 32 /* Class */))) {
return;
}
// Set up the members collection if it doesn't exist already
- if (!funcSymbol.members) {
- funcSymbol.members = ts.createMap();
- }
+ var symbolTable = isPrototypeProperty ?
+ (targetSymbol.members || (targetSymbol.members = ts.createMap())) :
+ (targetSymbol.exports || (targetSymbol.exports = ts.createMap()));
// Declare the method/property
- declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 0 /* PropertyExcludes */);
+ declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4 /* Property */, 0 /* PropertyExcludes */);
}
function bindCallExpression(node) {
// We're only inspecting call expressions to detect CommonJS modules, so we can skip
@@ -22409,15 +23470,7 @@ var ts;
}
}
function bindClassLikeDeclaration(node) {
- if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) {
- if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) {
- emitFlags |= 1024 /* HasClassExtends */;
- }
- if (ts.nodeIsDecorated(node)) {
- emitFlags |= 2048 /* HasDecorators */;
- }
- }
- if (node.kind === 226 /* ClassDeclaration */) {
+ if (node.kind === 228 /* ClassDeclaration */) {
bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */);
}
else {
@@ -22425,7 +23478,7 @@ var ts;
bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
// Add name of class expression into the map for semantic classifier
if (node.name) {
- classifiableNames[node.name.text] = node.name.text;
+ classifiableNames.set(node.name.text, node.name.text);
}
}
var symbol = node.symbol;
@@ -22438,14 +23491,15 @@ var ts;
// Note: we check for this here because this class may be merging into a module. The
// module might have an exported variable called 'prototype'. We can't allow that as
// that would clash with the built-in 'prototype' for the class.
- var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype");
- if (symbol.exports[prototypeSymbol.name]) {
+ var prototypeSymbol = createSymbol(4 /* Property */ | 16777216 /* Prototype */, "prototype");
+ var symbolExport = symbol.exports.get(prototypeSymbol.name);
+ if (symbolExport) {
if (node.name) {
node.name.parent = node;
}
- file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name));
+ file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name));
}
- symbol.exports[prototypeSymbol.name] = prototypeSymbol;
+ symbol.exports.set(prototypeSymbol.name, prototypeSymbol);
prototypeSymbol.parent = symbol;
}
function bindEnumDeclaration(node) {
@@ -22479,11 +23533,6 @@ var ts;
}
}
function bindParameter(node) {
- if (!ts.isDeclarationFile(file) &&
- !ts.isInAmbientContext(node) &&
- ts.nodeIsDecorated(node)) {
- emitFlags |= (2048 /* HasDecorators */ | 4096 /* HasParamDecorators */);
- }
if (inStrictMode) {
// It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
// strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
@@ -22499,13 +23548,13 @@ var ts;
// containing class.
if (ts.isParameterPropertyDeclaration(node)) {
var classDeclaration = node.parent.parent;
- declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
+ declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
}
}
function bindFunctionDeclaration(node) {
if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) {
- if (ts.isAsyncFunctionLike(node)) {
- emitFlags |= 8192 /* HasAsyncFunctions */;
+ if (ts.isAsyncFunction(node)) {
+ emitFlags |= 1024 /* HasAsyncFunctions */;
}
}
checkStrictModeFunctionName(node);
@@ -22519,8 +23568,8 @@ var ts;
}
function bindFunctionExpression(node) {
if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) {
- if (ts.isAsyncFunctionLike(node)) {
- emitFlags |= 8192 /* HasAsyncFunctions */;
+ if (ts.isAsyncFunction(node)) {
+ emitFlags |= 1024 /* HasAsyncFunctions */;
}
}
if (currentFlow) {
@@ -22532,11 +23581,8 @@ var ts;
}
function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) {
- if (ts.isAsyncFunctionLike(node)) {
- emitFlags |= 8192 /* HasAsyncFunctions */;
- }
- if (ts.nodeIsDecorated(node)) {
- emitFlags |= 2048 /* HasDecorators */;
+ if (ts.isAsyncFunction(node)) {
+ emitFlags |= 1024 /* HasAsyncFunctions */;
}
}
if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -22561,13 +23607,13 @@ var ts;
if (currentFlow === unreachableFlow) {
var reportError =
// report error on all statements except empty ones
- (ts.isStatementButNotDeclaration(node) && node.kind !== 206 /* EmptyStatement */) ||
+ (ts.isStatementButNotDeclaration(node) && node.kind !== 208 /* EmptyStatement */) ||
// report error on class declarations
- node.kind === 226 /* ClassDeclaration */ ||
+ node.kind === 228 /* ClassDeclaration */ ||
// report error on instantiated modules or const-enums only modules if preserveConstEnums is set
- (node.kind === 230 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) ||
+ (node.kind === 232 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) ||
// report error on regular enums and const enums if preserveConstEnums is set
- (node.kind === 229 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums));
+ (node.kind === 231 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums));
if (reportError) {
currentFlow = reportedUnreachableFlow;
// unreachable code is reported if
@@ -22581,7 +23627,7 @@ var ts;
// On the other side we do want to report errors on non-initialized 'lets' because of TDZ
var reportUnreachableCode = !options.allowUnreachableCode &&
!ts.isInAmbientContext(node) &&
- (node.kind !== 205 /* VariableStatement */ ||
+ (node.kind !== 207 /* VariableStatement */ ||
ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ ||
ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; }));
if (reportUnreachableCode) {
@@ -22601,56 +23647,56 @@ var ts;
function computeTransformFlagsForNode(node, subtreeFlags) {
var kind = node.kind;
switch (kind) {
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
return computeCallExpression(node, subtreeFlags);
- case 180 /* NewExpression */:
+ case 181 /* NewExpression */:
return computeNewExpression(node, subtreeFlags);
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return computeModuleDeclaration(node, subtreeFlags);
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return computeParenthesizedExpression(node, subtreeFlags);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return computeBinaryExpression(node, subtreeFlags);
- case 207 /* ExpressionStatement */:
+ case 209 /* ExpressionStatement */:
return computeExpressionStatement(node, subtreeFlags);
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
return computeParameter(node, subtreeFlags);
- case 185 /* ArrowFunction */:
+ case 186 /* ArrowFunction */:
return computeArrowFunction(node, subtreeFlags);
- case 184 /* FunctionExpression */:
+ case 185 /* FunctionExpression */:
return computeFunctionExpression(node, subtreeFlags);
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return computeFunctionDeclaration(node, subtreeFlags);
- case 223 /* VariableDeclaration */:
+ case 225 /* VariableDeclaration */:
return computeVariableDeclaration(node, subtreeFlags);
- case 224 /* VariableDeclarationList */:
+ case 226 /* VariableDeclarationList */:
return computeVariableDeclarationList(node, subtreeFlags);
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
return computeVariableStatement(node, subtreeFlags);
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
return computeLabeledStatement(node, subtreeFlags);
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
return computeClassDeclaration(node, subtreeFlags);
- case 197 /* ClassExpression */:
+ case 198 /* ClassExpression */:
return computeClassExpression(node, subtreeFlags);
- case 255 /* HeritageClause */:
+ case 258 /* HeritageClause */:
return computeHeritageClause(node, subtreeFlags);
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return computeCatchClause(node, subtreeFlags);
- case 199 /* ExpressionWithTypeArguments */:
+ case 200 /* ExpressionWithTypeArguments */:
return computeExpressionWithTypeArguments(node, subtreeFlags);
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
return computeConstructor(node, subtreeFlags);
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
return computePropertyDeclaration(node, subtreeFlags);
- case 149 /* MethodDeclaration */:
+ case 150 /* MethodDeclaration */:
return computeMethod(node, subtreeFlags);
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
return computeAccessor(node, subtreeFlags);
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
return computeImportEquals(node, subtreeFlags);
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
return computePropertyAccess(node, subtreeFlags);
default:
return computeOther(node, kind, subtreeFlags);
@@ -22677,8 +23723,8 @@ var ts;
switch (kind) {
case 96 /* SuperKeyword */:
return true;
- case 177 /* PropertyAccessExpression */:
- case 178 /* ElementAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
+ case 179 /* ElementAccessExpression */:
var expression = node.expression;
var expressionKind = expression.kind;
return expressionKind === 96 /* SuperKeyword */;
@@ -22702,12 +23748,12 @@ var ts;
var transformFlags = subtreeFlags;
var operatorTokenKind = node.operatorToken.kind;
var leftKind = node.left.kind;
- if (operatorTokenKind === 57 /* EqualsToken */ && leftKind === 176 /* ObjectLiteralExpression */) {
+ if (operatorTokenKind === 57 /* EqualsToken */ && leftKind === 177 /* ObjectLiteralExpression */) {
// Destructuring object assignments with are ES2015 syntax
// and possibly ESNext if they contain rest
transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
}
- else if (operatorTokenKind === 57 /* EqualsToken */ && leftKind === 175 /* ArrayLiteralExpression */) {
+ else if (operatorTokenKind === 57 /* EqualsToken */ && leftKind === 176 /* ArrayLiteralExpression */) {
// Destructuring assignments are ES2015 syntax.
transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */;
}
@@ -22757,8 +23803,8 @@ var ts;
// If the node is synthesized, it means the emitter put the parentheses there,
// not the user. If we didn't want them, the emitter would not have put them
// there.
- if (expressionKind === 200 /* AsExpression */
- || expressionKind === 182 /* TypeAssertionExpression */) {
+ if (expressionKind === 201 /* AsExpression */
+ || expressionKind === 183 /* TypeAssertionExpression */) {
transformFlags |= 3 /* AssertTypeScript */;
}
// If the expression of a ParenthesizedExpression is a destructuring assignment,
@@ -22883,10 +23929,9 @@ var ts;
}
// An async method declaration is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
}
- // Currently, we only support generators that were originally async function bodies.
- if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) {
+ if (node.asteriskToken) {
transformFlags |= 768 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
@@ -22940,7 +23985,7 @@ var ts;
}
// An async function declaration is ES2017 syntax.
if (modifierFlags & 256 /* Async */) {
- transformFlags |= 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
}
// function declarations with object rest destructuring are ES Next syntax
if (subtreeFlags & 1048576 /* ContainsObjectRest */) {
@@ -22957,7 +24002,7 @@ var ts;
// down-level generator.
// Currently we do not support transforming any other generator fucntions
// down level.
- if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) {
+ if (node.asteriskToken) {
transformFlags |= 768 /* AssertGenerator */;
}
}
@@ -22975,7 +24020,7 @@ var ts;
}
// An async function expression is ES2017 syntax.
if (ts.hasModifier(node, 256 /* Async */)) {
- transformFlags |= 16 /* AssertES2017 */;
+ transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */;
}
// function expressions with object rest destructuring are ES Next syntax
if (subtreeFlags & 1048576 /* ContainsObjectRest */) {
@@ -22990,9 +24035,7 @@ var ts;
// If a FunctionExpression is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
- // Currently we do not support transforming any other generator fucntions
- // down level.
- if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) {
+ if (node.asteriskToken) {
transformFlags |= 768 /* AssertGenerator */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
@@ -23123,9 +24166,9 @@ var ts;
var excludeFlags = 536872257 /* NodeExcludes */;
switch (kind) {
case 119 /* AsyncKeyword */:
- case 189 /* AwaitExpression */:
- // async/await is ES2017 syntax
- transformFlags |= 16 /* AssertES2017 */;
+ case 190 /* AwaitExpression */:
+ // async/await is ES2017 syntax, but may be ESNext syntax (for async generators)
+ transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */;
break;
case 113 /* PublicKeyword */:
case 111 /* PrivateKeyword */:
@@ -23133,81 +24176,98 @@ var ts;
case 116 /* AbstractKeyword */:
case 123 /* DeclareKeyword */:
case 75 /* ConstKeyword */:
- case 229 /* EnumDeclaration */:
- case 260 /* EnumMember */:
- case 182 /* TypeAssertionExpression */:
- case 200 /* AsExpression */:
- case 201 /* NonNullExpression */:
+ case 231 /* EnumDeclaration */:
+ case 263 /* EnumMember */:
+ case 183 /* TypeAssertionExpression */:
+ case 201 /* AsExpression */:
+ case 202 /* NonNullExpression */:
case 130 /* ReadonlyKeyword */:
// These nodes are TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */;
break;
- case 246 /* JsxElement */:
- case 247 /* JsxSelfClosingElement */:
- case 248 /* JsxOpeningElement */:
+ case 248 /* JsxElement */:
+ case 249 /* JsxSelfClosingElement */:
+ case 250 /* JsxOpeningElement */:
case 10 /* JsxText */:
- case 249 /* JsxClosingElement */:
- case 250 /* JsxAttribute */:
- case 251 /* JsxSpreadAttribute */:
- case 252 /* JsxExpression */:
+ case 251 /* JsxClosingElement */:
+ case 252 /* JsxAttribute */:
+ case 253 /* JsxAttributes */:
+ case 254 /* JsxSpreadAttribute */:
+ case 255 /* JsxExpression */:
// These nodes are Jsx syntax.
transformFlags |= 4 /* AssertJsx */;
break;
- case 213 /* ForOfStatement */:
- // for-of might be ESNext if it has a rest destructuring
- transformFlags |= 8 /* AssertESNext */;
- // FALLTHROUGH
case 12 /* NoSubstitutionTemplateLiteral */:
case 13 /* TemplateHead */:
case 14 /* TemplateMiddle */:
case 15 /* TemplateTail */:
- case 194 /* TemplateExpression */:
- case 181 /* TaggedTemplateExpression */:
- case 258 /* ShorthandPropertyAssignment */:
+ case 195 /* TemplateExpression */:
+ case 182 /* TaggedTemplateExpression */:
+ case 261 /* ShorthandPropertyAssignment */:
case 114 /* StaticKeyword */:
+ case 203 /* MetaProperty */:
// These nodes are ES6 syntax.
transformFlags |= 192 /* AssertES2015 */;
break;
- case 195 /* YieldExpression */:
- // This node is ES6 syntax.
- transformFlags |= 192 /* AssertES2015 */ | 16777216 /* ContainsYield */;
+ case 9 /* StringLiteral */:
+ if (node.hasExtendedUnicodeEscape) {
+ transformFlags |= 192 /* AssertES2015 */;
+ }
+ break;
+ case 8 /* NumericLiteral */:
+ if (node.numericLiteralFlags & 48 /* BinaryOrOctalSpecifier */) {
+ transformFlags |= 192 /* AssertES2015 */;
+ }
+ break;
+ case 215 /* ForOfStatement */:
+ // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
+ if (node.awaitModifier) {
+ transformFlags |= 8 /* AssertESNext */;
+ }
+ transformFlags |= 192 /* AssertES2015 */;
+ break;
+ case 196 /* YieldExpression */:
+ // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
+ // generator).
+ transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */;
break;
case 118 /* AnyKeyword */:
case 132 /* NumberKeyword */:
case 129 /* NeverKeyword */:
- case 134 /* StringKeyword */:
+ case 133 /* ObjectKeyword */:
+ case 135 /* StringKeyword */:
case 121 /* BooleanKeyword */:
- case 135 /* SymbolKeyword */:
+ case 136 /* SymbolKeyword */:
case 104 /* VoidKeyword */:
- case 143 /* TypeParameter */:
- case 146 /* PropertySignature */:
- case 148 /* MethodSignature */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
- case 156 /* TypePredicate */:
- case 157 /* TypeReference */:
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
- case 160 /* TypeQuery */:
- case 161 /* TypeLiteral */:
- case 162 /* ArrayType */:
- case 163 /* TupleType */:
- case 164 /* UnionType */:
- case 165 /* IntersectionType */:
- case 166 /* ParenthesizedType */:
- case 227 /* InterfaceDeclaration */:
- case 228 /* TypeAliasDeclaration */:
- case 167 /* ThisType */:
- case 168 /* TypeOperator */:
- case 169 /* IndexedAccessType */:
- case 170 /* MappedType */:
- case 171 /* LiteralType */:
+ case 144 /* TypeParameter */:
+ case 147 /* PropertySignature */:
+ case 149 /* MethodSignature */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
+ case 157 /* TypePredicate */:
+ case 158 /* TypeReference */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
+ case 161 /* TypeQuery */:
+ case 162 /* TypeLiteral */:
+ case 163 /* ArrayType */:
+ case 164 /* TupleType */:
+ case 165 /* UnionType */:
+ case 166 /* IntersectionType */:
+ case 167 /* ParenthesizedType */:
+ case 229 /* InterfaceDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
+ case 168 /* ThisType */:
+ case 169 /* TypeOperator */:
+ case 170 /* IndexedAccessType */:
+ case 171 /* MappedType */:
+ case 172 /* LiteralType */:
// Types and signatures are TypeScript syntax, and exclude all other facts.
transformFlags = 3 /* AssertTypeScript */;
excludeFlags = -3 /* TypeExcludes */;
break;
- case 142 /* ComputedPropertyName */:
+ case 143 /* ComputedPropertyName */:
// Even though computed property names are ES6, we don't treat them as such.
// This is so that they can flow through PropertyName transforms unaffected.
// Instead, we mark the container as ES6, so that it can properly handle the transform.
@@ -23224,10 +24284,10 @@ var ts;
transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */;
}
break;
- case 196 /* SpreadElement */:
+ case 197 /* SpreadElement */:
transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */;
break;
- case 259 /* SpreadAssignment */:
+ case 262 /* SpreadAssignment */:
transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */;
break;
case 96 /* SuperKeyword */:
@@ -23238,28 +24298,28 @@ var ts;
// Mark this node and its ancestors as containing a lexical `this` keyword.
transformFlags |= 16384 /* ContainsLexicalThis */;
break;
- case 172 /* ObjectBindingPattern */:
+ case 173 /* ObjectBindingPattern */:
transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */;
if (subtreeFlags & 524288 /* ContainsRest */) {
transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */;
}
excludeFlags = 537396545 /* BindingPatternExcludes */;
break;
- case 173 /* ArrayBindingPattern */:
+ case 174 /* ArrayBindingPattern */:
transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */;
excludeFlags = 537396545 /* BindingPatternExcludes */;
break;
- case 174 /* BindingElement */:
+ case 175 /* BindingElement */:
transformFlags |= 192 /* AssertES2015 */;
if (node.dotDotDotToken) {
transformFlags |= 524288 /* ContainsRest */;
}
break;
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
// This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */;
break;
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
excludeFlags = 540087617 /* ObjectLiteralExcludes */;
if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) {
// If an ObjectLiteralExpression contains a ComputedPropertyName, then it
@@ -23277,8 +24337,8 @@ var ts;
transformFlags |= 8 /* AssertESNext */;
}
break;
- case 175 /* ArrayLiteralExpression */:
- case 180 /* NewExpression */:
+ case 176 /* ArrayLiteralExpression */:
+ case 181 /* NewExpression */:
excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */;
if (subtreeFlags & 524288 /* ContainsSpread */) {
// If the this node contains a SpreadExpression, then it is an ES6
@@ -23286,23 +24346,23 @@ var ts;
transformFlags |= 192 /* AssertES2015 */;
}
break;
- case 209 /* DoStatement */:
- case 210 /* WhileStatement */:
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
+ case 211 /* DoStatement */:
+ case 212 /* WhileStatement */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
// A loop containing a block scoped binding *may* need to be transformed from ES6.
if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) {
transformFlags |= 192 /* AssertES2015 */;
}
break;
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) {
transformFlags |= 192 /* AssertES2015 */;
}
break;
- case 216 /* ReturnStatement */:
- case 214 /* ContinueStatement */:
- case 215 /* BreakStatement */:
+ case 218 /* ReturnStatement */:
+ case 216 /* ContinueStatement */:
+ case 217 /* BreakStatement */:
transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */;
break;
}
@@ -23318,56 +24378,57 @@ var ts;
*/
/* @internal */
function getTransformFlagsSubtreeExclusions(kind) {
- if (kind >= 156 /* FirstTypeNode */ && kind <= 171 /* LastTypeNode */) {
+ if (kind >= 157 /* FirstTypeNode */ && kind <= 172 /* LastTypeNode */) {
return -3 /* TypeExcludes */;
}
switch (kind) {
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
- case 175 /* ArrayLiteralExpression */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
+ case 176 /* ArrayLiteralExpression */:
return 537396545 /* ArrayLiteralOrCallOrNewExcludes */;
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return 574674241 /* ModuleExcludes */;
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
return 536872257 /* ParameterExcludes */;
- case 185 /* ArrowFunction */:
+ case 186 /* ArrowFunction */:
return 601249089 /* ArrowFunctionExcludes */;
- case 184 /* FunctionExpression */:
- case 225 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 227 /* FunctionDeclaration */:
return 601281857 /* FunctionExcludes */;
- case 224 /* VariableDeclarationList */:
+ case 226 /* VariableDeclarationList */:
return 546309441 /* VariableDeclarationListExcludes */;
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
return 539358529 /* ClassExcludes */;
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
return 601015617 /* ConstructorExcludes */;
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
return 601015617 /* MethodOrAccessorExcludes */;
case 118 /* AnyKeyword */:
case 132 /* NumberKeyword */:
case 129 /* NeverKeyword */:
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
+ case 133 /* ObjectKeyword */:
case 121 /* BooleanKeyword */:
- case 135 /* SymbolKeyword */:
+ case 136 /* SymbolKeyword */:
case 104 /* VoidKeyword */:
- case 143 /* TypeParameter */:
- case 146 /* PropertySignature */:
- case 148 /* MethodSignature */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
- case 227 /* InterfaceDeclaration */:
- case 228 /* TypeAliasDeclaration */:
+ case 144 /* TypeParameter */:
+ case 147 /* PropertySignature */:
+ case 149 /* MethodSignature */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
+ case 229 /* InterfaceDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
return -3 /* TypeExcludes */;
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
return 540087617 /* ObjectLiteralExcludes */;
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return 537920833 /* CatchClauseExcludes */;
- case 172 /* ObjectBindingPattern */:
- case 173 /* ArrayBindingPattern */:
+ case 173 /* ObjectBindingPattern */:
+ case 174 /* ArrayBindingPattern */:
return 537396545 /* BindingPatternExcludes */;
default:
return 536872257 /* NodeExcludes */;
@@ -23406,10 +24467,6 @@ var ts;
ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension));
return resolved.path;
}
- /** Create Resolved from a file with unknown extension. */
- function resolvedFromAnyFile(path) {
- return { path: path, extension: ts.extensionFromPath(path) };
- }
/** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */
function resolvedModuleFromResolved(_a, isExternalLibraryImport) {
var path = _a.path, extension = _a.extension;
@@ -23422,37 +24479,29 @@ var ts;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
ts.moduleHasNonRelativeName = moduleHasNonRelativeName;
- function tryReadTypesSection(extensions, packageJsonPath, baseDirectory, state) {
+ /** Reads from "main" or "types"/"typings" depending on `extensions`. */
+ function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) {
var jsonContent = readJson(packageJsonPath, state.host);
- switch (extensions) {
- case 2 /* DtsOnly */:
- case 0 /* TypeScript */:
- return tryReadFromField("typings") || tryReadFromField("types");
- case 1 /* JavaScript */:
- if (typeof jsonContent.main === "string") {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main);
- }
- return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main));
- }
- return undefined;
- }
+ return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main");
function tryReadFromField(fieldName) {
- if (ts.hasProperty(jsonContent, fieldName)) {
- var typesFile = jsonContent[fieldName];
- if (typeof typesFile === "string") {
- var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile));
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath);
- }
- return typesFilePath;
+ if (!ts.hasProperty(jsonContent, fieldName)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
}
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
- }
+ return;
+ }
+ var fileName = jsonContent[fieldName];
+ if (typeof fileName !== "string") {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName);
}
+ return;
+ }
+ var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
}
+ return path;
}
}
function readJson(path, host) {
@@ -23488,13 +24537,15 @@ var ts;
function getDefaultTypeRoots(currentDirectory, host) {
if (!host.directoryExists) {
return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
+ // And if it doesn't exist, tough.
}
var typeRoots;
- forEachAncestorDirectory(currentDirectory, function (directory) {
+ forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
if (host.directoryExists(atTypes)) {
(typeRoots || (typeRoots = [])).push(atTypes);
}
+ return undefined;
});
return typeRoots;
}
@@ -23555,7 +24606,11 @@ var ts;
return ts.forEach(typeRoots, function (typeRoot) {
var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
var candidateDirectory = ts.getDirectoryPath(candidate);
- return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(2 /* DtsOnly */, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState));
+ var directoryExists = directoryProbablyExists(candidateDirectory, host);
+ if (!directoryExists && traceEnabled) {
+ trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
+ }
+ return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState));
});
}
else {
@@ -23572,7 +24627,8 @@ var ts;
if (traceEnabled) {
trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
}
- resolvedFile = resolvedTypeScriptOnly(loadModuleFromNodeModules(2 /* DtsOnly */, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState));
+ var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined);
+ resolvedFile = resolvedTypeScriptOnly(result && result.value);
if (!resolvedFile && traceEnabled) {
trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
}
@@ -23587,13 +24643,13 @@ var ts;
}
ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
/**
- * Given a set of options, returns the set of type directive names
- * that should be included for this program automatically.
- * This list could either come from the config file,
- * or from enumerating the types root + initial secondary types lookup location.
- * More type directives might appear in the program later as a result of loading actual source files;
- * this list is only the set of defaults that are implicitly included.
- */
+ * Given a set of options, returns the set of type directive names
+ * that should be included for this program automatically.
+ * This list could either come from the config file,
+ * or from enumerating the types root + initial secondary types lookup location.
+ * More type directives might appear in the program later as a result of loading actual source files;
+ * this list is only the set of defaults that are implicitly included.
+ */
function getAutomaticTypeDirectiveNames(options, host) {
// Use explicit type list from tsconfig.json
if (options.types) {
@@ -23625,31 +24681,135 @@ var ts;
return result;
}
ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
- function resolveModuleName(moduleName, containingFile, compilerOptions, host) {
+ function createModuleResolutionCache(currentDirectory, getCanonicalFileName) {
+ var directoryToModuleNameMap = ts.createFileMap();
+ var moduleNameToDirectoryMap = ts.createMap();
+ return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName };
+ function getOrCreateCacheForDirectory(directoryName) {
+ var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
+ var perFolderCache = directoryToModuleNameMap.get(path);
+ if (!perFolderCache) {
+ perFolderCache = ts.createMap();
+ directoryToModuleNameMap.set(path, perFolderCache);
+ }
+ return perFolderCache;
+ }
+ function getOrCreateCacheForModuleName(nonRelativeModuleName) {
+ if (!moduleHasNonRelativeName(nonRelativeModuleName)) {
+ return undefined;
+ }
+ var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName);
+ if (!perModuleNameCache) {
+ perModuleNameCache = createPerModuleNameCache();
+ moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache);
+ }
+ return perModuleNameCache;
+ }
+ function createPerModuleNameCache() {
+ var directoryPathMap = ts.createFileMap();
+ return { get: get, set: set };
+ function get(directory) {
+ return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
+ }
+ /**
+ * At first this function add entry directory -> module resolution result to the table.
+ * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
+ * and for every parent folder in set it adds entry: parent -> module resolution. .
+ * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
+ * Set of parent folders that should have the same result will be:
+ * [
+ * /a/b/c/d, /a/b/c, /a/b
+ * ]
+ * this means that request for module resolution from file in any of these folder will be immediately found in cache.
+ */
+ function set(directory, result) {
+ var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
+ // if entry is already in cache do nothing
+ if (directoryPathMap.contains(path)) {
+ return;
+ }
+ directoryPathMap.set(path, result);
+ var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName;
+ // find common prefix between directory and resolved file name
+ // this common prefix should be the shorted path that has the same resolution
+ // directory: /a/b/c/d/e
+ // resolvedFileName: /a/b/foo.d.ts
+ var commonPrefix = getCommonPrefix(path, resolvedFileName);
+ var current = path;
+ while (true) {
+ var parent = ts.getDirectoryPath(current);
+ if (parent === current || directoryPathMap.contains(parent)) {
+ break;
+ }
+ directoryPathMap.set(parent, result);
+ current = parent;
+ if (current === commonPrefix) {
+ break;
+ }
+ }
+ }
+ function getCommonPrefix(directory, resolution) {
+ if (resolution === undefined) {
+ return undefined;
+ }
+ var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
+ // find first position where directory and resolution differs
+ var i = 0;
+ while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
+ i++;
+ }
+ // find last directory separator before position i
+ var sep = directory.lastIndexOf(ts.directorySeparator, i);
+ if (sep < 0) {
+ return undefined;
+ }
+ return directory.substr(0, sep);
+ }
+ }
+ }
+ ts.createModuleResolutionCache = createModuleResolutionCache;
+ function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
}
- var moduleResolution = compilerOptions.moduleResolution;
- if (moduleResolution === undefined) {
- moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
+ var containingDirectory = ts.getDirectoryPath(containingFile);
+ var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
+ var result = perFolderCache && perFolderCache.get(moduleName);
+ if (result) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
}
}
else {
- if (traceEnabled) {
- trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
+ var moduleResolution = compilerOptions.moduleResolution;
+ if (moduleResolution === undefined) {
+ moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
+ }
+ }
+ else {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
+ }
+ }
+ switch (moduleResolution) {
+ case ts.ModuleResolutionKind.NodeJs:
+ result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache);
+ break;
+ case ts.ModuleResolutionKind.Classic:
+ result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache);
+ break;
+ }
+ if (perFolderCache) {
+ perFolderCache.set(moduleName, result);
+ // put result in per-module name cache
+ var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName);
+ if (perModuleNameCache) {
+ perModuleNameCache.set(containingDirectory, result);
+ }
}
- }
- var result;
- switch (moduleResolution) {
- case ts.ModuleResolutionKind.NodeJs:
- result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
- case ts.ModuleResolutionKind.Classic:
- result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
- break;
}
if (traceEnabled) {
if (result.resolvedModule) {
@@ -23842,38 +25002,45 @@ var ts;
return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
}
}
- function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) {
+ function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) {
+ return nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, /*jsOnly*/ false);
+ }
+ ts.nodeModuleNameResolver = nodeModuleNameResolver;
+ /* @internal */
+ function nodeModuleNameResolverWorker(moduleName, containingFile, compilerOptions, host, cache, jsOnly) {
+ if (jsOnly === void 0) { jsOnly = false; }
var containingDirectory = ts.getDirectoryPath(containingFile);
var traceEnabled = isTraceEnabled(compilerOptions, host);
var failedLookupLocations = [];
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
- var result = tryResolve(0 /* TypeScript */) || tryResolve(1 /* JavaScript */);
- if (result) {
- var resolved = result.resolved, isExternalLibraryImport = result.isExternalLibraryImport;
+ var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript));
+ if (result && result.value) {
+ var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport;
return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations);
}
return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations };
function tryResolve(extensions) {
- var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state);
+ var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); };
+ var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state);
if (resolved) {
- return { resolved: resolved, isExternalLibraryImport: false };
+ return toSearchResult({ resolved: resolved, isExternalLibraryImport: false });
}
if (moduleHasNonRelativeName(moduleName)) {
if (traceEnabled) {
- trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
+ trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
}
- var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state);
+ var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache);
// For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
- return resolved_1 && { resolved: { path: realpath(resolved_1.path, host, traceEnabled), extension: resolved_1.extension }, isExternalLibraryImport: true };
+ return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } };
}
else {
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state);
- return resolved_2 && { resolved: resolved_2, isExternalLibraryImport: false };
+ var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
+ return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false });
}
}
}
- ts.nodeModuleNameResolver = nodeModuleNameResolver;
+ ts.nodeModuleNameResolverWorker = nodeModuleNameResolverWorker;
function realpath(path, host, traceEnabled) {
if (!host.realpath) {
return path;
@@ -23884,12 +25051,35 @@ var ts;
}
return real;
}
- function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) {
+ function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) {
if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
+ trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
}
- var resolvedFromFile = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state);
- return resolvedFromFile || loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state);
+ if (!ts.pathEndsWithDirectorySeparator(candidate)) {
+ if (!onlyRecordFailures) {
+ var parentOfCandidate = ts.getDirectoryPath(candidate);
+ if (!directoryProbablyExists(parentOfCandidate, state.host)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
+ }
+ onlyRecordFailures = true;
+ }
+ }
+ var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state);
+ if (resolvedFromFile) {
+ return resolvedFromFile;
+ }
+ }
+ if (!onlyRecordFailures) {
+ var candidateExists = directoryProbablyExists(candidate, state.host);
+ if (!candidateExists) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
+ }
+ onlyRecordFailures = true;
+ }
+ }
+ return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson);
}
/* @internal */
function directoryProbablyExists(directoryName, host) {
@@ -23928,11 +25118,11 @@ var ts;
}
}
switch (extensions) {
- case 2 /* DtsOnly */:
+ case Extensions.DtsOnly:
return tryExtension(".d.ts", ts.Extension.Dts);
- case 0 /* TypeScript */:
+ case Extensions.TypeScript:
return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts);
- case 1 /* JavaScript */:
+ case Extensions.JavaScript:
return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx);
}
function tryExtension(ext, extension) {
@@ -23942,120 +25132,191 @@ var ts;
}
/** Return the file if it exists. */
function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) {
- if (!onlyRecordFailures && state.host.fileExists(fileName)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
+ if (!onlyRecordFailures) {
+ if (state.host.fileExists(fileName)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
+ }
+ return fileName;
}
- return fileName;
- }
- else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
+ else {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
+ }
}
- failedLookupLocations.push(fileName);
- return undefined;
}
+ failedLookupLocations.push(fileName);
+ return undefined;
}
- function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) {
- var packageJsonPath = pathToPackageJson(candidate);
+ function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) {
+ if (considerPackageJson === void 0) { considerPackageJson = true; }
var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
- if (directoryExists && state.host.fileExists(packageJsonPath)) {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
- }
- var typesFile = tryReadTypesSection(extensions, packageJsonPath, candidate, state);
- if (typesFile) {
- var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host);
- // A package.json "typings" may specify an exact filename, or may choose to omit an extension.
- var fromFile = tryFile(typesFile, failedLookupLocations, onlyRecordFailures_1, state);
- if (fromFile) {
- // Note: this would allow a package.json to specify a ".js" file as typings. Maybe that should be forbidden.
- return resolvedFromAnyFile(fromFile);
- }
- var x = tryAddingExtensions(typesFile, 0 /* TypeScript */, failedLookupLocations, onlyRecordFailures_1, state);
- if (x) {
- return x;
+ if (considerPackageJson) {
+ var packageJsonPath = pathToPackageJson(candidate);
+ if (directoryExists && state.host.fileExists(packageJsonPath)) {
+ var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state);
+ if (fromPackageJson) {
+ return fromPackageJson;
}
}
else {
- if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field);
+ if (directoryExists && state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
}
+ // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
+ failedLookupLocations.push(packageJsonPath);
}
}
- else {
+ return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state);
+ }
+ function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
+ }
+ var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state);
+ if (!file) {
+ return undefined;
+ }
+ var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host);
+ var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state);
+ if (fromFile) {
+ var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile);
+ if (resolved) {
+ return resolved;
+ }
if (state.traceEnabled) {
- trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
+ trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
}
- // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
- failedLookupLocations.push(packageJsonPath);
}
- return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state);
+ // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
+ var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
+ // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
+ return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false);
+ }
+ /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
+ function resolvedIfExtensionMatches(extensions, path) {
+ var extension = ts.tryGetExtensionFromPath(path);
+ return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined;
+ }
+ /** True if `extension` is one of the supported `extensions`. */
+ function extensionIsOk(extensions, extension) {
+ switch (extensions) {
+ case Extensions.JavaScript:
+ return extension === ts.Extension.Js || extension === ts.Extension.Jsx;
+ case Extensions.TypeScript:
+ return extension === ts.Extension.Ts || extension === ts.Extension.Tsx || extension === ts.Extension.Dts;
+ case Extensions.DtsOnly:
+ return extension === ts.Extension.Dts;
+ }
}
function pathToPackageJson(directory) {
return ts.combinePaths(directory, "package.json");
}
- function loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state) {
- var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
- var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
+ function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) {
var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName));
return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) ||
loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
}
- function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state) {
- return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false);
+ function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) {
+ return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache);
}
function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) {
// Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
- return loadModuleFromNodeModulesWorker(2 /* DtsOnly */, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true);
+ return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined);
}
- function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) {
+ function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) {
+ var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName);
return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
- return loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly);
+ var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host);
+ if (resolutionFromCache) {
+ return resolutionFromCache;
+ }
+ return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly));
}
});
}
/** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */
function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) {
if (typesOnly === void 0) { typesOnly = false; }
- var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, directory, failedLookupLocations, state);
+ var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
+ var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
+ if (!nodeModulesFolderExists && state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
+ }
+ var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state);
if (packageResult) {
return packageResult;
}
- if (extensions !== 1 /* JavaScript */) {
- return loadModuleFromNodeModulesFolder(2 /* DtsOnly */, ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state);
+ if (extensions !== Extensions.JavaScript) {
+ var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
+ var nodeModulesAtTypesExists = nodeModulesFolderExists;
+ if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
+ }
+ nodeModulesAtTypesExists = false;
+ }
+ return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state);
+ }
+ }
+ /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
+ function mangleScopedPackage(moduleName, state) {
+ if (ts.startsWith(moduleName, "@")) {
+ var replaceSlash = moduleName.replace(ts.directorySeparator, "__");
+ if (replaceSlash !== moduleName) {
+ var mangled = replaceSlash.slice(1); // Take off the "@"
+ if (state.traceEnabled) {
+ trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
+ }
+ return mangled;
+ }
+ }
+ return moduleName;
+ }
+ function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) {
+ var result = cache && cache.get(containingDirectory);
+ if (result) {
+ if (traceEnabled) {
+ trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName);
+ }
+ return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } };
}
}
- function classicNameResolver(moduleName, containingFile, compilerOptions, host) {
+ function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) {
var traceEnabled = isTraceEnabled(compilerOptions, host);
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
var failedLookupLocations = [];
var containingDirectory = ts.getDirectoryPath(containingFile);
- var resolved = tryResolve(0 /* TypeScript */) || tryResolve(1 /* JavaScript */);
- return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ false, failedLookupLocations);
+ var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
+ return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations);
function tryResolve(extensions) {
var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state);
if (resolvedUsingSettings) {
- return resolvedUsingSettings;
+ return { value: resolvedUsingSettings };
}
+ var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName);
if (moduleHasNonRelativeName(moduleName)) {
// Climb up parent directories looking for a module.
var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) {
+ var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host);
+ if (resolutionFromCache) {
+ return resolutionFromCache;
+ }
var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
- return loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state);
+ return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state));
});
if (resolved_3) {
return resolved_3;
}
- if (extensions === 0 /* TypeScript */) {
+ if (extensions === Extensions.TypeScript) {
// If we didn't find the file normally, look it up in @types.
return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state);
}
}
else {
var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
- return loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state);
+ return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state));
}
}
}
@@ -24072,10 +25333,17 @@ var ts;
}
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
var failedLookupLocations = [];
- var resolved = loadModuleFromNodeModulesOneLevel(2 /* DtsOnly */, moduleName, globalCache, failedLookupLocations, state);
+ var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state);
return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations);
}
ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
+ /**
+ * Wraps value to SearchResult.
+ * @returns undefined if value is undefined or { value } otherwise
+ */
+ function toSearchResult(value) {
+ return value !== undefined ? { value: value } : undefined;
+ }
/** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */
function forEachAncestorDirectory(directory, callback) {
while (true) {
@@ -24128,23 +25396,34 @@ var ts;
// is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
// they no longer need the information (for example, if the user started editing again).
var cancellationToken;
+ var requestedExternalEmitHelpers;
+ var externalHelpersModule;
var Symbol = ts.objectAllocator.getSymbolConstructor();
var Type = ts.objectAllocator.getTypeConstructor();
var Signature = ts.objectAllocator.getSignatureConstructor();
var typeCount = 0;
var symbolCount = 0;
+ var symbolInstantiationDepth = 0;
var emptyArray = [];
var emptySymbols = ts.createMap();
var compilerOptions = host.getCompilerOptions();
- var languageVersion = compilerOptions.target || 0 /* ES3 */;
+ var languageVersion = ts.getEmitScriptTarget(compilerOptions);
var modulekind = ts.getEmitModuleKind(compilerOptions);
var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters;
var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System;
- var strictNullChecks = compilerOptions.strictNullChecks;
+ var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks;
+ var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny;
+ var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis;
var emitResolver = createResolver();
- var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined");
+ var nodeBuilder = createNodeBuilder();
+ var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
undefinedSymbol.declarations = [];
- var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments");
+ var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
+ // for public members that accept a Node or one of its subtypes, we must guard against
+ // synthetic nodes created during transformations by calling `getParseTreeNode`.
+ // for most of these, we perform the guard only on `checker` to avoid any possible
+ // extra cost of calling `getParseTreeNode` when calling these functions from inside the
+ // checker.
var checker = {
getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
@@ -24153,49 +25432,129 @@ var ts;
isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
+ getMergedSymbol: getMergedSymbol,
getDiagnostics: getDiagnostics,
getGlobalDiagnostics: getGlobalDiagnostics,
- getTypeOfSymbolAtLocation: getTypeOfSymbolAtLocation,
- getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration,
+ getTypeOfSymbolAtLocation: function (symbol, location) {
+ location = ts.getParseTreeNode(location);
+ return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType;
+ },
+ getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) {
+ parameter = ts.getParseTreeNode(parameter, ts.isParameter);
+ ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
+ return getSymbolsOfParameterPropertyDeclaration(parameter, parameterName);
+ },
getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
getPropertiesOfType: getPropertiesOfType,
getPropertyOfType: getPropertyOfType,
+ getIndexInfoOfType: getIndexInfoOfType,
getSignaturesOfType: getSignaturesOfType,
getIndexTypeOfType: getIndexTypeOfType,
getBaseTypes: getBaseTypes,
+ getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
+ getWidenedType: getWidenedType,
+ getTypeFromTypeNode: function (node) {
+ node = ts.getParseTreeNode(node, ts.isTypeNode);
+ return node ? getTypeFromTypeNode(node) : unknownType;
+ },
+ getParameterType: getTypeAtPosition,
getReturnTypeOfSignature: getReturnTypeOfSignature,
getNonNullableType: getNonNullableType,
- getSymbolsInScope: getSymbolsInScope,
- getSymbolAtLocation: getSymbolAtLocation,
- getShorthandAssignmentValueSymbol: getShorthandAssignmentValueSymbol,
- getExportSpecifierLocalTargetSymbol: getExportSpecifierLocalTargetSymbol,
- getTypeAtLocation: getTypeOfNode,
- getPropertySymbolOfDestructuringAssignment: getPropertySymbolOfDestructuringAssignment,
- typeToString: typeToString,
+ typeToTypeNode: nodeBuilder.typeToTypeNode,
+ indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
+ signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
+ getSymbolsInScope: function (location, meaning) {
+ location = ts.getParseTreeNode(location);
+ return location ? getSymbolsInScope(location, meaning) : [];
+ },
+ getSymbolAtLocation: function (node) {
+ node = ts.getParseTreeNode(node);
+ return node ? getSymbolAtLocation(node) : undefined;
+ },
+ getShorthandAssignmentValueSymbol: function (node) {
+ node = ts.getParseTreeNode(node);
+ return node ? getShorthandAssignmentValueSymbol(node) : undefined;
+ },
+ getExportSpecifierLocalTargetSymbol: function (node) {
+ node = ts.getParseTreeNode(node, ts.isExportSpecifier);
+ return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
+ },
+ getTypeAtLocation: function (node) {
+ node = ts.getParseTreeNode(node);
+ return node ? getTypeOfNode(node) : unknownType;
+ },
+ getPropertySymbolOfDestructuringAssignment: function (location) {
+ location = ts.getParseTreeNode(location, ts.isIdentifier);
+ return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
+ },
+ signatureToString: function (signature, enclosingDeclaration, flags, kind) {
+ return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
+ },
+ typeToString: function (type, enclosingDeclaration, flags) {
+ return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
+ },
getSymbolDisplayBuilder: getSymbolDisplayBuilder,
- symbolToString: symbolToString,
+ symbolToString: function (symbol, enclosingDeclaration, meaning) {
+ return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning);
+ },
getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
getRootSymbols: getRootSymbols,
- getContextualType: getContextualType,
+ getContextualType: function (node) {
+ node = ts.getParseTreeNode(node, ts.isExpression);
+ return node ? getContextualType(node) : undefined;
+ },
getFullyQualifiedName: getFullyQualifiedName,
- getResolvedSignature: getResolvedSignature,
- getConstantValue: getConstantValue,
- isValidPropertyAccess: isValidPropertyAccess,
- getSignatureFromDeclaration: getSignatureFromDeclaration,
- isImplementationOfOverload: isImplementationOfOverload,
+ getResolvedSignature: function (node, candidatesOutArray) {
+ node = ts.getParseTreeNode(node, ts.isCallLikeExpression);
+ return node ? getResolvedSignature(node, candidatesOutArray) : undefined;
+ },
+ getConstantValue: function (node) {
+ node = ts.getParseTreeNode(node, canHaveConstantValue);
+ return node ? getConstantValue(node) : undefined;
+ },
+ isValidPropertyAccess: function (node, propertyName) {
+ node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName);
+ return node ? isValidPropertyAccess(node, propertyName) : false;
+ },
+ getSignatureFromDeclaration: function (declaration) {
+ declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike);
+ return declaration ? getSignatureFromDeclaration(declaration) : undefined;
+ },
+ isImplementationOfOverload: function (node) {
+ node = ts.getParseTreeNode(node, ts.isFunctionLike);
+ return node ? isImplementationOfOverload(node) : undefined;
+ },
+ getImmediateAliasedSymbol: function (symbol) {
+ ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here.");
+ var links = getSymbolLinks(symbol);
+ if (!links.immediateTarget) {
+ var node = getDeclarationOfAliasSymbol(symbol);
+ ts.Debug.assert(!!node);
+ links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
+ }
+ return links.immediateTarget;
+ },
getAliasedSymbol: resolveAlias,
getEmitResolver: getEmitResolver,
getExportsOfModule: getExportsOfModuleAsArray,
+ getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
getAmbientModules: getAmbientModules,
- getJsxElementAttributesType: getJsxElementAttributesType,
+ getAllAttributesTypeFromJsxOpeningLikeElement: function (node) {
+ node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement);
+ return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined;
+ },
getJsxIntrinsicTagNames: getJsxIntrinsicTagNames,
- isOptionalParameter: isOptionalParameter,
+ isOptionalParameter: function (node) {
+ node = ts.getParseTreeNode(node, ts.isParameter);
+ return node ? isOptionalParameter(node) : false;
+ },
tryGetMemberInModuleExports: tryGetMemberInModuleExports,
tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
// we deliberately exclude augmentations
// since we are only interested in declarations of the module itself
return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
- }
+ },
+ getApparentType: getApparentType
};
var tupleTypes = [];
var unionTypes = ts.createMap();
@@ -24204,8 +25563,8 @@ var ts;
var numericLiteralTypes = ts.createMap();
var indexedAccessTypes = ts.createMap();
var evolvingArrayTypes = [];
- var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown");
- var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__");
+ var unknownSymbol = createSymbol(4 /* Property */, "unknown");
+ var resolvingSymbol = createSymbol(0, "__resolving__");
var anyType = createIntrinsicType(1 /* Any */, "any");
var autoType = createIntrinsicType(1 /* Any */, "any");
var unknownType = createIntrinsicType(1 /* Any */, "unknown");
@@ -24222,8 +25581,9 @@ var ts;
var voidType = createIntrinsicType(1024 /* Void */, "void");
var neverType = createIntrinsicType(8192 /* Never */, "never");
var silentNeverType = createIntrinsicType(8192 /* Never */, "never");
+ var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object");
var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
- var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */ | 67108864 /* Transient */, "__type");
+ var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type");
emptyTypeLiteralSymbol.members = ts.createMap();
var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined);
var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
@@ -24233,21 +25593,20 @@ var ts;
// in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */;
var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
+ var circularConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
+ var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
var globals = ts.createMap();
/**
* List of every ambient module with a "*" wildcard.
* Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
* This is only used if there is no exact match.
- */
+ */
var patternAmbientModules;
- var getGlobalESSymbolConstructorSymbol;
- var getGlobalPromiseConstructorSymbol;
- var tryGetGlobalPromiseConstructorSymbol;
var globalObjectType;
var globalFunctionType;
var globalArrayType;
@@ -24256,29 +25615,29 @@ var ts;
var globalNumberType;
var globalBooleanType;
var globalRegExpType;
+ var globalThisType;
var anyArrayType;
var autoArrayType;
var anyReadonlyArrayType;
// The library files are only loaded when the feature is used.
// This allows users to just specify library files they want to used through --lib
// and they will not get an error from not having unrelated library files
- var getGlobalTemplateStringsArrayType;
- var getGlobalESSymbolType;
- var getGlobalIterableType;
- var getGlobalIteratorType;
- var getGlobalIterableIteratorType;
- var getGlobalClassDecoratorType;
- var getGlobalParameterDecoratorType;
- var getGlobalPropertyDecoratorType;
- var getGlobalMethodDecoratorType;
- var getGlobalTypedPropertyDescriptorType;
- var getGlobalPromiseType;
- var tryGetGlobalPromiseType;
- var getGlobalPromiseLikeType;
- var getInstantiatedGlobalPromiseLikeType;
- var getGlobalPromiseConstructorLikeType;
- var getGlobalThenableType;
- var jsxElementClassType;
+ var deferredGlobalESSymbolConstructorSymbol;
+ var deferredGlobalESSymbolType;
+ var deferredGlobalTypedPropertyDescriptorType;
+ var deferredGlobalPromiseType;
+ var deferredGlobalPromiseConstructorSymbol;
+ var deferredGlobalPromiseConstructorLikeType;
+ var deferredGlobalIterableType;
+ var deferredGlobalIteratorType;
+ var deferredGlobalIterableIteratorType;
+ var deferredGlobalAsyncIterableType;
+ var deferredGlobalAsyncIteratorType;
+ var deferredGlobalAsyncIterableIteratorType;
+ var deferredGlobalTemplateStringsArrayType;
+ var deferredJsxElementClassType;
+ var deferredJsxElementType;
+ var deferredJsxStatelessElementType;
var deferredNodes;
var deferredUnusedIdentifierNodes;
var flowLoopStart = 0;
@@ -24299,6 +25658,7 @@ var ts;
var visitedFlowNodes = [];
var visitedFlowTypes = [];
var potentialThisCollisions = [];
+ var potentialNewTargetCollisions = [];
var awaitedTypeStack = [];
var diagnostics = ts.createDiagnosticCollection();
var TypeFacts;
@@ -24364,7 +25724,7 @@ var ts;
TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts";
TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts";
})(TypeFacts || (TypeFacts = {}));
- var typeofEQFacts = ts.createMap({
+ var typeofEQFacts = ts.createMapFromTemplate({
"string": 1 /* TypeofEQString */,
"number": 2 /* TypeofEQNumber */,
"boolean": 4 /* TypeofEQBoolean */,
@@ -24373,7 +25733,7 @@ var ts;
"object": 16 /* TypeofEQObject */,
"function": 32 /* TypeofEQFunction */
});
- var typeofNEFacts = ts.createMap({
+ var typeofNEFacts = ts.createMapFromTemplate({
"string": 128 /* TypeofNEString */,
"number": 256 /* TypeofNENumber */,
"boolean": 512 /* TypeofNEBoolean */,
@@ -24382,14 +25742,14 @@ var ts;
"object": 2048 /* TypeofNEObject */,
"function": 4096 /* TypeofNEFunction */
});
- var typeofTypesByName = ts.createMap({
+ var typeofTypesByName = ts.createMapFromTemplate({
"string": stringType,
"number": numberType,
"boolean": booleanType,
"symbol": esSymbolType,
"undefined": undefinedType
});
- var jsxElementType;
+ var typeofType = createTypeofType();
var _jsxNamespace;
var _jsxFactoryEntity;
/** Things we lazy load from the JSX namespace */
@@ -24417,8 +25777,14 @@ var ts;
TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
})(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
+ var CheckMode;
+ (function (CheckMode) {
+ CheckMode[CheckMode["Normal"] = 0] = "Normal";
+ CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
+ })(CheckMode || (CheckMode = {}));
var builtinGlobals = ts.createMap();
- builtinGlobals[undefinedSymbol.name] = undefinedSymbol;
+ builtinGlobals.set(undefinedSymbol.name, undefinedSymbol);
initializeTypeChecker();
return checker;
function getJsxNamespace() {
@@ -24450,7 +25816,12 @@ var ts;
}
function createSymbol(flags, name) {
symbolCount++;
- return new Symbol(flags, name);
+ var symbol = (new Symbol(flags | 134217728 /* Transient */, name));
+ symbol.checkFlags = 0;
+ return symbol;
+ }
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 134217728 /* Transient */) !== 0;
}
function getExcludedSymbolFlags(flags) {
var result = 0;
@@ -24496,7 +25867,7 @@ var ts;
mergedSymbols[source.mergeId] = target;
}
function cloneSymbol(symbol) {
- var result = createSymbol(symbol.flags | 33554432 /* Merged */, symbol.name);
+ var result = createSymbol(symbol.flags, symbol.name);
result.declarations = symbol.declarations.slice(0);
result.parent = symbol.parent;
if (symbol.valueDeclaration)
@@ -24519,13 +25890,11 @@ var ts;
target.flags |= source.flags;
if (source.valueDeclaration &&
(!target.valueDeclaration ||
- (target.valueDeclaration.kind === 230 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 230 /* ModuleDeclaration */))) {
+ (target.valueDeclaration.kind === 232 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 232 /* ModuleDeclaration */))) {
// other kinds of value declarations take precedence over modules
target.valueDeclaration = source.valueDeclaration;
}
- ts.forEach(source.declarations, function (node) {
- target.declarations.push(node);
- });
+ ts.addRange(target.declarations, source.declarations);
if (source.members) {
if (!target.members)
target.members = ts.createMap();
@@ -24538,6 +25907,9 @@ var ts;
}
recordMergedSymbol(target, source);
}
+ else if (target.flags & 1024 /* NamespaceModule */) {
+ error(source.valueDeclaration.name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target));
+ }
else {
var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */
? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
@@ -24550,18 +25922,19 @@ var ts;
}
}
function mergeSymbolTable(target, source) {
- for (var id in source) {
- var targetSymbol = target[id];
+ source.forEach(function (sourceSymbol, id) {
+ var targetSymbol = target.get(id);
if (!targetSymbol) {
- target[id] = source[id];
+ target.set(id, sourceSymbol);
}
else {
- if (!(targetSymbol.flags & 33554432 /* Merged */)) {
- target[id] = targetSymbol = cloneSymbol(targetSymbol);
+ if (!(targetSymbol.flags & 134217728 /* Transient */)) {
+ targetSymbol = cloneSymbol(targetSymbol);
+ target.set(id, targetSymbol);
}
- mergeSymbol(targetSymbol, source[id]);
+ mergeSymbol(targetSymbol, sourceSymbol);
}
- }
+ });
}
function mergeModuleAugmentation(moduleName) {
var moduleAugmentation = moduleName.parent;
@@ -24590,7 +25963,7 @@ var ts;
if (mainModule.flags & 1920 /* Namespace */) {
// if module symbol has already been merged - it is safe to use it.
// otherwise clone it
- mainModule = mainModule.flags & 33554432 /* Merged */ ? mainModule : cloneSymbol(mainModule);
+ mainModule = mainModule.flags & 134217728 /* Transient */ ? mainModule : cloneSymbol(mainModule);
mergeSymbol(mainModule, moduleAugmentation.symbol);
}
else {
@@ -24599,21 +25972,22 @@ var ts;
}
}
function addToSymbolTable(target, source, message) {
- for (var id in source) {
- if (target[id]) {
+ source.forEach(function (sourceSymbol, id) {
+ var targetSymbol = target.get(id);
+ if (targetSymbol) {
// Error on redeclarations
- ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message));
+ ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(id, message));
}
else {
- target[id] = source[id];
+ target.set(id, sourceSymbol);
}
- }
+ });
function addDeclarationDiagnostic(id, message) {
return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
}
}
function getSymbolLinks(symbol) {
- if (symbol.flags & 67108864 /* Transient */)
+ if (symbol.flags & 134217728 /* Transient */)
return symbol;
var id = getSymbolId(symbol);
return symbolLinks[id] || (symbolLinks[id] = {});
@@ -24625,14 +25999,17 @@ var ts;
function getObjectFlags(type) {
return type.flags & 32768 /* Object */ ? type.objectFlags : 0;
}
+ function getCheckFlags(symbol) {
+ return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0;
+ }
function isGlobalSourceFile(node) {
- return node.kind === 261 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 264 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
- var symbol = symbols[name];
+ var symbol = symbols.get(name);
if (symbol) {
- ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
+ ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
if (symbol.flags & meaning) {
return symbol;
}
@@ -24669,12 +26046,12 @@ var ts;
if (declarationFile !== useFile) {
if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
(!compilerOptions.outFile && !compilerOptions.out)) {
- // nodes are in different files and order cannot be determines
+ // nodes are in different files and order cannot be determined
return true;
}
// declaration is after usage
// can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
- if (isUsedInFunctionOrNonStaticProperty(usage)) {
+ if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
return true;
}
var sourceFiles = host.getSourceFiles();
@@ -24682,20 +26059,41 @@ var ts;
}
if (declaration.pos <= usage.pos) {
// declaration is before usage
- // still might be illegal if usage is in the initializer of the variable declaration
- return declaration.kind !== 223 /* VariableDeclaration */ ||
- !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
+ if (declaration.kind === 175 /* BindingElement */) {
+ // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
+ var errorBindingElement = ts.getAncestor(usage, 175 /* BindingElement */);
+ if (errorBindingElement) {
+ return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
+ declaration.pos < errorBindingElement.pos;
+ }
+ // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
+ return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 225 /* VariableDeclaration */), usage);
+ }
+ else if (declaration.kind === 225 /* VariableDeclaration */) {
+ // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
+ return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
+ }
+ return true;
+ }
+ // declaration is after usage, but it can still be legal if usage is deferred:
+ // 1. inside an export specifier
+ // 2. inside a function
+ // 3. inside an instance property initializer, a reference to a non-instance property
+ // 4. inside a static property initializer, a reference to a static method in the same class
+ // or if usage is in a type context:
+ // 1. inside a type query (typeof in type position)
+ if (usage.parent.kind === 245 /* ExportSpecifier */) {
+ // export specifiers do not use the variable, they only make it available for use
+ return true;
}
- // declaration is after usage
- // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
var container = ts.getEnclosingBlockScopeContainer(declaration);
- return isUsedInFunctionOrNonStaticProperty(usage, container);
+ return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container);
function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
var container = ts.getEnclosingBlockScopeContainer(declaration);
switch (declaration.parent.parent.kind) {
- case 205 /* VariableStatement */:
- case 211 /* ForStatement */:
- case 213 /* ForOfStatement */:
+ case 207 /* VariableStatement */:
+ case 213 /* ForStatement */:
+ case 215 /* ForOfStatement */:
// variable statement/for/for-of statement case,
// use site should not be inside variable declaration (initializer of declaration or binding element)
if (isSameScopeDescendentOf(usage, declaration, container)) {
@@ -24704,8 +26102,8 @@ var ts;
break;
}
switch (declaration.parent.parent.kind) {
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
// ForIn/ForOf case - use site should not be used in expression part
if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) {
return true;
@@ -24713,25 +26111,31 @@ var ts;
}
return false;
}
- function isUsedInFunctionOrNonStaticProperty(usage, container) {
- var current = usage;
- while (current) {
+ function isUsedInFunctionOrInstanceProperty(usage, declaration, container) {
+ return !!ts.findAncestor(usage, function (current) {
if (current === container) {
- return false;
+ return "quit";
}
if (ts.isFunctionLike(current)) {
return true;
}
- var initializerOfNonStaticProperty = current.parent &&
- current.parent.kind === 147 /* PropertyDeclaration */ &&
- (ts.getModifierFlags(current.parent) & 32 /* Static */) === 0 &&
+ var initializerOfProperty = current.parent &&
+ current.parent.kind === 148 /* PropertyDeclaration */ &&
current.parent.initializer === current;
- if (initializerOfNonStaticProperty) {
- return true;
+ if (initializerOfProperty) {
+ if (ts.getModifierFlags(current.parent) & 32 /* Static */) {
+ if (declaration.kind === 150 /* MethodDeclaration */) {
+ return true;
+ }
+ }
+ else {
+ var isDeclarationInstanceProperty = declaration.kind === 148 /* PropertyDeclaration */ && !(ts.getModifierFlags(declaration) & 32 /* Static */);
+ if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
+ return true;
+ }
+ }
}
- current = current.parent;
- }
- return false;
+ });
}
}
// Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
@@ -24756,11 +26160,11 @@ var ts;
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
- if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 278 /* JSDocComment */) {
+ if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 282 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
? lastLocation === location.type ||
- lastLocation.kind === 144 /* Parameter */ ||
- lastLocation.kind === 143 /* TypeParameter */
+ lastLocation.kind === 145 /* Parameter */ ||
+ lastLocation.kind === 144 /* TypeParameter */
: false;
}
if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) {
@@ -24769,9 +26173,9 @@ var ts;
// however it is detected separately when checking initializers of parameters
// to make sure that they reference no variables declared after them.
useResult =
- lastLocation.kind === 144 /* Parameter */ ||
+ lastLocation.kind === 145 /* Parameter */ ||
(lastLocation === location.type &&
- result.valueDeclaration.kind === 144 /* Parameter */);
+ result.valueDeclaration.kind === 145 /* Parameter */);
}
}
if (useResult) {
@@ -24783,16 +26187,17 @@ var ts;
}
}
switch (location.kind) {
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
- case 230 /* ModuleDeclaration */:
+ // falls through
+ case 232 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 261 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 264 /* SourceFile */ || ts.isAmbientModule(location)) {
// It's an external module. First see if the module has an export default and if the local
// name of that export default matches.
- if (result = moduleExports["default"]) {
+ if (result = moduleExports.get("default")) {
var localSymbol = ts.getLocalSymbolForExportDefault(result);
if (localSymbol && (result.flags & meaning) && localSymbol.name === name) {
break loop;
@@ -24810,9 +26215,10 @@ var ts;
// 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
// an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
// which is not the desired behavior.
- if (moduleExports[name] &&
- moduleExports[name].flags === 8388608 /* Alias */ &&
- ts.getDeclarationOfKind(moduleExports[name], 243 /* ExportSpecifier */)) {
+ var moduleExport = moduleExports.get(name);
+ if (moduleExport &&
+ moduleExport.flags === 8388608 /* Alias */ &&
+ ts.getDeclarationOfKind(moduleExport, 245 /* ExportSpecifier */)) {
break;
}
}
@@ -24820,13 +26226,13 @@ var ts;
break loop;
}
break;
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
break loop;
}
break;
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
// TypeScript 1.0 spec (April 2014): 8.4.1
// Initializer expressions for instance member variables are evaluated in the scope
// of the class constructor body but are not permitted to reference parameters or
@@ -24843,10 +26249,15 @@ var ts;
}
}
break;
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 227 /* InterfaceDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 229 /* InterfaceDeclaration */:
if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) {
+ if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
+ // ignore type parameters not declared in this container
+ result = undefined;
+ break;
+ }
if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) {
// TypeScript 1.0 spec (April 2014): 3.4.1
// The scope of a type parameter extends over the entire declaration with which the type
@@ -24856,7 +26267,7 @@ var ts;
}
break loop;
}
- if (location.kind === 197 /* ClassExpression */ && meaning & 32 /* Class */) {
+ if (location.kind === 198 /* ClassExpression */ && meaning & 32 /* Class */) {
var className = location.name;
if (className && name === className.text) {
result = location.symbol;
@@ -24872,9 +26283,9 @@ var ts;
// [foo<T>()]() { } // <-- Reference to T from class's own computed property
// }
//
- case 142 /* ComputedPropertyName */:
+ case 143 /* ComputedPropertyName */:
grandparent = location.parent.parent;
- if (ts.isClassLike(grandparent) || grandparent.kind === 227 /* InterfaceDeclaration */) {
+ if (ts.isClassLike(grandparent) || grandparent.kind === 229 /* InterfaceDeclaration */) {
// A reference to this grandparent's type parameters would be an error
if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793064 /* Type */)) {
error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
@@ -24882,19 +26293,19 @@ var ts;
}
}
break;
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 225 /* FunctionDeclaration */:
- case 185 /* ArrowFunction */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 227 /* FunctionDeclaration */:
+ case 186 /* ArrowFunction */:
if (meaning & 3 /* Variable */ && name === "arguments") {
result = argumentsSymbol;
break loop;
}
break;
- case 184 /* FunctionExpression */:
+ case 185 /* FunctionExpression */:
if (meaning & 3 /* Variable */ && name === "arguments") {
result = argumentsSymbol;
break loop;
@@ -24907,7 +26318,7 @@ var ts;
}
}
break;
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
// Decorators are resolved at the class declaration. Resolving at the parameter
// or member would result in looking up locals in the method.
//
@@ -24916,7 +26327,7 @@ var ts;
// method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
// }
//
- if (location.parent && location.parent.kind === 144 /* Parameter */) {
+ if (location.parent && location.parent.kind === 145 /* Parameter */) {
location = location.parent;
}
//
@@ -24945,7 +26356,8 @@ var ts;
!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) &&
!checkAndReportErrorForExtendingInterface(errorLocation) &&
!checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
- !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning)) {
+ !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
+ !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) {
error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg));
}
}
@@ -24967,31 +26379,41 @@ var ts;
// interface bar {}
// }
// const foo/*1*/: foo/*2*/.bar;
- // The foo at /*1*/ and /*2*/ will share same symbol with two meaning
- // block - scope variable and namespace module. However, only when we
+ // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
+ // block-scoped variable and namespace module. However, only when we
// try to resolve name in /*1*/ which is used in variable position,
- // we want to check for block- scoped
- if (meaning & 2 /* BlockScopedVariable */) {
+ // we want to check for block-scoped
+ if (meaning & 2 /* BlockScopedVariable */ ||
+ ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 107455 /* Value */) === 107455 /* Value */)) {
var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
- if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */) {
+ if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
}
}
// If we're in an external module, we can't reference value symbols created from UMD export declarations
if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) {
var decls = result.declarations;
- if (decls && decls.length === 1 && decls[0].kind === 233 /* NamespaceExportDeclaration */) {
+ if (decls && decls.length === 1 && decls[0].kind === 235 /* NamespaceExportDeclaration */) {
error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name);
}
}
}
return result;
}
+ function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (decl.kind === 144 /* TypeParameter */ && decl.parent === container) {
+ return true;
+ }
+ }
+ return false;
+ }
function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
if ((errorLocation.kind === 70 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) {
return false;
}
- var container = ts.getThisContainer(errorLocation, /* includeArrowFunctions */ true);
+ var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ true);
var location = container;
while (location) {
if (ts.isClassLike(location.parent)) {
@@ -25034,9 +26456,9 @@ var ts;
function getEntityNameForExtendingInterface(node) {
switch (node.kind) {
case 70 /* Identifier */:
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
- case 199 /* ExpressionWithTypeArguments */:
+ case 200 /* ExpressionWithTypeArguments */:
ts.Debug.assert(ts.isEntityNameExpression(node.expression));
return node.expression;
default:
@@ -25063,13 +26485,38 @@ var ts;
}
return false;
}
+ function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
+ if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */ & ~793064 /* Type */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined));
+ if (symbol) {
+ error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, name);
+ return true;
+ }
+ }
+ else if (meaning & (793064 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) {
+ var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined));
+ if (symbol) {
+ error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, name);
+ return true;
+ }
+ }
+ return false;
+ }
function checkResolvedBlockScopedVariable(result, errorLocation) {
- ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0);
+ ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
// Block-scoped variables cannot be used before their definition
- var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; });
- ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined");
- if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 223 /* VariableDeclaration */), errorLocation)) {
- error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name));
+ var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 231 /* EnumDeclaration */) ? d : undefined; });
+ ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined");
+ if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
+ if (result.flags & 2 /* BlockScopedVariable */) {
+ error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name));
+ }
+ else if (result.flags & 32 /* Class */) {
+ error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name));
+ }
+ else if (result.flags & 384 /* Enum */) {
+ error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name));
+ }
}
}
/* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
@@ -25077,56 +26524,50 @@ var ts;
* Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
*/
function isSameScopeDescendentOf(initial, parent, stopAt) {
- if (!parent) {
- return false;
- }
- for (var current = initial; current && current !== stopAt && !ts.isFunctionLike(current); current = current.parent) {
- if (current === parent) {
- return true;
- }
- }
- return false;
+ return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
}
function getAnyImportSyntax(node) {
if (ts.isAliasSymbolDeclaration(node)) {
- if (node.kind === 234 /* ImportEqualsDeclaration */) {
+ if (node.kind === 236 /* ImportEqualsDeclaration */) {
return node;
}
- while (node && node.kind !== 235 /* ImportDeclaration */) {
- node = node.parent;
- }
- return node;
+ return ts.findAncestor(node, function (n) { return n.kind === 237 /* ImportDeclaration */; });
}
}
function getDeclarationOfAliasSymbol(symbol) {
- return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; });
+ return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration);
}
- function getTargetOfImportEqualsDeclaration(node) {
- if (node.moduleReference.kind === 245 /* ExternalModuleReference */) {
+ function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
+ if (node.moduleReference.kind === 247 /* ExternalModuleReference */) {
return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node)));
}
- return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference);
+ return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
}
- function getTargetOfImportClause(node) {
+ function getTargetOfImportClause(node, dontResolveAlias) {
var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
if (moduleSymbol) {
- var exportDefaultSymbol = ts.isShorthandAmbientModuleSymbol(moduleSymbol) ?
- moduleSymbol :
- moduleSymbol.exports["export="] ?
- getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") :
- resolveSymbol(moduleSymbol.exports["default"]);
+ var exportDefaultSymbol = void 0;
+ if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
+ exportDefaultSymbol = moduleSymbol;
+ }
+ else {
+ var exportValue = moduleSymbol.exports.get("export=");
+ exportDefaultSymbol = exportValue
+ ? getPropertyOfType(getTypeOfSymbol(exportValue), "default")
+ : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias);
+ }
if (!exportDefaultSymbol && !allowSyntheticDefaultImports) {
error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
}
else if (!exportDefaultSymbol && allowSyntheticDefaultImports) {
- return resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol);
+ return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
}
return exportDefaultSymbol;
}
}
- function getTargetOfNamespaceImport(node) {
+ function getTargetOfNamespaceImport(node, dontResolveAlias) {
var moduleSpecifier = node.parent.parent.moduleSpecifier;
- return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier);
+ return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias);
}
// This function creates a synthetic symbol that combines the value side of one symbol with the
// type/namespace side of another symbol. Consider this example:
@@ -25161,12 +26602,9 @@ var ts;
result.exports = valueSymbol.exports;
return result;
}
- function getExportOfModule(symbol, name) {
+ function getExportOfModule(symbol, name, dontResolveAlias) {
if (symbol.flags & 1536 /* Module */) {
- var exportedSymbol = getExportsOfSymbol(symbol)[name];
- if (exportedSymbol) {
- return resolveSymbol(exportedSymbol);
- }
+ return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias);
}
}
function getPropertyOfVariable(symbol, name) {
@@ -25177,74 +26615,75 @@ var ts;
}
}
}
- function getExternalModuleMember(node, specifier) {
+ function getExternalModuleMember(node, specifier, dontResolveAlias) {
var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
- var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier);
+ var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias);
if (targetSymbol) {
- var name_16 = specifier.propertyName || specifier.name;
- if (name_16.text) {
+ var name = specifier.propertyName || specifier.name;
+ if (name.text) {
if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
return moduleSymbol;
}
var symbolFromVariable = void 0;
// First check if module was specified with "export=". If so, get the member from the resolved type
- if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) {
- symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_16.text);
+ if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) {
+ symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.text);
}
else {
- symbolFromVariable = getPropertyOfVariable(targetSymbol, name_16.text);
+ symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text);
}
// if symbolFromVariable is export - get its final target
- symbolFromVariable = resolveSymbol(symbolFromVariable);
- var symbolFromModule = getExportOfModule(targetSymbol, name_16.text);
+ symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
+ var symbolFromModule = getExportOfModule(targetSymbol, name.text, dontResolveAlias);
// If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default
- if (!symbolFromModule && allowSyntheticDefaultImports && name_16.text === "default") {
- symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol);
+ if (!symbolFromModule && allowSyntheticDefaultImports && name.text === "default") {
+ symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
}
var symbol = symbolFromModule && symbolFromVariable ?
combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
symbolFromModule || symbolFromVariable;
if (!symbol) {
- error(name_16, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_16));
+ error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name));
}
return symbol;
}
}
}
- function getTargetOfImportSpecifier(node) {
- return getExternalModuleMember(node.parent.parent.parent, node);
+ function getTargetOfImportSpecifier(node, dontResolveAlias) {
+ return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
}
- function getTargetOfNamespaceExportDeclaration(node) {
- return resolveExternalModuleSymbol(node.parent.symbol);
+ function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
+ return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
}
- function getTargetOfExportSpecifier(node) {
+ function getTargetOfExportSpecifier(node, dontResolveAlias) {
return node.parent.parent.moduleSpecifier ?
- getExternalModuleMember(node.parent.parent, node) :
- resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */);
+ getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
+ resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
}
- function getTargetOfExportAssignment(node) {
- return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */);
+ function getTargetOfExportAssignment(node, dontResolveAlias) {
+ return resolveEntityName(node.expression, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
}
- function getTargetOfAliasDeclaration(node) {
+ function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
switch (node.kind) {
- case 234 /* ImportEqualsDeclaration */:
- return getTargetOfImportEqualsDeclaration(node);
- case 236 /* ImportClause */:
- return getTargetOfImportClause(node);
- case 237 /* NamespaceImport */:
- return getTargetOfNamespaceImport(node);
- case 239 /* ImportSpecifier */:
- return getTargetOfImportSpecifier(node);
- case 243 /* ExportSpecifier */:
- return getTargetOfExportSpecifier(node);
- case 240 /* ExportAssignment */:
- return getTargetOfExportAssignment(node);
- case 233 /* NamespaceExportDeclaration */:
- return getTargetOfNamespaceExportDeclaration(node);
- }
- }
- function resolveSymbol(symbol) {
- return symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */)) ? resolveAlias(symbol) : symbol;
+ case 236 /* ImportEqualsDeclaration */:
+ return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
+ case 238 /* ImportClause */:
+ return getTargetOfImportClause(node, dontRecursivelyResolve);
+ case 239 /* NamespaceImport */:
+ return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
+ case 241 /* ImportSpecifier */:
+ return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
+ case 245 /* ExportSpecifier */:
+ return getTargetOfExportSpecifier(node, dontRecursivelyResolve);
+ case 242 /* ExportAssignment */:
+ return getTargetOfExportAssignment(node, dontRecursivelyResolve);
+ case 235 /* NamespaceExportDeclaration */:
+ return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
+ }
+ }
+ function resolveSymbol(symbol, dontResolveAlias) {
+ var shouldResolve = !dontResolveAlias && symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */));
+ return shouldResolve ? resolveAlias(symbol) : symbol;
}
function resolveAlias(symbol) {
ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here.");
@@ -25286,11 +26725,11 @@ var ts;
links.referenced = true;
var node = getDeclarationOfAliasSymbol(symbol);
ts.Debug.assert(!!node);
- if (node.kind === 240 /* ExportAssignment */) {
+ if (node.kind === 242 /* ExportAssignment */) {
// export default <symbol>
checkExpressionCached(node.expression);
}
- else if (node.kind === 243 /* ExportSpecifier */) {
+ else if (node.kind === 245 /* ExportSpecifier */) {
// export { <symbol> } or export { <symbol> as foo }
checkExpressionCached(node.propertyName || node.name);
}
@@ -25312,20 +26751,22 @@ var ts;
entityName = entityName.parent;
}
// Check for case 1 and 3 in the above example
- if (entityName.kind === 70 /* Identifier */ || entityName.parent.kind === 141 /* QualifiedName */) {
+ if (entityName.kind === 70 /* Identifier */ || entityName.parent.kind === 142 /* QualifiedName */) {
return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
}
else {
// Case 2 in above example
// entityName.kind could be a QualifiedName or a Missing identifier
- ts.Debug.assert(entityName.parent.kind === 234 /* ImportEqualsDeclaration */);
+ ts.Debug.assert(entityName.parent.kind === 236 /* ImportEqualsDeclaration */);
return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
}
}
function getFullyQualifiedName(symbol) {
return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol);
}
- // Resolves a qualified name and any involved aliases
+ /**
+ * Resolves a qualified name and any involved aliases.
+ */
function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
if (ts.nodeIsMissing(name)) {
return undefined;
@@ -25338,9 +26779,23 @@ var ts;
return undefined;
}
}
- else if (name.kind === 141 /* QualifiedName */ || name.kind === 177 /* PropertyAccessExpression */) {
- var left = name.kind === 141 /* QualifiedName */ ? name.left : name.expression;
- var right = name.kind === 141 /* QualifiedName */ ? name.right : name.name;
+ else if (name.kind === 142 /* QualifiedName */ || name.kind === 178 /* PropertyAccessExpression */) {
+ var left = void 0;
+ if (name.kind === 142 /* QualifiedName */) {
+ left = name.left;
+ }
+ else if (name.kind === 178 /* PropertyAccessExpression */ &&
+ (name.expression.kind === 184 /* ParenthesizedExpression */ || ts.isEntityNameExpression(name.expression))) {
+ left = name.expression;
+ }
+ else {
+ // If the expression in property-access expression is not entity-name or parenthsizedExpression (e.g. it is a call expression), it won't be able to successfully resolve the name.
+ // This is the case when we are trying to do any language service operation in heritage clauses. By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression
+ // will attempt to checkPropertyAccessExpression to resolve symbol.
+ // i.e class C extends foo()./*do language service operation here*/B {}
+ return undefined;
+ }
+ var right = name.kind === 142 /* QualifiedName */ ? name.right : name.name;
var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location);
if (!namespace || ts.nodeIsMissing(right)) {
return undefined;
@@ -25356,10 +26811,19 @@ var ts;
return undefined;
}
}
+ else if (name.kind === 184 /* ParenthesizedExpression */) {
+ // If the expression in parenthesizedExpression is not an entity-name (e.g. it is a call expression), it won't be able to successfully resolve the name.
+ // This is the case when we are trying to do any language service operation in heritage clauses.
+ // By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression will attempt to checkPropertyAccessExpression to resolve symbol.
+ // i.e class C extends foo()./*do language service operation here*/B {}
+ return ts.isEntityNameExpression(name.expression) ?
+ resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) :
+ undefined;
+ }
else {
ts.Debug.fail("Unknown entity name kind.");
}
- ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
+ ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
}
function resolveExternalModuleName(location, moduleReferenceExpression) {
@@ -25367,7 +26831,7 @@ var ts;
}
function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
if (isForAugmentation === void 0) { isForAugmentation = false; }
- if (moduleReferenceExpression.kind !== 9 /* StringLiteral */) {
+ if (moduleReferenceExpression.kind !== 9 /* StringLiteral */ && moduleReferenceExpression.kind !== 12 /* NoSubstitutionTemplateLiteral */) {
return;
}
var moduleReferenceLiteral = moduleReferenceExpression;
@@ -25409,11 +26873,10 @@ var ts;
// May be an untyped module. If so, ignore resolutionDiagnostic.
if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) {
if (isForAugmentation) {
- ts.Debug.assert(!!moduleNotFoundError);
var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
- error(errorNode, diag, moduleName, resolvedModule.resolvedFileName);
+ error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
}
- else if (compilerOptions.noImplicitAny && moduleNotFoundError) {
+ else if (noImplicitAny && moduleNotFoundError) {
error(errorNode, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName);
}
// Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
@@ -25439,30 +26902,38 @@ var ts;
}
// An external module with an 'export =' declaration resolves to the target of the 'export =' declaration,
// and an external module with no 'export =' declaration resolves to the module itself.
- function resolveExternalModuleSymbol(moduleSymbol) {
- return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports["export="])) || moduleSymbol;
+ function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
+ return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol;
}
// An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
// references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
// combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
- function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression) {
- var symbol = resolveExternalModuleSymbol(moduleSymbol);
- if (symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) {
+ function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) {
+ var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
+ if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) {
error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol));
symbol = undefined;
}
return symbol;
}
function hasExportAssignmentSymbol(moduleSymbol) {
- return moduleSymbol.exports["export="] !== undefined;
+ return moduleSymbol.exports.get("export=") !== undefined;
}
function getExportsOfModuleAsArray(moduleSymbol) {
return symbolsToArray(getExportsOfModule(moduleSymbol));
}
+ function getExportsAndPropertiesOfModule(moduleSymbol) {
+ var exports = getExportsOfModuleAsArray(moduleSymbol);
+ var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
+ if (exportEquals !== moduleSymbol) {
+ ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
+ }
+ return exports;
+ }
function tryGetMemberInModuleExports(memberName, moduleSymbol) {
var symbolTable = getExportsOfModule(moduleSymbol);
if (symbolTable) {
- return symbolTable[memberName];
+ return symbolTable.get(memberName);
}
}
function getExportsOfSymbol(symbol) {
@@ -25477,24 +26948,28 @@ var ts;
* Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
*/
function extendExportSymbols(target, source, lookupTable, exportNode) {
- for (var id in source) {
- if (id !== "default" && !target[id]) {
- target[id] = source[id];
+ source && source.forEach(function (sourceSymbol, id) {
+ if (id === "default")
+ return;
+ var targetSymbol = target.get(id);
+ if (!targetSymbol) {
+ target.set(id, sourceSymbol);
if (lookupTable && exportNode) {
- lookupTable[id] = {
+ lookupTable.set(id, {
specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
- };
+ });
}
}
- else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) {
- if (!lookupTable[id].exportsWithDuplicate) {
- lookupTable[id].exportsWithDuplicate = [exportNode];
+ else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
+ var collisionTracker = lookupTable.get(id);
+ if (!collisionTracker.exportsWithDuplicate) {
+ collisionTracker.exportsWithDuplicate = [exportNode];
}
else {
- lookupTable[id].exportsWithDuplicate.push(exportNode);
+ collisionTracker.exportsWithDuplicate.push(exportNode);
}
}
- }
+ });
}
function getExportsForModule(moduleSymbol) {
var visitedSymbols = [];
@@ -25510,27 +26985,27 @@ var ts;
visitedSymbols.push(symbol);
var symbols = ts.cloneMap(symbol.exports);
// All export * declarations are collected in an __export symbol by the binder
- var exportStars = symbol.exports["__export"];
+ var exportStars = symbol.exports.get("__export");
if (exportStars) {
var nestedSymbols = ts.createMap();
- var lookupTable = ts.createMap();
+ var lookupTable_1 = ts.createMap();
for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
var node = _a[_i];
var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
var exportedSymbols = visit(resolvedModule);
- extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node);
+ extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
}
- for (var id in lookupTable) {
- var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate;
+ lookupTable_1.forEach(function (_a, id) {
+ var exportsWithDuplicate = _a.exportsWithDuplicate;
// It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
- if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols[id]) {
- continue;
+ if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
+ return;
}
- for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) {
- var node = exportsWithDuplicate_1[_b];
- diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable[id].specifierText, id));
+ for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
+ var node = exportsWithDuplicate_1[_i];
+ diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, id));
}
- }
+ });
extendExportSymbols(symbols, nestedSymbols);
}
return symbols;
@@ -25552,26 +27027,13 @@ var ts;
: symbol;
}
function symbolIsValue(symbol) {
- // If it is an instantiated symbol, then it is a value if the symbol it is an
- // instantiation of is a value.
- if (symbol.flags & 16777216 /* Instantiated */) {
- return symbolIsValue(getSymbolLinks(symbol).target);
- }
- // If the symbol has the value flag, it is trivially a value.
- if (symbol.flags & 107455 /* Value */) {
- return true;
- }
- // If it is an alias, then it is a value if the symbol it resolves to is a value.
- if (symbol.flags & 8388608 /* Alias */) {
- return (resolveAlias(symbol).flags & 107455 /* Value */) !== 0;
- }
- return false;
+ return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 8388608 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */);
}
function findConstructorDeclaration(node) {
var members = node.members;
for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
var member = members_1[_i];
- if (member.kind === 150 /* Constructor */ && ts.nodeIsPresent(member.body)) {
+ if (member.kind === 151 /* Constructor */ && ts.nodeIsPresent(member.body)) {
return member;
}
}
@@ -25599,6 +27061,9 @@ var ts;
type.symbol = symbol;
return type;
}
+ function createTypeofType() {
+ return getUnionType(ts.convertToArray(typeofEQFacts.keys(), function (s) { return getLiteralTypeForText(32 /* StringLiteral */, s); }));
+ }
// A reserved member name starts with two underscores, but the third character cannot be an underscore
// or the @ symbol. A third underscore indicates an escaped form of an identifer that started
// with at least two underscores. The @ character indicates that the name is denoted by a well known ES
@@ -25611,16 +27076,15 @@ var ts;
}
function getNamedMembers(members) {
var result;
- for (var id in members) {
+ members.forEach(function (symbol, id) {
if (!isReservedMemberName(id)) {
if (!result)
result = [];
- var symbol = members[id];
if (symbolIsValue(symbol)) {
result.push(symbol);
}
}
- }
+ });
return result || emptyArray;
}
function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
@@ -25639,20 +27103,21 @@ var ts;
}
function forEachSymbolTableInScope(enclosingDeclaration, callback) {
var result;
- for (var location_1 = enclosingDeclaration; location_1; location_1 = location_1.parent) {
+ for (var location = enclosingDeclaration; location; location = location.parent) {
// Locals of a source file are not in scope (because they get merged into the global symbol table)
- if (location_1.locals && !isGlobalSourceFile(location_1)) {
- if (result = callback(location_1.locals)) {
+ if (location.locals && !isGlobalSourceFile(location)) {
+ if (result = callback(location.locals)) {
return result;
}
}
- switch (location_1.kind) {
- case 261 /* SourceFile */:
- if (!ts.isExternalOrCommonJsModule(location_1)) {
+ switch (location.kind) {
+ case 264 /* SourceFile */:
+ if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
- case 230 /* ModuleDeclaration */:
- if (result = callback(getSymbolOfNode(location_1).exports)) {
+ // falls through
+ case 232 /* ModuleDeclaration */:
+ if (result = callback(getSymbolOfNode(location).exports)) {
return result;
}
break;
@@ -25666,6 +27131,16 @@ var ts;
}
function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) {
function getAccessibleSymbolChainFromSymbolTable(symbols) {
+ return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []);
+ }
+ function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) {
+ if (ts.contains(visitedSymbolTables, symbols)) {
+ return undefined;
+ }
+ visitedSymbolTables.push(symbols);
+ var result = trySymbolTable(symbols);
+ visitedSymbolTables.pop();
+ return result;
function canQualifySymbol(symbolFromSymbolTable, meaning) {
// If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) {
@@ -25684,31 +27159,33 @@ var ts;
canQualifySymbol(symbolFromSymbolTable, meaning);
}
}
- // If symbol is directly available by its name in the symbol table
- if (isAccessible(symbols[symbol.name])) {
- return [symbol];
- }
- // Check if symbol is any of the alias
- return ts.forEachProperty(symbols, function (symbolFromSymbolTable) {
- if (symbolFromSymbolTable.flags & 8388608 /* Alias */
- && symbolFromSymbolTable.name !== "export="
- && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243 /* ExportSpecifier */)) {
- if (!useOnlyExternalAliasing ||
- // Is this external alias, then use it to name
- ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) {
- var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
- if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) {
- return [symbolFromSymbolTable];
- }
- // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
- // but only if the symbolFromSymbolTable can be qualified
- var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined;
- if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
- return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
+ function trySymbolTable(symbols) {
+ // If symbol is directly available by its name in the symbol table
+ if (isAccessible(symbols.get(symbol.name))) {
+ return [symbol];
+ }
+ // Check if symbol is any of the alias
+ return ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
+ if (symbolFromSymbolTable.flags & 8388608 /* Alias */
+ && symbolFromSymbolTable.name !== "export="
+ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 245 /* ExportSpecifier */)) {
+ if (!useOnlyExternalAliasing ||
+ // Is this external alias, then use it to name
+ ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) {
+ var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
+ if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) {
+ return [symbolFromSymbolTable];
+ }
+ // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
+ // but only if the symbolFromSymbolTable can be qualified
+ var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined;
+ if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
+ return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
+ }
}
}
- }
- });
+ });
+ }
}
if (symbol) {
if (!(isPropertyOrMethodDeclarationSymbol(symbol))) {
@@ -25720,7 +27197,7 @@ var ts;
var qualify = false;
forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
// If symbol of this name is not available in the symbol table we are ok
- var symbolFromSymbolTable = symbolTable[symbol.name];
+ var symbolFromSymbolTable = symbolTable.get(symbol.name);
if (!symbolFromSymbolTable) {
// Continue to the next symbol table
return false;
@@ -25731,7 +27208,7 @@ var ts;
return true;
}
// Qualify if the symbol from symbol table has same meaning as expected
- symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 243 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
+ symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 245 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
if (symbolFromSymbolTable.flags & meaning) {
qualify = true;
return true;
@@ -25746,10 +27223,10 @@ var ts;
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
switch (declaration.kind) {
- case 147 /* PropertyDeclaration */:
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 148 /* PropertyDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
continue;
default:
return false;
@@ -25822,15 +27299,12 @@ var ts;
}
return { accessibility: 0 /* Accessible */ };
function getExternalModuleContainer(declaration) {
- for (; declaration; declaration = declaration.parent) {
- if (hasExternalModuleSymbol(declaration)) {
- return getSymbolOfNode(declaration);
- }
- }
+ var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
+ return node && getSymbolOfNode(node);
}
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 261 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 264 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -25871,12 +27345,12 @@ var ts;
function isEntityNameVisible(entityName, enclosingDeclaration) {
// get symbol of the first identifier of the entityName
var meaning;
- if (entityName.parent.kind === 160 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) {
+ if (entityName.parent.kind === 161 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) {
// Typeof value
meaning = 107455 /* Value */ | 1048576 /* ExportValue */;
}
- else if (entityName.kind === 141 /* QualifiedName */ || entityName.kind === 177 /* PropertyAccessExpression */ ||
- entityName.parent.kind === 234 /* ImportEqualsDeclaration */) {
+ else if (entityName.kind === 142 /* QualifiedName */ || entityName.kind === 178 /* PropertyAccessExpression */ ||
+ entityName.parent.kind === 236 /* ImportEqualsDeclaration */) {
// Left identifier from type reference or TypeAlias
// Entity name of the import declaration
meaning = 1920 /* Namespace */;
@@ -25928,6 +27402,516 @@ var ts;
}
return result;
}
+ function createNodeBuilder() {
+ var context;
+ return {
+ typeToTypeNode: function (type, enclosingDeclaration, flags) {
+ context = createNodeBuilderContext(enclosingDeclaration, flags);
+ var resultingNode = typeToTypeNodeHelper(type);
+ var result = context.encounteredError ? undefined : resultingNode;
+ return result;
+ },
+ indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) {
+ context = createNodeBuilderContext(enclosingDeclaration, flags);
+ var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind);
+ var result = context.encounteredError ? undefined : resultingNode;
+ return result;
+ },
+ signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) {
+ context = createNodeBuilderContext(enclosingDeclaration, flags);
+ var resultingNode = signatureToSignatureDeclarationHelper(signature, kind);
+ var result = context.encounteredError ? undefined : resultingNode;
+ return result;
+ }
+ };
+ function createNodeBuilderContext(enclosingDeclaration, flags) {
+ return {
+ enclosingDeclaration: enclosingDeclaration,
+ flags: flags,
+ encounteredError: false,
+ inObjectTypeLiteral: false,
+ checkAlias: true,
+ symbolStack: undefined
+ };
+ }
+ function typeToTypeNodeHelper(type) {
+ if (!type) {
+ context.encounteredError = true;
+ // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)?
+ return undefined;
+ }
+ if (type.flags & 1 /* Any */) {
+ return ts.createKeywordTypeNode(118 /* AnyKeyword */);
+ }
+ if (type.flags & 2 /* String */) {
+ return ts.createKeywordTypeNode(135 /* StringKeyword */);
+ }
+ if (type.flags & 4 /* Number */) {
+ return ts.createKeywordTypeNode(132 /* NumberKeyword */);
+ }
+ if (type.flags & 8 /* Boolean */) {
+ return ts.createKeywordTypeNode(121 /* BooleanKeyword */);
+ }
+ if (type.flags & 16 /* Enum */) {
+ var name = symbolToName(type.symbol, /*expectsIdentifier*/ false);
+ return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined);
+ }
+ if (type.flags & (32 /* StringLiteral */)) {
+ return ts.createLiteralTypeNode((ts.createLiteral(type.text)));
+ }
+ if (type.flags & (64 /* NumberLiteral */)) {
+ return ts.createLiteralTypeNode((ts.createNumericLiteral(type.text)));
+ }
+ if (type.flags & 128 /* BooleanLiteral */) {
+ return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse();
+ }
+ if (type.flags & 256 /* EnumLiteral */) {
+ var name = symbolToName(type.symbol, /*expectsIdentifier*/ false);
+ return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined);
+ }
+ if (type.flags & 1024 /* Void */) {
+ return ts.createKeywordTypeNode(104 /* VoidKeyword */);
+ }
+ if (type.flags & 2048 /* Undefined */) {
+ return ts.createKeywordTypeNode(138 /* UndefinedKeyword */);
+ }
+ if (type.flags & 4096 /* Null */) {
+ return ts.createKeywordTypeNode(94 /* NullKeyword */);
+ }
+ if (type.flags & 8192 /* Never */) {
+ return ts.createKeywordTypeNode(129 /* NeverKeyword */);
+ }
+ if (type.flags & 512 /* ESSymbol */) {
+ return ts.createKeywordTypeNode(136 /* SymbolKeyword */);
+ }
+ if (type.flags & 16777216 /* NonPrimitive */) {
+ return ts.createKeywordTypeNode(133 /* ObjectKeyword */);
+ }
+ if (type.flags & 16384 /* TypeParameter */ && type.isThisType) {
+ if (context.inObjectTypeLiteral) {
+ if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowThisInObjectLiteral)) {
+ context.encounteredError = true;
+ }
+ }
+ return ts.createThis();
+ }
+ var objectFlags = getObjectFlags(type);
+ if (objectFlags & 4 /* Reference */) {
+ ts.Debug.assert(!!(type.flags & 32768 /* Object */));
+ return typeReferenceToTypeNode(type);
+ }
+ if (objectFlags & 3 /* ClassOrInterface */) {
+ ts.Debug.assert(!!(type.flags & 32768 /* Object */));
+ var name = symbolToName(type.symbol, /*expectsIdentifier*/ false);
+ // TODO(aozgaa): handle type arguments.
+ return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined);
+ }
+ if (type.flags & 16384 /* TypeParameter */) {
+ var name = symbolToName(type.symbol, /*expectsIdentifier*/ false);
+ // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
+ return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined);
+ }
+ if (context.checkAlias && type.aliasSymbol) {
+ var name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false);
+ var typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments);
+ return ts.createTypeReferenceNode(name, typeArgumentNodes);
+ }
+ context.checkAlias = false;
+ if (type.flags & 65536 /* Union */) {
+ var formattedUnionTypes = formatUnionTypes(type.types);
+ var unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes);
+ if (unionTypeNodes && unionTypeNodes.length > 0) {
+ return ts.createUnionOrIntersectionTypeNode(165 /* UnionType */, unionTypeNodes);
+ }
+ else {
+ if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyUnionOrIntersection)) {
+ context.encounteredError = true;
+ }
+ return undefined;
+ }
+ }
+ if (type.flags & 131072 /* Intersection */) {
+ return ts.createUnionOrIntersectionTypeNode(166 /* IntersectionType */, mapToTypeNodeArray(type.types));
+ }
+ if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
+ ts.Debug.assert(!!(type.flags & 32768 /* Object */));
+ // The type is an object literal type.
+ return createAnonymousTypeNode(type);
+ }
+ if (type.flags & 262144 /* Index */) {
+ var indexedType = type.type;
+ var indexTypeNode = typeToTypeNodeHelper(indexedType);
+ return ts.createTypeOperatorNode(indexTypeNode);
+ }
+ if (type.flags & 524288 /* IndexedAccess */) {
+ var objectTypeNode = typeToTypeNodeHelper(type.objectType);
+ var indexTypeNode = typeToTypeNodeHelper(type.indexType);
+ return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
+ }
+ ts.Debug.fail("Should be unreachable.");
+ function mapToTypeNodeArray(types) {
+ var result = [];
+ for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
+ var type_1 = types_1[_i];
+ var typeNode = typeToTypeNodeHelper(type_1);
+ if (typeNode) {
+ result.push(typeNode);
+ }
+ }
+ return result;
+ }
+ function createMappedTypeNodeFromType(type) {
+ ts.Debug.assert(!!(type.flags & 32768 /* Object */));
+ var typeParameter = getTypeParameterFromMappedType(type);
+ var typeParameterNode = typeParameterToDeclaration(typeParameter);
+ var templateType = getTemplateTypeFromMappedType(type);
+ var templateTypeNode = typeToTypeNodeHelper(templateType);
+ var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(130 /* ReadonlyKeyword */) : undefined;
+ var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(54 /* QuestionToken */) : undefined;
+ return ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
+ }
+ function createAnonymousTypeNode(type) {
+ var symbol = type.symbol;
+ if (symbol) {
+ // Always use 'typeof T' for type of class, enum, and module objects
+ if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) ||
+ symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
+ shouldWriteTypeOfFunctionSymbol()) {
+ return createTypeQueryNodeFromSymbol(symbol);
+ }
+ else if (ts.contains(context.symbolStack, symbol)) {
+ // If type is an anonymous type literal in a type alias declaration, use type alias name
+ var typeAlias = getTypeAliasForTypeLiteral(type);
+ if (typeAlias) {
+ // The specified symbol flags need to be reinterpreted as type flags
+ var entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false);
+ return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined);
+ }
+ else {
+ return ts.createKeywordTypeNode(118 /* AnyKeyword */);
+ }
+ }
+ else {
+ // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
+ // of types allows us to catch circular references to instantiations of the same anonymous type
+ if (!context.symbolStack) {
+ context.symbolStack = [];
+ }
+ context.symbolStack.push(symbol);
+ var result = createTypeNodeFromObjectType(type);
+ context.symbolStack.pop();
+ return result;
+ }
+ }
+ else {
+ // Anonymous types without a symbol are never circular.
+ return createTypeNodeFromObjectType(type);
+ }
+ function shouldWriteTypeOfFunctionSymbol() {
+ var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ &&
+ ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; }));
+ var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
+ (symbol.parent ||
+ ts.forEach(symbol.declarations, function (declaration) {
+ return declaration.parent.kind === 264 /* SourceFile */ || declaration.parent.kind === 233 /* ModuleBlock */;
+ }));
+ if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
+ // typeof is allowed only for static/non local functions
+ return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively
+ }
+ }
+ }
+ function createTypeNodeFromObjectType(type) {
+ if (type.objectFlags & 32 /* Mapped */) {
+ if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) {
+ return createMappedTypeNodeFromType(type);
+ }
+ }
+ var resolved = resolveStructuredTypeMembers(type);
+ if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
+ if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
+ return ts.createTypeLiteralNode(/*members*/ undefined);
+ }
+ if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
+ var signature = resolved.callSignatures[0];
+ return signatureToSignatureDeclarationHelper(signature, 159 /* FunctionType */);
+ }
+ if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
+ var signature = resolved.constructSignatures[0];
+ return signatureToSignatureDeclarationHelper(signature, 160 /* ConstructorType */);
+ }
+ }
+ var saveInObjectTypeLiteral = context.inObjectTypeLiteral;
+ context.inObjectTypeLiteral = true;
+ var members = createTypeNodesFromResolvedType(resolved);
+ context.inObjectTypeLiteral = saveInObjectTypeLiteral;
+ return ts.createTypeLiteralNode(members);
+ }
+ function createTypeQueryNodeFromSymbol(symbol) {
+ var entityName = symbolToName(symbol, /*expectsIdentifier*/ false);
+ return ts.createTypeQueryNode(entityName);
+ }
+ function typeReferenceToTypeNode(type) {
+ var typeArguments = type.typeArguments || emptyArray;
+ if (type.target === globalArrayType) {
+ var elementType = typeToTypeNodeHelper(typeArguments[0]);
+ return ts.createArrayTypeNode(elementType);
+ }
+ else if (type.target.objectFlags & 8 /* Tuple */) {
+ if (typeArguments.length > 0) {
+ var tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type)));
+ if (tupleConstituentNodes && tupleConstituentNodes.length > 0) {
+ return ts.createTupleTypeNode(tupleConstituentNodes);
+ }
+ }
+ if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowEmptyTuple)) {
+ context.encounteredError = true;
+ }
+ return undefined;
+ }
+ else {
+ var outerTypeParameters = type.target.outerTypeParameters;
+ var i = 0;
+ var qualifiedName = undefined;
+ if (outerTypeParameters) {
+ var length_1 = outerTypeParameters.length;
+ while (i < length_1) {
+ // Find group of type arguments for type parameters with the same declaring container.
+ var start = i;
+ var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
+ do {
+ i++;
+ } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
+ // When type parameters are their own type arguments for the whole group (i.e. we have
+ // the default outer type arguments), we don't show the group.
+ if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
+ var qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true);
+ if (!qualifiedName) {
+ qualifiedName = ts.createQualifiedName(qualifiedNamePart, /*right*/ undefined);
+ }
+ else {
+ ts.Debug.assert(!qualifiedName.right);
+ qualifiedName.right = qualifiedNamePart;
+ qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined);
+ }
+ }
+ }
+ }
+ var entityName = undefined;
+ var nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true);
+ if (qualifiedName) {
+ ts.Debug.assert(!qualifiedName.right);
+ qualifiedName.right = nameIdentifier;
+ entityName = qualifiedName;
+ }
+ else {
+ entityName = nameIdentifier;
+ }
+ var typeParameterCount = (type.target.typeParameters || emptyArray).length;
+ var typeArgumentNodes = ts.some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined;
+ return ts.createTypeReferenceNode(entityName, typeArgumentNodes);
+ }
+ }
+ function createTypeNodesFromResolvedType(resolvedType) {
+ var typeElements = [];
+ for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
+ var signature = _a[_i];
+ typeElements.push(signatureToSignatureDeclarationHelper(signature, 154 /* CallSignature */));
+ }
+ for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
+ var signature = _c[_b];
+ typeElements.push(signatureToSignatureDeclarationHelper(signature, 155 /* ConstructSignature */));
+ }
+ if (resolvedType.stringIndexInfo) {
+ typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */));
+ }
+ if (resolvedType.numberIndexInfo) {
+ typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */));
+ }
+ var properties = resolvedType.properties;
+ if (!properties) {
+ return typeElements;
+ }
+ for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) {
+ var propertySymbol = properties_2[_d];
+ var propertyType = getTypeOfSymbol(propertySymbol);
+ var oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0];
+ if (!oldDeclaration) {
+ return;
+ }
+ var propertyName = oldDeclaration.name;
+ var optionalToken = propertySymbol.flags & 67108864 /* Optional */ ? ts.createToken(54 /* QuestionToken */) : undefined;
+ if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) {
+ var signatures = getSignaturesOfType(propertyType, 0 /* Call */);
+ for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) {
+ var signature = signatures_1[_e];
+ var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 149 /* MethodSignature */);
+ methodDeclaration.name = propertyName;
+ methodDeclaration.questionToken = optionalToken;
+ typeElements.push(methodDeclaration);
+ }
+ }
+ else {
+ // TODO(aozgaa): should we create a node with explicit or implict any?
+ var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : ts.createKeywordTypeNode(118 /* AnyKeyword */);
+ typeElements.push(ts.createPropertySignature(propertyName, optionalToken, propertyTypeNode,
+ /*initializer*/ undefined));
+ }
+ }
+ return typeElements.length ? typeElements : undefined;
+ }
+ }
+ function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind) {
+ var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 135 /* StringKeyword */ : 132 /* NumberKeyword */);
+ var name = ts.getNameFromIndexInfo(indexInfo);
+ var indexingParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, name,
+ /*questionToken*/ undefined, indexerTypeNode,
+ /*initializer*/ undefined);
+ var typeNode = typeToTypeNodeHelper(indexInfo.type);
+ return ts.createIndexSignatureDeclaration(
+ /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(130 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
+ }
+ function signatureToSignatureDeclarationHelper(signature, kind) {
+ var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter); });
+ var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter); });
+ var returnTypeNode;
+ if (signature.typePredicate) {
+ var typePredicate = signature.typePredicate;
+ var parameterName = typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode();
+ var typeNode = typeToTypeNodeHelper(typePredicate.type);
+ returnTypeNode = ts.createTypePredicateNode(parameterName, typeNode);
+ }
+ else {
+ var returnType = getReturnTypeOfSignature(signature);
+ returnTypeNode = returnType && typeToTypeNodeHelper(returnType);
+ }
+ var returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== 118 /* AnyKeyword */ ? returnTypeNode : undefined;
+ return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny);
+ }
+ function typeParameterToDeclaration(type) {
+ var constraint = getConstraintFromTypeParameter(type);
+ var constraintNode = constraint && typeToTypeNodeHelper(constraint);
+ var defaultParameter = getDefaultFromTypeParameter(type);
+ var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter);
+ var name = symbolToName(type.symbol, /*expectsIdentifier*/ true);
+ return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
+ }
+ function symbolToParameterDeclaration(parameterSymbol) {
+ var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 145 /* Parameter */);
+ var parameterType = getTypeOfSymbol(parameterSymbol);
+ var parameterTypeNode = typeToTypeNodeHelper(parameterType);
+ // TODO(aozgaa): In the future, check initializer accessibility.
+ var parameterNode = ts.createParameter(parameterDeclaration.decorators, parameterDeclaration.modifiers, parameterDeclaration.dotDotDotToken && ts.createToken(23 /* DotDotDotToken */),
+ // Clone name to remove trivia.
+ ts.getSynthesizedClone(parameterDeclaration.name), parameterDeclaration.questionToken && ts.createToken(54 /* QuestionToken */), parameterTypeNode, parameterDeclaration.initializer);
+ return parameterNode;
+ }
+ function symbolToName(symbol, expectsIdentifier) {
+ // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
+ var chain;
+ var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
+ if (!isTypeParameter && context.enclosingDeclaration) {
+ chain = getSymbolChain(symbol, 0 /* None */, /*endOfChain*/ true);
+ ts.Debug.assert(chain && chain.length > 0);
+ }
+ else {
+ chain = [symbol];
+ }
+ if (expectsIdentifier && chain.length !== 1
+ && !context.encounteredError
+ && !(context.flags & ts.NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) {
+ context.encounteredError = true;
+ }
+ return createEntityNameFromSymbolChain(chain, chain.length - 1);
+ function createEntityNameFromSymbolChain(chain, index) {
+ ts.Debug.assert(chain && 0 <= index && index < chain.length);
+ // const parentIndex = index - 1;
+ var symbol = chain[index];
+ var typeParameterString = "";
+ if (index > 0) {
+ var parentSymbol = chain[index - 1];
+ var typeParameters = void 0;
+ if (getCheckFlags(symbol) & 1 /* Instantiated */) {
+ typeParameters = getTypeParametersOfClassOrInterface(parentSymbol);
+ }
+ else {
+ var targetSymbol = getTargetSymbol(parentSymbol);
+ if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
+ typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
+ }
+ }
+ if (typeParameters && typeParameters.length > 0) {
+ if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowTypeParameterInQualifiedName)) {
+ context.encounteredError = true;
+ }
+ var writer = ts.getSingleLineStringWriter();
+ var displayBuilder = getSymbolDisplayBuilder();
+ displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0);
+ typeParameterString = writer.string();
+ ts.releaseStringWriter(writer);
+ }
+ }
+ var symbolName = getNameOfSymbol(symbol);
+ var symbolNameWithTypeParameters = typeParameterString.length > 0 ? symbolName + "<" + typeParameterString + ">" : symbolName;
+ var identifier = ts.createIdentifier(symbolNameWithTypeParameters);
+ return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
+ }
+ /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
+ function getSymbolChain(symbol, meaning, endOfChain) {
+ var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
+ var parentSymbol;
+ if (!accessibleSymbolChain ||
+ needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
+ // Go up and add our parent.
+ var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
+ if (parent) {
+ var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
+ if (parentChain) {
+ parentSymbol = parent;
+ accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]);
+ }
+ }
+ }
+ if (accessibleSymbolChain) {
+ return accessibleSymbolChain;
+ }
+ if (
+ // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
+ endOfChain ||
+ // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
+ !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) &&
+ // If a parent symbol is an anonymous type, don't write it.
+ !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
+ return [symbol];
+ }
+ }
+ function getNameOfSymbol(symbol) {
+ var declaration = ts.firstOrUndefined(symbol.declarations);
+ if (declaration) {
+ if (declaration.name) {
+ return ts.declarationNameToString(declaration.name);
+ }
+ if (declaration.parent && declaration.parent.kind === 225 /* VariableDeclaration */) {
+ return ts.declarationNameToString(declaration.parent.name);
+ }
+ if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.allowAnonymousIdentifier)) {
+ context.encounteredError = true;
+ }
+ switch (declaration.kind) {
+ case 198 /* ClassExpression */:
+ return "(Anonymous class)";
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ return "(Anonymous function)";
+ }
+ }
+ return symbol.name;
+ }
+ }
+ }
function typePredicateToString(typePredicate, enclosingDeclaration, flags) {
var writer = ts.getSingleLineStringWriter();
getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags);
@@ -25971,11 +27955,8 @@ var ts;
}
function getTypeAliasForTypeLiteral(type) {
if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
- var node = type.symbol.declarations[0].parent;
- while (node.kind === 166 /* ParenthesizedType */) {
- node = node.parent;
- }
- if (node.kind === 228 /* TypeAliasDeclaration */) {
+ var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 167 /* ParenthesizedType */; });
+ if (node.kind === 230 /* TypeAliasDeclaration */) {
return getSymbolOfNode(node);
}
}
@@ -25983,29 +27964,32 @@ var ts;
}
function isTopLevelInExternalModuleAugmentation(node) {
return node && node.parent &&
- node.parent.kind === 231 /* ModuleBlock */ &&
+ node.parent.kind === 233 /* ModuleBlock */ &&
ts.isExternalModuleAugmentation(node.parent.parent);
}
function literalTypeToString(type) {
return type.flags & 32 /* StringLiteral */ ? "\"" + ts.escapeString(type.text) + "\"" : type.text;
}
- function getSymbolDisplayBuilder() {
- function getNameOfSymbol(symbol) {
- if (symbol.declarations && symbol.declarations.length) {
- var declaration = symbol.declarations[0];
- if (declaration.name) {
- return ts.declarationNameToString(declaration.name);
- }
- switch (declaration.kind) {
- case 197 /* ClassExpression */:
- return "(Anonymous class)";
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- return "(Anonymous function)";
- }
+ function getNameOfSymbol(symbol) {
+ if (symbol.declarations && symbol.declarations.length) {
+ var declaration = symbol.declarations[0];
+ if (declaration.name) {
+ return ts.declarationNameToString(declaration.name);
+ }
+ if (declaration.parent && declaration.parent.kind === 225 /* VariableDeclaration */) {
+ return ts.declarationNameToString(declaration.parent.name);
+ }
+ switch (declaration.kind) {
+ case 198 /* ClassExpression */:
+ return "(Anonymous class)";
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ return "(Anonymous function)";
}
- return symbol.name;
}
+ return symbol.name;
+ }
+ function getSymbolDisplayBuilder() {
/**
* Writes only the name of the symbol out to the writer. Uses the original source text
* for the name of the symbol if it is available to match how the user wrote the name.
@@ -26047,7 +28031,7 @@ var ts;
if (parentSymbol) {
// Write type arguments of instantiated class/interface here
if (flags & 1 /* WriteTypeParametersOrArguments */) {
- if (symbol.flags & 16777216 /* Instantiated */) {
+ if (getCheckFlags(symbol) & 1 /* Instantiated */) {
buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration);
}
else {
@@ -26075,9 +28059,9 @@ var ts;
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
// Go up and add our parent.
- var parent_5 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
- if (parent_5) {
- walkSymbol(parent_5, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
+ var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
+ if (parent) {
+ walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
}
}
if (accessibleSymbolChain) {
@@ -26115,7 +28099,7 @@ var ts;
function writeType(type, flags) {
var nextFlags = flags & ~512 /* InTypeAlias */;
// Write undefined/null type as any
- if (type.flags & 16015 /* Intrinsic */) {
+ if (type.flags & 16793231 /* Intrinsic */) {
// Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving
writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && isTypeAny(type)
? "any"
@@ -26142,7 +28126,7 @@ var ts;
else if (!(flags & 512 /* InTypeAlias */) && type.aliasSymbol &&
isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) {
var typeArguments = type.aliasTypeArguments;
- writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags);
+ writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags);
}
else if (type.flags & 196608 /* UnionOrIntersection */) {
writeUnionOrIntersectionType(type, nextFlags);
@@ -26223,18 +28207,18 @@ var ts;
var outerTypeParameters = type.target.outerTypeParameters;
var i = 0;
if (outerTypeParameters) {
- var length_1 = outerTypeParameters.length;
- while (i < length_1) {
+ var length_2 = outerTypeParameters.length;
+ while (i < length_2) {
// Find group of type arguments for type parameters with the same declaring container.
var start = i;
- var parent_6 = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
+ var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
do {
i++;
- } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_6);
+ } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
// When type parameters are their own type arguments for the whole group (i.e. we have
// the default outer type arguments), we don't show the group.
if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
- writeSymbolTypeReference(parent_6, typeArguments, start, i, flags);
+ writeSymbolTypeReference(parent, typeArguments, start, i, flags);
writePunctuation(writer, 22 /* DotToken */);
}
}
@@ -26261,7 +28245,8 @@ var ts;
var symbol = type.symbol;
if (symbol) {
// Always use 'typeof T' for type of class, enum, and module objects
- if (symbol.flags & (32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
+ if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) ||
+ symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) {
writeTypeOfSymbol(type, flags);
}
else if (shouldWriteTypeOfFunctionSymbol()) {
@@ -26300,7 +28285,7 @@ var ts;
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent ||
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 261 /* SourceFile */ || declaration.parent.kind === 231 /* ModuleBlock */;
+ return declaration.parent.kind === 264 /* SourceFile */ || declaration.parent.kind === 233 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -26314,32 +28299,13 @@ var ts;
writeSpace(writer);
buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags);
}
- function writeIndexSignature(info, keyword) {
- if (info) {
- if (info.isReadonly) {
- writeKeyword(writer, 130 /* ReadonlyKeyword */);
- writeSpace(writer);
- }
- writePunctuation(writer, 20 /* OpenBracketToken */);
- writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x");
- writePunctuation(writer, 55 /* ColonToken */);
- writeSpace(writer);
- writeKeyword(writer, keyword);
- writePunctuation(writer, 21 /* CloseBracketToken */);
- writePunctuation(writer, 55 /* ColonToken */);
- writeSpace(writer);
- writeType(info.type, 0 /* None */);
- writePunctuation(writer, 24 /* SemicolonToken */);
- writer.writeLine();
- }
- }
function writePropertyWithModifiers(prop) {
if (isReadonlySymbol(prop)) {
writeKeyword(writer, 130 /* ReadonlyKeyword */);
writeSpace(writer);
}
buildSymbolDisplay(prop, writer);
- if (prop.flags & 536870912 /* Optional */) {
+ if (prop.flags & 67108864 /* Optional */) {
writePunctuation(writer, 54 /* QuestionToken */);
}
}
@@ -26416,15 +28382,15 @@ var ts;
writePunctuation(writer, 24 /* SemicolonToken */);
writer.writeLine();
}
- writeIndexSignature(resolved.stringIndexInfo, 134 /* StringKeyword */);
- writeIndexSignature(resolved.numberIndexInfo, 132 /* NumberKeyword */);
+ buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack);
+ buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack);
for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
var p = _e[_d];
var t = getTypeOfSymbol(p);
if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) {
var signatures = getSignaturesOfType(t, 0 /* Call */);
- for (var _f = 0, signatures_1 = signatures; _f < signatures_1.length; _f++) {
- var signature = signatures_1[_f];
+ for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) {
+ var signature = signatures_2[_f];
writePropertyWithModifiers(p);
buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack);
writePunctuation(writer, 24 /* SemicolonToken */);
@@ -26483,33 +28449,44 @@ var ts;
writeSpace(writer);
buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack);
}
+ var defaultType = getDefaultFromTypeParameter(tp);
+ if (defaultType) {
+ writeSpace(writer);
+ writePunctuation(writer, 57 /* EqualsToken */);
+ writeSpace(writer);
+ buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack);
+ }
}
function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) {
var parameterNode = p.valueDeclaration;
- if (ts.isRestParameter(parameterNode)) {
+ if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) {
writePunctuation(writer, 23 /* DotDotDotToken */);
}
- if (ts.isBindingPattern(parameterNode.name)) {
+ if (parameterNode && ts.isBindingPattern(parameterNode.name)) {
buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack);
}
else {
appendSymbolNameOnly(p, writer);
}
- if (isOptionalParameter(parameterNode)) {
+ if (parameterNode && isOptionalParameter(parameterNode)) {
writePunctuation(writer, 54 /* QuestionToken */);
}
writePunctuation(writer, 55 /* ColonToken */);
writeSpace(writer);
- buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack);
+ var type = getTypeOfSymbol(p);
+ if (parameterNode && isRequiredInitializedParameter(parameterNode)) {
+ type = includeFalsyTypes(type, 2048 /* Undefined */);
+ }
+ buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack);
}
function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) {
// We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node.
- if (bindingPattern.kind === 172 /* ObjectBindingPattern */) {
+ if (bindingPattern.kind === 173 /* ObjectBindingPattern */) {
writePunctuation(writer, 16 /* OpenBraceToken */);
buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); });
writePunctuation(writer, 17 /* CloseBraceToken */);
}
- else if (bindingPattern.kind === 173 /* ArrayBindingPattern */) {
+ else if (bindingPattern.kind === 174 /* ArrayBindingPattern */) {
writePunctuation(writer, 20 /* OpenBracketToken */);
var elements = bindingPattern.elements;
buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); });
@@ -26523,9 +28500,9 @@ var ts;
if (ts.isOmittedExpression(bindingElement)) {
return;
}
- ts.Debug.assert(bindingElement.kind === 174 /* BindingElement */);
+ ts.Debug.assert(bindingElement.kind === 175 /* BindingElement */);
if (bindingElement.propertyName) {
- writer.writeSymbol(ts.getTextOfNode(bindingElement.propertyName), bindingElement.symbol);
+ writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName));
writePunctuation(writer, 55 /* ColonToken */);
writeSpace(writer);
}
@@ -26597,6 +28574,10 @@ var ts;
buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack);
}
function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) {
+ var returnType = getReturnTypeOfSignature(signature);
+ if (flags & 2048 /* SuppressAnyReturnType */ && isTypeAny(returnType)) {
+ return;
+ }
if (flags & 8 /* WriteArrowStyleSignature */) {
writeSpace(writer);
writePunctuation(writer, 35 /* EqualsGreaterThanToken */);
@@ -26609,7 +28590,6 @@ var ts;
buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack);
}
else {
- var returnType = getReturnTypeOfSignature(signature);
buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack);
}
}
@@ -26629,6 +28609,32 @@ var ts;
buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack);
buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack);
}
+ function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) {
+ if (info) {
+ if (info.isReadonly) {
+ writeKeyword(writer, 130 /* ReadonlyKeyword */);
+ writeSpace(writer);
+ }
+ writePunctuation(writer, 20 /* OpenBracketToken */);
+ writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x");
+ writePunctuation(writer, 55 /* ColonToken */);
+ writeSpace(writer);
+ switch (kind) {
+ case 1 /* Number */:
+ writeKeyword(writer, 132 /* NumberKeyword */);
+ break;
+ case 0 /* String */:
+ writeKeyword(writer, 135 /* StringKeyword */);
+ break;
+ }
+ writePunctuation(writer, 21 /* CloseBracketToken */);
+ writePunctuation(writer, 55 /* ColonToken */);
+ writeSpace(writer);
+ buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack);
+ writePunctuation(writer, 24 /* SemicolonToken */);
+ writer.writeLine();
+ }
+ }
return _displayBuilder || (_displayBuilder = {
buildSymbolDisplay: buildSymbolDisplay,
buildTypeDisplay: buildTypeDisplay,
@@ -26639,6 +28645,7 @@ var ts;
buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters,
buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol,
buildSignatureDisplay: buildSignatureDisplay,
+ buildIndexSignatureDisplay: buildIndexSignatureDisplay,
buildReturnTypeDisplay: buildReturnTypeDisplay
});
}
@@ -26653,75 +28660,76 @@ var ts;
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 174 /* BindingElement */:
+ case 175 /* BindingElement */:
return isDeclarationVisible(node.parent.parent);
- case 223 /* VariableDeclaration */:
+ case 225 /* VariableDeclaration */:
if (ts.isBindingPattern(node.name) &&
!node.name.elements.length) {
// If the binding pattern is empty, this variable declaration is not visible
return false;
}
- // Otherwise fall through
- case 230 /* ModuleDeclaration */:
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 228 /* TypeAliasDeclaration */:
- case 225 /* FunctionDeclaration */:
- case 229 /* EnumDeclaration */:
- case 234 /* ImportEqualsDeclaration */:
+ // falls through
+ case 232 /* ModuleDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
+ case 227 /* FunctionDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
// external module augmentation is always visible
if (ts.isExternalModuleAugmentation(node)) {
return true;
}
- var parent_7 = getDeclarationContainer(node);
+ var parent = getDeclarationContainer(node);
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
- !(node.kind !== 234 /* ImportEqualsDeclaration */ && parent_7.kind !== 261 /* SourceFile */ && ts.isInAmbientContext(parent_7))) {
- return isGlobalSourceFile(parent_7);
+ !(node.kind !== 236 /* ImportEqualsDeclaration */ && parent.kind !== 264 /* SourceFile */ && ts.isInAmbientContext(parent))) {
+ return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
- return isDeclarationVisible(parent_7);
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ return isDeclarationVisible(parent);
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) {
// Private/protected properties/methods are not visible
return false;
}
- // Public properties/methods are visible if its parents are visible, so const it fall into next case statement
- case 150 /* Constructor */:
- case 154 /* ConstructSignature */:
- case 153 /* CallSignature */:
- case 155 /* IndexSignature */:
- case 144 /* Parameter */:
- case 231 /* ModuleBlock */:
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
- case 161 /* TypeLiteral */:
- case 157 /* TypeReference */:
- case 162 /* ArrayType */:
- case 163 /* TupleType */:
- case 164 /* UnionType */:
- case 165 /* IntersectionType */:
- case 166 /* ParenthesizedType */:
+ // Public properties/methods are visible if its parents are visible, so:
+ // falls through
+ case 151 /* Constructor */:
+ case 155 /* ConstructSignature */:
+ case 154 /* CallSignature */:
+ case 156 /* IndexSignature */:
+ case 145 /* Parameter */:
+ case 233 /* ModuleBlock */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
+ case 162 /* TypeLiteral */:
+ case 158 /* TypeReference */:
+ case 163 /* ArrayType */:
+ case 164 /* TupleType */:
+ case 165 /* UnionType */:
+ case 166 /* IntersectionType */:
+ case 167 /* ParenthesizedType */:
return isDeclarationVisible(node.parent);
// Default binding, import specifier and namespace import is visible
// only on demand so by default it is not visible
- case 236 /* ImportClause */:
- case 237 /* NamespaceImport */:
- case 239 /* ImportSpecifier */:
+ case 238 /* ImportClause */:
+ case 239 /* NamespaceImport */:
+ case 241 /* ImportSpecifier */:
return false;
// Type parameters are always visible
- case 143 /* TypeParameter */:
+ case 144 /* TypeParameter */:
// Source file and namespace export are always visible
- case 261 /* SourceFile */:
- case 233 /* NamespaceExportDeclaration */:
+ case 264 /* SourceFile */:
+ case 235 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
return false;
default:
return false;
@@ -26730,10 +28738,10 @@ var ts;
}
function collectLinkedAliases(node) {
var exportSymbol;
- if (node.parent && node.parent.kind === 240 /* ExportAssignment */) {
+ if (node.parent && node.parent.kind === 242 /* ExportAssignment */) {
exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node);
}
- else if (node.parent.kind === 243 /* ExportSpecifier */) {
+ else if (node.parent.kind === 245 /* ExportSpecifier */) {
var exportSpecifier = node.parent;
exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ?
getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) :
@@ -26778,8 +28786,8 @@ var ts;
var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
if (resolutionCycleStartIndex >= 0) {
// A cycle was found
- var length_2 = resolutionTargets.length;
- for (var i = resolutionCycleStartIndex; i < length_2; i++) {
+ var length_3 = resolutionTargets.length;
+ for (var i = resolutionCycleStartIndex; i < length_3; i++) {
resolutionResults[i] = false;
}
return false;
@@ -26823,21 +28831,20 @@ var ts;
return resolutionResults.pop();
}
function getDeclarationContainer(node) {
- node = ts.getRootDeclaration(node);
- while (node) {
+ node = ts.findAncestor(ts.getRootDeclaration(node), function (node) {
switch (node.kind) {
- case 223 /* VariableDeclaration */:
- case 224 /* VariableDeclarationList */:
- case 239 /* ImportSpecifier */:
- case 238 /* NamedImports */:
- case 237 /* NamespaceImport */:
- case 236 /* ImportClause */:
- node = node.parent;
- break;
+ case 225 /* VariableDeclaration */:
+ case 226 /* VariableDeclarationList */:
+ case 241 /* ImportSpecifier */:
+ case 240 /* NamedImports */:
+ case 239 /* NamespaceImport */:
+ case 238 /* ImportClause */:
+ return false;
default:
- return node.parent;
+ return true;
}
- }
+ });
+ return node && node.parent;
}
function getTypeOfPrototypeProperty(prototype) {
// TypeScript 1.0 spec (April 2014): 8.4
@@ -26855,9 +28862,6 @@ var ts;
function isTypeAny(type) {
return type && (type.flags & 1 /* Any */) !== 0;
}
- function isTypeNever(type) {
- return type && (type.flags & 8192 /* Never */) !== 0;
- }
// Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
// assigned by contextual typing.
function getTypeForBindingElementParent(node) {
@@ -26865,24 +28869,29 @@ var ts;
return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
}
function isComputedNonLiteralName(name) {
- return name.kind === 142 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression);
+ return name.kind === 143 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression);
}
function getRestType(source, properties, symbol) {
- ts.Debug.assert(!!(source.flags & 32768 /* Object */), "Rest types only support object types right now.");
+ source = filterType(source, function (t) { return !(t.flags & 6144 /* Nullable */); });
+ if (source.flags & 8192 /* Never */) {
+ return emptyObjectType;
+ }
+ if (source.flags & 65536 /* Union */) {
+ return mapType(source, function (t) { return getRestType(t, properties, symbol); });
+ }
var members = ts.createMap();
var names = ts.createMap();
- for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) {
- var name_17 = properties_2[_i];
- names[ts.getTextOfPropertyName(name_17)] = true;
+ for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
+ var name = properties_3[_i];
+ names.set(ts.getTextOfPropertyName(name), true);
}
for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) {
var prop = _b[_a];
- var inNamesToRemove = prop.name in names;
+ var inNamesToRemove = names.has(prop.name);
var isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */);
- var isMethod = prop.flags & 8192 /* Method */;
var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
- if (!inNamesToRemove && !isPrivate && !isMethod && !isSetOnlyAccessor) {
- members[prop.name] = prop;
+ if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) {
+ members.set(prop.name, prop);
}
}
var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
@@ -26907,9 +28916,9 @@ var ts;
return parentType;
}
var type;
- if (pattern.kind === 172 /* ObjectBindingPattern */) {
+ if (pattern.kind === 173 /* ObjectBindingPattern */) {
if (declaration.dotDotDotToken) {
- if (!(parentType.flags & 32768 /* Object */)) {
+ if (!isValidSpreadType(parentType)) {
error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
return unknownType;
}
@@ -26924,8 +28933,8 @@ var ts;
}
else {
// Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
- var name_18 = declaration.propertyName || declaration.name;
- if (isComputedNonLiteralName(name_18)) {
+ var name = declaration.propertyName || declaration.name;
+ if (isComputedNonLiteralName(name)) {
// computed properties with non-literal names are treated as 'any'
return anyType;
}
@@ -26934,12 +28943,12 @@ var ts;
}
// Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature,
// or otherwise the type of the string index signature.
- var text = ts.getTextOfPropertyName(name_18);
+ var text = ts.getTextOfPropertyName(name);
type = getTypeOfPropertyOfType(parentType, text) ||
isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) ||
getIndexTypeOfType(parentType, 0 /* String */);
if (!type) {
- error(name_18, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_18));
+ error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name));
return unknownType;
}
}
@@ -26948,7 +28957,7 @@ var ts;
// This elementType will be used if the specific property corresponding to this index is not
// present (aka the tuple element property). This call also checks that the parentType is in
// fact an iterable or array (depending on target language).
- var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false);
+ var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterable*/ false);
if (declaration.dotDotDotToken) {
// Rest element has an array type with the same element type as the parent type
type = createArrayType(elementType);
@@ -26979,7 +28988,7 @@ var ts;
getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) :
type;
}
- function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) {
+ function getTypeForDeclarationFromJSDocComment(declaration) {
var jsdocType = ts.getJSDocType(declaration);
if (jsdocType) {
return getTypeFromTypeNode(jsdocType);
@@ -26992,44 +29001,46 @@ var ts;
}
function isEmptyArrayLiteral(node) {
var expr = ts.skipParentheses(node);
- return expr.kind === 175 /* ArrayLiteralExpression */ && expr.elements.length === 0;
+ return expr.kind === 176 /* ArrayLiteralExpression */ && expr.elements.length === 0;
}
function addOptionality(type, optional) {
return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type;
}
// Return the inferred type for a variable, parameter, or property declaration
function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
- if (declaration.flags & 2097152 /* JavaScriptFile */) {
+ if (declaration.flags & 65536 /* JavaScriptFile */) {
// If this is a variable in a JavaScript file, then use the JSDoc type (if it has
// one as its type), otherwise fallback to the below standard TS codepaths to
// try to figure it out.
- var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration);
+ var type = getTypeForDeclarationFromJSDocComment(declaration);
if (type && type !== unknownType) {
return type;
}
}
// A variable declared in a for..in statement is of type string, or of type keyof T when the
// right hand expression is of a type parameter type.
- if (declaration.parent.parent.kind === 212 /* ForInStatement */) {
+ if (declaration.parent.parent.kind === 214 /* ForInStatement */) {
var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression));
return indexType.flags & (16384 /* TypeParameter */ | 262144 /* Index */) ? indexType : stringType;
}
- if (declaration.parent.parent.kind === 213 /* ForOfStatement */) {
+ if (declaration.parent.parent.kind === 215 /* ForOfStatement */) {
// checkRightHandSideOfForOf will return undefined if the for-of expression type was
// missing properties/signatures required to get its iteratedType (like
// [Symbol.iterator] or next). This may be because we accessed properties from anyType,
// or it may have led to an error inside getElementTypeOfIterable.
- return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType;
+ var forOfStatement = declaration.parent.parent;
+ return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType;
}
if (ts.isBindingPattern(declaration.parent)) {
return getTypeForBindingElement(declaration);
}
// Use type from type annotation if one is present
if (declaration.type) {
- return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality);
+ var declaredType = getTypeFromTypeNode(declaration.type);
+ return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality);
}
- if ((compilerOptions.noImplicitAny || declaration.flags & 2097152 /* JavaScriptFile */) &&
- declaration.kind === 223 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
+ if ((noImplicitAny || declaration.flags & 65536 /* JavaScriptFile */) &&
+ declaration.kind === 225 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
!(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !ts.isInAmbientContext(declaration)) {
// If --noImplicitAny is on or the declaration is in a Javascript file,
// use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
@@ -27043,11 +29054,11 @@ var ts;
return autoArrayType;
}
}
- if (declaration.kind === 144 /* Parameter */) {
+ if (declaration.kind === 145 /* Parameter */) {
var func = declaration.parent;
// For a parameter of a set accessor, use the type of the get accessor if one is present
- if (func.kind === 152 /* SetAccessor */ && !ts.hasDynamicName(func)) {
- var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 151 /* GetAccessor */);
+ if (func.kind === 153 /* SetAccessor */ && !ts.hasDynamicName(func)) {
+ var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 152 /* GetAccessor */);
if (getter) {
var getterSignature = getSignatureFromDeclaration(getter);
var thisParameter = getAccessorThisParameter(func);
@@ -27076,8 +29087,13 @@ var ts;
var type = checkDeclarationInitializer(declaration);
return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality);
}
+ if (ts.isJsxAttribute(declaration)) {
+ // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
+ // I.e <Elem attr /> is sugar for <Elem attr={true} />
+ return trueType;
+ }
// If it is a short-hand property assignment, use the type of the identifier
- if (declaration.kind === 258 /* ShorthandPropertyAssignment */) {
+ if (declaration.kind === 261 /* ShorthandPropertyAssignment */) {
return checkIdentifier(declaration.name);
}
// If the declaration specifies a binding pattern, use the type implied by the binding pattern
@@ -27087,6 +29103,38 @@ var ts;
// No type specified and nothing can be inferred
return undefined;
}
+ function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) {
+ var types = [];
+ var definedInConstructor = false;
+ var definedInMethod = false;
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var declaration = _a[_i];
+ var expression = declaration.kind === 193 /* BinaryExpression */ ? declaration :
+ declaration.kind === 178 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 193 /* BinaryExpression */) :
+ undefined;
+ if (!expression) {
+ return unknownType;
+ }
+ if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 98 /* ThisKeyword */) {
+ if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 151 /* Constructor */) {
+ definedInConstructor = true;
+ }
+ else {
+ definedInMethod = true;
+ }
+ }
+ if (expression.flags & 65536 /* JavaScriptFile */) {
+ // If there is a JSDoc type, use it
+ var type = getTypeForDeclarationFromJSDocComment(expression.parent);
+ if (type && type !== unknownType) {
+ types.push(getWidenedType(type));
+ continue;
+ }
+ }
+ types.push(getWidenedLiteralType(checkExpressionCached(expression.right)));
+ }
+ return getWidenedType(addOptionality(getUnionType(types, /*subtypeReduction*/ true), definedInMethod && !definedInConstructor));
+ }
// Return the type implied by a binding pattern element. This is the type of the initializer of the element if
// one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
// pattern. Otherwise, it is the type any.
@@ -27097,7 +29145,7 @@ var ts;
if (ts.isBindingPattern(element.name)) {
return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
}
- if (reportErrors && compilerOptions.noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) {
+ if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) {
reportImplicitAnyError(element, anyType);
}
return anyType;
@@ -27105,22 +29153,27 @@ var ts;
// Return the type implied by an object binding pattern
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
var members = ts.createMap();
+ var stringIndexInfo;
var hasComputedProperties = false;
ts.forEach(pattern.elements, function (e) {
var name = e.propertyName || e.name;
- if (isComputedNonLiteralName(name) || e.dotDotDotToken) {
- // do not include computed properties or rests in the implied type
+ if (isComputedNonLiteralName(name)) {
+ // do not include computed properties in the implied type
hasComputedProperties = true;
return;
}
+ if (e.dotDotDotToken) {
+ stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
+ return;
+ }
var text = ts.getTextOfPropertyName(name);
- var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0);
+ var flags = 4 /* Property */ | (e.initializer ? 67108864 /* Optional */ : 0);
var symbol = createSymbol(flags, text);
symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
symbol.bindingElement = e;
- members[symbol.name] = symbol;
+ members.set(symbol.name, symbol);
});
- var result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined);
+ var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined);
if (includePatternInType) {
result.pattern = pattern;
}
@@ -27153,7 +29206,7 @@ var ts;
// parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
// the parameter.
function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
- return pattern.kind === 172 /* ObjectBindingPattern */
+ return pattern.kind === 173 /* ObjectBindingPattern */
? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
: getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
}
@@ -27175,7 +29228,7 @@ var ts;
// During a normal type check we'll never get to here with a property assignment (the check of the containing
// object literal uses a different path). We exclude widening only so that language services and type verification
// tools see the actual type.
- if (declaration.kind === 257 /* PropertyAssignment */) {
+ if (declaration.kind === 260 /* PropertyAssignment */) {
return type;
}
return getWidenedType(type);
@@ -27183,7 +29236,7 @@ var ts;
// Rest parameters default to type any[], other parameters default to type any
type = declaration.dotDotDotToken ? anyArrayType : anyType;
// Report implicit any errors unless this is a private property within an ambient declaration
- if (reportErrors && compilerOptions.noImplicitAny) {
+ if (reportErrors && noImplicitAny) {
if (!declarationBelongsToPrivateAmbientMember(declaration)) {
reportImplicitAnyError(declaration, type);
}
@@ -27192,14 +29245,14 @@ var ts;
}
function declarationBelongsToPrivateAmbientMember(declaration) {
var root = ts.getRootDeclaration(declaration);
- var memberDeclaration = root.kind === 144 /* Parameter */ ? root.parent : root;
+ var memberDeclaration = root.kind === 145 /* Parameter */ ? root.parent : root;
return isPrivateWithinAmbient(memberDeclaration);
}
function getTypeOfVariableOrParameterOrProperty(symbol) {
var links = getSymbolLinks(symbol);
if (!links.type) {
// Handle prototype property
- if (symbol.flags & 134217728 /* Prototype */) {
+ if (symbol.flags & 16777216 /* Prototype */) {
return links.type = getTypeOfPrototypeProperty(symbol);
}
// Handle catch clause variables
@@ -27208,10 +29261,10 @@ var ts;
return links.type = anyType;
}
// Handle export default expressions
- if (declaration.kind === 240 /* ExportAssignment */) {
+ if (declaration.kind === 242 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
- if (declaration.flags & 2097152 /* JavaScriptFile */ && declaration.kind === 286 /* JSDocPropertyTag */ && declaration.typeExpression) {
+ if (declaration.flags & 65536 /* JavaScriptFile */ && declaration.kind === 290 /* JSDocPropertyTag */ && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
// Handle variable, parameter or property
@@ -27224,36 +29277,15 @@ var ts;
// * exports.p = expr
// * this.p = expr
// * className.prototype.method = expr
- if (declaration.kind === 192 /* BinaryExpression */ ||
- declaration.kind === 177 /* PropertyAccessExpression */ && declaration.parent.kind === 192 /* BinaryExpression */) {
- // Use JS Doc type if present on parent expression statement
- if (declaration.flags & 2097152 /* JavaScriptFile */) {
- var jsdocType = ts.getJSDocType(declaration.parent);
- if (jsdocType) {
- return links.type = getTypeFromTypeNode(jsdocType);
- }
- }
- var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 192 /* BinaryExpression */ ?
- checkExpressionCached(decl.right) :
- checkExpressionCached(decl.parent.right); });
- type = getUnionType(declaredTypes, /*subtypeReduction*/ true);
+ if (declaration.kind === 193 /* BinaryExpression */ ||
+ declaration.kind === 178 /* PropertyAccessExpression */ && declaration.parent.kind === 193 /* BinaryExpression */) {
+ type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol);
}
else {
type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true);
}
if (!popTypeResolution()) {
- if (symbol.valueDeclaration.type) {
- // Variable has type annotation that circularly references the variable itself
- type = unknownType;
- error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
- }
- else {
- // Variable has initializer that circularly references the variable itself
- type = anyType;
- if (compilerOptions.noImplicitAny) {
- error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
- }
- }
+ type = reportCircularityError(symbol);
}
links.type = type;
}
@@ -27261,7 +29293,7 @@ var ts;
}
function getAnnotatedAccessorType(accessor) {
if (accessor) {
- if (accessor.kind === 151 /* GetAccessor */) {
+ if (accessor.kind === 152 /* GetAccessor */) {
return accessor.type && getTypeFromTypeNode(accessor.type);
}
else {
@@ -27281,10 +29313,10 @@ var ts;
function getTypeOfAccessors(symbol) {
var links = getSymbolLinks(symbol);
if (!links.type) {
- var getter = ts.getDeclarationOfKind(symbol, 151 /* GetAccessor */);
- var setter = ts.getDeclarationOfKind(symbol, 152 /* SetAccessor */);
- if (getter && getter.flags & 2097152 /* JavaScriptFile */) {
- var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter);
+ var getter = ts.getDeclarationOfKind(symbol, 152 /* GetAccessor */);
+ var setter = ts.getDeclarationOfKind(symbol, 153 /* SetAccessor */);
+ if (getter && getter.flags & 65536 /* JavaScriptFile */) {
+ var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
if (jsDocType) {
return links.type = jsDocType;
}
@@ -27310,7 +29342,7 @@ var ts;
type = getReturnTypeFromBody(getter);
}
else {
- if (compilerOptions.noImplicitAny) {
+ if (noImplicitAny) {
if (setter) {
error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
}
@@ -27325,8 +29357,8 @@ var ts;
}
if (!popTypeResolution()) {
type = anyType;
- if (compilerOptions.noImplicitAny) {
- var getter_1 = ts.getDeclarationOfKind(symbol, 151 /* GetAccessor */);
+ if (noImplicitAny) {
+ var getter_1 = ts.getDeclarationOfKind(symbol, 152 /* GetAccessor */);
error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol));
}
}
@@ -27334,6 +29366,10 @@ var ts;
}
return links.type;
}
+ function getBaseTypeVariableOfClass(symbol) {
+ var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
+ return baseConstructorType.flags & 540672 /* TypeVariable */ ? baseConstructorType : undefined;
+ }
function getTypeOfFuncClassEnumModule(symbol) {
var links = getSymbolLinks(symbol);
if (!links.type) {
@@ -27342,8 +29378,13 @@ var ts;
}
else {
var type = createObjectType(16 /* Anonymous */, symbol);
- links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ?
- includeFalsyTypes(type, 2048 /* Undefined */) : type;
+ if (symbol.flags & 32 /* Class */) {
+ var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
+ links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
+ }
+ else {
+ links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type;
+ }
}
}
return links.type;
@@ -27373,12 +29414,39 @@ var ts;
function getTypeOfInstantiatedSymbol(symbol) {
var links = getSymbolLinks(symbol);
if (!links.type) {
- links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
+ if (symbolInstantiationDepth === 100) {
+ error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite);
+ links.type = unknownType;
+ }
+ else {
+ if (!pushTypeResolution(symbol, 0 /* Type */)) {
+ return unknownType;
+ }
+ symbolInstantiationDepth++;
+ var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
+ symbolInstantiationDepth--;
+ if (!popTypeResolution()) {
+ type = reportCircularityError(symbol);
+ }
+ links.type = type;
+ }
}
return links.type;
}
+ function reportCircularityError(symbol) {
+ // Check if variable has type annotation that circularly references the variable itself
+ if (symbol.valueDeclaration.type) {
+ error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
+ return unknownType;
+ }
+ // Otherwise variable has initializer that circularly references the variable itself
+ if (noImplicitAny) {
+ error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol));
+ }
+ return anyType;
+ }
function getTypeOfSymbol(symbol) {
- if (symbol.flags & 16777216 /* Instantiated */) {
+ if (getCheckFlags(symbol) & 1 /* Instantiated */) {
return getTypeOfInstantiatedSymbol(symbol);
}
if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
@@ -27398,22 +29466,33 @@ var ts;
}
return unknownType;
}
+ function isReferenceToType(type, target) {
+ return type !== undefined
+ && target !== undefined
+ && (getObjectFlags(type) & 4 /* Reference */) !== 0
+ && type.target === target;
+ }
function getTargetType(type) {
return getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
}
function hasBaseType(type, checkBase) {
return check(type);
function check(type) {
- var target = getTargetType(type);
- return target === checkBase || ts.forEach(getBaseTypes(target), check);
+ if (getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
+ var target = getTargetType(type);
+ return target === checkBase || ts.forEach(getBaseTypes(target), check);
+ }
+ else if (type.flags & 131072 /* Intersection */) {
+ return ts.forEach(type.types, check);
+ }
}
}
// Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
// The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
// in-place and returns the same array.
function appendTypeParameters(typeParameters, declarations) {
- for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
- var declaration = declarations_2[_i];
+ for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
+ var declaration = declarations_3[_i];
var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration));
if (!typeParameters) {
typeParameters = [tp];
@@ -27433,9 +29512,9 @@ var ts;
if (!node) {
return typeParameters;
}
- if (node.kind === 226 /* ClassDeclaration */ || node.kind === 197 /* ClassExpression */ ||
- node.kind === 225 /* FunctionDeclaration */ || node.kind === 184 /* FunctionExpression */ ||
- node.kind === 149 /* MethodDeclaration */ || node.kind === 185 /* ArrowFunction */) {
+ if (node.kind === 228 /* ClassDeclaration */ || node.kind === 198 /* ClassExpression */ ||
+ node.kind === 227 /* FunctionDeclaration */ || node.kind === 185 /* FunctionExpression */ ||
+ node.kind === 150 /* MethodDeclaration */ || node.kind === 186 /* ArrowFunction */) {
var declarations = node.typeParameters;
if (declarations) {
return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations);
@@ -27445,8 +29524,8 @@ var ts;
}
// The outer type parameters are those defined by enclosing generic classes, methods, or functions.
function getOuterTypeParametersOfClassOrInterface(symbol) {
- var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 227 /* InterfaceDeclaration */);
- return appendOuterTypeParameters(undefined, declaration);
+ var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 229 /* InterfaceDeclaration */);
+ return appendOuterTypeParameters(/*typeParameters*/ undefined, declaration);
}
// The local type parameters are the combined set of type parameters from all declarations of the class,
// interface, or type alias.
@@ -27454,8 +29533,8 @@ var ts;
var result;
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var node = _a[_i];
- if (node.kind === 227 /* InterfaceDeclaration */ || node.kind === 226 /* ClassDeclaration */ ||
- node.kind === 197 /* ClassExpression */ || node.kind === 228 /* TypeAliasDeclaration */) {
+ if (node.kind === 229 /* InterfaceDeclaration */ || node.kind === 228 /* ClassDeclaration */ ||
+ node.kind === 198 /* ClassExpression */ || node.kind === 230 /* TypeAliasDeclaration */) {
var declaration = node;
if (declaration.typeParameters) {
result = appendTypeParameters(result, declaration.typeParameters);
@@ -27469,29 +29548,50 @@ var ts;
function getTypeParametersOfClassOrInterface(symbol) {
return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
}
+ // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
+ // rest parameter of type any[].
+ function isMixinConstructorType(type) {
+ var signatures = getSignaturesOfType(type, 1 /* Construct */);
+ if (signatures.length === 1) {
+ var s = signatures[0];
+ return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType;
+ }
+ return false;
+ }
function isConstructorType(type) {
- return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 1 /* Construct */).length > 0;
+ if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) {
+ return true;
+ }
+ if (type.flags & 540672 /* TypeVariable */) {
+ var constraint = getBaseConstraintOfType(type);
+ return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint);
+ }
+ return false;
}
function getBaseTypeNodeOfClass(type) {
return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration);
}
- function getConstructorsForTypeArguments(type, typeArgumentNodes) {
- var typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0;
- return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (sig.typeParameters ? sig.typeParameters.length : 0) === typeArgCount; });
+ function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
+ var typeArgCount = ts.length(typeArgumentNodes);
+ var isJavaScript = ts.isInJavaScriptFile(location);
+ return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
}
- function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) {
- var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes);
+ function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
+ var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
if (typeArgumentNodes) {
var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode);
signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); });
}
return signatures;
}
- // The base constructor of a class can resolve to
- // undefinedType if the class has no extends clause,
- // unknownType if an error occurred during resolution of the extends expression,
- // nullType if the extends expression is the null value, or
- // an object type with at least one construct signature.
+ /**
+ * The base constructor of a class can resolve to
+ * * undefinedType if the class has no extends clause,
+ * * unknownType if an error occurred during resolution of the extends expression,
+ * * nullType if the extends expression is the null value,
+ * * anyType if the extends expression has type any, or
+ * * an object type with at least one construct signature.
+ */
function getBaseConstructorTypeOfClass(type) {
if (!type.resolvedBaseConstructorType) {
var baseTypeNode = getBaseTypeNodeOfClass(type);
@@ -27502,7 +29602,7 @@ var ts;
return unknownType;
}
var baseConstructorType = checkExpression(baseTypeNode.expression);
- if (baseConstructorType.flags & 32768 /* Object */) {
+ if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */)) {
// Resolving the members of a class requires us to resolve the base class of that class.
// We force resolution here such that we catch circularities now.
resolveStructuredTypeMembers(baseConstructorType);
@@ -27511,7 +29611,7 @@ var ts;
error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
return type.resolvedBaseConstructorType = unknownType;
}
- if (baseConstructorType !== unknownType && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
+ if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
return type.resolvedBaseConstructorType = unknownType;
}
@@ -27540,8 +29640,8 @@ var ts;
}
function resolveBaseTypesOfClass(type) {
type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
- var baseConstructorType = getBaseConstructorTypeOfClass(type);
- if (!(baseConstructorType.flags & 32768 /* Object */)) {
+ var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
+ if (!(baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 1 /* Any */))) {
return;
}
var baseTypeNode = getBaseTypeNodeOfClass(type);
@@ -27554,11 +29654,14 @@ var ts;
// type arguments in the same manner as a type reference to get the same error reporting experience.
baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
}
+ else if (baseConstructorType.flags & 1 /* Any */) {
+ baseType = baseConstructorType;
+ }
else {
// The class derives from a "class-like" constructor function, check that we have at least one construct signature
// with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
// we check that all instantiated signatures return the same type.
- var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments);
+ var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
if (!constructors.length) {
error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
return;
@@ -27576,7 +29679,7 @@ var ts;
if (baseType === unknownType) {
return;
}
- if (!(getObjectFlags(getTargetType(baseType)) & 3 /* ClassOrInterface */)) {
+ if (!isValidBaseType(baseType)) {
error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType));
return;
}
@@ -27602,16 +29705,22 @@ var ts;
}
return true;
}
+ // A valid base type is `any`, any non-generic object type or intersection of non-generic
+ // object types.
+ function isValidBaseType(type) {
+ return type.flags & (32768 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
+ type.flags & 131072 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); });
+ }
function resolveBaseTypesOfInterface(type) {
type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray;
for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- if (declaration.kind === 227 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
+ if (declaration.kind === 229 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
var node = _c[_b];
var baseType = getTypeFromTypeNode(node);
if (baseType !== unknownType) {
- if (getObjectFlags(getTargetType(baseType)) & 3 /* ClassOrInterface */) {
+ if (isValidBaseType(baseType)) {
if (type !== baseType && !hasBaseType(baseType, type)) {
if (type.resolvedBaseTypes === emptyArray) {
type.resolvedBaseTypes = [baseType];
@@ -27638,7 +29747,7 @@ var ts;
function isIndependentInterface(symbol) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- if (declaration.kind === 227 /* InterfaceDeclaration */) {
+ if (declaration.kind === 229 /* InterfaceDeclaration */) {
if (declaration.flags & 64 /* ContainsThis */) {
return false;
}
@@ -27676,7 +29785,7 @@ var ts;
type.outerTypeParameters = outerTypeParameters;
type.localTypeParameters = localTypeParameters;
type.instantiations = ts.createMap();
- type.instantiations[getTypeListId(type.typeParameters)] = type;
+ type.instantiations.set(getTypeListId(type.typeParameters), type);
type.target = type;
type.typeArguments = type.typeParameters;
type.thisType = createType(16384 /* TypeParameter */);
@@ -27695,7 +29804,7 @@ var ts;
if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
return unknownType;
}
- var declaration = ts.getDeclarationOfKind(symbol, 285 /* JSDocTypedefTag */);
+ var declaration = ts.getDeclarationOfKind(symbol, 289 /* JSDocTypedefTag */);
var type = void 0;
if (declaration) {
if (declaration.jsDocTypeLiteral) {
@@ -27706,7 +29815,7 @@ var ts;
}
}
else {
- declaration = ts.getDeclarationOfKind(symbol, 228 /* TypeAliasDeclaration */);
+ declaration = ts.getDeclarationOfKind(symbol, 230 /* TypeAliasDeclaration */);
type = getTypeFromTypeNode(declaration.type);
}
if (popTypeResolution()) {
@@ -27716,7 +29825,7 @@ var ts;
// an instantiation of the type alias with the type parameters supplied as type arguments.
links.typeParameters = typeParameters;
links.instantiations = ts.createMap();
- links.instantiations[getTypeListId(typeParameters)] = type;
+ links.instantiations.set(getTypeListId(typeParameters), type);
}
}
else {
@@ -27733,14 +29842,14 @@ var ts;
return !ts.isInAmbientContext(member);
}
return expr.kind === 8 /* NumericLiteral */ ||
- expr.kind === 190 /* PrefixUnaryExpression */ && expr.operator === 37 /* MinusToken */ &&
+ expr.kind === 191 /* PrefixUnaryExpression */ && expr.operator === 37 /* MinusToken */ &&
expr.operand.kind === 8 /* NumericLiteral */ ||
- expr.kind === 70 /* Identifier */ && !!symbol.exports[expr.text];
+ expr.kind === 70 /* Identifier */ && !!symbol.exports.get(expr.text);
}
function enumHasLiteralMembers(symbol) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- if (declaration.kind === 229 /* EnumDeclaration */) {
+ if (declaration.kind === 231 /* EnumDeclaration */) {
for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
var member = _c[_b];
if (!isLiteralEnumMember(symbol, member)) {
@@ -27765,10 +29874,10 @@ var ts;
enumType.symbol = symbol;
if (enumHasLiteralMembers(symbol)) {
var memberTypeList = [];
- var memberTypes = ts.createMap();
+ var memberTypes = [];
for (var _i = 0, _a = enumType.symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- if (declaration.kind === 229 /* EnumDeclaration */) {
+ if (declaration.kind === 231 /* EnumDeclaration */) {
computeEnumMemberValues(declaration);
for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
var member = _c[_b];
@@ -27785,7 +29894,7 @@ var ts;
if (memberTypeList.length > 1) {
enumType.flags |= 65536 /* Union */;
enumType.types = memberTypeList;
- unionTypes[getTypeListId(memberTypeList)] = enumType;
+ unionTypes.set(getTypeListId(memberTypeList), enumType);
}
}
}
@@ -27806,9 +29915,6 @@ var ts;
if (!links.declaredType) {
var type = createType(16384 /* TypeParameter */);
type.symbol = symbol;
- if (!ts.getDeclarationOfKind(symbol, 143 /* TypeParameter */).constraint) {
- type.constraint = noConstraintType;
- }
links.declaredType = type;
}
return links.declaredType;
@@ -27821,7 +29927,6 @@ var ts;
return links.declaredType;
}
function getDeclaredTypeOfSymbol(symbol) {
- ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0);
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
return getDeclaredTypeOfClassOrInterface(symbol);
}
@@ -27860,19 +29965,20 @@ var ts;
function isIndependentType(node) {
switch (node.kind) {
case 118 /* AnyKeyword */:
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
case 132 /* NumberKeyword */:
case 121 /* BooleanKeyword */:
- case 135 /* SymbolKeyword */:
+ case 136 /* SymbolKeyword */:
+ case 133 /* ObjectKeyword */:
case 104 /* VoidKeyword */:
- case 137 /* UndefinedKeyword */:
+ case 138 /* UndefinedKeyword */:
case 94 /* NullKeyword */:
case 129 /* NeverKeyword */:
- case 171 /* LiteralType */:
+ case 172 /* LiteralType */:
return true;
- case 162 /* ArrayType */:
+ case 163 /* ArrayType */:
return isIndependentType(node.elementType);
- case 157 /* TypeReference */:
+ case 158 /* TypeReference */:
return isIndependentTypeReference(node);
}
return false;
@@ -27885,7 +29991,7 @@ var ts;
// A function-like declaration is considered independent (free of this references) if it has a return type
// annotation that is considered independent and if each parameter is considered independent.
function isIndependentFunctionLikeDeclaration(node) {
- if (node.kind !== 150 /* Constructor */ && (!node.type || !isIndependentType(node.type))) {
+ if (node.kind !== 151 /* Constructor */ && (!node.type || !isIndependentType(node.type))) {
return false;
}
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
@@ -27906,12 +30012,12 @@ var ts;
var declaration = symbol.declarations[0];
if (declaration) {
switch (declaration.kind) {
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
return isIndependentVariableLikeDeclaration(declaration);
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
return isIndependentFunctionLikeDeclaration(declaration);
}
}
@@ -27922,7 +30028,7 @@ var ts;
var result = ts.createMap();
for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
var symbol = symbols_1[_i];
- result[symbol.name] = symbol;
+ result.set(symbol.name, symbol);
}
return result;
}
@@ -27932,15 +30038,15 @@ var ts;
var result = ts.createMap();
for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
var symbol = symbols_2[_i];
- result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper);
+ result.set(symbol.name, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper));
}
return result;
}
function addInheritedMembers(symbols, baseSymbols) {
for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
var s = baseSymbols_1[_i];
- if (!symbols[s.name]) {
- symbols[s.name] = s;
+ if (!symbols.has(s.name)) {
+ symbols.set(s.name, s);
}
}
}
@@ -27948,8 +30054,8 @@ var ts;
if (!type.declaredProperties) {
var symbol = type.symbol;
type.declaredProperties = getNamedMembers(symbol.members);
- type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]);
- type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]);
+ type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call"));
+ type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new"));
type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
}
@@ -27957,7 +30063,14 @@ var ts;
}
function getTypeWithThisArgument(type, thisArgument) {
if (getObjectFlags(type) & 4 /* Reference */) {
- return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType]));
+ var target = type.target;
+ var typeArguments = type.typeArguments;
+ if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
+ return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
+ }
+ }
+ else if (type.flags & 131072 /* Intersection */) {
+ return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); }));
}
return type;
}
@@ -27993,10 +30106,14 @@ var ts;
for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
var baseType = baseTypes_1[_i];
var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
- addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType));
+ addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
- stringIndexInfo = stringIndexInfo || getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
+ if (!stringIndexInfo) {
+ stringIndexInfo = instantiatedBaseType === anyType ?
+ createIndexInfo(anyType, /*isReadonly*/ false) :
+ getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
+ }
numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
}
}
@@ -28035,14 +30152,16 @@ var ts;
return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)];
}
var baseTypeNode = getBaseTypeNodeOfClass(classType);
+ var isJavaScript = ts.isInJavaScriptFile(baseTypeNode);
var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode);
- var typeArgCount = typeArguments ? typeArguments.length : 0;
+ var typeArgCount = ts.length(typeArguments);
var result = [];
for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
var baseSig = baseSignatures_1[_i];
- var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0;
- if (typeParamCount === typeArgCount) {
- var sig = typeParamCount ? createSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig);
+ var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
+ var typeParamCount = ts.length(baseSig.typeParameters);
+ if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) {
+ var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig);
sig.typeParameters = classType.localTypeParameters;
sig.resolvedReturnType = classType;
result.push(sig);
@@ -28105,7 +30224,7 @@ var ts;
s = cloneSignature(signature);
if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) {
var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true);
- s.thisParameter = createTransientSymbol(signature.thisParameter, thisType);
+ s.thisParameter = createSymbolWithType(signature.thisParameter, thisType);
}
// Clear resolved return type we possibly got from cloneSignature
s.resolvedReturnType = undefined;
@@ -28121,8 +30240,8 @@ var ts;
function getUnionIndexInfo(types, kind) {
var indexTypes = [];
var isAnyReadonly = false;
- for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
- var type = types_1[_i];
+ for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
+ var type = types_2[_i];
var indexInfo = getIndexInfoOfType(type, kind);
if (!indexInfo) {
return undefined;
@@ -28150,22 +30269,57 @@ var ts;
function unionSpreadIndexInfos(info1, info2) {
return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
}
+ function includeMixinType(type, types, index) {
+ var mixedTypes = [];
+ for (var i = 0; i < types.length; i++) {
+ if (i === index) {
+ mixedTypes.push(type);
+ }
+ else if (isMixinConstructorType(types[i])) {
+ mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
+ }
+ }
+ return getIntersectionType(mixedTypes);
+ }
function resolveIntersectionTypeMembers(type) {
// The members and properties collections are empty for intersection types. To get all properties of an
// intersection type use getPropertiesOfType (only the language service uses this).
var callSignatures = emptyArray;
var constructSignatures = emptyArray;
- var stringIndexInfo = undefined;
- var numberIndexInfo = undefined;
- for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
- var t = _a[_i];
+ var stringIndexInfo;
+ var numberIndexInfo;
+ var types = type.types;
+ var mixinCount = ts.countWhere(types, isMixinConstructorType);
+ var _loop_3 = function (i) {
+ var t = type.types[i];
+ // When an intersection type contains mixin constructor types, the construct signatures from
+ // those types are discarded and their return types are mixed into the return types of all
+ // other construct signatures in the intersection type. For example, the intersection type
+ // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
+ // 'new(s: string) => A & B'.
+ if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) {
+ var signatures = getSignaturesOfType(t, 1 /* Construct */);
+ if (signatures.length && mixinCount > 0) {
+ signatures = ts.map(signatures, function (s) {
+ var clone = cloneSignature(s);
+ clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i);
+ return clone;
+ });
+ }
+ constructSignatures = ts.concatenate(constructSignatures, signatures);
+ }
callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */));
- constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(t, 1 /* Construct */));
stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
+ };
+ for (var i = 0; i < types.length; i++) {
+ _loop_3(i);
}
setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
}
+ /**
+ * Converts an AnonymousType to a ResolvedType.
+ */
function resolveAnonymousTypeMembers(type) {
var symbol = type.symbol;
if (type.target) {
@@ -28178,8 +30332,8 @@ var ts;
}
else if (symbol.flags & 2048 /* TypeLiteral */) {
var members = symbol.members;
- var callSignatures = getSignaturesOfSymbol(members["__call"]);
- var constructSignatures = getSignaturesOfSymbol(members["__new"]);
+ var callSignatures = getSignaturesOfSymbol(members.get("__call"));
+ var constructSignatures = getSignaturesOfSymbol(members.get("__new"));
var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
@@ -28188,23 +30342,27 @@ var ts;
// Combinations of function, class, enum and module
var members = emptySymbols;
var constructSignatures = emptyArray;
- if (symbol.flags & 1952 /* HasExports */) {
+ var stringIndexInfo = undefined;
+ if (symbol.exports) {
members = getExportsOfSymbol(symbol);
}
if (symbol.flags & 32 /* Class */) {
var classType = getDeclaredTypeOfClassOrInterface(symbol);
- constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]);
+ constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor"));
if (!constructSignatures.length) {
constructSignatures = getDefaultConstructSignatures(classType);
}
var baseConstructorType = getBaseConstructorTypeOfClass(classType);
- if (baseConstructorType.flags & 32768 /* Object */) {
+ if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 540672 /* TypeVariable */)) {
members = createSymbolTable(getNamedMembers(members));
- addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType));
+ addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
+ }
+ else if (baseConstructorType === anyType) {
+ stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
}
}
var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined;
- setStructuredTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexInfo);
+ setStructuredTypeMembers(type, members, emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo);
// We resolve the members before computing the signatures because a signature may use
// typeof with a qualified name expression that circularly references the type we are
// in the process of resolving (see issue #6072). The temporarily empty signature list
@@ -28218,7 +30376,6 @@ var ts;
function resolveMappedTypeMembers(type) {
var members = ts.createMap();
var stringIndexInfo;
- var numberIndexInfo;
// Resolve upfront such that recursive references see an empty object type.
setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined);
// In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
@@ -28226,43 +30383,53 @@ var ts;
var typeParameter = getTypeParameterFromMappedType(type);
var constraintType = getConstraintTypeFromMappedType(type);
var templateType = getTemplateTypeFromMappedType(type);
- var isReadonly = !!type.declaration.readonlyToken;
- var isOptional = !!type.declaration.questionToken;
- // First, if the constraint type is a type parameter, obtain the base constraint. Then,
- // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X.
- // Finally, iterate over the constituents of the resulting iteration type.
- var keyType = constraintType.flags & 16384 /* TypeParameter */ ? getApparentType(constraintType) : constraintType;
- var iterationType = keyType.flags & 262144 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType;
- forEachType(iterationType, function (t) {
+ var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
+ var templateReadonly = !!type.declaration.readonlyToken;
+ var templateOptional = !!type.declaration.questionToken;
+ if (type.declaration.typeParameter.constraint.kind === 169 /* TypeOperator */) {
+ // We have a { [P in keyof T]: X }
+ for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
+ var propertySymbol = _a[_i];
+ addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol);
+ }
+ if (getIndexInfoOfType(modifiersType, 0 /* String */)) {
+ addMemberForKeyType(stringType);
+ }
+ }
+ else {
+ // First, if the constraint type is a type parameter, obtain the base constraint. Then,
+ // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X.
+ // Finally, iterate over the constituents of the resulting iteration type.
+ var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentType(constraintType) : constraintType;
+ var iterationType = keyType.flags & 262144 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType;
+ forEachType(iterationType, addMemberForKeyType);
+ }
+ setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined);
+ function addMemberForKeyType(t, propertySymbol) {
// Create a mapper from T to the current iteration type constituent. Then, if the
// mapped type is itself an instantiated type, combine the iteration mapper with the
// instantiation mapper.
- var iterationMapper = createUnaryTypeMapper(typeParameter, t);
+ var iterationMapper = createTypeMapper([typeParameter], [t]);
var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper;
var propType = instantiateType(templateType, templateMapper);
- // If the current iteration type constituent is a literal type, create a property.
- // Otherwise, for type string create a string index signature and for type number
- // create a numeric index signature.
- if (t.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */ | 256 /* EnumLiteral */)) {
+ // If the current iteration type constituent is a string literal type, create a property.
+ // Otherwise, for type string create a string index signature.
+ if (t.flags & 32 /* StringLiteral */) {
var propName = t.text;
- var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | (isOptional ? 536870912 /* Optional */ : 0), propName);
- prop.type = addOptionality(propType, isOptional);
- prop.isReadonly = isReadonly;
- members[propName] = prop;
+ var modifiersProp = getPropertyOfType(modifiersType, propName);
+ var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */);
+ var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName);
+ prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 /* Readonly */ : 0;
+ prop.type = propType;
+ if (propertySymbol) {
+ prop.syntheticOrigin = propertySymbol;
+ }
+ members.set(propName, prop);
}
else if (t.flags & 2 /* String */) {
- stringIndexInfo = createIndexInfo(propType, isReadonly);
- }
- else if (t.flags & 4 /* Number */) {
- numberIndexInfo = createIndexInfo(propType, isReadonly);
+ stringIndexInfo = createIndexInfo(propType, templateReadonly);
}
- });
- // If we created both a string and a numeric string index signature, and if the two index
- // signatures have identical types, discard the redundant numeric index signature.
- if (stringIndexInfo && numberIndexInfo && isTypeIdenticalTo(stringIndexInfo.type, numberIndexInfo.type)) {
- numberIndexInfo = undefined;
}
- setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo);
}
function getTypeParameterFromMappedType(type) {
return type.typeParameter ||
@@ -28275,16 +30442,34 @@ var ts;
function getTemplateTypeFromMappedType(type) {
return type.templateType ||
(type.templateType = type.declaration.type ?
- instantiateType(getTypeFromTypeNode(type.declaration.type), type.mapper || identityMapper) :
+ instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) :
unknownType);
}
- function getErasedTemplateTypeFromMappedType(type) {
- return instantiateType(getTemplateTypeFromMappedType(type), createUnaryTypeMapper(getTypeParameterFromMappedType(type), anyType));
+ function getModifiersTypeFromMappedType(type) {
+ if (!type.modifiersType) {
+ var constraintDeclaration = type.declaration.typeParameter.constraint;
+ if (constraintDeclaration.kind === 169 /* TypeOperator */) {
+ // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
+ // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
+ // 'keyof T' to a literal union type and we can't recover T from that type.
+ type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper);
+ }
+ else {
+ // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
+ // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
+ // the modifiers type is T. Otherwise, the modifiers type is {}.
+ var declaredType = getTypeFromMappedTypeNode(type.declaration);
+ var constraint = getConstraintTypeFromMappedType(declaredType);
+ var extendedConstraint = constraint && constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
+ type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType;
+ }
+ }
+ return type.modifiersType;
}
function isGenericMappedType(type) {
if (getObjectFlags(type) & 32 /* Mapped */) {
var constraintType = getConstraintTypeFromMappedType(type);
- return !!(constraintType.flags & (16384 /* TypeParameter */ | 262144 /* Index */));
+ return maybeTypeOfKind(constraintType, 540672 /* TypeVariable */ | 262144 /* Index */);
}
return false;
}
@@ -28321,42 +30506,40 @@ var ts;
return emptyArray;
}
/** If the given type is an object type and that type has a property by the given name,
- * return the symbol for that property. Otherwise return undefined. */
+ * return the symbol for that property. Otherwise return undefined.
+ */
function getPropertyOfObjectType(type, name) {
if (type.flags & 32768 /* Object */) {
var resolved = resolveStructuredTypeMembers(type);
- var symbol = resolved.members[name];
+ var symbol = resolved.members.get(name);
if (symbol && symbolIsValue(symbol)) {
return symbol;
}
}
}
function getPropertiesOfUnionOrIntersectionType(type) {
- for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
- var current = _a[_i];
- for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
- var prop = _c[_b];
- getUnionOrIntersectionProperty(type, prop.name);
- }
- // The properties of a union type are those that are present in all constituent types, so
- // we only need to check the properties of the first type
- if (type.flags & 65536 /* Union */) {
- break;
- }
- }
- var props = type.resolvedProperties;
- if (props) {
- var result = [];
- for (var key in props) {
- var prop = props[key];
- // We need to filter out partial properties in union types
- if (!(prop.flags & 268435456 /* SyntheticProperty */ && prop.isPartial)) {
- result.push(prop);
+ if (!type.resolvedProperties) {
+ var members = ts.createMap();
+ for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
+ var current = _a[_i];
+ for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
+ var prop = _c[_b];
+ if (!members.has(prop.name)) {
+ var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.name);
+ if (combinedProp) {
+ members.set(prop.name, combinedProp);
+ }
+ }
+ }
+ // The properties of a union type are those that are present in all constituent types, so
+ // we only need to check the properties of the first type
+ if (type.flags & 65536 /* Union */) {
+ break;
}
}
- return result;
+ type.resolvedProperties = getNamedMembers(members);
}
- return emptyArray;
+ return type.resolvedProperties;
}
function getPropertiesOfType(type) {
type = getApparentType(type);
@@ -28364,25 +30547,114 @@ var ts;
getPropertiesOfUnionOrIntersectionType(type) :
getPropertiesOfObjectType(type);
}
+ function getConstraintOfType(type) {
+ return type.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
+ type.flags & 524288 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
+ getBaseConstraintOfType(type);
+ }
+ function getConstraintOfTypeParameter(typeParameter) {
+ return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
+ }
+ function getConstraintOfIndexedAccess(type) {
+ var baseObjectType = getBaseConstraintOfType(type.objectType);
+ var baseIndexType = getBaseConstraintOfType(type.indexType);
+ return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined;
+ }
+ function getBaseConstraintOfType(type) {
+ if (type.flags & (540672 /* TypeVariable */ | 196608 /* UnionOrIntersection */)) {
+ var constraint = getResolvedBaseConstraint(type);
+ if (constraint !== noConstraintType && constraint !== circularConstraintType) {
+ return constraint;
+ }
+ }
+ else if (type.flags & 262144 /* Index */) {
+ return stringType;
+ }
+ return undefined;
+ }
+ function hasNonCircularBaseConstraint(type) {
+ return getResolvedBaseConstraint(type) !== circularConstraintType;
+ }
/**
- * The apparent type of a type parameter is the base constraint instantiated with the type parameter
- * as the type argument for the 'this' type.
+ * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
+ * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
+ * circularly references the type variable.
*/
- function getApparentTypeOfTypeParameter(type) {
- if (!type.resolvedApparentType) {
- var constraintType = getConstraintOfTypeParameter(type);
- while (constraintType && constraintType.flags & 16384 /* TypeParameter */) {
- constraintType = getConstraintOfTypeParameter(constraintType);
+ function getResolvedBaseConstraint(type) {
+ var typeStack;
+ var circular;
+ if (!type.resolvedBaseConstraint) {
+ typeStack = [];
+ var constraint = getBaseConstraint(type);
+ type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type);
+ }
+ return type.resolvedBaseConstraint;
+ function getBaseConstraint(t) {
+ if (ts.contains(typeStack, t)) {
+ circular = true;
+ return undefined;
+ }
+ typeStack.push(t);
+ var result = computeBaseConstraint(t);
+ typeStack.pop();
+ return result;
+ }
+ function computeBaseConstraint(t) {
+ if (t.flags & 16384 /* TypeParameter */) {
+ var constraint = getConstraintFromTypeParameter(t);
+ return t.isThisType ? constraint :
+ constraint ? getBaseConstraint(constraint) : undefined;
+ }
+ if (t.flags & 196608 /* UnionOrIntersection */) {
+ var types = t.types;
+ var baseTypes = [];
+ for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
+ var type_2 = types_3[_i];
+ var baseType = getBaseConstraint(type_2);
+ if (baseType) {
+ baseTypes.push(baseType);
+ }
+ }
+ return t.flags & 65536 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
+ t.flags & 131072 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
+ undefined;
}
- type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type);
+ if (t.flags & 262144 /* Index */) {
+ return stringType;
+ }
+ if (t.flags & 524288 /* IndexedAccess */) {
+ var baseObjectType = getBaseConstraint(t.objectType);
+ var baseIndexType = getBaseConstraint(t.indexType);
+ var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined;
+ return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined;
+ }
+ return t;
}
- return type.resolvedApparentType;
+ }
+ function getApparentTypeOfIntersectionType(type) {
+ return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type));
}
/**
- * The apparent type of an indexed access T[K] is the type of T's string index signature, if any.
+ * Gets the default type for a type parameter.
+ *
+ * If the type parameter is the result of an instantiation, this gets the instantiated
+ * default type of its target. If the type parameter has no default type, `undefined`
+ * is returned.
+ *
+ * This function *does not* perform a circularity check.
*/
- function getApparentTypeOfIndexedAccess(type) {
- return getIndexTypeOfType(getApparentType(type.objectType), 0 /* String */) || type;
+ function getDefaultFromTypeParameter(typeParameter) {
+ if (!typeParameter.default) {
+ if (typeParameter.target) {
+ var targetDefault = getDefaultFromTypeParameter(typeParameter.target);
+ typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
+ }
+ else {
+ var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameter(decl) && decl.default; });
+ typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
+ }
+ }
+ return typeParameter.default === noConstraintType ? undefined : typeParameter.default;
}
/**
* For a type parameter, return the base constraint of the type parameter. For the string, number,
@@ -28390,28 +30662,31 @@ var ts;
* type itself. Note that the apparent type of a union type is the union type itself.
*/
function getApparentType(type) {
- var t = type.flags & 16384 /* TypeParameter */ ? getApparentTypeOfTypeParameter(type) :
- type.flags & 524288 /* IndexedAccess */ ? getApparentTypeOfIndexedAccess(type) :
- type;
- return t.flags & 262178 /* StringLike */ ? globalStringType :
- t.flags & 340 /* NumberLike */ ? globalNumberType :
- t.flags & 136 /* BooleanLike */ ? globalBooleanType :
- t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType() :
- t;
+ var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type;
+ return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
+ t.flags & 262178 /* StringLike */ ? globalStringType :
+ t.flags & 340 /* NumberLike */ ? globalNumberType :
+ t.flags & 136 /* BooleanLike */ ? globalBooleanType :
+ t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
+ t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType :
+ t;
}
function createUnionOrIntersectionProperty(containingType, name) {
- var types = containingType.types;
var props;
+ var types = containingType.types;
+ var isUnion = containingType.flags & 65536 /* Union */;
+ var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0;
// Flags we want to propagate to the result if they exist in all source symbols
- var commonFlags = (containingType.flags & 131072 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */;
- var isReadonly = false;
- var isPartial = false;
- for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
- var current = types_2[_i];
+ var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */;
+ var syntheticFlag = 4 /* SyntheticMethod */;
+ var checkFlags = 0;
+ for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
+ var current = types_4[_i];
var type = getApparentType(current);
if (type !== unknownType) {
var prop = getPropertyOfType(type, name);
- if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))) {
+ var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0;
+ if (prop && !(modifiers & excludeModifiers)) {
commonFlags &= prop.flags;
if (!props) {
props = [prop];
@@ -28419,25 +30694,29 @@ var ts;
else if (!ts.contains(props, prop)) {
props.push(prop);
}
- if (isReadonlySymbol(prop)) {
- isReadonly = true;
+ checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
+ (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) |
+ (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) |
+ (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) |
+ (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0);
+ if (!isMethodLike(prop)) {
+ syntheticFlag = 2 /* SyntheticProperty */;
}
}
- else if (containingType.flags & 65536 /* Union */) {
- isPartial = true;
+ else if (isUnion) {
+ checkFlags |= 16 /* Partial */;
}
}
}
if (!props) {
return undefined;
}
- if (props.length === 1 && !isPartial) {
+ if (props.length === 1 && !(checkFlags & 16 /* Partial */)) {
return props[0];
}
var propTypes = [];
var declarations = [];
var commonType = undefined;
- var hasNonUniformType = false;
for (var _a = 0, props_1 = props; _a < props_1.length; _a++) {
var prop = props_1[_a];
if (prop.declarations) {
@@ -28448,17 +30727,15 @@ var ts;
commonType = type;
}
else if (type !== commonType) {
- hasNonUniformType = true;
+ checkFlags |= 32 /* HasNonUniformType */;
}
propTypes.push(type);
}
- var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */ | commonFlags, name);
+ var result = createSymbol(4 /* Property */ | commonFlags, name);
+ result.checkFlags = syntheticFlag | checkFlags;
result.containingType = containingType;
- result.hasNonUniformType = hasNonUniformType;
- result.isPartial = isPartial;
result.declarations = declarations;
- result.isReadonly = isReadonly;
- result.type = containingType.flags & 65536 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes);
+ result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
return result;
}
// Return the symbol for a given property in a union or intersection type, or undefined if the property
@@ -28467,12 +30744,12 @@ var ts;
// these partial properties when identifying discriminant properties, but otherwise they are filtered out
// and do not appear to be present in the union type.
function getUnionOrIntersectionProperty(type, name) {
- var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap());
- var property = properties[name];
+ var properties = type.propertyCache || (type.propertyCache = ts.createMap());
+ var property = properties.get(name);
if (!property) {
property = createUnionOrIntersectionProperty(type, name);
if (property) {
- properties[name] = property;
+ properties.set(name, property);
}
}
return property;
@@ -28480,7 +30757,7 @@ var ts;
function getPropertyOfUnionOrIntersectionType(type, name) {
var property = getUnionOrIntersectionProperty(type, name);
// We need to filter out partial properties in union types
- return property && !(property.flags & 268435456 /* SyntheticProperty */ && property.isPartial) ? property : undefined;
+ return property && !(getCheckFlags(property) & 16 /* Partial */) ? property : undefined;
}
/**
* Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
@@ -28494,7 +30771,7 @@ var ts;
type = getApparentType(type);
if (type.flags & 32768 /* Object */) {
var resolved = resolveStructuredTypeMembers(type);
- var symbol = resolved.members[name];
+ var symbol = resolved.members.get(name);
if (symbol && symbolIsValue(symbol)) {
return symbol;
}
@@ -28561,7 +30838,7 @@ var ts;
return undefined;
}
function getTypeParametersFromJSDocTemplate(declaration) {
- if (declaration.flags & 2097152 /* JavaScriptFile */) {
+ if (declaration.flags & 65536 /* JavaScriptFile */) {
var templateTag = ts.getJSDocTemplateTag(declaration);
if (templateTag) {
return getTypeParametersFromDeclaration(templateTag.typeParameters);
@@ -28583,16 +30860,16 @@ var ts;
}
function symbolsToArray(symbols) {
var result = [];
- for (var id in symbols) {
+ symbols.forEach(function (symbol, id) {
if (!isReservedMemberName(id)) {
- result.push(symbols[id]);
+ result.push(symbol);
}
- }
+ });
return result;
}
function isJSDocOptionalParameter(node) {
- if (node.flags & 2097152 /* JavaScriptFile */) {
- if (node.type && node.type.kind === 273 /* JSDocOptionalType */) {
+ if (node.flags & 65536 /* JavaScriptFile */) {
+ if (node.type && node.type.kind === 277 /* JSDocOptionalType */) {
return true;
}
var paramTags = ts.getJSDocParameterTags(node);
@@ -28603,7 +30880,7 @@ var ts;
return true;
}
if (paramTag.typeExpression) {
- return paramTag.typeExpression.type.kind === 273 /* JSDocOptionalType */;
+ return paramTag.typeExpression.type.kind === 277 /* JSDocOptionalType */;
}
}
}
@@ -28628,6 +30905,12 @@ var ts;
ts.Debug.assert(parameterIndex >= 0);
return parameterIndex >= signature.minArgumentCount;
}
+ var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
+ if (iife) {
+ return !node.type &&
+ !node.dotDotDotToken &&
+ ts.indexOf(node.parent.parameters, node) >= iife.arguments.length;
+ }
return false;
}
function createTypePredicateFromTypePredicateNode(node) {
@@ -28647,19 +30930,68 @@ var ts;
};
}
}
+ /**
+ * Gets the minimum number of type arguments needed to satisfy all non-optional type
+ * parameters.
+ */
+ function getMinTypeArgumentCount(typeParameters) {
+ var minTypeArgumentCount = 0;
+ if (typeParameters) {
+ for (var i = 0; i < typeParameters.length; i++) {
+ if (!getDefaultFromTypeParameter(typeParameters[i])) {
+ minTypeArgumentCount = i + 1;
+ }
+ }
+ }
+ return minTypeArgumentCount;
+ }
+ /**
+ * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined
+ * when a default type is supplied, a new array will be created and returned.
+ *
+ * @param typeArguments The supplied type arguments.
+ * @param typeParameters The requested type parameters.
+ * @param minTypeArgumentCount The minimum number of required type arguments.
+ */
+ function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) {
+ var numTypeParameters = ts.length(typeParameters);
+ if (numTypeParameters) {
+ var numTypeArguments = ts.length(typeArguments);
+ var isJavaScript = ts.isInJavaScriptFile(location);
+ if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) {
+ if (!typeArguments) {
+ typeArguments = [];
+ }
+ // Map an unsatisfied type parameter with a default type.
+ // If a type parameter does not have a default type, or if the default type
+ // is a forward reference, the empty object type is used.
+ for (var i = numTypeArguments; i < numTypeParameters; i++) {
+ typeArguments[i] = isJavaScript ? anyType : emptyObjectType;
+ }
+ for (var i = numTypeArguments; i < numTypeParameters; i++) {
+ var mapper = createTypeMapper(typeParameters, typeArguments);
+ var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
+ typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : isJavaScript ? anyType : emptyObjectType;
+ }
+ }
+ }
+ return typeArguments;
+ }
function getSignatureFromDeclaration(declaration) {
var links = getNodeLinks(declaration);
if (!links.resolvedSignature) {
var parameters = [];
var hasLiteralTypes = false;
- var minArgumentCount = -1;
+ var minArgumentCount = 0;
var thisParameter = undefined;
var hasThisParameter = void 0;
+ var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
+ var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration);
// If this is a JSDoc construct signature, then skip the first parameter in the
// parameter list. The first parameter represents the return type of the construct
// signature.
- for (var i = isJSConstructSignature ? 1 : 0, n = declaration.parameters.length; i < n; i++) {
+ for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
var param = declaration.parameters[i];
var paramSymbol = param.symbol;
// Include parameter symbol instead of property symbol in the signature
@@ -28674,43 +31006,36 @@ var ts;
else {
parameters.push(paramSymbol);
}
- if (param.type && param.type.kind === 171 /* LiteralType */) {
+ if (param.type && param.type.kind === 172 /* LiteralType */) {
hasLiteralTypes = true;
}
- if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
- if (minArgumentCount < 0) {
- minArgumentCount = i - (hasThisParameter ? 1 : 0);
- }
- }
- else {
- // If we see any required parameters, it means the prior ones were not in fact optional.
- minArgumentCount = -1;
+ // Record a new minimum argument count if this is not an optional parameter
+ var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken ||
+ iife && parameters.length > iife.arguments.length && !param.type ||
+ isJSDocOptionalParameter(param) ||
+ isUntypedSignatureInJSFile;
+ if (!isOptionalParameter_1) {
+ minArgumentCount = parameters.length;
}
}
// If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
- if ((declaration.kind === 151 /* GetAccessor */ || declaration.kind === 152 /* SetAccessor */) &&
+ if ((declaration.kind === 152 /* GetAccessor */ || declaration.kind === 153 /* SetAccessor */) &&
!ts.hasDynamicName(declaration) &&
(!hasThisParameter || !thisParameter)) {
- var otherKind = declaration.kind === 151 /* GetAccessor */ ? 152 /* SetAccessor */ : 151 /* GetAccessor */;
+ var otherKind = declaration.kind === 152 /* GetAccessor */ ? 153 /* SetAccessor */ : 152 /* GetAccessor */;
var other = ts.getDeclarationOfKind(declaration.symbol, otherKind);
if (other) {
thisParameter = getAnnotatedAccessorThisParameter(other);
}
}
- if (minArgumentCount < 0) {
- minArgumentCount = declaration.parameters.length - (hasThisParameter ? 1 : 0);
- }
- if (isJSConstructSignature) {
- minArgumentCount--;
- }
- var classType = declaration.kind === 150 /* Constructor */ ?
+ var classType = declaration.kind === 151 /* Constructor */ ?
getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
: undefined;
var typeParameters = classType ? classType.localTypeParameters :
declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) :
getTypeParametersFromJSDocTemplate(declaration);
var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType);
- var typePredicate = declaration.type && declaration.type.kind === 156 /* TypePredicate */ ?
+ var typePredicate = declaration.type && declaration.type.kind === 157 /* TypePredicate */ ?
createTypePredicateFromTypePredicateNode(declaration.type) :
undefined;
links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes);
@@ -28727,7 +31052,7 @@ var ts;
else if (declaration.type) {
return getTypeFromTypeNode(declaration.type);
}
- if (declaration.flags & 2097152 /* JavaScriptFile */) {
+ if (declaration.flags & 65536 /* JavaScriptFile */) {
var type = getReturnTypeFromJSDocComment(declaration);
if (type && type !== unknownType) {
return type;
@@ -28735,35 +31060,63 @@ var ts;
}
// TypeScript 1.0 spec (April 2014):
// If only one accessor includes a type annotation, the other behaves as if it had the same type annotation.
- if (declaration.kind === 151 /* GetAccessor */ && !ts.hasDynamicName(declaration)) {
- var setter = ts.getDeclarationOfKind(declaration.symbol, 152 /* SetAccessor */);
+ if (declaration.kind === 152 /* GetAccessor */ && !ts.hasDynamicName(declaration)) {
+ var setter = ts.getDeclarationOfKind(declaration.symbol, 153 /* SetAccessor */);
return getAnnotatedAccessorType(setter);
}
if (ts.nodeIsMissing(declaration.body)) {
return anyType;
}
}
+ function containsArgumentsReference(declaration) {
+ var links = getNodeLinks(declaration);
+ if (links.containsArgumentsReference === undefined) {
+ if (links.flags & 8192 /* CaptureArguments */) {
+ links.containsArgumentsReference = true;
+ }
+ else {
+ links.containsArgumentsReference = traverse(declaration.body);
+ }
+ }
+ return links.containsArgumentsReference;
+ function traverse(node) {
+ if (!node)
+ return false;
+ switch (node.kind) {
+ case 70 /* Identifier */:
+ return node.text === "arguments" && ts.isPartOfExpression(node);
+ case 148 /* PropertyDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ return node.name.kind === 143 /* ComputedPropertyName */
+ && traverse(node.name);
+ default:
+ return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse);
+ }
+ }
+ }
function getSignaturesOfSymbol(symbol) {
if (!symbol)
return emptyArray;
var result = [];
- for (var i = 0, len = symbol.declarations.length; i < len; i++) {
+ for (var i = 0; i < symbol.declarations.length; i++) {
var node = symbol.declarations[i];
switch (node.kind) {
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
- case 225 /* FunctionDeclaration */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 274 /* JSDocFunctionType */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
+ case 227 /* FunctionDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 278 /* JSDocFunctionType */:
// Don't include signature if node is the implementation of an overloaded function. A node is considered
// an implementation node if it has a body and the previous node is of the same kind and immediately
// precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
@@ -28810,7 +31163,7 @@ var ts;
}
if (!popTypeResolution()) {
type = anyType;
- if (compilerOptions.noImplicitAny) {
+ if (noImplicitAny) {
var declaration = signature.declaration;
if (declaration.name) {
error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name));
@@ -28834,9 +31187,14 @@ var ts;
return anyType;
}
function getSignatureInstantiation(signature, typeArguments) {
+ typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters));
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
var id = getTypeListId(typeArguments);
- return instantiations[id] || (instantiations[id] = createSignatureInstantiation(signature, typeArguments));
+ var instantiation = instantiations.get(id);
+ if (!instantiation) {
+ instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
+ }
+ return instantiation;
}
function createSignatureInstantiation(signature, typeArguments) {
return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true);
@@ -28855,7 +31213,7 @@ var ts;
// object type literal or interface (using the new keyword). Each way of declaring a constructor
// will result in a different declaration kind.
if (!signature.isolatedSignatureType) {
- var isConstructor = signature.declaration.kind === 150 /* Constructor */ || signature.declaration.kind === 154 /* ConstructSignature */;
+ var isConstructor = signature.declaration.kind === 151 /* Constructor */ || signature.declaration.kind === 155 /* ConstructSignature */;
var type = createObjectType(16 /* Anonymous */);
type.members = emptySymbols;
type.properties = emptyArray;
@@ -28866,10 +31224,10 @@ var ts;
return signature.isolatedSignatureType;
}
function getIndexSymbol(symbol) {
- return symbol.members["__index"];
+ return symbol.members.get("__index");
}
function getIndexDeclarationOfSymbol(symbol, kind) {
- var syntaxKind = kind === 1 /* Number */ ? 132 /* NumberKeyword */ : 134 /* StringKeyword */;
+ var syntaxKind = kind === 1 /* Number */ ? 132 /* NumberKeyword */ : 135 /* StringKeyword */;
var indexSymbol = getIndexSymbol(symbol);
if (indexSymbol) {
for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
@@ -28896,21 +31254,9 @@ var ts;
return undefined;
}
function getConstraintDeclaration(type) {
- return ts.getDeclarationOfKind(type.symbol, 143 /* TypeParameter */).constraint;
+ return ts.getDeclarationOfKind(type.symbol, 144 /* TypeParameter */).constraint;
}
- function hasConstraintReferenceTo(type, target) {
- var checked;
- while (type && type.flags & 16384 /* TypeParameter */ && !(type.isThisType) && !ts.contains(checked, type)) {
- if (type === target) {
- return true;
- }
- (checked || (checked = [])).push(type);
- var constraintDeclaration = getConstraintDeclaration(type);
- type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration);
- }
- return false;
- }
- function getConstraintOfTypeParameter(typeParameter) {
+ function getConstraintFromTypeParameter(typeParameter) {
if (!typeParameter.constraint) {
if (typeParameter.target) {
var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
@@ -28918,28 +31264,23 @@ var ts;
}
else {
var constraintDeclaration = getConstraintDeclaration(typeParameter);
- var constraint = getTypeFromTypeNode(constraintDeclaration);
- if (hasConstraintReferenceTo(constraint, typeParameter)) {
- error(constraintDeclaration, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter));
- constraint = unknownType;
- }
- typeParameter.constraint = constraint;
+ typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType;
}
}
return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
}
function getParentSymbolOfTypeParameter(typeParameter) {
- return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 143 /* TypeParameter */).parent);
+ return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 144 /* TypeParameter */).parent);
}
function getTypeListId(types) {
var result = "";
if (types) {
- var length_3 = types.length;
+ var length_4 = types.length;
var i = 0;
- while (i < length_3) {
+ while (i < length_4) {
var startId = types[i].id;
var count = 1;
- while (i + count < length_3 && types[i + count].id === startId + count) {
+ while (i + count < length_4 && types[i + count].id === startId + count) {
count++;
}
if (result.length) {
@@ -28960,8 +31301,8 @@ var ts;
// that care about the presence of such types at arbitrary depth in a containing type.
function getPropagatingFlagsOfTypes(types, excludeKinds) {
var result = 0;
- for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
- var type = types_3[_i];
+ for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
+ var type = types_5[_i];
if (!(type.flags & excludeKinds)) {
result |= type.flags;
}
@@ -28970,9 +31311,10 @@ var ts;
}
function createTypeReference(target, typeArguments) {
var id = getTypeListId(typeArguments);
- var type = target.instantiations[id];
+ var type = target.instantiations.get(id);
if (!type) {
- type = target.instantiations[id] = createObjectType(4 /* Reference */, target.symbol);
+ type = createObjectType(4 /* Reference */, target.symbol);
+ target.instantiations.set(id, type);
type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
type.target = target;
type.typeArguments = typeArguments;
@@ -28988,21 +31330,26 @@ var ts;
return type;
}
function getTypeReferenceArity(type) {
- return type.target.typeParameters ? type.target.typeParameters.length : 0;
+ return ts.length(type.target.typeParameters);
}
// Get type from reference to class or interface
function getTypeFromClassOrInterfaceReference(node, symbol) {
var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
var typeParameters = type.localTypeParameters;
if (typeParameters) {
- if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) {
- error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), typeParameters.length);
+ var numTypeArguments = ts.length(node.typeArguments);
+ var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
+ if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
+ error(node, minTypeArgumentCount === typeParameters.length
+ ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s
+ : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), minTypeArgumentCount, typeParameters.length);
return unknownType;
}
// In a type reference, the outer type parameters of the referenced class or interface are automatically
// supplied as type arguments and the type reference only specifies arguments for the local type parameters
// of the class or interface.
- return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode)));
+ var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node));
+ return createTypeReference(type, typeArguments);
}
if (node.typeArguments) {
error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type));
@@ -29015,7 +31362,11 @@ var ts;
var links = getSymbolLinks(symbol);
var typeParameters = links.typeParameters;
var id = getTypeListId(typeArguments);
- return links.instantiations[id] || (links.instantiations[id] = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, typeArguments)));
+ var instantiation = links.instantiations.get(id);
+ if (!instantiation) {
+ links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters)))));
+ }
+ return instantiation;
}
// Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
// references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
@@ -29024,8 +31375,12 @@ var ts;
var type = getDeclaredTypeOfSymbol(symbol);
var typeParameters = getSymbolLinks(symbol).typeParameters;
if (typeParameters) {
- if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) {
- error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length);
+ var numTypeArguments = ts.length(node.typeArguments);
+ var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
+ if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
+ error(node, minTypeArgumentCount === typeParameters.length
+ ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s
+ : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
return unknownType;
}
var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode);
@@ -29047,11 +31402,11 @@ var ts;
}
function getTypeReferenceName(node) {
switch (node.kind) {
- case 157 /* TypeReference */:
+ case 158 /* TypeReference */:
return node.typeName;
- case 272 /* JSDocTypeReference */:
+ case 276 /* JSDocTypeReference */:
return node.name;
- case 199 /* ExpressionWithTypeArguments */:
+ case 200 /* ExpressionWithTypeArguments */:
// We only support expressions that are simple qualified names. For other
// expressions this produces undefined.
var expr = node.expression;
@@ -29077,7 +31432,7 @@ var ts;
if (symbol.flags & 524288 /* TypeAlias */) {
return getTypeFromTypeAliasReference(node, symbol);
}
- if (symbol.flags & 107455 /* Value */ && node.kind === 272 /* JSDocTypeReference */) {
+ if (symbol.flags & 107455 /* Value */ && node.kind === 276 /* JSDocTypeReference */) {
// A JSDocTypeReference may have resolved to a value (as opposed to a type). In
// that case, the type of this reference is just the type of the value we resolved
// to.
@@ -29085,19 +31440,54 @@ var ts;
}
return getTypeFromNonGenericTypeReference(node, symbol);
}
+ function getPrimitiveTypeFromJSDocTypeReference(node) {
+ if (ts.isIdentifier(node.name)) {
+ switch (node.name.text) {
+ case "String":
+ return stringType;
+ case "Number":
+ return numberType;
+ case "Boolean":
+ return booleanType;
+ case "Void":
+ return voidType;
+ case "Undefined":
+ return undefinedType;
+ case "Null":
+ return nullType;
+ case "Object":
+ return anyType;
+ case "Function":
+ return anyFunctionType;
+ case "Array":
+ case "array":
+ return !node.typeArguments || !node.typeArguments.length ? createArrayType(anyType) : undefined;
+ case "Promise":
+ case "promise":
+ return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined;
+ }
+ }
+ }
+ function getTypeFromJSDocNullableTypeNode(node) {
+ var type = getTypeFromTypeNode(node.type);
+ return strictNullChecks ? getUnionType([type, nullType]) : type;
+ }
function getTypeFromTypeReference(node) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
var symbol = void 0;
var type = void 0;
- if (node.kind === 272 /* JSDocTypeReference */) {
- var typeReferenceName = getTypeReferenceName(node);
- symbol = resolveTypeReferenceName(typeReferenceName);
- type = getTypeReferenceType(node, symbol);
+ if (node.kind === 276 /* JSDocTypeReference */) {
+ type = getPrimitiveTypeFromJSDocTypeReference(node);
+ if (!type) {
+ var typeReferenceName = getTypeReferenceName(node);
+ symbol = resolveTypeReferenceName(typeReferenceName);
+ type = getTypeReferenceType(node, symbol);
+ }
}
else {
// We only support expressions that are simple qualified names. For other expressions this produces undefined.
- var typeNameOrExpression = node.kind === 157 /* TypeReference */
+ var typeNameOrExpression = node.kind === 158 /* TypeReference */
? node.typeName
: ts.isEntityNameExpression(node.expression)
? node.expression
@@ -29129,12 +31519,12 @@ var ts;
function getTypeOfGlobalSymbol(symbol, arity) {
function getTypeDeclaration(symbol) {
var declarations = symbol.declarations;
- for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
- var declaration = declarations_3[_i];
+ for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
+ var declaration = declarations_4[_i];
switch (declaration.kind) {
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 229 /* EnumDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 231 /* EnumDeclaration */:
return declaration;
}
}
@@ -29147,24 +31537,68 @@ var ts;
error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name);
return arity ? emptyGenericType : emptyObjectType;
}
- if ((type.typeParameters ? type.typeParameters.length : 0) !== arity) {
+ if (ts.length(type.typeParameters) !== arity) {
error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity);
return arity ? emptyGenericType : emptyObjectType;
}
return type;
}
- function getGlobalValueSymbol(name) {
- return getGlobalSymbol(name, 107455 /* Value */, ts.Diagnostics.Cannot_find_global_value_0);
+ function getGlobalValueSymbol(name, reportErrors) {
+ return getGlobalSymbol(name, 107455 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
}
- function getGlobalTypeSymbol(name) {
- return getGlobalSymbol(name, 793064 /* Type */, ts.Diagnostics.Cannot_find_global_type_0);
+ function getGlobalTypeSymbol(name, reportErrors) {
+ return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
}
function getGlobalSymbol(name, meaning, diagnostic) {
return resolveName(undefined, name, meaning, diagnostic, name);
}
- function getGlobalType(name, arity) {
+ function getGlobalType(name, arity, reportErrors) {
+ var symbol = getGlobalTypeSymbol(name, reportErrors);
+ return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
+ }
+ function getGlobalTypedPropertyDescriptorType() {
+ return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
+ }
+ function getGlobalTemplateStringsArrayType() {
+ return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
+ }
+ function getGlobalESSymbolConstructorSymbol(reportErrors) {
+ return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
+ }
+ function getGlobalESSymbolType(reportErrors) {
+ return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
+ }
+ function getGlobalPromiseType(reportErrors) {
+ return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
+ }
+ function getGlobalPromiseConstructorSymbol(reportErrors) {
+ return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
+ }
+ function getGlobalPromiseConstructorLikeType(reportErrors) {
+ return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
+ }
+ function getGlobalAsyncIterableType(reportErrors) {
+ return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
+ }
+ function getGlobalAsyncIteratorType(reportErrors) {
+ return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
+ }
+ function getGlobalAsyncIterableIteratorType(reportErrors) {
+ return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
+ }
+ function getGlobalIterableType(reportErrors) {
+ return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
+ }
+ function getGlobalIteratorType(reportErrors) {
+ return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
+ }
+ function getGlobalIterableIteratorType(reportErrors) {
+ return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
+ }
+ function getGlobalTypeOrUndefined(name, arity) {
if (arity === void 0) { arity = 0; }
- return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity);
+ var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined);
+ return symbol && getTypeOfGlobalSymbol(symbol, arity);
}
/**
* Returns a type that is inside a namespace at the global scope, e.g.
@@ -29176,25 +31610,25 @@ var ts;
return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol);
}
/**
- * Creates a TypeReference for a generic `TypedPropertyDescriptor<T>`.
- */
- function createTypedPropertyDescriptorType(propertyType) {
- var globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType();
- return globalTypedPropertyDescriptorType !== emptyGenericType
- ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType])
- : emptyObjectType;
- }
- /**
* Instantiates a global type that is generic with some element type, and returns that instantiation.
*/
function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
}
- function createIterableType(elementType) {
- return createTypeFromGenericGlobalType(getGlobalIterableType(), [elementType]);
+ function createTypedPropertyDescriptorType(propertyType) {
+ return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
+ }
+ function createAsyncIterableType(iteratedType) {
+ return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]);
+ }
+ function createAsyncIterableIteratorType(iteratedType) {
+ return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
}
- function createIterableIteratorType(elementType) {
- return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(), [elementType]);
+ function createIterableType(iteratedType) {
+ return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
+ }
+ function createIterableIteratorType(iteratedType) {
+ return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]);
}
function createArrayType(elementType) {
return createTypeFromGenericGlobalType(globalArrayType, [elementType]);
@@ -29219,7 +31653,7 @@ var ts;
for (var i = 0; i < arity; i++) {
var typeParameter = createType(16384 /* TypeParameter */);
typeParameters.push(typeParameter);
- var property = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i);
+ var property = createSymbol(4 /* Property */, "" + i);
property.type = typeParameter;
properties.push(property);
}
@@ -29228,7 +31662,7 @@ var ts;
type.outerTypeParameters = undefined;
type.localTypeParameters = typeParameters;
type.instantiations = ts.createMap();
- type.instantiations[getTypeListId(type.typeParameters)] = type;
+ type.instantiations.set(getTypeListId(type.typeParameters), type);
type.target = type;
type.typeArguments = type.typeParameters;
type.thisType = createType(16384 /* TypeParameter */);
@@ -29312,14 +31746,14 @@ var ts;
// Add the given types to the given type set. Order is preserved, duplicates are removed,
// and nested types of the given kind are flattened into the set.
function addTypesToUnion(typeSet, types) {
- for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
- var type = types_4[_i];
+ for (var _i = 0, types_6 = types; _i < types_6.length; _i++) {
+ var type = types_6[_i];
addTypeToUnion(typeSet, type);
}
}
function containsIdenticalType(types, type) {
- for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
- var t = types_5[_i];
+ for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
+ var t = types_7[_i];
if (isTypeIdenticalTo(t, type)) {
return true;
}
@@ -29327,8 +31761,9 @@ var ts;
return false;
}
function isSubtypeOfAny(candidate, types) {
- for (var i = 0, len = types.length; i < len; i++) {
- if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) {
+ for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
+ var type = types_8[_i];
+ if (candidate !== type && isTypeSubtypeOf(candidate, type)) {
return true;
}
}
@@ -29414,10 +31849,11 @@ var ts;
return types[0];
}
var id = getTypeListId(types);
- var type = unionTypes[id];
+ var type = unionTypes.get(id);
if (!type) {
var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */);
- type = unionTypes[id] = createType(65536 /* Union */ | propagatedFlags);
+ type = createType(65536 /* Union */ | propagatedFlags);
+ unionTypes.set(id, type);
type.types = types;
type.aliasSymbol = aliasSymbol;
type.aliasTypeArguments = aliasTypeArguments;
@@ -29438,15 +31874,27 @@ var ts;
else if (type.flags & 1 /* Any */) {
typeSet.containsAny = true;
}
+ else if (getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) {
+ typeSet.containsEmptyObject = true;
+ }
else if (!(type.flags & 8192 /* Never */) && (strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) {
- typeSet.push(type);
+ if (type.flags & 32768 /* Object */) {
+ typeSet.containsObjectType = true;
+ }
+ if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) {
+ typeSet.unionIndex = typeSet.length;
+ }
+ if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ &&
+ type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) {
+ typeSet.push(type);
+ }
}
}
// Add the given types to the given type set. Order is preserved, duplicates are removed,
// and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet, types) {
- for (var _i = 0, types_6 = types; _i < types_6.length; _i++) {
- var type = types_6[_i];
+ for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
+ var type = types_9[_i];
addTypeToIntersection(typeSet, type);
}
}
@@ -29464,31 +31912,31 @@ var ts;
if (types.length === 0) {
return emptyObjectType;
}
- var _loop_2 = function (i) {
- var type_1 = types[i];
- if (type_1.flags & 65536 /* Union */) {
- return { value: getUnionType(ts.map(type_1.types, function (t) { return getIntersectionType(ts.replaceElement(types, i, t)); }),
- /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments) };
- }
- };
- for (var i = 0; i < types.length; i++) {
- var state_2 = _loop_2(i);
- if (typeof state_2 === "object")
- return state_2.value;
- }
var typeSet = [];
addTypesToIntersection(typeSet, types);
if (typeSet.containsAny) {
return anyType;
}
+ if (typeSet.containsEmptyObject && !typeSet.containsObjectType) {
+ typeSet.push(emptyObjectType);
+ }
if (typeSet.length === 1) {
return typeSet[0];
}
+ var unionIndex = typeSet.unionIndex;
+ if (unionIndex !== undefined) {
+ // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
+ // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
+ var unionType = typeSet[unionIndex];
+ return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }),
+ /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments);
+ }
var id = getTypeListId(typeSet);
- var type = intersectionTypes[id];
+ var type = intersectionTypes.get(id);
if (!type) {
var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */);
- type = intersectionTypes[id] = createType(131072 /* Intersection */ | propagatedFlags);
+ type = createType(131072 /* Intersection */ | propagatedFlags);
+ intersectionTypes.set(id, type);
type.types = typeSet;
type.aliasSymbol = aliasSymbol;
type.aliasTypeArguments = aliasTypeArguments;
@@ -29502,7 +31950,7 @@ var ts;
}
return links.resolvedType;
}
- function getIndexTypeForTypeParameter(type) {
+ function getIndexTypeForGenericType(type) {
if (!type.resolvedIndexType) {
type.resolvedIndexType = createType(262144 /* Index */);
type.resolvedIndexType.type = type;
@@ -29518,7 +31966,7 @@ var ts;
return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName));
}
function getIndexType(type) {
- return type.flags & 16384 /* TypeParameter */ ? getIndexTypeForTypeParameter(type) :
+ return maybeTypeOfKind(type, 540672 /* TypeVariable */) ? getIndexTypeForGenericType(type) :
getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) :
type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType :
getLiteralTypeFromPropertyNames(type);
@@ -29541,7 +31989,7 @@ var ts;
return type;
}
function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) {
- var accessExpression = accessNode && accessNode.kind === 178 /* ElementAccessExpression */ ? accessNode : undefined;
+ var accessExpression = accessNode && accessNode.kind === 179 /* ElementAccessExpression */ ? accessNode : undefined;
var propName = indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */ | 256 /* EnumLiteral */) ?
indexType.text :
accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
@@ -29570,14 +32018,14 @@ var ts;
getIndexInfoOfType(objectType, 0 /* String */) ||
undefined;
if (indexInfo) {
- if (accessExpression && ts.isAssignmentTarget(accessExpression) && indexInfo.isReadonly) {
+ if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
return unknownType;
}
return indexInfo.type;
}
if (accessExpression && !isConstEnumObjectType(objectType)) {
- if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
+ if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) {
if (getIndexTypeOfType(objectType, 1 /* Number */)) {
error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
}
@@ -29589,7 +32037,7 @@ var ts;
}
}
if (accessNode) {
- var indexNode = accessNode.kind === 178 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType;
+ var indexNode = accessNode.kind === 179 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType;
if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) {
error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.text, typeToString(objectType));
}
@@ -29599,32 +32047,32 @@ var ts;
else {
error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
}
+ return unknownType;
}
- return unknownType;
+ return anyType;
}
function getIndexedAccessForMappedType(type, indexType, accessNode) {
- var accessExpression = accessNode && accessNode.kind === 178 /* ElementAccessExpression */ ? accessNode : undefined;
+ var accessExpression = accessNode && accessNode.kind === 179 /* ElementAccessExpression */ ? accessNode : undefined;
if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) {
error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type));
return unknownType;
}
- var mapper = createUnaryTypeMapper(getTypeParameterFromMappedType(type), indexType);
+ var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]);
var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper;
- return addOptionality(instantiateType(getTemplateTypeFromMappedType(type), templateMapper), !!type.declaration.questionToken);
+ return instantiateType(getTemplateTypeFromMappedType(type), templateMapper);
}
function getIndexedAccessType(objectType, indexType, accessNode) {
- if (indexType.flags & 16384 /* TypeParameter */ ||
- objectType.flags & 16384 /* TypeParameter */ && indexType.flags & 262144 /* Index */ ||
+ // If the index type is generic, if the object type is generic and doesn't originate in an expression,
+ // or if the object type is a mapped type with a generic constraint, we are performing a higher-order
+ // index access where we cannot meaningfully access the properties of the object type. Note that for a
+ // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to
+ // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved
+ // eagerly using the constraint type of 'this' at the given location.
+ if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) ||
+ maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 179 /* ElementAccessExpression */) ||
isGenericMappedType(objectType)) {
- // If either the object type or the index type are type parameters, or if the object type is a mapped
- // type with a generic constraint, we are performing a higher-order index access where we cannot
- // meaningfully access the properties of the object type. In those cases, we first check that the
- // index type is assignable to 'keyof T' for the object type.
- if (accessNode) {
- if (!isTypeAssignableTo(indexType, getIndexType(objectType))) {
- error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
- return unknownType;
- }
+ if (objectType.flags & 1 /* Any */) {
+ return objectType;
}
// If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes
// the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we construct the
@@ -29634,8 +32082,13 @@ var ts;
}
// Otherwise we defer the operation by creating an indexed access type.
var id = objectType.id + "," + indexType.id;
- return indexedAccessTypes[id] || (indexedAccessTypes[id] = createIndexedAccessType(objectType, indexType));
+ var type = indexedAccessTypes.get(id);
+ if (!type) {
+ indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType));
+ }
+ return type;
}
+ // In the following we resolve T[K] to the type of the property in T selected by K.
var apparentObjectType = getApparentType(objectType);
if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) {
var propTypes = [];
@@ -29677,7 +32130,7 @@ var ts;
if (!links.resolvedType) {
// Deferred resolution of members is handled by resolveObjectTypeMembers
var aliasSymbol = getAliasSymbolForTypeNode(node);
- if (ts.isEmpty(node.symbol.members) && !aliasSymbol) {
+ if (node.symbol.members.size === 0 && !aliasSymbol) {
links.resolvedType = emptyTypeLiteralType;
}
else {
@@ -29690,7 +32143,7 @@ var ts;
return links.resolvedType;
}
function getAliasSymbolForTypeNode(node) {
- return node.parent.kind === 228 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined;
+ return node.parent.kind === 230 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined;
}
function getAliasTypeArgumentsForTypeNode(node) {
var symbol = getAliasSymbolForTypeNode(node);
@@ -29701,11 +32154,27 @@ var ts;
* this function should be called in a left folding style, with left = previous result of getSpreadType
* and right = the new element to be spread.
*/
- function getSpreadType(left, right, isFromObjectLiteral) {
- ts.Debug.assert(!!(left.flags & (32768 /* Object */ | 1 /* Any */)) && !!(right.flags & (32768 /* Object */ | 1 /* Any */)), "Only object types may be spread.");
+ function getSpreadType(left, right) {
if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
return anyType;
}
+ left = filterType(left, function (t) { return !(t.flags & 6144 /* Nullable */); });
+ if (left.flags & 8192 /* Never */) {
+ return right;
+ }
+ right = filterType(right, function (t) { return !(t.flags & 6144 /* Nullable */); });
+ if (right.flags & 8192 /* Never */) {
+ return left;
+ }
+ if (left.flags & 65536 /* Union */) {
+ return mapType(left, function (t) { return getSpreadType(t, right); });
+ }
+ if (right.flags & 65536 /* Union */) {
+ return mapType(right, function (t) { return getSpreadType(left, t); });
+ }
+ if (right.flags & 16777216 /* NonPrimitive */) {
+ return emptyObjectType;
+ }
var members = ts.createMap();
var skippedPrivateMembers = ts.createMap();
var stringIndexInfo;
@@ -29722,42 +32191,55 @@ var ts;
for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
var rightProp = _a[_i];
// we approximate own properties as non-methods plus methods that are inside the object literal
- var isOwnProperty = !(rightProp.flags & 8192 /* Method */) || isFromObjectLiteral;
var isSetterWithoutGetter = rightProp.flags & 65536 /* SetAccessor */ && !(rightProp.flags & 32768 /* GetAccessor */);
if (getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
- skippedPrivateMembers[rightProp.name] = true;
+ skippedPrivateMembers.set(rightProp.name, true);
}
- else if (isOwnProperty && !isSetterWithoutGetter) {
- members[rightProp.name] = rightProp;
+ else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) {
+ members.set(rightProp.name, getNonReadonlySymbol(rightProp));
}
}
for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
var leftProp = _c[_b];
if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */)
- || leftProp.name in skippedPrivateMembers) {
+ || skippedPrivateMembers.has(leftProp.name)
+ || isClassMethod(leftProp)) {
continue;
}
- if (leftProp.name in members) {
- var rightProp = members[leftProp.name];
+ if (members.has(leftProp.name)) {
+ var rightProp = members.get(leftProp.name);
var rightType = getTypeOfSymbol(rightProp);
- if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 536870912 /* Optional */) {
+ if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 67108864 /* Optional */) {
var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
- var flags = 4 /* Property */ | 67108864 /* Transient */ | (leftProp.flags & 536870912 /* Optional */);
+ var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */);
var result = createSymbol(flags, leftProp.name);
result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]);
result.leftSpread = leftProp;
result.rightSpread = rightProp;
result.declarations = declarations;
- result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp);
- members[leftProp.name] = result;
+ members.set(leftProp.name, result);
}
}
else {
- members[leftProp.name] = leftProp;
+ members.set(leftProp.name, getNonReadonlySymbol(leftProp));
}
}
return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo);
}
+ function getNonReadonlySymbol(prop) {
+ if (!isReadonlySymbol(prop)) {
+ return prop;
+ }
+ var flags = 4 /* Property */ | (prop.flags & 67108864 /* Optional */);
+ var result = createSymbol(flags, prop.name);
+ result.type = getTypeOfSymbol(prop);
+ result.declarations = prop.declarations;
+ result.syntheticOrigin = prop;
+ return result;
+ }
+ function isClassMethod(prop) {
+ return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); });
+ }
function createLiteralType(flags, text) {
var type = createType(flags);
type.text = text;
@@ -29779,7 +32261,11 @@ var ts;
}
function getLiteralTypeForText(flags, text) {
var map = flags & 32 /* StringLiteral */ ? stringLiteralTypes : numericLiteralTypes;
- return map[text] || (map[text] = createLiteralType(flags, text));
+ var type = map.get(text);
+ if (!type) {
+ map.set(text, type = createLiteralType(flags, text));
+ }
+ return type;
}
function getTypeFromLiteralTypeNode(node) {
var links = getNodeLinks(node);
@@ -29807,9 +32293,9 @@ var ts;
function getThisType(node) {
var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
var parent = container && container.parent;
- if (parent && (ts.isClassLike(parent) || parent.kind === 227 /* InterfaceDeclaration */)) {
+ if (parent && (ts.isClassLike(parent) || parent.kind === 229 /* InterfaceDeclaration */)) {
if (!(ts.getModifierFlags(container) & 32 /* Static */) &&
- (container.kind !== 150 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) {
+ (container.kind !== 151 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) {
return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
}
}
@@ -29826,87 +32312,84 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 118 /* AnyKeyword */:
- case 263 /* JSDocAllType */:
- case 264 /* JSDocUnknownType */:
+ case 267 /* JSDocAllType */:
+ case 268 /* JSDocUnknownType */:
return anyType;
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
return stringType;
case 132 /* NumberKeyword */:
return numberType;
case 121 /* BooleanKeyword */:
return booleanType;
- case 135 /* SymbolKeyword */:
+ case 136 /* SymbolKeyword */:
return esSymbolType;
case 104 /* VoidKeyword */:
return voidType;
- case 137 /* UndefinedKeyword */:
+ case 138 /* UndefinedKeyword */:
return undefinedType;
case 94 /* NullKeyword */:
return nullType;
case 129 /* NeverKeyword */:
return neverType;
- case 289 /* JSDocNullKeyword */:
- return nullType;
- case 290 /* JSDocUndefinedKeyword */:
- return undefinedType;
- case 291 /* JSDocNeverKeyword */:
- return neverType;
- case 167 /* ThisType */:
+ case 133 /* ObjectKeyword */:
+ return nonPrimitiveType;
+ case 168 /* ThisType */:
case 98 /* ThisKeyword */:
return getTypeFromThisTypeNode(node);
- case 171 /* LiteralType */:
+ case 172 /* LiteralType */:
return getTypeFromLiteralTypeNode(node);
- case 288 /* JSDocLiteralType */:
+ case 292 /* JSDocLiteralType */:
return getTypeFromLiteralTypeNode(node.literal);
- case 157 /* TypeReference */:
- case 272 /* JSDocTypeReference */:
+ case 158 /* TypeReference */:
+ case 276 /* JSDocTypeReference */:
return getTypeFromTypeReference(node);
- case 156 /* TypePredicate */:
+ case 157 /* TypePredicate */:
return booleanType;
- case 199 /* ExpressionWithTypeArguments */:
+ case 200 /* ExpressionWithTypeArguments */:
return getTypeFromTypeReference(node);
- case 160 /* TypeQuery */:
+ case 161 /* TypeQuery */:
return getTypeFromTypeQueryNode(node);
- case 162 /* ArrayType */:
- case 265 /* JSDocArrayType */:
+ case 163 /* ArrayType */:
+ case 269 /* JSDocArrayType */:
return getTypeFromArrayTypeNode(node);
- case 163 /* TupleType */:
+ case 164 /* TupleType */:
return getTypeFromTupleTypeNode(node);
- case 164 /* UnionType */:
- case 266 /* JSDocUnionType */:
+ case 165 /* UnionType */:
+ case 270 /* JSDocUnionType */:
return getTypeFromUnionTypeNode(node);
- case 165 /* IntersectionType */:
+ case 166 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 166 /* ParenthesizedType */:
- case 268 /* JSDocNullableType */:
- case 269 /* JSDocNonNullableType */:
- case 276 /* JSDocConstructorType */:
- case 277 /* JSDocThisType */:
- case 273 /* JSDocOptionalType */:
+ case 272 /* JSDocNullableType */:
+ return getTypeFromJSDocNullableTypeNode(node);
+ case 167 /* ParenthesizedType */:
+ case 273 /* JSDocNonNullableType */:
+ case 280 /* JSDocConstructorType */:
+ case 281 /* JSDocThisType */:
+ case 277 /* JSDocOptionalType */:
return getTypeFromTypeNode(node.type);
- case 270 /* JSDocRecordType */:
+ case 274 /* JSDocRecordType */:
return getTypeFromTypeNode(node.literal);
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
- case 161 /* TypeLiteral */:
- case 287 /* JSDocTypeLiteral */:
- case 274 /* JSDocFunctionType */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
+ case 162 /* TypeLiteral */:
+ case 291 /* JSDocTypeLiteral */:
+ case 278 /* JSDocFunctionType */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
- case 168 /* TypeOperator */:
+ case 169 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
- case 169 /* IndexedAccessType */:
+ case 170 /* IndexedAccessType */:
return getTypeFromIndexedAccessTypeNode(node);
- case 170 /* MappedType */:
+ case 171 /* MappedType */:
return getTypeFromMappedTypeNode(node);
// This function assumes that an identifier or qualified name is a type expression
// Callers should first ensure this by calling isTypeNode
case 70 /* Identifier */:
- case 141 /* QualifiedName */:
+ case 142 /* QualifiedName */:
var symbol = getSymbolAtLocation(node);
return symbol && getDeclaredTypeOfSymbol(symbol);
- case 267 /* JSDocTupleType */:
+ case 271 /* JSDocTupleType */:
return getTypeFromJSDocTupleType(node);
- case 275 /* JSDocVariadicType */:
+ case 279 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
default:
return unknownType;
@@ -29933,13 +32416,13 @@ var ts;
var instantiations = mapper.instantiations || (mapper.instantiations = []);
return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper));
}
- function createUnaryTypeMapper(source, target) {
+ function makeUnaryTypeMapper(source, target) {
return function (t) { return t === source ? target : t; };
}
- function createBinaryTypeMapper(source1, target1, source2, target2) {
+ function makeBinaryTypeMapper(source1, target1, source2, target2) {
return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; };
}
- function createArrayTypeMapper(sources, targets) {
+ function makeArrayTypeMapper(sources, targets) {
return function (t) {
for (var i = 0; i < sources.length; i++) {
if (t === sources[i]) {
@@ -29950,15 +32433,23 @@ var ts;
};
}
function createTypeMapper(sources, targets) {
- var count = sources.length;
- var mapper = count == 1 ? createUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) :
- count == 2 ? createBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) :
- createArrayTypeMapper(sources, targets);
+ var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) :
+ sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) :
+ makeArrayTypeMapper(sources, targets);
mapper.mappedTypes = sources;
return mapper;
}
function createTypeEraser(sources) {
- return createTypeMapper(sources, undefined);
+ return createTypeMapper(sources, /*targets*/ undefined);
+ }
+ /**
+ * Maps forward-references to later types parameters to the empty object type.
+ * This is used during inference when instantiating type parameter defaults.
+ */
+ function createBackreferenceMapper(typeParameters, index) {
+ var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; };
+ mapper.mappedTypes = typeParameters;
+ return mapper;
}
function getInferenceMapper(context) {
if (!context.mapper) {
@@ -29983,7 +32474,12 @@ var ts;
}
function combineTypeMappers(mapper1, mapper2) {
var mapper = function (t) { return instantiateType(mapper1(t), mapper2); };
- mapper.mappedTypes = mapper1.mappedTypes;
+ mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes);
+ return mapper;
+ }
+ function createReplacementMapper(source, target, baseMapper) {
+ var mapper = function (t) { return t === source ? target : baseMapper(t); };
+ mapper.mappedTypes = baseMapper.mappedTypes;
return mapper;
}
function cloneTypeParameter(typeParameter) {
@@ -30031,7 +32527,7 @@ var ts;
return result;
}
function instantiateSymbol(symbol, mapper) {
- if (symbol.flags & 16777216 /* Instantiated */) {
+ if (getCheckFlags(symbol) & 1 /* Instantiated */) {
var links = getSymbolLinks(symbol);
// If symbol being instantiated is itself a instantiation, fetch the original target and combine the
// type mappers. This ensures that original type identities are properly preserved and that aliases
@@ -30041,7 +32537,8 @@ var ts;
}
// Keep the flags from the symbol we're instantiating. Mark that is instantiated, and
// also transient so that we can just store data on it directly.
- var result = createSymbol(16777216 /* Instantiated */ | 67108864 /* Transient */ | symbol.flags, symbol.name);
+ var result = createSymbol(symbol.flags, symbol.name);
+ result.checkFlags = 1 /* Instantiated */;
result.declarations = symbol.declarations;
result.parent = symbol.parent;
result.target = symbol;
@@ -30060,25 +32557,24 @@ var ts;
return result;
}
function instantiateMappedType(type, mapper) {
- // Check if we have an isomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some
- // type parameter T. If so, the mapped type is distributive over a union type and when T is instantiated
+ // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some
+ // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated
// to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for
- // isomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a
+ // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a
// union type A | undefined, we produce { [P in keyof A]: X } | undefined.
var constraintType = getConstraintTypeFromMappedType(type);
if (constraintType.flags & 262144 /* Index */) {
- var typeParameter_1 = constraintType.type;
- var mappedTypeParameter = mapper(typeParameter_1);
- if (typeParameter_1 !== mappedTypeParameter) {
- return mapType(mappedTypeParameter, function (t) {
- if (isMappableType(t)) {
- var replacementMapper = createUnaryTypeMapper(typeParameter_1, t);
- var combinedMapper = mapper.mappedTypes && mapper.mappedTypes.length === 1 ? replacementMapper : combineTypeMappers(replacementMapper, mapper);
- combinedMapper.mappedTypes = mapper.mappedTypes;
- return instantiateMappedObjectType(type, combinedMapper);
- }
- return t;
- });
+ var typeVariable_1 = constraintType.type;
+ if (typeVariable_1.flags & 16384 /* TypeParameter */) {
+ var mappedTypeVariable = instantiateType(typeVariable_1, mapper);
+ if (typeVariable_1 !== mappedTypeVariable) {
+ return mapType(mappedTypeVariable, function (t) {
+ if (isMappableType(t)) {
+ return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper));
+ }
+ return t;
+ });
+ }
}
}
return instantiateMappedObjectType(type, mapper);
@@ -30102,26 +32598,28 @@ var ts;
// Starting with the parent of the symbol's declaration, check if the mapper maps any of
// the type parameters introduced by enclosing declarations. We just pick the first
// declaration since multiple declarations will all have the same parent anyway.
- var node = symbol.declarations[0].parent;
- while (node) {
+ return !!ts.findAncestor(symbol.declarations[0], function (node) {
+ if (node.kind === 232 /* ModuleDeclaration */ || node.kind === 264 /* SourceFile */) {
+ return "quit";
+ }
switch (node.kind) {
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
- case 225 /* FunctionDeclaration */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 227 /* InterfaceDeclaration */:
- case 228 /* TypeAliasDeclaration */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
+ case 227 /* FunctionDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 229 /* InterfaceDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
var declaration = node;
if (declaration.typeParameters) {
for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) {
@@ -30131,25 +32629,34 @@ var ts;
}
}
}
- if (ts.isClassLike(node) || node.kind === 227 /* InterfaceDeclaration */) {
+ if (ts.isClassLike(node) || node.kind === 229 /* InterfaceDeclaration */) {
var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
if (thisType && ts.contains(mappedTypes, thisType)) {
return true;
}
}
break;
- case 230 /* ModuleDeclaration */:
- case 261 /* SourceFile */:
- return false;
+ case 171 /* MappedType */:
+ if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) {
+ return true;
+ }
+ break;
+ case 278 /* JSDocFunctionType */:
+ var func = node;
+ for (var _b = 0, _c = func.parameters; _b < _c.length; _b++) {
+ var p = _c[_b];
+ if (ts.contains(mappedTypes, getTypeOfNode(p))) {
+ return true;
+ }
+ }
+ break;
}
- node = node.parent;
- }
- return false;
+ });
}
function isTopLevelTypeAlias(symbol) {
if (symbol.declarations && symbol.declarations.length) {
var parentKind = symbol.declarations[0].parent.kind;
- return parentKind === 261 /* SourceFile */ || parentKind === 231 /* ModuleBlock */;
+ return parentKind === 264 /* SourceFile */ || parentKind === 233 /* ModuleBlock */;
}
return false;
}
@@ -30226,28 +32733,36 @@ var ts;
// Returns true if the given expression contains (at any level of nesting) a function or arrow expression
// that is subject to contextual typing.
function isContextSensitive(node) {
- ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
+ ts.Debug.assert(node.kind !== 150 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
switch (node.kind) {
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
return isContextSensitiveFunctionLikeDeclaration(node);
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
return ts.forEach(node.properties, isContextSensitive);
- case 175 /* ArrayLiteralExpression */:
+ case 176 /* ArrayLiteralExpression */:
return ts.forEach(node.elements, isContextSensitive);
- case 193 /* ConditionalExpression */:
+ case 194 /* ConditionalExpression */:
return isContextSensitive(node.whenTrue) ||
isContextSensitive(node.whenFalse);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return node.operatorToken.kind === 53 /* BarBarToken */ &&
(isContextSensitive(node.left) || isContextSensitive(node.right));
- case 257 /* PropertyAssignment */:
+ case 260 /* PropertyAssignment */:
return isContextSensitive(node.initializer);
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
return isContextSensitiveFunctionLikeDeclaration(node);
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return isContextSensitive(node.expression);
+ case 253 /* JsxAttributes */:
+ return ts.forEach(node.properties, isContextSensitive);
+ case 252 /* JsxAttribute */:
+ // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
+ return node.initializer && isContextSensitive(node.initializer);
+ case 255 /* JsxExpression */:
+ // It is possible to that node.expression is undefined (e.g <div x={} />)
+ return node.expression && isContextSensitive(node.expression);
}
return false;
}
@@ -30261,7 +32776,7 @@ var ts;
return true;
}
// For arrow functions we now know we're not context sensitive.
- if (node.kind === 185 /* ArrowFunction */) {
+ if (node.kind === 186 /* ArrowFunction */) {
return false;
}
// If the first parameter is not an explicit 'this' parameter, then the function has
@@ -30283,9 +32798,12 @@ var ts;
result.properties = resolved.properties;
result.callSignatures = emptyArray;
result.constructSignatures = emptyArray;
- type = result;
+ return result;
}
}
+ else if (type.flags & 131072 /* Intersection */) {
+ return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
+ }
return type;
}
// TYPE CHECKING
@@ -30308,7 +32826,7 @@ var ts;
// subtype of T but not structurally identical to T. This specifically means that two distinct but
// structurally identical types (such as two classes) are not considered instances of each other.
function isTypeInstanceOf(source, target) {
- return source === target || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target);
+ return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target);
}
/**
* This is *not* a bi-directional relationship.
@@ -30334,12 +32852,13 @@ var ts;
return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
}
function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
- return compareSignaturesRelated(source, target, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */;
+ return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, ignoreReturnTypes, /*reportErrors*/ false,
+ /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */;
}
/**
* See signatureRelatedTo, compareSignaturesIdentical
*/
- function compareSignaturesRelated(source, target, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
+ function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) {
// TODO (drosen): De-duplicate code between related functions.
if (source === target) {
return -1 /* True */;
@@ -30374,9 +32893,23 @@ var ts;
var sourceParams = source.parameters;
var targetParams = target.parameters;
for (var i = 0; i < checkCount; i++) {
- var s = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source);
- var t = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target);
- var related = compareTypes(s, t, /*reportErrors*/ false) || compareTypes(t, s, reportErrors);
+ var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source);
+ var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target);
+ var sourceSig = getSingleCallSignature(getNonNullableType(sourceType));
+ var targetSig = getSingleCallSignature(getNonNullableType(targetType));
+ // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
+ // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
+ // they naturally relate only contra-variantly). However, if the source and target parameters both have
+ // function types with a single call signature, we known we are relating two callback parameters. In
+ // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
+ // similar to return values, callback parameters are output positions. This means that a Promise<T>,
+ // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
+ // with respect to T.
+ var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate &&
+ (getFalsyFlags(sourceType) & 6144 /* Nullable */) === (getFalsyFlags(targetType) & 6144 /* Nullable */);
+ var related = callbacks ?
+ compareSignaturesRelated(targetSig, sourceSig, /*checkAsCallback*/ true, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) :
+ !checkAsCallback && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
if (!related) {
if (reportErrors) {
errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name);
@@ -30404,7 +32937,11 @@ var ts;
}
}
else {
- result &= compareTypes(sourceReturnType, targetReturnType, reportErrors);
+ // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
+ // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
+ // wouldn't be co-variant for T without this rule.
+ result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
+ compareTypes(sourceReturnType, targetReturnType, reportErrors);
}
}
return result;
@@ -30471,18 +33008,33 @@ var ts;
sourceNonRestParamCount;
}
}
+ function isEmptyResolvedType(t) {
+ return t.properties.length === 0 &&
+ t.callSignatures.length === 0 &&
+ t.constructSignatures.length === 0 &&
+ !t.stringIndexInfo &&
+ !t.numberIndexInfo;
+ }
+ function isEmptyObjectType(type) {
+ return type.flags & 32768 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
+ type.flags & 65536 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) :
+ type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) :
+ false;
+ }
function isEnumTypeRelatedTo(source, target, errorReporter) {
if (source === target) {
return true;
}
var id = source.id + "," + target.id;
- if (enumRelation[id] !== undefined) {
- return enumRelation[id];
+ var relation = enumRelation.get(id);
+ if (relation !== undefined) {
+ return relation;
}
if (source.symbol.name !== target.symbol.name ||
!(source.symbol.flags & 256 /* RegularEnum */) || !(target.symbol.flags & 256 /* RegularEnum */) ||
(source.flags & 65536 /* Union */) !== (target.flags & 65536 /* Union */)) {
- return enumRelation[id] = false;
+ enumRelation.set(id, false);
+ return false;
}
var targetEnumType = getTypeOfSymbol(target.symbol);
for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) {
@@ -30493,11 +33045,13 @@ var ts;
if (errorReporter) {
errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */));
}
- return enumRelation[id] = false;
+ enumRelation.set(id, false);
+ return false;
}
}
}
- return enumRelation[id] = true;
+ enumRelation.set(id, true);
+ return true;
}
function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
if (target.flags & 8192 /* Never */)
@@ -30518,6 +33072,8 @@ var ts;
return true;
if (source.flags & 4096 /* Null */ && (!strictNullChecks || target.flags & 4096 /* Null */))
return true;
+ if (source.flags & 32768 /* Object */ && target.flags & 16777216 /* NonPrimitive */)
+ return true;
if (relation === assignableRelation || relation === comparableRelation) {
if (source.flags & 1 /* Any */)
return true;
@@ -30549,13 +33105,13 @@ var ts;
}
if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) {
var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id;
- var related = relation[id];
+ var related = relation.get(id);
if (related !== undefined) {
return related === 1 /* Succeeded */;
}
}
- if (source.flags & 507904 /* StructuredOrTypeParameter */ || target.flags & 507904 /* StructuredOrTypeParameter */) {
- return checkTypeRelatedTo(source, target, relation, undefined, undefined, undefined);
+ if (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */) {
+ return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
}
return false;
}
@@ -30619,14 +33175,35 @@ var ts;
if ((globalStringType === source && stringType === target) ||
(globalNumberType === source && numberType === target) ||
(globalBooleanType === source && booleanType === target) ||
- (getGlobalESSymbolType() === source && esSymbolType === target)) {
+ (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
}
}
- // Compare two types and return
- // Ternary.True if they are related with no assumptions,
- // Ternary.Maybe if they are related with assumptions of other relationships, or
- // Ternary.False if they are not related.
+ function isUnionOrIntersectionTypeWithoutNullableConstituents(type) {
+ if (!(type.flags & 196608 /* UnionOrIntersection */)) {
+ return false;
+ }
+ // at this point we know that this is union or intersection type possibly with nullable constituents.
+ // check if we still will have compound type if we ignore nullable components.
+ var seenNonNullable = false;
+ for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
+ var t = _a[_i];
+ if (t.flags & 6144 /* Nullable */) {
+ continue;
+ }
+ if (seenNonNullable) {
+ return true;
+ }
+ seenNonNullable = true;
+ }
+ return false;
+ }
+ /**
+ * Compare two types and return
+ * * Ternary.True if they are related with no assumptions,
+ * * Ternary.Maybe if they are related with assumptions of other relationships, or
+ * * Ternary.False if they are not related.
+ */
function isRelatedTo(source, target, reportErrors, headMessage) {
var result;
if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) {
@@ -30654,7 +33231,7 @@ var ts;
// and intersection types are further deconstructed on the target side, we don't want to
// make the check again (as it might fail for a partial target type). Therefore we obtain
// the regular source type and proceed with that.
- if (target.flags & 196608 /* UnionOrIntersection */) {
+ if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) {
source = getRegularTypeOfObjectLiteral(source);
}
}
@@ -30673,122 +33250,37 @@ var ts;
return result;
}
}
- else if (target.flags & 65536 /* Union */) {
- if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) {
- return result;
- }
- }
- else if (target.flags & 131072 /* Intersection */) {
- if (result = typeRelatedToEachType(source, target, reportErrors)) {
- return result;
- }
- }
- else if (source.flags & 131072 /* Intersection */) {
- // Check to see if any constituents of the intersection are immediately related to the target.
- //
- // Don't report errors though. Checking whether a constituent is related to the source is not actually
- // useful and leads to some confusing error messages. Instead it is better to let the below checks
- // take care of this, or to not elaborate at all. For instance,
- //
- // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
- //
- // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
- // than to report that 'D' is not assignable to 'A' or 'B'.
- //
- // - For a primitive type or type parameter (such as 'number = A & B') there is no point in
- // breaking the intersection apart.
- if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) {
- return result;
- }
- }
- if (target.flags & 16384 /* TypeParameter */) {
- // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P].
- if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) {
- if (!source.declaration.questionToken) {
- var templateType = getTemplateTypeFromMappedType(source);
- var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
- if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
- return result;
- }
- }
- }
- else {
- // Given a type parameter K with a constraint keyof T, a type S is
- // assignable to K if S is assignable to keyof T.
- var constraint = getConstraintOfTypeParameter(target);
- if (constraint && constraint.flags & 262144 /* Index */) {
- if (result = isRelatedTo(source, constraint, reportErrors)) {
- return result;
- }
- }
- }
- }
- else if (target.flags & 262144 /* Index */) {
- // A keyof S is related to a keyof T if T is related to S.
- if (source.flags & 262144 /* Index */) {
- if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
- return result;
- }
- }
- // Given a type parameter T with a constraint C, a type S is assignable to
- // keyof T if S is assignable to keyof C.
- var constraint = getConstraintOfTypeParameter(target.type);
- if (constraint) {
- if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) {
- return result;
- }
- }
- }
- else if (target.flags & 524288 /* IndexedAccess */) {
- // if we have indexed access types with identical index types, see if relationship holds for
- // the two object types.
- if (source.flags & 524288 /* IndexedAccess */ && source.indexType === target.indexType) {
- if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
- return result;
- }
- }
- }
- if (source.flags & 16384 /* TypeParameter */) {
- // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X.
- if (getObjectFlags(target) & 32 /* Mapped */ && getConstraintTypeFromMappedType(target) === getIndexType(source)) {
- var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
- var templateType = getTemplateTypeFromMappedType(target);
- if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
+ else {
+ if (target.flags & 65536 /* Union */) {
+ if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) {
return result;
}
}
- else {
- var constraint = getConstraintOfTypeParameter(source);
- if (!constraint || constraint.flags & 1 /* Any */) {
- constraint = emptyObjectType;
- }
- // The constraint may need to be further instantiated with its 'this' type.
- constraint = getTypeWithThisArgument(constraint, source);
- // Report constraint errors only if the constraint is not the empty object type
- var reportConstraintErrors = reportErrors && constraint !== emptyObjectType;
- if (result = isRelatedTo(constraint, target, reportConstraintErrors)) {
- errorInfo = saveErrorInfo;
+ else if (target.flags & 131072 /* Intersection */) {
+ if (result = typeRelatedToEachType(source, target, reportErrors)) {
return result;
}
}
- }
- else {
- if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
- // We have type references to same target type, see if relationship holds for all type arguments
- if (result = typeArgumentsRelatedTo(source, target, reportErrors)) {
+ else if (source.flags & 131072 /* Intersection */) {
+ // Check to see if any constituents of the intersection are immediately related to the target.
+ //
+ // Don't report errors though. Checking whether a constituent is related to the source is not actually
+ // useful and leads to some confusing error messages. Instead it is better to let the below checks
+ // take care of this, or to not elaborate at all. For instance,
+ //
+ // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
+ //
+ // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
+ // than to report that 'D' is not assignable to 'A' or 'B'.
+ //
+ // - For a primitive type or type parameter (such as 'number = A & B') there is no point in
+ // breaking the intersection apart.
+ if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) {
return result;
}
}
- // Even if relationship doesn't hold for unions, intersections, or generic type references,
- // it may hold in a structural comparison.
- var apparentSource = getApparentType(source);
- // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
- // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
- // relates to X. Thus, we include intersection types on the source side here.
- if (apparentSource.flags & (32768 /* Object */ | 131072 /* Intersection */) && target.flags & 32768 /* Object */) {
- // Report structural errors only if we haven't reported any errors yet
- var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 8190 /* Primitive */);
- if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) {
+ if (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */) {
+ if (result = recursiveTypeRelatedTo(source, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
}
@@ -30808,13 +33300,7 @@ var ts;
function isIdenticalTo(source, target) {
var result;
if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) {
- if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
- // We have type references to same target type, see if all type arguments are identical
- if (result = typeArgumentsRelatedTo(source, target, /*reportErrors*/ false)) {
- return result;
- }
- }
- return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false);
+ return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false);
}
if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ ||
source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) {
@@ -30830,45 +33316,49 @@ var ts;
// is considered known if the object type is empty and the check is for assignability, if the object type has
// index signatures, or if the property is actually declared in the object type. In a union or intersection
// type, a property is considered known if it is known in any constituent type.
- function isKnownProperty(type, name) {
+ function isKnownProperty(type, name, isComparingJsxAttributes) {
if (type.flags & 32768 /* Object */) {
var resolved = resolveStructuredTypeMembers(type);
- if ((relation === assignableRelation || relation === comparableRelation) && (type === globalObjectType || isEmptyObjectType(resolved)) ||
- resolved.stringIndexInfo ||
- (resolved.numberIndexInfo && isNumericLiteralName(name)) ||
- getPropertyOfType(type, name)) {
+ if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) ||
+ getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
+ // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
return true;
}
}
else if (type.flags & 196608 /* UnionOrIntersection */) {
for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
var t = _a[_i];
- if (isKnownProperty(t, name)) {
+ if (isKnownProperty(t, name, isComparingJsxAttributes)) {
return true;
}
}
}
return false;
}
- function isEmptyObjectType(t) {
- return t.properties.length === 0 &&
- t.callSignatures.length === 0 &&
- t.constructSignatures.length === 0 &&
- !t.stringIndexInfo &&
- !t.numberIndexInfo;
- }
function hasExcessProperties(source, target, reportErrors) {
if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
+ var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */);
+ if ((relation === assignableRelation || relation === comparableRelation) &&
+ (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
+ return false;
+ }
for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) {
var prop = _a[_i];
- if (!isKnownProperty(target, prop.name)) {
+ if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) {
if (reportErrors) {
// We know *exactly* where things went wrong when comparing the types.
// Use this property as the error node as this will be more helpful in
// reasoning about what went wrong.
ts.Debug.assert(!!errorNode);
- errorNode = prop.valueDeclaration;
- reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target));
+ if (ts.isJsxAttributes(errorNode)) {
+ // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
+ // However, using an object-literal error message will be very confusing to the users so we give different a message.
+ reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target));
+ }
+ else {
+ errorNode = prop.valueDeclaration;
+ reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target));
+ }
}
return true;
}
@@ -30894,20 +33384,42 @@ var ts;
if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) {
return -1 /* True */;
}
- var len = targetTypes.length;
- for (var i = 0; i < len; i++) {
- var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1);
+ for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
+ var type = targetTypes_1[_i];
+ var related = isRelatedTo(source, type, /*reportErrors*/ false);
if (related) {
return related;
}
}
+ if (reportErrors) {
+ var discriminantType = findMatchingDiscriminantType(source, target);
+ isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
+ }
return 0 /* False */;
}
+ function findMatchingDiscriminantType(source, target) {
+ var sourceProperties = getPropertiesOfObjectType(source);
+ if (sourceProperties) {
+ for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
+ var sourceProperty = sourceProperties_1[_i];
+ if (isDiscriminantProperty(target, sourceProperty.name)) {
+ var sourceType = getTypeOfSymbol(sourceProperty);
+ for (var _a = 0, _b = target.types; _a < _b.length; _a++) {
+ var type = _b[_a];
+ var targetType = getTypeOfPropertyOfType(type, sourceProperty.name);
+ if (targetType && isRelatedTo(sourceType, targetType)) {
+ return type;
+ }
+ }
+ }
+ }
+ }
+ }
function typeRelatedToEachType(source, target, reportErrors) {
var result = -1 /* True */;
var targetTypes = target.types;
- for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
- var targetType = targetTypes_1[_i];
+ for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
+ var targetType = targetTypes_2[_i];
var related = isRelatedTo(source, targetType, reportErrors);
if (!related) {
return 0 /* False */;
@@ -30960,22 +33472,22 @@ var ts;
}
return result;
}
- // Determine if two object types are related by structure. First, check if the result is already available in the global cache.
+ // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
// Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
// Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
// equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
// and issue an error. Otherwise, actually compare the structure of the two types.
- function objectTypeRelatedTo(source, originalSource, target, reportErrors) {
+ function recursiveTypeRelatedTo(source, target, reportErrors) {
if (overflow) {
return 0 /* False */;
}
var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id;
- var related = relation[id];
+ var related = relation.get(id);
if (related !== undefined) {
if (reportErrors && related === 2 /* Failed */) {
// We are elaborating errors and the cached result is an unreported failure. Record the result as a reported
// failure and continue computing the relation such that errors get reported.
- relation[id] = 3 /* FailedAndReported */;
+ relation.set(id, 3 /* FailedAndReported */);
}
else {
return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
@@ -30984,7 +33496,7 @@ var ts;
if (depth > 0) {
for (var i = 0; i < depth; i++) {
// If source and target are already being compared, consider them related with assumptions
- if (maybeStack[i][id]) {
+ if (maybeStack[i].get(id)) {
return 1 /* Maybe */;
}
}
@@ -31002,75 +33514,192 @@ var ts;
sourceStack[depth] = source;
targetStack[depth] = target;
maybeStack[depth] = ts.createMap();
- maybeStack[depth][id] = 1 /* Succeeded */;
+ maybeStack[depth].set(id, 1 /* Succeeded */);
depth++;
var saveExpandingFlags = expandingFlags;
- if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth))
+ if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth))
expandingFlags |= 1;
- if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth))
+ if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth))
expandingFlags |= 2;
- var result;
- if (expandingFlags === 3) {
- result = 1 /* Maybe */;
- }
- else if (isGenericMappedType(source) || isGenericMappedType(target)) {
- result = mappedTypeRelatedTo(source, target, reportErrors);
- }
- else {
- result = propertiesRelatedTo(source, target, reportErrors);
- if (result) {
- result &= signaturesRelatedTo(source, target, 0 /* Call */, reportErrors);
- if (result) {
- result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportErrors);
- if (result) {
- result &= indexTypesRelatedTo(source, originalSource, target, 0 /* String */, reportErrors);
- if (result) {
- result &= indexTypesRelatedTo(source, originalSource, target, 1 /* Number */, reportErrors);
- }
- }
- }
- }
- }
+ var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */;
expandingFlags = saveExpandingFlags;
depth--;
if (result) {
var maybeCache = maybeStack[depth];
// If result is definitely true, copy assumptions to global cache, else copy to next level up
var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1];
- ts.copyProperties(maybeCache, destinationCache);
+ ts.copyEntries(maybeCache, destinationCache);
}
else {
// A false result goes straight into global cache (when something is false under assumptions it
// will also be false without assumptions)
- relation[id] = reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */;
+ relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */);
}
return result;
}
- // A type [P in S]: X is related to a type [P in T]: Y if T is related to S and X is related to Y.
- function mappedTypeRelatedTo(source, target, reportErrors) {
- if (isGenericMappedType(target)) {
- if (isGenericMappedType(source)) {
- var result_2;
- if (relation === identityRelation) {
- var readonlyMatches = !source.declaration.readonlyToken === !target.declaration.readonlyToken;
- var optionalMatches = !source.declaration.questionToken === !target.declaration.questionToken;
- if (readonlyMatches && optionalMatches) {
- if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
- return result_2 & isRelatedTo(getErasedTemplateTypeFromMappedType(source), getErasedTemplateTypeFromMappedType(target), reportErrors);
- }
+ function structuredTypeRelatedTo(source, target, reportErrors) {
+ var result;
+ var saveErrorInfo = errorInfo;
+ if (target.flags & 16384 /* TypeParameter */) {
+ // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P].
+ if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) {
+ if (!source.declaration.questionToken) {
+ var templateType = getTemplateTypeFromMappedType(source);
+ var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
+ if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
+ return result;
}
}
+ }
+ }
+ else if (target.flags & 262144 /* Index */) {
+ // A keyof S is related to a keyof T if T is related to S.
+ if (source.flags & 262144 /* Index */) {
+ if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
+ return result;
+ }
+ }
+ // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
+ // constraint of T.
+ var constraint = getConstraintOfType(target.type);
+ if (constraint) {
+ if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) {
+ return result;
+ }
+ }
+ }
+ else if (target.flags & 524288 /* IndexedAccess */) {
+ // A type S is related to a type T[K] if S is related to A[K], where K is string-like and
+ // A is the apparent type of S.
+ var constraint = getConstraintOfType(target);
+ if (constraint) {
+ if (result = isRelatedTo(source, constraint, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
+ }
+ if (source.flags & 16384 /* TypeParameter */) {
+ // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X.
+ if (getObjectFlags(target) & 32 /* Mapped */ && getConstraintTypeFromMappedType(target) === getIndexType(source)) {
+ var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
+ var templateType = getTemplateTypeFromMappedType(target);
+ if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
+ else {
+ var constraint = getConstraintOfTypeParameter(source);
+ // A type parameter with no constraint is not related to the non-primitive object type.
+ if (constraint || !(target.flags & 16777216 /* NonPrimitive */)) {
+ if (!constraint || constraint.flags & 1 /* Any */) {
+ constraint = emptyObjectType;
+ }
+ // The constraint may need to be further instantiated with its 'this' type.
+ constraint = getTypeWithThisArgument(constraint, source);
+ // Report constraint errors only if the constraint is not the empty object type
+ var reportConstraintErrors = reportErrors && constraint !== emptyObjectType;
+ if (result = isRelatedTo(constraint, target, reportConstraintErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
+ }
+ }
+ else if (source.flags & 524288 /* IndexedAccess */) {
+ // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and
+ // A is the apparent type of S.
+ var constraint = getConstraintOfType(source);
+ if (constraint) {
+ if (result = isRelatedTo(constraint, target, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
+ else if (target.flags & 524288 /* IndexedAccess */ && source.indexType === target.indexType) {
+ // if we have indexed access types with identical index types, see if relationship holds for
+ // the two object types.
+ if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
+ return result;
+ }
+ }
+ }
+ else {
+ if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) {
+ // We have type references to same target type, see if relationship holds for all type arguments
+ if (result = typeArgumentsRelatedTo(source, target, reportErrors)) {
+ return result;
+ }
+ }
+ // Even if relationship doesn't hold for unions, intersections, or generic type references,
+ // it may hold in a structural comparison.
+ var sourceIsPrimitive = !!(source.flags & 8190 /* Primitive */);
+ if (relation !== identityRelation) {
+ source = getApparentType(source);
+ }
+ // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
+ // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
+ // relates to X. Thus, we include intersection types on the source side here.
+ if (source.flags & (32768 /* Object */ | 131072 /* Intersection */) && target.flags & 32768 /* Object */) {
+ // Report structural errors only if we haven't reported any errors yet
+ var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive;
+ if (isGenericMappedType(source) || isGenericMappedType(target)) {
+ result = mappedTypeRelatedTo(source, target, reportStructuralErrors);
+ }
else {
- if (relation === comparableRelation || !source.declaration.questionToken || target.declaration.questionToken) {
- if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
- return result_2 & isRelatedTo(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target), reportErrors);
+ result = propertiesRelatedTo(source, target, reportStructuralErrors);
+ if (result) {
+ result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
+ if (result) {
+ result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
+ if (result) {
+ result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors);
+ if (result) {
+ result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors);
+ }
+ }
}
}
}
+ if (result) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
}
}
- else if (relation !== identityRelation && isEmptyObjectType(resolveStructuredTypeMembers(target))) {
- return -1 /* True */;
+ return 0 /* False */;
+ }
+ // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
+ // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
+ // that S and T are contra-variant whereas X and Y are co-variant.
+ function mappedTypeRelatedTo(source, target, reportErrors) {
+ if (isGenericMappedType(target)) {
+ if (isGenericMappedType(source)) {
+ var sourceReadonly = !!source.declaration.readonlyToken;
+ var sourceOptional = !!source.declaration.questionToken;
+ var targetReadonly = !!target.declaration.readonlyToken;
+ var targetOptional = !!target.declaration.questionToken;
+ var modifiersRelated = relation === identityRelation ?
+ sourceReadonly === targetReadonly && sourceOptional === targetOptional :
+ relation === comparableRelation || !sourceOptional || targetOptional;
+ if (modifiersRelated) {
+ var result_2;
+ if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
+ var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
+ return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
+ }
+ }
+ }
+ else if (target.declaration.questionToken && isEmptyObjectType(source)) {
+ return -1 /* True */;
+ }
+ }
+ else if (relation !== identityRelation) {
+ var resolved = resolveStructuredTypeMembers(target);
+ if (isEmptyResolvedType(resolved) || resolved.stringIndexInfo && resolved.stringIndexInfo.type.flags & 1 /* Any */) {
+ return -1 /* True */;
+ }
}
return 0 /* False */;
}
@@ -31081,22 +33710,28 @@ var ts;
var result = -1 /* True */;
var properties = getPropertiesOfObjectType(target);
var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */);
- for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
- var targetProp = properties_3[_i];
+ for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) {
+ var targetProp = properties_4[_i];
var sourceProp = getPropertyOfType(source, targetProp.name);
if (sourceProp !== targetProp) {
if (!sourceProp) {
- if (!(targetProp.flags & 536870912 /* Optional */) || requireOptionalProperties) {
+ if (!(targetProp.flags & 67108864 /* Optional */) || requireOptionalProperties) {
if (reportErrors) {
reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source));
}
return 0 /* False */;
}
}
- else if (!(targetProp.flags & 134217728 /* Prototype */)) {
+ else if (!(targetProp.flags & 16777216 /* Prototype */)) {
var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp);
var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp);
if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
+ if (getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) {
+ if (reportErrors) {
+ reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source));
+ }
+ return 0 /* False */;
+ }
if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
if (reportErrors) {
if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
@@ -31110,12 +33745,9 @@ var ts;
}
}
else if (targetPropFlags & 16 /* Protected */) {
- var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32 /* Class */;
- var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined;
- var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp));
- if (!sourceClass || !hasBaseType(sourceClass, targetClass)) {
+ if (!isValidOverrideOf(sourceProp, targetProp)) {
if (reportErrors) {
- reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass));
+ reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target));
}
return 0 /* False */;
}
@@ -31135,7 +33767,7 @@ var ts;
}
result &= related;
// When checking for comparability, be more lenient with optional properties.
- if (relation !== comparableRelation && sourceProp.flags & 536870912 /* Optional */ && !(targetProp.flags & 536870912 /* Optional */)) {
+ if (relation !== comparableRelation && sourceProp.flags & 67108864 /* Optional */ && !(targetProp.flags & 67108864 /* Optional */)) {
// TypeScript 1.0 spec (April 2014): 3.8.3
// S is a subtype of a type T, and T is a supertype of S if ...
// S' and T are object types and, for each member M in T..
@@ -31163,8 +33795,8 @@ var ts;
return 0 /* False */;
}
var result = -1 /* True */;
- for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
- var sourceProp = sourceProperties_1[_i];
+ for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
+ var sourceProp = sourceProperties_2[_i];
var targetProp = getPropertyOfObjectType(target, sourceProp.name);
if (!targetProp) {
return 0 /* False */;
@@ -31228,7 +33860,7 @@ var ts;
* See signatureAssignableTo, compareSignaturesIdentical
*/
function signatureRelatedTo(source, target, reportErrors) {
- return compareSignaturesRelated(source, target, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo);
+ return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo);
}
function signaturesIdenticalTo(source, target, kind) {
var sourceSignatures = getSignaturesOfType(source, kind);
@@ -31237,7 +33869,7 @@ var ts;
return 0 /* False */;
}
var result = -1 /* True */;
- for (var i = 0, len = sourceSignatures.length; i < len; i++) {
+ for (var i = 0; i < sourceSignatures.length; i++) {
var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
if (!related) {
return 0 /* False */;
@@ -31270,12 +33902,12 @@ var ts;
}
return related;
}
- function indexTypesRelatedTo(source, originalSource, target, kind, reportErrors) {
+ function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) {
if (relation === identityRelation) {
return indexTypesIdenticalTo(source, target, kind);
}
var targetInfo = getIndexInfoOfType(target, kind);
- if (!targetInfo || ((targetInfo.type.flags & 1 /* Any */) && !(originalSource.flags & 8190 /* Primitive */))) {
+ if (!targetInfo || targetInfo.type.flags & 1 /* Any */ && !sourceIsPrimitive) {
// Index signature of type any permits assignment from everything but primitives
return -1 /* True */;
}
@@ -31337,6 +33969,45 @@ var ts;
return false;
}
}
+ // Invoke the callback for each underlying property symbol of the given symbol and return the first
+ // value that isn't undefined.
+ function forEachProperty(prop, callback) {
+ if (getCheckFlags(prop) & 6 /* Synthetic */) {
+ for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
+ var t = _a[_i];
+ var p = getPropertyOfType(t, prop.name);
+ var result = p && forEachProperty(p, callback);
+ if (result) {
+ return result;
+ }
+ }
+ return undefined;
+ }
+ return callback(prop);
+ }
+ // Return the declaring class type of a property or undefined if property not declared in class
+ function getDeclaringClass(prop) {
+ return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
+ }
+ // Return true if some underlying source property is declared in a class that derives
+ // from the given base class.
+ function isPropertyInClassDerivedFrom(prop, baseClass) {
+ return forEachProperty(prop, function (sp) {
+ var sourceClass = getDeclaringClass(sp);
+ return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
+ });
+ }
+ // Return true if source property is a valid override of protected parts of target property.
+ function isValidOverrideOf(sourceProp, targetProp) {
+ return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
+ !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
+ }
+ // Return true if the given class derives from each of the declaring classes of the protected
+ // constituents of the given property.
+ function isClassDerivedFromDeclaringClasses(checkClass, prop) {
+ return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
+ !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
+ }
// Return true if the given type is the constructor type for an abstract class
function isAbstractConstructorType(type) {
if (getObjectFlags(type) & 16 /* Anonymous */) {
@@ -31350,22 +34021,24 @@ var ts;
}
return false;
}
- // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case
- // when structural type comparisons have been started for 10 or more instantiations of the same generic type. It is possible,
- // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely expanding.
- // Effectively, we will generate a false positive when two types are structurally equal to at least 10 levels, but unequal at
- // some level beyond that.
- function isDeeplyNestedGeneric(type, stack, depth) {
- // We track type references (created by createTypeReference) and instantiated types (created by instantiateType)
- if (getObjectFlags(type) & (4 /* Reference */ | 64 /* Instantiated */) && depth >= 5) {
+ // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
+ // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
+ // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
+ // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
+ // levels, but unequal at some level beyond that.
+ function isDeeplyNestedType(type, stack, depth) {
+ // We track all object types that have an associated symbol (representing the origin of the type)
+ if (depth >= 5 && type.flags & 32768 /* Object */) {
var symbol = type.symbol;
- var count = 0;
- for (var i = 0; i < depth; i++) {
- var t = stack[i];
- if (getObjectFlags(t) & (4 /* Reference */ | 64 /* Instantiated */) && t.symbol === symbol) {
- count++;
- if (count >= 5)
- return true;
+ if (symbol) {
+ var count = 0;
+ for (var i = 0; i < depth; i++) {
+ var t = stack[i];
+ if (t.flags & 32768 /* Object */ && t.symbol === symbol) {
+ count++;
+ if (count >= 5)
+ return true;
+ }
}
}
}
@@ -31392,7 +34065,7 @@ var ts;
}
}
else {
- if ((sourceProp.flags & 536870912 /* Optional */) !== (targetProp.flags & 536870912 /* Optional */)) {
+ if ((sourceProp.flags & 67108864 /* Optional */) !== (targetProp.flags & 67108864 /* Optional */)) {
return 0 /* False */;
}
}
@@ -31436,7 +34109,7 @@ var ts;
// the constraints with a common set of type arguments to get relatable entities in places where
// type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile,
// particularly as we're comparing erased versions of the signatures below.
- if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) {
+ if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
return 0 /* False */;
}
// Spec 1.0 Section 3.8.3 & 3.8.4:
@@ -31476,8 +34149,8 @@ var ts;
return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1;
}
function isSupertypeOfEach(candidate, types) {
- for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
- var t = types_7[_i];
+ for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
+ var t = types_10[_i];
if (candidate !== t && !isTypeSubtypeOf(t, candidate))
return false;
}
@@ -31485,8 +34158,8 @@ var ts;
}
function literalTypesWithSameBaseType(types) {
var commonBaseType;
- for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
- var t = types_8[_i];
+ for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
+ var t = types_11[_i];
var baseType = getBaseTypeOfLiteralType(t);
if (!commonBaseType) {
commonBaseType = baseType;
@@ -31592,8 +34265,8 @@ var ts;
}
function getFalsyFlagsOfTypes(types) {
var result = 0;
- for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
- var t = types_9[_i];
+ for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
+ var t = types_12[_i];
result |= getFalsyFlags(t);
}
return result;
@@ -31625,7 +34298,7 @@ var ts;
types.push(undefinedType);
if (flags & 4096 /* Null */)
types.push(nullType);
- return getUnionType(types, /*subtypeReduction*/ true);
+ return getUnionType(types);
}
function removeDefinitelyFalsyTypes(type) {
return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ?
@@ -31644,8 +34317,8 @@ var ts;
getSignaturesOfType(type, 0 /* Call */).length === 0 &&
getSignaturesOfType(type, 1 /* Construct */).length === 0;
}
- function createTransientSymbol(source, type) {
- var symbol = createSymbol(source.flags | 67108864 /* Transient */, source.name);
+ function createSymbolWithType(source, type) {
+ var symbol = createSymbol(source.flags, source.name);
symbol.declarations = source.declarations;
symbol.parent = source.parent;
symbol.type = type;
@@ -31661,9 +34334,8 @@ var ts;
var property = _a[_i];
var original = getTypeOfSymbol(property);
var updated = f(original);
- members[property.name] = updated === original ? property : createTransientSymbol(property, updated);
+ members.set(property.name, updated === original ? property : createSymbolWithType(property, updated));
}
- ;
return members;
}
/**
@@ -31687,11 +34359,19 @@ var ts;
type.regularType = regularNew;
return regularNew;
}
+ function getWidenedProperty(prop) {
+ var original = getTypeOfSymbol(prop);
+ var widened = getWidenedType(original);
+ return widened === original ? prop : createSymbolWithType(prop, widened);
+ }
function getWidenedTypeOfObjectLiteral(type) {
- var members = transformTypeOfMembers(type, function (prop) {
- var widened = getWidenedType(prop);
- return prop === widened ? prop : widened;
- });
+ var members = ts.createMap();
+ for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
+ var prop = _a[_i];
+ // Since get accessors already widen their return value there is no need to
+ // widen accessor based properties here.
+ members.set(prop.name, prop.flags & 4 /* Property */ ? getWidenedProperty(prop) : prop);
+ }
var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
@@ -31763,25 +34443,25 @@ var ts;
var typeAsString = typeToString(getWidenedType(type));
var diagnostic;
switch (declaration.kind) {
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type;
break;
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
diagnostic = declaration.dotDotDotToken ?
ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type :
ts.Diagnostics.Parameter_0_implicitly_has_an_1_type;
break;
- case 174 /* BindingElement */:
+ case 175 /* BindingElement */:
diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
break;
- case 225 /* FunctionDeclaration */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
+ case 227 /* FunctionDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
if (!declaration.name) {
error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
@@ -31794,7 +34474,7 @@ var ts;
error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString);
}
function reportErrorsFromWidening(declaration, type) {
- if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) {
+ if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) {
// Report implicit any error within type if possible, otherwise report error on declaration
if (!reportWideningErrorsInType(type)) {
reportImplicitAnyError(declaration, type);
@@ -31821,13 +34501,14 @@ var ts;
callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
}
}
- function createInferenceContext(signature, inferUnionTypes) {
+ function createInferenceContext(signature, inferUnionTypes, useAnyForNoInferences) {
var inferences = ts.map(signature.typeParameters, createTypeInferencesObject);
return {
signature: signature,
inferUnionTypes: inferUnionTypes,
inferences: inferences,
inferredTypes: new Array(signature.typeParameters.length),
+ useAnyForNoInferences: useAnyForNoInferences
};
}
function createTypeInferencesObject() {
@@ -31841,25 +34522,73 @@ var ts;
// Return true if the given type could possibly reference a type parameter for which
// we perform type inference (i.e. a type parameter of a generic function). We cache
// results for union and intersection types for performance reasons.
- function couldContainTypeParameters(type) {
+ function couldContainTypeVariables(type) {
var objectFlags = getObjectFlags(type);
- return !!(type.flags & 16384 /* TypeParameter */ ||
- objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeParameters) ||
+ return !!(type.flags & 540672 /* TypeVariable */ ||
+ objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) ||
objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) ||
objectFlags & 32 /* Mapped */ ||
- type.flags & 196608 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeParameters(type));
+ type.flags & 196608 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type));
}
- function couldUnionOrIntersectionContainTypeParameters(type) {
- if (type.couldContainTypeParameters === undefined) {
- type.couldContainTypeParameters = ts.forEach(type.types, couldContainTypeParameters);
+ function couldUnionOrIntersectionContainTypeVariables(type) {
+ if (type.couldContainTypeVariables === undefined) {
+ type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables);
}
- return type.couldContainTypeParameters;
+ return type.couldContainTypeVariables;
}
function isTypeParameterAtTopLevel(type, typeParameter) {
return type === typeParameter || type.flags & 196608 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); });
}
- function inferTypes(context, originalSource, originalTarget) {
- var typeParameters = context.signature.typeParameters;
+ // Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
+ // an object type with the same set of properties as the source type, where the type of each
+ // property is computed by inferring from the source property type to X for the type
+ // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
+ function inferTypeForHomomorphicMappedType(source, target) {
+ var properties = getPropertiesOfType(source);
+ var indexInfo = getIndexInfoOfType(source, 0 /* String */);
+ if (properties.length === 0 && !indexInfo) {
+ return undefined;
+ }
+ var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target));
+ var typeVariableArray = [typeVariable];
+ var typeInferences = createTypeInferencesObject();
+ var typeInferencesArray = [typeInferences];
+ var templateType = getTemplateTypeFromMappedType(target);
+ var readonlyMask = target.declaration.readonlyToken ? false : true;
+ var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */;
+ var members = createSymbolTable(properties);
+ for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
+ var prop = properties_5[_i];
+ var inferredPropType = inferTargetType(getTypeOfSymbol(prop));
+ if (!inferredPropType) {
+ return undefined;
+ }
+ var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.name);
+ inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0;
+ inferredProp.declarations = prop.declarations;
+ inferredProp.type = inferredPropType;
+ members.set(prop.name, inferredProp);
+ }
+ if (indexInfo) {
+ var inferredIndexType = inferTargetType(indexInfo.type);
+ if (!inferredIndexType) {
+ return undefined;
+ }
+ indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly);
+ }
+ return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined);
+ function inferTargetType(sourceType) {
+ typeInferences.primary = undefined;
+ typeInferences.secondary = undefined;
+ inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType);
+ var inferences = typeInferences.primary || typeInferences.secondary;
+ return inferences && getUnionType(inferences, /*subtypeReduction*/ true);
+ }
+ }
+ function inferTypesWithContext(context, originalSource, originalTarget) {
+ inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget);
+ }
+ function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) {
var sourceStack;
var targetStack;
var depth = 0;
@@ -31875,7 +34604,7 @@ var ts;
return false;
}
function inferFromTypes(source, target) {
- if (!couldContainTypeParameters(target)) {
+ if (!couldContainTypeVariables(target)) {
return;
}
if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
@@ -31927,7 +34656,7 @@ var ts;
target = removeTypesFromUnionOrIntersection(target, matchingTypes);
}
}
- if (target.flags & 16384 /* TypeParameter */) {
+ if (target.flags & 540672 /* TypeVariable */) {
// If target is a type parameter, make an inference, unless the source type contains
// the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
// Because the anyFunctionType is internal, it should not be exposed to the user by adding
@@ -31937,9 +34666,9 @@ var ts;
if (source.flags & 8388608 /* ContainsAnyFunctionType */) {
return;
}
- for (var i = 0; i < typeParameters.length; i++) {
- if (target === typeParameters[i]) {
- var inferences = context.inferences[i];
+ for (var i = 0; i < typeVariables.length; i++) {
+ if (target === typeVariables[i]) {
+ var inferences = typeInferences[i];
if (!inferences.isFixed) {
// Any inferences that are made to a type parameter in a union type are inferior
// to inferences made to a flat (non-union) type. This is because if we infer to
@@ -31953,7 +34682,7 @@ var ts;
if (!ts.contains(candidates, source)) {
candidates.push(source);
}
- if (!isTypeParameterAtTopLevel(originalTarget, target)) {
+ if (target.flags & 16384 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) {
inferences.topLevel = false;
}
}
@@ -31972,25 +34701,25 @@ var ts;
}
else if (target.flags & 196608 /* UnionOrIntersection */) {
var targetTypes = target.types;
- var typeParameterCount = 0;
- var typeParameter = void 0;
- // First infer to each type in union or intersection that isn't a type parameter
- for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) {
- var t = targetTypes_2[_d];
- if (t.flags & 16384 /* TypeParameter */ && ts.contains(typeParameters, t)) {
- typeParameter = t;
- typeParameterCount++;
+ var typeVariableCount = 0;
+ var typeVariable = void 0;
+ // First infer to each type in union or intersection that isn't a type variable
+ for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) {
+ var t = targetTypes_3[_d];
+ if (t.flags & 540672 /* TypeVariable */ && ts.contains(typeVariables, t)) {
+ typeVariable = t;
+ typeVariableCount++;
}
else {
inferFromTypes(source, t);
}
}
- // Next, if target containings a single naked type parameter, make a secondary inference to that type
- // parameter. This gives meaningful results for union types in co-variant positions and intersection
+ // Next, if target containings a single naked type variable, make a secondary inference to that type
+ // variable. This gives meaningful results for union types in co-variant positions and intersection
// types in contra-variant positions (such as callback parameters).
- if (typeParameterCount === 1) {
+ if (typeVariableCount === 1) {
inferiority++;
- inferFromTypes(source, typeParameter);
+ inferFromTypes(source, typeVariable);
inferiority--;
}
}
@@ -32008,14 +34737,14 @@ var ts;
if (isInProcess(source, target)) {
return;
}
- if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) {
+ if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) {
return;
}
var key = source.id + "," + target.id;
- if (visited[key]) {
+ if (visited.get(key)) {
return;
}
- visited[key] = true;
+ visited.set(key, true);
if (depth === 0) {
sourceStack = [];
targetStack = [];
@@ -32031,12 +34760,25 @@ var ts;
function inferFromObjectTypes(source, target) {
if (getObjectFlags(target) & 32 /* Mapped */) {
var constraintType = getConstraintTypeFromMappedType(target);
- if (getObjectFlags(source) & 32 /* Mapped */) {
- inferFromTypes(getConstraintTypeFromMappedType(source), constraintType);
- inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
+ if (constraintType.flags & 262144 /* Index */) {
+ // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
+ // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
+ // type and then make a secondary inference from that type to T. We make a secondary inference
+ // such that direct inferences to T get priority over inferences to Partial<T>, for example.
+ var index = ts.indexOf(typeVariables, constraintType.type);
+ if (index >= 0 && !typeInferences[index].isFixed) {
+ var inferredType = inferTypeForHomomorphicMappedType(source, target);
+ if (inferredType) {
+ inferiority++;
+ inferFromTypes(inferredType, typeVariables[index]);
+ inferiority--;
+ }
+ }
return;
}
if (constraintType.flags & 16384 /* TypeParameter */) {
+ // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type
+ // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X.
inferFromTypes(getIndexType(source), constraintType);
inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target));
return;
@@ -32049,8 +34791,8 @@ var ts;
}
function inferFromProperties(source, target) {
var properties = getPropertiesOfObjectType(target);
- for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) {
- var targetProp = properties_4[_i];
+ for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) {
+ var targetProp = properties_6[_i];
var sourceProp = getPropertyOfObjectType(source, targetProp.name);
if (sourceProp) {
inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
@@ -32100,8 +34842,8 @@ var ts;
}
}
function typeIdenticalToSomeType(type, types) {
- for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
- var t = types_10[_i];
+ for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
+ var t = types_13[_i];
if (isTypeIdenticalTo(t, type)) {
return true;
}
@@ -32151,11 +34893,20 @@ var ts;
inferenceSucceeded = !!unionOrSuperType;
}
else {
- // Infer the empty object type when no inferences were made. It is important to remember that
- // in this case, inference still succeeds, meaning there is no error for not having inference
- // candidates. An inference error only occurs when there are *conflicting* candidates, i.e.
+ // Infer either the default or the empty object type when no inferences were
+ // made. It is important to remember that in this case, inference still
+ // succeeds, meaning there is no error for not having inference candidates. An
+ // inference error only occurs when there are *conflicting* candidates, i.e.
// candidates with no common supertype.
- inferredType = emptyObjectType;
+ var defaultType = getDefaultFromTypeParameter(context.signature.typeParameters[index]);
+ if (defaultType) {
+ // Instantiate the default type. Any forward reference to a type
+ // parameter should be instantiated to the empty object type.
+ inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), getInferenceMapper(context)));
+ }
+ else {
+ inferredType = context.useAnyForNoInferences ? anyType : emptyObjectType;
+ }
inferenceSucceeded = true;
}
context.inferredTypes[index] = inferredType;
@@ -32196,19 +34947,7 @@ var ts;
// TypeScript 1.0 spec (April 2014): 3.6.3
// A type query consists of the keyword typeof followed by an expression.
// The expression is restricted to a single identifier or a sequence of identifiers separated by periods
- while (node) {
- switch (node.kind) {
- case 160 /* TypeQuery */:
- return true;
- case 70 /* Identifier */:
- case 141 /* QualifiedName */:
- node = node.parent;
- continue;
- default:
- return false;
- }
- }
- ts.Debug.fail("should not get here");
+ return !!ts.findAncestor(node, function (n) { return n.kind === 161 /* TypeQuery */ ? true : n.kind === 70 /* Identifier */ || n.kind === 142 /* QualifiedName */ ? false : "quit"; });
}
// Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
// separated by dots). The key consists of the id of the symbol referenced by the
@@ -32222,7 +34961,7 @@ var ts;
if (node.kind === 98 /* ThisKeyword */) {
return "0";
}
- if (node.kind === 177 /* PropertyAccessExpression */) {
+ if (node.kind === 178 /* PropertyAccessExpression */) {
var key = getFlowCacheKey(node.expression);
return key && key + "." + node.name.text;
}
@@ -32233,7 +34972,7 @@ var ts;
case 70 /* Identifier */:
case 98 /* ThisKeyword */:
return node;
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
return getLeftmostIdentifierOrThis(node.expression);
}
return undefined;
@@ -32242,19 +34981,21 @@ var ts;
switch (source.kind) {
case 70 /* Identifier */:
return target.kind === 70 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
- (target.kind === 223 /* VariableDeclaration */ || target.kind === 174 /* BindingElement */) &&
+ (target.kind === 225 /* VariableDeclaration */ || target.kind === 175 /* BindingElement */) &&
getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
case 98 /* ThisKeyword */:
return target.kind === 98 /* ThisKeyword */;
- case 177 /* PropertyAccessExpression */:
- return target.kind === 177 /* PropertyAccessExpression */ &&
+ case 96 /* SuperKeyword */:
+ return target.kind === 96 /* SuperKeyword */;
+ case 178 /* PropertyAccessExpression */:
+ return target.kind === 178 /* PropertyAccessExpression */ &&
source.name.text === target.name.text &&
isMatchingReference(source.expression, target.expression);
}
return false;
}
function containsMatchingReference(source, target) {
- while (source.kind === 177 /* PropertyAccessExpression */) {
+ while (source.kind === 178 /* PropertyAccessExpression */) {
source = source.expression;
if (isMatchingReference(source, target)) {
return true;
@@ -32267,7 +35008,7 @@ var ts;
// a possible discriminant if its type differs in the constituents of containing union type, and if every
// choice is a unit type or a union of unit types.
function containsMatchingReferenceDiscriminant(source, target) {
- return target.kind === 177 /* PropertyAccessExpression */ &&
+ return target.kind === 178 /* PropertyAccessExpression */ &&
containsMatchingReference(source, target.expression) &&
isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text);
}
@@ -32275,7 +35016,7 @@ var ts;
if (expr.kind === 70 /* Identifier */) {
return getTypeOfSymbol(getResolvedSymbol(expr));
}
- if (expr.kind === 177 /* PropertyAccessExpression */) {
+ if (expr.kind === 178 /* PropertyAccessExpression */) {
var type = getDeclaredTypeOfReference(expr.expression);
return type && getTypeOfPropertyOfType(type, expr.name.text);
}
@@ -32284,9 +35025,9 @@ var ts;
function isDiscriminantProperty(type, name) {
if (type && type.flags & 65536 /* Union */) {
var prop = getUnionOrIntersectionProperty(type, name);
- if (prop && prop.flags & 268435456 /* SyntheticProperty */) {
+ if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) {
if (prop.isDiscriminantProperty === undefined) {
- prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop));
+ prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop));
}
return prop.isDiscriminantProperty;
}
@@ -32305,7 +35046,7 @@ var ts;
}
}
}
- if (callExpression.expression.kind === 177 /* PropertyAccessExpression */ &&
+ if (callExpression.expression.kind === 178 /* PropertyAccessExpression */ &&
isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
return true;
}
@@ -32347,8 +35088,8 @@ var ts;
}
function getTypeFactsOfTypes(types) {
var result = 0 /* None */;
- for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
- var t = types_11[_i];
+ for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
+ var t = types_14[_i];
result |= getTypeFacts(t);
}
return result;
@@ -32358,7 +35099,7 @@ var ts;
// check. This gives us a quicker out in the common case where an object type is not a function.
var resolved = resolveStructuredTypeMembers(type);
return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
- resolved.members["bind"] && isTypeSubtypeOf(type, globalFunctionType));
+ resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
}
function getTypeFacts(type) {
var flags = type.flags;
@@ -32401,9 +35142,11 @@ var ts;
if (flags & 512 /* ESSymbol */) {
return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */;
}
- if (flags & 16384 /* TypeParameter */) {
- var constraint = getConstraintOfTypeParameter(type);
- return getTypeFacts(constraint || emptyObjectType);
+ if (flags & 16777216 /* NonPrimitive */) {
+ return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */;
+ }
+ if (flags & 540672 /* TypeVariable */) {
+ return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType);
}
if (flags & 196608 /* UnionOrIntersection */) {
return getTypeFactsOfTypes(type.types);
@@ -32429,17 +35172,23 @@ var ts;
}
function getTypeOfDestructuredArrayElement(type, index) {
return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) ||
- checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false) ||
+ checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) ||
unknownType;
}
function getTypeOfDestructuredSpreadExpression(type) {
- return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false) || unknownType);
+ return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType);
}
function getAssignedTypeOfBinaryExpression(node) {
- return node.parent.kind === 175 /* ArrayLiteralExpression */ || node.parent.kind === 257 /* PropertyAssignment */ ?
+ var isDestructuringDefaultAssignment = node.parent.kind === 176 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
+ node.parent.kind === 260 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
+ return isDestructuringDefaultAssignment ?
getTypeWithDefault(getAssignedType(node), node.right) :
getTypeOfExpression(node.right);
}
+ function isDestructuringAssignmentTarget(parent) {
+ return parent.parent.kind === 193 /* BinaryExpression */ && parent.parent.left === parent ||
+ parent.parent.kind === 215 /* ForOfStatement */ && parent.parent.initializer === parent;
+ }
function getAssignedTypeOfArrayLiteralElement(node, element) {
return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element));
}
@@ -32455,21 +35204,21 @@ var ts;
function getAssignedType(node) {
var parent = node.parent;
switch (parent.kind) {
- case 212 /* ForInStatement */:
+ case 214 /* ForInStatement */:
return stringType;
- case 213 /* ForOfStatement */:
- return checkRightHandSideOfForOf(parent.expression) || unknownType;
- case 192 /* BinaryExpression */:
+ case 215 /* ForOfStatement */:
+ return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType;
+ case 193 /* BinaryExpression */:
return getAssignedTypeOfBinaryExpression(parent);
- case 186 /* DeleteExpression */:
+ case 187 /* DeleteExpression */:
return undefinedType;
- case 175 /* ArrayLiteralExpression */:
+ case 176 /* ArrayLiteralExpression */:
return getAssignedTypeOfArrayLiteralElement(parent, node);
- case 196 /* SpreadElement */:
+ case 197 /* SpreadElement */:
return getAssignedTypeOfSpreadExpression(parent);
- case 257 /* PropertyAssignment */:
+ case 260 /* PropertyAssignment */:
return getAssignedTypeOfPropertyAssignment(parent);
- case 258 /* ShorthandPropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
return getAssignedTypeOfShorthandPropertyAssignment(parent);
}
return unknownType;
@@ -32477,7 +35226,7 @@ var ts;
function getInitialTypeOfBindingElement(node) {
var pattern = node.parent;
var parentType = getInitialType(pattern.parent);
- var type = pattern.kind === 172 /* ObjectBindingPattern */ ?
+ var type = pattern.kind === 173 /* ObjectBindingPattern */ ?
getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
!node.dotDotDotToken ?
getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) :
@@ -32495,35 +35244,35 @@ var ts;
if (node.initializer) {
return getTypeOfInitializer(node.initializer);
}
- if (node.parent.parent.kind === 212 /* ForInStatement */) {
+ if (node.parent.parent.kind === 214 /* ForInStatement */) {
return stringType;
}
- if (node.parent.parent.kind === 213 /* ForOfStatement */) {
- return checkRightHandSideOfForOf(node.parent.parent.expression) || unknownType;
+ if (node.parent.parent.kind === 215 /* ForOfStatement */) {
+ return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType;
}
return unknownType;
}
function getInitialType(node) {
- return node.kind === 223 /* VariableDeclaration */ ?
+ return node.kind === 225 /* VariableDeclaration */ ?
getInitialTypeOfVariableDeclaration(node) :
getInitialTypeOfBindingElement(node);
}
function getInitialOrAssignedType(node) {
- return node.kind === 223 /* VariableDeclaration */ || node.kind === 174 /* BindingElement */ ?
+ return node.kind === 225 /* VariableDeclaration */ || node.kind === 175 /* BindingElement */ ?
getInitialType(node) :
getAssignedType(node);
}
function isEmptyArrayAssignment(node) {
- return node.kind === 223 /* VariableDeclaration */ && node.initializer &&
+ return node.kind === 225 /* VariableDeclaration */ && node.initializer &&
isEmptyArrayLiteral(node.initializer) ||
- node.kind !== 174 /* BindingElement */ && node.parent.kind === 192 /* BinaryExpression */ &&
+ node.kind !== 175 /* BindingElement */ && node.parent.kind === 193 /* BinaryExpression */ &&
isEmptyArrayLiteral(node.parent.right);
}
function getReferenceCandidate(node) {
switch (node.kind) {
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return getReferenceCandidate(node.expression);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
switch (node.operatorToken.kind) {
case 57 /* EqualsToken */:
return getReferenceCandidate(node.left);
@@ -32535,13 +35284,13 @@ var ts;
}
function getReferenceRoot(node) {
var parent = node.parent;
- return parent.kind === 183 /* ParenthesizedExpression */ ||
- parent.kind === 192 /* BinaryExpression */ && parent.operatorToken.kind === 57 /* EqualsToken */ && parent.left === node ||
- parent.kind === 192 /* BinaryExpression */ && parent.operatorToken.kind === 25 /* CommaToken */ && parent.right === node ?
+ return parent.kind === 184 /* ParenthesizedExpression */ ||
+ parent.kind === 193 /* BinaryExpression */ && parent.operatorToken.kind === 57 /* EqualsToken */ && parent.left === node ||
+ parent.kind === 193 /* BinaryExpression */ && parent.operatorToken.kind === 25 /* CommaToken */ && parent.right === node ?
getReferenceRoot(parent) : node;
}
function getTypeOfSwitchClause(clause) {
- if (clause.kind === 253 /* CaseClause */) {
+ if (clause.kind === 256 /* CaseClause */) {
var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
return isUnitType(caseType) ? caseType : undefined;
}
@@ -32589,8 +35338,32 @@ var ts;
}
return f(type) ? type : neverType;
}
- function mapType(type, f) {
- return type.flags & 65536 /* Union */ ? getUnionType(ts.map(type.types, f)) : f(type);
+ // Apply a mapping function to a type and return the resulting type. If the source type
+ // is a union type, the mapping function is applied to each constituent type and a union
+ // of the resulting types is returned.
+ function mapType(type, mapper) {
+ if (!(type.flags & 65536 /* Union */)) {
+ return mapper(type);
+ }
+ var types = type.types;
+ var mappedType;
+ var mappedTypes;
+ for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
+ var current = types_15[_i];
+ var t = mapper(current);
+ if (t) {
+ if (!mappedType) {
+ mappedType = t;
+ }
+ else if (!mappedTypes) {
+ mappedTypes = [mappedType, t];
+ }
+ else {
+ mappedTypes.push(t);
+ }
+ }
+ }
+ return mappedTypes ? getUnionType(mappedTypes) : mappedType;
}
function extractTypesOfKind(type, kind) {
return filterType(type, function (t) { return (t.flags & kind) !== 0; });
@@ -32634,7 +35407,7 @@ var ts;
// we defer subtype reduction until the evolving array type is finalized into a manifest
// array type.
function addEvolvingArrayElementType(evolvingArrayType, node) {
- var elementType = getBaseTypeOfLiteralType(getTypeOfExpression(node));
+ var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node));
return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
}
function createFinalArrayType(elementType) {
@@ -32656,8 +35429,8 @@ var ts;
}
function isEvolvingArrayTypeList(types) {
var hasEvolvingArrayType = false;
- for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
- var t = types_12[_i];
+ for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
+ var t = types_16[_i];
if (!(t.flags & 8192 /* Never */)) {
if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) {
return false;
@@ -32680,11 +35453,11 @@ var ts;
function isEvolvingArrayOperationTarget(node) {
var root = getReferenceRoot(node);
var parent = root.parent;
- var isLengthPushOrUnshift = parent.kind === 177 /* PropertyAccessExpression */ && (parent.name.text === "length" ||
- parent.parent.kind === 179 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name));
- var isElementAssignment = parent.kind === 178 /* ElementAccessExpression */ &&
+ var isLengthPushOrUnshift = parent.kind === 178 /* PropertyAccessExpression */ && (parent.name.text === "length" ||
+ parent.parent.kind === 180 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name));
+ var isElementAssignment = parent.kind === 179 /* ElementAccessExpression */ &&
parent.expression === root &&
- parent.parent.kind === 192 /* BinaryExpression */ &&
+ parent.parent.kind === 193 /* BinaryExpression */ &&
parent.parent.operatorToken.kind === 57 /* EqualsToken */ &&
parent.parent.left === parent &&
!ts.isAssignmentTarget(parent.parent) &&
@@ -32711,14 +35484,12 @@ var ts;
}
return false;
}
- function getFlowTypeOfReference(reference, declaredType, assumeInitialized, flowContainer) {
+ function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
+ if (initialType === void 0) { initialType = declaredType; }
var key;
- if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 1033215 /* Narrowable */)) {
+ if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810431 /* Narrowable */)) {
return declaredType;
}
- var initialType = assumeInitialized ? declaredType :
- declaredType === autoType || declaredType === autoArrayType ? undefinedType :
- includeFalsyTypes(declaredType, 2048 /* Undefined */);
var visitedFlowStart = visitedFlowCount;
var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
visitedFlowCount = visitedFlowStart;
@@ -32727,7 +35498,7 @@ var ts;
// on empty arrays are possible without implicit any errors and new element types can be inferred without
// type mismatch errors.
var resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType);
- if (reference.parent.kind === 201 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) {
+ if (reference.parent.kind === 202 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) {
return declaredType;
}
return resultType;
@@ -32744,7 +35515,19 @@ var ts;
}
}
var type = void 0;
- if (flow.flags & 16 /* Assignment */) {
+ if (flow.flags & 4096 /* AfterFinally */) {
+ // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement
+ flow.locked = true;
+ type = getTypeAtFlowNode(flow.antecedent);
+ flow.locked = false;
+ }
+ else if (flow.flags & 2048 /* PreFinally */) {
+ // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel
+ // so here just redirect to antecedent
+ flow = flow.antecedent;
+ continue;
+ }
+ else if (flow.flags & 16 /* Assignment */) {
type = getTypeAtFlowAssignment(flow);
if (!type) {
flow = flow.antecedent;
@@ -32776,7 +35559,7 @@ var ts;
else if (flow.flags & 2 /* Start */) {
// Check if we should continue with the control flow of the containing function.
var container = flow.container;
- if (container && container !== flowContainer && reference.kind !== 177 /* PropertyAccessExpression */) {
+ if (container && container !== flowContainer && reference.kind !== 178 /* PropertyAccessExpression */ && reference.kind !== 98 /* ThisKeyword */) {
flow = container.flowNode;
continue;
}
@@ -32830,7 +35613,7 @@ var ts;
}
function getTypeAtFlowArrayMutation(flow) {
var node = flow.node;
- var expr = node.kind === 179 /* CallExpression */ ?
+ var expr = node.kind === 180 /* CallExpression */ ?
node.expression.expression :
node.left.expression;
if (isMatchingReference(reference, getReferenceCandidate(expr))) {
@@ -32838,7 +35621,7 @@ var ts;
var type = getTypeFromFlowType(flowType);
if (getObjectFlags(type) & 256 /* EvolvingArray */) {
var evolvedType_1 = type;
- if (node.kind === 179 /* CallExpression */) {
+ if (node.kind === 180 /* CallExpression */) {
for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
var arg = _a[_i];
evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
@@ -32897,6 +35680,12 @@ var ts;
var seenIncomplete = false;
for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
var antecedent = _a[_i];
+ if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) {
+ // if flow correspond to branch from pre-try to finally and this branch is locked - this means that
+ // we initially have started following the flow outside the finally block.
+ // in this case we should ignore this branch.
+ continue;
+ }
var flowType = getTypeAtFlowNode(antecedent);
var type = getTypeFromFlowType(flowType);
// If the type at a particular antecedent path is the declared type and the
@@ -32929,8 +35718,9 @@ var ts;
if (!key) {
key = getFlowCacheKey(reference);
}
- if (cache[key]) {
- return cache[key];
+ var cached = cache.get(key);
+ if (cached) {
+ return cached;
}
// If this flow loop junction and reference are already being processed, return
// the union of the types computed for each branch so far, marked as incomplete.
@@ -32965,8 +35755,9 @@ var ts;
// If we see a value appear in the cache it is a sign that control flow analysis
// was restarted and completed by checkExpressionCached. We can simply pick up
// the resulting type and bail out.
- if (cache[key]) {
- return cache[key];
+ var cached_1 = cache.get(key);
+ if (cached_1) {
+ return cached_1;
}
if (!ts.contains(antecedentTypes, type)) {
antecedentTypes.push(type);
@@ -32990,10 +35781,11 @@ var ts;
if (isIncomplete(firstAntecedentType)) {
return createFlowType(result, /*incomplete*/ true);
}
- return cache[key] = result;
+ cache.set(key, result);
+ return result;
}
function isMatchingReferenceDiscriminant(expr) {
- return expr.kind === 177 /* PropertyAccessExpression */ &&
+ return expr.kind === 178 /* PropertyAccessExpression */ &&
declaredType.flags & 65536 /* Union */ &&
isMatchingReference(reference, expr.expression) &&
isDiscriminantProperty(declaredType, expr.name.text);
@@ -33027,10 +35819,10 @@ var ts;
var operator_1 = expr.operatorToken.kind;
var left_1 = getReferenceCandidate(expr.left);
var right_1 = getReferenceCandidate(expr.right);
- if (left_1.kind === 187 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) {
+ if (left_1.kind === 188 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) {
return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
}
- if (right_1.kind === 187 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) {
+ if (right_1.kind === 188 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) {
return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
}
if (isMatchingReference(reference, left_1)) {
@@ -33076,7 +35868,7 @@ var ts;
assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */;
return getTypeWithFacts(type, facts);
}
- if (type.flags & 33281 /* NotUnionOrUnit */) {
+ if (type.flags & 16810497 /* NotUnionOrUnit */) {
return type;
}
if (assumeTrue) {
@@ -33107,14 +35899,22 @@ var ts;
// We narrow a non-union type to an exact primitive type if the non-union type
// is a supertype of that primitive type. For example, type 'any' can be narrowed
// to one of the primitive types.
- var targetType = typeofTypesByName[literal.text];
- if (targetType && isTypeSubtypeOf(targetType, type)) {
- return targetType;
+ var targetType = typeofTypesByName.get(literal.text);
+ if (targetType) {
+ if (isTypeSubtypeOf(targetType, type)) {
+ return targetType;
+ }
+ if (type.flags & 540672 /* TypeVariable */) {
+ var constraint = getBaseConstraintOfType(type) || anyType;
+ if (isTypeSubtypeOf(targetType, constraint)) {
+ return getIntersectionType([type, targetType]);
+ }
+ }
}
}
var facts = assumeTrue ?
- typeofEQFacts[literal.text] || 64 /* TypeofEQHostObject */ :
- typeofNEFacts[literal.text] || 8192 /* TypeofNEHostObject */;
+ typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ :
+ typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */;
return getTypeWithFacts(type, facts);
}
function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
@@ -33197,10 +35997,9 @@ var ts;
// Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
// type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
// two types.
- var targetType = type.flags & 16384 /* TypeParameter */ ? getApparentType(type) : type;
return isTypeSubtypeOf(candidate, type) ? candidate :
isTypeAssignableTo(type, candidate) ? type :
- isTypeAssignableTo(candidate, targetType) ? candidate :
+ isTypeAssignableTo(candidate, type) ? candidate :
getIntersectionType([type, candidate]);
}
function narrowTypeByTypePredicate(type, callExpression, assumeTrue) {
@@ -33229,7 +36028,7 @@ var ts;
}
else {
var invokedExpression = ts.skipParentheses(callExpression.expression);
- if (invokedExpression.kind === 178 /* ElementAccessExpression */ || invokedExpression.kind === 177 /* PropertyAccessExpression */) {
+ if (invokedExpression.kind === 179 /* ElementAccessExpression */ || invokedExpression.kind === 178 /* PropertyAccessExpression */) {
var accessExpression = invokedExpression;
var possibleReference = ts.skipParentheses(accessExpression.expression);
if (isMatchingReference(reference, possibleReference)) {
@@ -33248,15 +36047,16 @@ var ts;
switch (expr.kind) {
case 70 /* Identifier */:
case 98 /* ThisKeyword */:
- case 177 /* PropertyAccessExpression */:
+ case 96 /* SuperKeyword */:
+ case 178 /* PropertyAccessExpression */:
return narrowTypeByTruthiness(type, expr, assumeTrue);
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
return narrowTypeByTypePredicate(type, expr, assumeTrue);
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return narrowType(type, expr.expression, assumeTrue);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return narrowTypeByBinaryExpression(type, expr, assumeTrue);
- case 190 /* PrefixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
if (expr.operator === 50 /* ExclamationToken */) {
return narrowType(type, expr.operand, !assumeTrue);
}
@@ -33289,15 +36089,12 @@ var ts;
return getTypeOfSymbol(symbol);
}
function getControlFlowContainer(node) {
- while (true) {
- node = node.parent;
- if (ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
- node.kind === 231 /* ModuleBlock */ ||
- node.kind === 261 /* SourceFile */ ||
- node.kind === 147 /* PropertyDeclaration */) {
- return node;
- }
- }
+ return ts.findAncestor(node.parent, function (node) {
+ return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
+ node.kind === 233 /* ModuleBlock */ ||
+ node.kind === 264 /* SourceFile */ ||
+ node.kind === 148 /* PropertyDeclaration */;
+ });
}
// Check if a parameter is assigned anywhere within its declaring function.
function isParameterAssigned(symbol) {
@@ -33312,21 +36109,13 @@ var ts;
return symbol.isAssigned || false;
}
function hasParentWithAssignmentsMarked(node) {
- while (true) {
- node = node.parent;
- if (!node) {
- return false;
- }
- if (ts.isFunctionLike(node) && getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */) {
- return true;
- }
- }
+ return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); });
}
function markParameterAssignments(node) {
if (node.kind === 70 /* Identifier */) {
if (ts.isAssignmentTarget(node)) {
var symbol = getResolvedSymbol(node);
- if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 144 /* Parameter */) {
+ if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 145 /* Parameter */) {
symbol.isAssigned = true;
}
}
@@ -33338,6 +36127,15 @@ var ts;
function isConstVariable(symbol) {
return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
}
+ /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
+ function removeOptionalityFromDeclaredType(declaredType, declaration) {
+ var annotationIncludesUndefined = strictNullChecks &&
+ declaration.kind === 145 /* Parameter */ &&
+ declaration.initializer &&
+ getFalsyFlags(declaredType) & 2048 /* Undefined */ &&
+ !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */);
+ return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType;
+ }
function checkIdentifier(node) {
var symbol = getResolvedSymbol(node);
if (symbol === unknownSymbol) {
@@ -33352,16 +36150,14 @@ var ts;
if (symbol === argumentsSymbol) {
var container = ts.getContainingFunction(node);
if (languageVersion < 2 /* ES2015 */) {
- if (container.kind === 185 /* ArrowFunction */) {
+ if (container.kind === 186 /* ArrowFunction */) {
error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
}
else if (ts.hasModifier(container, 256 /* Async */)) {
error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method);
}
}
- if (node.flags & 524288 /* AwaitContext */) {
- getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
- }
+ getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
return getTypeOfSymbol(symbol);
}
if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
@@ -33373,7 +36169,7 @@ var ts;
// Due to the emit for class decorators, any reference to the class from inside of the class body
// must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
// behavior of class names in ES6.
- if (declaration_1.kind === 226 /* ClassDeclaration */
+ if (declaration_1.kind === 228 /* ClassDeclaration */
&& ts.nodeIsDecorated(declaration_1)) {
var container = ts.getContainingClass(node);
while (container !== undefined) {
@@ -33385,14 +36181,14 @@ var ts;
container = ts.getContainingClass(container);
}
}
- else if (declaration_1.kind === 197 /* ClassExpression */) {
+ else if (declaration_1.kind === 198 /* ClassExpression */) {
// When we emit a class expression with static members that contain a reference
// to the constructor in the initializer, we will need to substitute that
// binding with an alias as the class name is not in scope.
var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
while (container !== undefined) {
if (container.parent === declaration_1) {
- if (container.kind === 147 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
+ if (container.kind === 148 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */;
getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */;
}
@@ -33404,6 +36200,7 @@ var ts;
}
checkCollisionWithCapturedSuperVariable(node, node);
checkCollisionWithCapturedThisVariable(node, node);
+ checkCollisionWithCapturedNewTargetVariable(node, node);
checkNestedBlockScopedBinding(node, symbol);
var type = getTypeOfSymbol(localOrExportSymbol);
var declaration = localOrExportSymbol.valueDeclaration;
@@ -33426,15 +36223,15 @@ var ts;
// The declaration container is the innermost function that encloses the declaration of the variable
// or parameter. The flow container is the innermost function starting with which we analyze the control
// flow graph to determine the control flow based type.
- var isParameter = ts.getRootDeclaration(declaration).kind === 144 /* Parameter */;
+ var isParameter = ts.getRootDeclaration(declaration).kind === 145 /* Parameter */;
var declarationContainer = getControlFlowContainer(declaration);
var flowContainer = getControlFlowContainer(node);
var isOuterVariable = flowContainer !== declarationContainer;
// When the control flow originates in a function expression or arrow function and we are referencing
// a const variable or parameter from an outer function, we extend the origin of the control flow
// analysis to include the immediately enclosing function.
- while (flowContainer !== declarationContainer && (flowContainer.kind === 184 /* FunctionExpression */ ||
- flowContainer.kind === 185 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
+ while (flowContainer !== declarationContainer && (flowContainer.kind === 185 /* FunctionExpression */ ||
+ flowContainer.kind === 186 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
(isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
flowContainer = getControlFlowContainer(flowContainer);
}
@@ -33442,15 +36239,18 @@ var ts;
// the entire control flow graph from the variable's declaration (i.e. when the flow container and
// declaration container are the same).
var assumeInitialized = isParameter || isOuterVariable ||
- type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0) ||
+ type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node)) ||
ts.isInAmbientContext(declaration);
- var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer);
+ var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) :
+ type === autoType || type === autoArrayType ? undefinedType :
+ includeFalsyTypes(type, 2048 /* Undefined */);
+ var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
// A variable is considered uninitialized when it is possible to analyze the entire control flow graph
// from declaration to use, and when the variable's declared type doesn't include undefined but the
// control flow based type does include undefined.
if (type === autoType || type === autoArrayType) {
if (flowType === autoType || flowType === autoArrayType) {
- if (compilerOptions.noImplicitAny) {
+ if (noImplicitAny) {
error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType));
error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
}
@@ -33465,19 +36265,12 @@ var ts;
return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
}
function isInsideFunction(node, threshold) {
- var current = node;
- while (current && current !== threshold) {
- if (ts.isFunctionLike(current)) {
- return true;
- }
- current = current.parent;
- }
- return false;
+ return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
}
function checkNestedBlockScopedBinding(node, symbol) {
if (languageVersion >= 2 /* ES2015 */ ||
(symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
- symbol.valueDeclaration.parent.kind === 256 /* CatchClause */) {
+ symbol.valueDeclaration.parent.kind === 259 /* CatchClause */) {
return;
}
// 1. walk from the use site up to the declaration and check
@@ -33502,8 +36295,8 @@ var ts;
}
// mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
// if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
- if (container.kind === 211 /* ForStatement */ &&
- ts.getAncestor(symbol.valueDeclaration, 224 /* VariableDeclarationList */).parent === container &&
+ if (container.kind === 213 /* ForStatement */ &&
+ ts.getAncestor(symbol.valueDeclaration, 226 /* VariableDeclarationList */).parent === container &&
isAssignedInBodyOfForStatement(node, container)) {
getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */;
}
@@ -33515,9 +36308,9 @@ var ts;
}
}
function isAssignedInBodyOfForStatement(node, container) {
- var current = node;
// skip parenthesized nodes
- while (current.parent.kind === 183 /* ParenthesizedExpression */) {
+ var current = node;
+ while (current.parent.kind === 184 /* ParenthesizedExpression */) {
current = current.parent;
}
// check if node is used as LHS in some assignment expression
@@ -33525,7 +36318,7 @@ var ts;
if (ts.isAssignmentTarget(current)) {
isAssigned = true;
}
- else if ((current.parent.kind === 190 /* PrefixUnaryExpression */ || current.parent.kind === 191 /* PostfixUnaryExpression */)) {
+ else if ((current.parent.kind === 191 /* PrefixUnaryExpression */ || current.parent.kind === 192 /* PostfixUnaryExpression */)) {
var expr = current.parent;
isAssigned = expr.operator === 42 /* PlusPlusToken */ || expr.operator === 43 /* MinusMinusToken */;
}
@@ -33534,19 +36327,11 @@ var ts;
}
// at this point we know that node is the target of assignment
// now check that modification happens inside the statement part of the ForStatement
- while (current !== container) {
- if (current === container.statement) {
- return true;
- }
- else {
- current = current.parent;
- }
- }
- return false;
+ return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
}
function captureLexicalThis(node, container) {
getNodeLinks(node).flags |= 2 /* LexicalThis */;
- if (container.kind === 147 /* PropertyDeclaration */ || container.kind === 150 /* Constructor */) {
+ if (container.kind === 148 /* PropertyDeclaration */ || container.kind === 151 /* Constructor */) {
var classNode = container.parent;
getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
}
@@ -33589,58 +36374,63 @@ var ts;
var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
return baseConstructorType === nullWideningType;
}
+ function checkThisBeforeSuper(node, container, diagnosticMessage) {
+ var containingClassDecl = container.parent;
+ var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl);
+ // If a containing class does not have extends clause or the class extends null
+ // skip checking whether super statement is called before "this" accessing.
+ if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
+ var superCall = getSuperCallInConstructor(container);
+ // We should give an error in the following cases:
+ // - No super-call
+ // - "this" is accessing before super-call.
+ // i.e super(this)
+ // this.x; super();
+ // We want to make sure that super-call is done before accessing "this" so that
+ // "this" is not accessed as a parameter of the super-call.
+ if (!superCall || superCall.end > node.pos) {
+ // In ES6, super inside constructor of class-declaration has to precede "this" accessing
+ error(node, diagnosticMessage);
+ }
+ }
+ }
function checkThisExpression(node) {
// Stop at the first arrow function so that we can
// tell whether 'this' needs to be captured.
var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
var needToCaptureLexicalThis = false;
- if (container.kind === 150 /* Constructor */) {
- var containingClassDecl = container.parent;
- var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl);
- // If a containing class does not have extends clause or the class extends null
- // skip checking whether super statement is called before "this" accessing.
- if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
- var superCall = getSuperCallInConstructor(container);
- // We should give an error in the following cases:
- // - No super-call
- // - "this" is accessing before super-call.
- // i.e super(this)
- // this.x; super();
- // We want to make sure that super-call is done before accessing "this" so that
- // "this" is not accessed as a parameter of the super-call.
- if (!superCall || superCall.end > node.pos) {
- // In ES6, super inside constructor of class-declaration has to precede "this" accessing
- error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
- }
- }
+ if (container.kind === 151 /* Constructor */) {
+ checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
}
// Now skip arrow functions to get the "real" owner of 'this'.
- if (container.kind === 185 /* ArrowFunction */) {
+ if (container.kind === 186 /* ArrowFunction */) {
container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
// When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code
needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */);
}
switch (container.kind) {
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
// do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
break;
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
// do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
break;
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
if (isInConstructorArgumentInitializer(node, container)) {
error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
+ // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
}
break;
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
if (ts.getModifierFlags(container) & 32 /* Static */) {
error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
+ // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
}
break;
- case 142 /* ComputedPropertyName */:
+ case 143 /* ComputedPropertyName */:
error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
break;
}
@@ -33652,8 +36442,8 @@ var ts;
// Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
// If this is a function in a JS file, it might be a class method. Check if it's the RHS
// of a x.prototype.y = function [name]() { .... }
- if (container.kind === 184 /* FunctionExpression */ &&
- ts.isInJavaScriptFile(container.parent) &&
+ if (container.kind === 185 /* FunctionExpression */ &&
+ container.parent.kind === 193 /* BinaryExpression */ &&
ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) {
// Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container')
var className = container.parent // x.prototype.y = f
@@ -33673,7 +36463,7 @@ var ts;
if (ts.isClassLike(container.parent)) {
var symbol = getSymbolOfNode(container.parent);
var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
- return getFlowTypeOfReference(node, type, /*assumeInitialized*/ true, /*flowContainer*/ undefined);
+ return getFlowTypeOfReference(node, type);
}
if (ts.isInJavaScriptFile(node)) {
var type = getTypeForThisExpressionFromJSDoc(container);
@@ -33681,7 +36471,7 @@ var ts;
return type;
}
}
- if (compilerOptions.noImplicitThis) {
+ if (noImplicitThis) {
// With noImplicitThis, functions may not reference 'this' if it has type 'any'
error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
}
@@ -33689,28 +36479,23 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 274 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 278 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
- if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 277 /* JSDocThisType */) {
+ if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 281 /* JSDocThisType */) {
return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
}
}
}
function isInConstructorArgumentInitializer(node, constructorDecl) {
- for (var n = node; n && n !== constructorDecl; n = n.parent) {
- if (n.kind === 144 /* Parameter */) {
- return true;
- }
- }
- return false;
+ return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 145 /* Parameter */; });
}
function checkSuperExpression(node) {
- var isCallExpression = node.parent.kind === 179 /* CallExpression */ && node.parent.expression === node;
+ var isCallExpression = node.parent.kind === 180 /* CallExpression */ && node.parent.expression === node;
var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
var needToCaptureLexicalThis = false;
// adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
if (!isCallExpression) {
- while (container && container.kind === 185 /* ArrowFunction */) {
+ while (container && container.kind === 186 /* ArrowFunction */) {
container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
}
@@ -33723,17 +36508,14 @@ var ts;
// class B {
// [super.foo()]() {}
// }
- var current = node;
- while (current && current !== container && current.kind !== 142 /* ComputedPropertyName */) {
- current = current.parent;
- }
- if (current && current.kind === 142 /* ComputedPropertyName */) {
+ var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 143 /* ComputedPropertyName */; });
+ if (current && current.kind === 143 /* ComputedPropertyName */) {
error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
}
else if (isCallExpression) {
error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
}
- else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 176 /* ObjectLiteralExpression */)) {
+ else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 177 /* ObjectLiteralExpression */)) {
error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
}
else {
@@ -33741,6 +36523,9 @@ var ts;
}
return unknownType;
}
+ if (!isCallExpression && container.kind === 151 /* Constructor */) {
+ checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
+ }
if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) {
nodeCheckFlag = 512 /* SuperStatic */;
}
@@ -33804,7 +36589,7 @@ var ts;
// This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set.
// This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment
// while a property access can.
- if (container.kind === 149 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) {
+ if (container.kind === 150 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) {
if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
}
@@ -33818,7 +36603,7 @@ var ts;
// in this case they should also use correct lexical this
captureLexicalThis(node.parent, container);
}
- if (container.parent.kind === 176 /* ObjectLiteralExpression */) {
+ if (container.parent.kind === 177 /* ObjectLiteralExpression */) {
if (languageVersion < 2 /* ES2015 */) {
error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
return unknownType;
@@ -33838,7 +36623,7 @@ var ts;
}
return unknownType;
}
- if (container.kind === 150 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
+ if (container.kind === 151 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
// issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
return unknownType;
@@ -33853,7 +36638,7 @@ var ts;
if (isCallExpression) {
// TS 1.0 SPEC (April 2014): 4.8.1
// Super calls are only permitted in constructors of derived classes
- return container.kind === 150 /* Constructor */;
+ return container.kind === 151 /* Constructor */;
}
else {
// TS 1.0 SPEC (April 2014)
@@ -33861,29 +36646,47 @@ var ts;
// - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
// - In a static member function or static member accessor
// topmost container must be something that is directly nested in the class declaration\object literal expression
- if (ts.isClassLike(container.parent) || container.parent.kind === 176 /* ObjectLiteralExpression */) {
+ if (ts.isClassLike(container.parent) || container.parent.kind === 177 /* ObjectLiteralExpression */) {
if (ts.getModifierFlags(container) & 32 /* Static */) {
- return container.kind === 149 /* MethodDeclaration */ ||
- container.kind === 148 /* MethodSignature */ ||
- container.kind === 151 /* GetAccessor */ ||
- container.kind === 152 /* SetAccessor */;
+ return container.kind === 150 /* MethodDeclaration */ ||
+ container.kind === 149 /* MethodSignature */ ||
+ container.kind === 152 /* GetAccessor */ ||
+ container.kind === 153 /* SetAccessor */;
}
else {
- return container.kind === 149 /* MethodDeclaration */ ||
- container.kind === 148 /* MethodSignature */ ||
- container.kind === 151 /* GetAccessor */ ||
- container.kind === 152 /* SetAccessor */ ||
- container.kind === 147 /* PropertyDeclaration */ ||
- container.kind === 146 /* PropertySignature */ ||
- container.kind === 150 /* Constructor */;
+ return container.kind === 150 /* MethodDeclaration */ ||
+ container.kind === 149 /* MethodSignature */ ||
+ container.kind === 152 /* GetAccessor */ ||
+ container.kind === 153 /* SetAccessor */ ||
+ container.kind === 148 /* PropertyDeclaration */ ||
+ container.kind === 147 /* PropertySignature */ ||
+ container.kind === 151 /* Constructor */;
}
}
}
return false;
}
}
+ function getContainingObjectLiteral(func) {
+ return (func.kind === 150 /* MethodDeclaration */ ||
+ func.kind === 152 /* GetAccessor */ ||
+ func.kind === 153 /* SetAccessor */) && func.parent.kind === 177 /* ObjectLiteralExpression */ ? func.parent :
+ func.kind === 185 /* FunctionExpression */ && func.parent.kind === 260 /* PropertyAssignment */ ? func.parent.parent :
+ undefined;
+ }
+ function getThisTypeArgument(type) {
+ return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined;
+ }
+ function getThisTypeFromContextualType(type) {
+ return mapType(type, function (t) {
+ return t.flags & 131072 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
+ });
+ }
function getContextualThisParameterType(func) {
- if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== 185 /* ArrowFunction */) {
+ if (func.kind === 186 /* ArrowFunction */) {
+ return undefined;
+ }
+ if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
var contextualSignature = getContextualSignature(func);
if (contextualSignature) {
var thisParameter = contextualSignature.thisParameter;
@@ -33892,6 +36695,40 @@ var ts;
}
}
}
+ if (noImplicitThis) {
+ var containingLiteral = getContainingObjectLiteral(func);
+ if (containingLiteral) {
+ // We have an object literal method. Check if the containing object literal has a contextual type
+ // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
+ // any directly enclosing object literals.
+ var contextualType = getApparentTypeOfContextualType(containingLiteral);
+ var literal = containingLiteral;
+ var type = contextualType;
+ while (type) {
+ var thisType = getThisTypeFromContextualType(type);
+ if (thisType) {
+ return instantiateType(thisType, getContextualMapper(containingLiteral));
+ }
+ if (literal.parent.kind !== 260 /* PropertyAssignment */) {
+ break;
+ }
+ literal = literal.parent.parent;
+ type = getApparentTypeOfContextualType(literal);
+ }
+ // There was no contextual ThisType<T> for the containing object literal, so the contextual type
+ // for 'this' is the non-null form of the contextual type for the containing object literal or
+ // the type of the object literal itself.
+ return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral);
+ }
+ // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
+ // contextual type for 'this' is 'obj'.
+ if (func.parent.kind === 193 /* BinaryExpression */ && func.parent.operatorToken.kind === 57 /* EqualsToken */) {
+ var target = func.parent.left;
+ if (target.kind === 178 /* PropertyAccessExpression */ || target.kind === 179 /* ElementAccessExpression */) {
+ return checkExpressionCached(target.expression);
+ }
+ }
+ }
return undefined;
}
// Return contextual type of parameter or undefined if no contextual type is available
@@ -33899,23 +36736,23 @@ var ts;
var func = parameter.parent;
if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
var iife = ts.getImmediatelyInvokedFunctionExpression(func);
- if (iife) {
+ if (iife && iife.arguments) {
var indexOfParameter = ts.indexOf(func.parameters, parameter);
- if (iife.arguments && indexOfParameter < iife.arguments.length) {
- if (parameter.dotDotDotToken) {
- var restTypes = [];
- for (var i = indexOfParameter; i < iife.arguments.length; i++) {
- restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i])));
- }
- return createArrayType(getUnionType(restTypes));
- }
- var links = getNodeLinks(iife);
- var cached = links.resolvedSignature;
- links.resolvedSignature = anySignature;
- var type = getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter]));
- links.resolvedSignature = cached;
- return type;
- }
+ if (parameter.dotDotDotToken) {
+ var restTypes = [];
+ for (var i = indexOfParameter; i < iife.arguments.length; i++) {
+ restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i])));
+ }
+ return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined;
+ }
+ var links = getNodeLinks(iife);
+ var cached = links.resolvedSignature;
+ links.resolvedSignature = anySignature;
+ var type = indexOfParameter < iife.arguments.length ?
+ getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) :
+ parameter.initializer ? undefined : undefinedWideningType;
+ links.resolvedSignature = cached;
+ return type;
}
var contextualSignature = getContextualSignature(func);
if (contextualSignature) {
@@ -33949,7 +36786,7 @@ var ts;
if (declaration.type) {
return getTypeFromTypeNode(declaration.type);
}
- if (declaration.kind === 144 /* Parameter */) {
+ if (declaration.kind === 145 /* Parameter */) {
var type = getContextuallyTypedParameterType(declaration);
if (type) {
return type;
@@ -33960,11 +36797,11 @@ var ts;
}
if (ts.isBindingPattern(declaration.parent)) {
var parentDeclaration = declaration.parent.parent;
- var name_19 = declaration.propertyName || declaration.name;
- if (ts.isVariableLike(parentDeclaration) &&
+ var name = declaration.propertyName || declaration.name;
+ if (parentDeclaration.kind !== 175 /* BindingElement */ &&
parentDeclaration.type &&
- !ts.isBindingPattern(name_19)) {
- var text = ts.getTextOfPropertyName(name_19);
+ !ts.isBindingPattern(name)) {
+ var text = ts.getTextOfPropertyName(name);
if (text) {
return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text);
}
@@ -33975,33 +36812,34 @@ var ts;
}
function getContextualTypeForReturnExpression(node) {
var func = ts.getContainingFunction(node);
- if (ts.isAsyncFunctionLike(func)) {
- var contextualReturnType = getContextualReturnType(func);
- if (contextualReturnType) {
- return getPromisedType(contextualReturnType);
+ if (func) {
+ var functionFlags = ts.getFunctionFlags(func);
+ if (functionFlags & 1 /* Generator */) {
+ return undefined;
}
- return undefined;
- }
- if (func && !func.asteriskToken) {
- return getContextualReturnType(func);
+ var contextualReturnType = getContextualReturnType(func);
+ return functionFlags & 2 /* Async */
+ ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function
+ : contextualReturnType; // Regular function
}
return undefined;
}
function getContextualTypeForYieldOperand(node) {
var func = ts.getContainingFunction(node);
if (func) {
+ var functionFlags = ts.getFunctionFlags(func);
var contextualReturnType = getContextualReturnType(func);
if (contextualReturnType) {
return node.asteriskToken
? contextualReturnType
- : getElementTypeOfIterableIterator(contextualReturnType);
+ : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
}
}
return undefined;
}
function isInParameterInitializerBeforeContainingFunction(node) {
while (node.parent && !ts.isFunctionLike(node.parent)) {
- if (node.parent.kind === 144 /* Parameter */ && node.parent.initializer === node) {
+ if (node.parent.kind === 145 /* Parameter */ && node.parent.initializer === node) {
return true;
}
node = node.parent;
@@ -34012,8 +36850,8 @@ var ts;
// If the containing function has a return type annotation, is a constructor, or is a get accessor whose
// corresponding set accessor has a type annotation, return statements in the function are contextually typed
if (functionDecl.type ||
- functionDecl.kind === 150 /* Constructor */ ||
- functionDecl.kind === 151 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 152 /* SetAccessor */))) {
+ functionDecl.kind === 151 /* Constructor */ ||
+ functionDecl.kind === 152 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 153 /* SetAccessor */))) {
return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl));
}
// Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
@@ -34035,7 +36873,7 @@ var ts;
return undefined;
}
function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
- if (template.parent.kind === 181 /* TaggedTemplateExpression */) {
+ if (template.parent.kind === 182 /* TaggedTemplateExpression */) {
return getContextualTypeForArgument(template.parent, substitutionExpression);
}
return undefined;
@@ -34069,41 +36907,14 @@ var ts;
}
return undefined;
}
- // Apply a mapping function to a contextual type and return the resulting type. If the contextual type
- // is a union type, the mapping function is applied to each constituent type and a union of the resulting
- // types is returned.
- function applyToContextualType(type, mapper) {
- if (!(type.flags & 65536 /* Union */)) {
- return mapper(type);
- }
- var types = type.types;
- var mappedType;
- var mappedTypes;
- for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
- var current = types_13[_i];
- var t = mapper(current);
- if (t) {
- if (!mappedType) {
- mappedType = t;
- }
- else if (!mappedTypes) {
- mappedTypes = [mappedType, t];
- }
- else {
- mappedTypes.push(t);
- }
- }
- }
- return mappedTypes ? getUnionType(mappedTypes) : mappedType;
- }
function getTypeOfPropertyOfContextualType(type, name) {
- return applyToContextualType(type, function (t) {
+ return mapType(type, function (t) {
var prop = t.flags & 229376 /* StructuredType */ ? getPropertyOfType(t, name) : undefined;
return prop ? getTypeOfSymbol(prop) : undefined;
});
}
function getIndexTypeOfContextualType(type, kind) {
- return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); });
+ return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); });
}
// Return true if the given contextual type is a tuple-like type
function contextualTypeIsTupleLikeType(type) {
@@ -34150,7 +36961,7 @@ var ts;
var index = ts.indexOf(arrayLiteral.elements, node);
return getTypeOfPropertyOfContextualType(type, "" + index)
|| getIndexTypeOfContextualType(type, 1 /* Number */)
- || (languageVersion >= 2 /* ES2015 */ ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined);
+ || getIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false, /*checkAssignability*/ false);
}
return undefined;
}
@@ -34160,19 +36971,19 @@ var ts;
return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined;
}
function getContextualTypeForJsxAttribute(attribute) {
- var kind = attribute.kind;
- var jsxElement = attribute.parent;
- var attrsType = getJsxElementAttributesType(jsxElement);
- if (attribute.kind === 250 /* JsxAttribute */) {
- if (!attrsType || isTypeAny(attrsType)) {
+ // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
+ // which is a type of the parameter of the signature we are trying out.
+ // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
+ var attributesType = getContextualType(attribute.parent);
+ if (ts.isJsxAttribute(attribute)) {
+ if (!attributesType || isTypeAny(attributesType)) {
return undefined;
}
- return getTypeOfPropertyOfType(attrsType, attribute.name.text);
+ return getTypeOfPropertyOfType(attributesType, attribute.name.text);
}
- else if (attribute.kind === 251 /* JsxSpreadAttribute */) {
- return attrsType;
+ else {
+ return attributesType;
}
- ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]");
}
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
@@ -34207,45 +37018,52 @@ var ts;
}
var parent = node.parent;
switch (parent.kind) {
- case 223 /* VariableDeclaration */:
- case 144 /* Parameter */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 174 /* BindingElement */:
+ case 225 /* VariableDeclaration */:
+ case 145 /* Parameter */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 175 /* BindingElement */:
return getContextualTypeForInitializerExpression(node);
- case 185 /* ArrowFunction */:
- case 216 /* ReturnStatement */:
+ case 186 /* ArrowFunction */:
+ case 218 /* ReturnStatement */:
return getContextualTypeForReturnExpression(node);
- case 195 /* YieldExpression */:
+ case 196 /* YieldExpression */:
return getContextualTypeForYieldOperand(parent);
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
return getContextualTypeForArgument(parent, node);
- case 182 /* TypeAssertionExpression */:
- case 200 /* AsExpression */:
+ case 183 /* TypeAssertionExpression */:
+ case 201 /* AsExpression */:
return getTypeFromTypeNode(parent.type);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return getContextualTypeForBinaryOperand(node);
- case 257 /* PropertyAssignment */:
- case 258 /* ShorthandPropertyAssignment */:
+ case 260 /* PropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
return getContextualTypeForObjectLiteralElement(parent);
- case 175 /* ArrayLiteralExpression */:
+ case 176 /* ArrayLiteralExpression */:
return getContextualTypeForElementExpression(node);
- case 193 /* ConditionalExpression */:
+ case 194 /* ConditionalExpression */:
return getContextualTypeForConditionalOperand(node);
- case 202 /* TemplateSpan */:
- ts.Debug.assert(parent.parent.kind === 194 /* TemplateExpression */);
+ case 204 /* TemplateSpan */:
+ ts.Debug.assert(parent.parent.kind === 195 /* TemplateExpression */);
return getContextualTypeForSubstitutionExpression(parent.parent, node);
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return getContextualType(parent);
- case 252 /* JsxExpression */:
+ case 255 /* JsxExpression */:
return getContextualType(parent);
- case 250 /* JsxAttribute */:
- case 251 /* JsxSpreadAttribute */:
+ case 252 /* JsxAttribute */:
+ case 254 /* JsxSpreadAttribute */:
return getContextualTypeForJsxAttribute(parent);
+ case 250 /* JsxOpeningElement */:
+ case 249 /* JsxSelfClosingElement */:
+ return getAttributesTypeFromJsxOpeningLikeElement(parent);
}
return undefined;
}
+ function getContextualMapper(node) {
+ node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; });
+ return node ? node.contextualMapper : identityMapper;
+ }
// If the given type is an object or union type, if that type has a single signature, and if
// that signature is non-generic, return the signature. Otherwise return undefined.
function getNonGenericSignature(type, node) {
@@ -34273,7 +37091,7 @@ var ts;
return sourceLength < targetParameterCount;
}
function isFunctionExpressionOrArrowFunction(node) {
- return node.kind === 184 /* FunctionExpression */ || node.kind === 185 /* ArrowFunction */;
+ return node.kind === 185 /* FunctionExpression */ || node.kind === 186 /* ArrowFunction */;
}
function getContextualSignatureForFunctionLikeDeclaration(node) {
// Only function expressions, arrow functions, and object literal methods are contextually typed.
@@ -34292,7 +37110,7 @@ var ts;
// all identical ignoring their return type, the result is same signature but with return type as
// union type of return types from these signatures
function getContextualSignature(node) {
- ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
+ ts.Debug.assert(node.kind !== 150 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
var type = getContextualTypeForFunctionLikeDeclaration(node);
if (!type) {
return undefined;
@@ -34302,8 +37120,8 @@ var ts;
}
var signatureList;
var types = type.types;
- for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
- var current = types_14[_i];
+ for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
+ var current = types_17[_i];
var signature = getNonGenericSignature(current, node);
if (signature) {
if (!signatureList) {
@@ -34330,46 +37148,25 @@ var ts;
}
return result;
}
- /**
- * Detect if the mapper implies an inference context. Specifically, there are 4 possible values
- * for a mapper. Let's go through each one of them:
- *
- * 1. undefined - this means we are not doing inferential typing, but we may do contextual typing,
- * which could cause us to assign a parameter a type
- * 2. identityMapper - means we want to avoid assigning a parameter a type, whether or not we are in
- * inferential typing (context is undefined for the identityMapper)
- * 3. a mapper created by createInferenceMapper - we are doing inferential typing, we want to assign
- * types to parameters and fix type parameters (context is defined)
- * 4. an instantiation mapper created by createTypeMapper or createTypeEraser - this should never be
- * passed as the contextual mapper when checking an expression (context is undefined for these)
- *
- * isInferentialContext is detecting if we are in case 3
- */
- function isInferentialContext(mapper) {
- return mapper && mapper.context;
- }
- function checkSpreadExpression(node, contextualMapper) {
- // It is usually not safe to call checkExpressionCached if we can be contextually typing.
- // You can tell that we are contextually typing because of the contextualMapper parameter.
- // While it is true that a spread element can have a contextual type, it does not do anything
- // with this type. It is neither affected by it, nor does it propagate it to its operand.
- // So the fact that contextualMapper is passed is not important, because the operand of a spread
- // element is not contextually typed.
- var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper);
- return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false);
+ function checkSpreadExpression(node, checkMode) {
+ if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
+ checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */);
+ }
+ var arrayOrIterableType = checkExpression(node.expression, checkMode);
+ return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterable*/ false);
}
function hasDefaultValue(node) {
- return (node.kind === 174 /* BindingElement */ && !!node.initializer) ||
- (node.kind === 192 /* BinaryExpression */ && node.operatorToken.kind === 57 /* EqualsToken */);
+ return (node.kind === 175 /* BindingElement */ && !!node.initializer) ||
+ (node.kind === 193 /* BinaryExpression */ && node.operatorToken.kind === 57 /* EqualsToken */);
}
- function checkArrayLiteral(node, contextualMapper) {
+ function checkArrayLiteral(node, checkMode) {
var elements = node.elements;
var hasSpreadElement = false;
var elementTypes = [];
var inDestructuringPattern = ts.isAssignmentTarget(node);
for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
var e = elements_1[_i];
- if (inDestructuringPattern && e.kind === 196 /* SpreadElement */) {
+ if (inDestructuringPattern && e.kind === 197 /* SpreadElement */) {
// Given the following situation:
// var c: {};
// [...c] = ["", 0];
@@ -34382,18 +37179,18 @@ var ts;
// get the contextual element type from it. So we do something similar to
// getContextualTypeForElementExpression, which will crucially not error
// if there is no index type / iterated type.
- var restArrayType = checkExpression(e.expression, contextualMapper);
+ var restArrayType = checkExpression(e.expression, checkMode);
var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) ||
- (languageVersion >= 2 /* ES2015 */ ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined);
+ getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false, /*checkAssignability*/ false);
if (restElementType) {
elementTypes.push(restElementType);
}
}
else {
- var type = checkExpressionForMutableLocation(e, contextualMapper);
+ var type = checkExpressionForMutableLocation(e, checkMode);
elementTypes.push(type);
}
- hasSpreadElement = hasSpreadElement || e.kind === 196 /* SpreadElement */;
+ hasSpreadElement = hasSpreadElement || e.kind === 197 /* SpreadElement */;
}
if (!hasSpreadElement) {
// If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
@@ -34408,7 +37205,7 @@ var ts;
var pattern = contextualType.pattern;
// If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting
// tuple type with the corresponding binding or assignment element types to make the lengths equal.
- if (pattern && (pattern.kind === 173 /* ArrayBindingPattern */ || pattern.kind === 175 /* ArrayLiteralExpression */)) {
+ if (pattern && (pattern.kind === 174 /* ArrayBindingPattern */ || pattern.kind === 176 /* ArrayLiteralExpression */)) {
var patternElements = pattern.elements;
for (var i = elementTypes.length; i < patternElements.length; i++) {
var patternElement = patternElements[i];
@@ -34416,7 +37213,7 @@ var ts;
elementTypes.push(contextualType.typeArguments[i]);
}
else {
- if (patternElement.kind !== 198 /* OmittedExpression */) {
+ if (patternElement.kind !== 199 /* OmittedExpression */) {
error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
}
elementTypes.push(unknownType);
@@ -34433,7 +37230,7 @@ var ts;
strictNullChecks ? neverType : undefinedWideningType);
}
function isNumericName(name) {
- return name.kind === 142 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text);
+ return name.kind === 143 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text);
}
function isNumericComputedName(name) {
// It seems odd to consider an expression of type Any to result in a numeric name,
@@ -34495,7 +37292,7 @@ var ts;
var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType;
return createIndexInfo(unionType, /*isReadonly*/ false);
}
- function checkObjectLiteral(node, contextualMapper) {
+ function checkObjectLiteral(node, checkMode) {
var inDestructuringPattern = ts.isAssignmentTarget(node);
// Grammar checking
checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
@@ -34505,7 +37302,8 @@ var ts;
var propagatedFlags = 0;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
- (contextualType.pattern.kind === 172 /* ObjectBindingPattern */ || contextualType.pattern.kind === 176 /* ObjectLiteralExpression */);
+ (contextualType.pattern.kind === 173 /* ObjectBindingPattern */ || contextualType.pattern.kind === 177 /* ObjectLiteralExpression */);
+ var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node);
var typeFlags = 0;
var patternWithComputedProperties = false;
var hasComputedStringProperty = false;
@@ -34514,29 +37312,29 @@ var ts;
for (var i = 0; i < node.properties.length; i++) {
var memberDecl = node.properties[i];
var member = memberDecl.symbol;
- if (memberDecl.kind === 257 /* PropertyAssignment */ ||
- memberDecl.kind === 258 /* ShorthandPropertyAssignment */ ||
+ if (memberDecl.kind === 260 /* PropertyAssignment */ ||
+ memberDecl.kind === 261 /* ShorthandPropertyAssignment */ ||
ts.isObjectLiteralMethod(memberDecl)) {
var type = void 0;
- if (memberDecl.kind === 257 /* PropertyAssignment */) {
- type = checkPropertyAssignment(memberDecl, contextualMapper);
+ if (memberDecl.kind === 260 /* PropertyAssignment */) {
+ type = checkPropertyAssignment(memberDecl, checkMode);
}
- else if (memberDecl.kind === 149 /* MethodDeclaration */) {
- type = checkObjectLiteralMethod(memberDecl, contextualMapper);
+ else if (memberDecl.kind === 150 /* MethodDeclaration */) {
+ type = checkObjectLiteralMethod(memberDecl, checkMode);
}
else {
- ts.Debug.assert(memberDecl.kind === 258 /* ShorthandPropertyAssignment */);
- type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper);
+ ts.Debug.assert(memberDecl.kind === 261 /* ShorthandPropertyAssignment */);
+ type = checkExpressionForMutableLocation(memberDecl.name, checkMode);
}
typeFlags |= type.flags;
- var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | member.flags, member.name);
+ var prop = createSymbol(4 /* Property */ | member.flags, member.name);
if (inDestructuringPattern) {
// If object literal is an assignment pattern and if the assignment pattern specifies a default value
// for the property, make the property optional.
- var isOptional = (memberDecl.kind === 257 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
- (memberDecl.kind === 258 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
+ var isOptional = (memberDecl.kind === 260 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
+ (memberDecl.kind === 261 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
if (isOptional) {
- prop.flags |= 536870912 /* Optional */;
+ prop.flags |= 67108864 /* Optional */;
}
if (ts.hasDynamicName(memberDecl)) {
patternWithComputedProperties = true;
@@ -34547,9 +37345,9 @@ var ts;
// binding pattern specifies a default value for the property, make the property optional.
var impliedProp = getPropertyOfType(contextualType, member.name);
if (impliedProp) {
- prop.flags |= impliedProp.flags & 536870912 /* Optional */;
+ prop.flags |= impliedProp.flags & 67108864 /* Optional */;
}
- else if (!compilerOptions.suppressExcessPropertyErrors) {
+ else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
}
}
@@ -34562,9 +37360,12 @@ var ts;
prop.target = member;
member = prop;
}
- else if (memberDecl.kind === 259 /* SpreadAssignment */) {
+ else if (memberDecl.kind === 262 /* SpreadAssignment */) {
+ if (languageVersion < 2 /* ES2015 */) {
+ checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
+ }
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true);
+ spread = getSpreadType(spread, createObjectLiteralType());
propertiesArray = [];
propertiesTable = ts.createMap();
hasComputedStringProperty = false;
@@ -34572,11 +37373,11 @@ var ts;
typeFlags = 0;
}
var type = checkExpression(memberDecl.expression);
- if (!(type.flags & (32768 /* Object */ | 1 /* Any */))) {
+ if (!isValidSpreadType(type)) {
error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
return unknownType;
}
- spread = getSpreadType(spread, type, /*isFromObjectLiteral*/ false);
+ spread = getSpreadType(spread, type);
offset = i + 1;
continue;
}
@@ -34586,8 +37387,8 @@ var ts;
// an ordinary function declaration(section 6.1) with no parameters.
// A set accessor declaration is processed in the same manner
// as an ordinary function declaration with a single parameter and a Void return type.
- ts.Debug.assert(memberDecl.kind === 151 /* GetAccessor */ || memberDecl.kind === 152 /* SetAccessor */);
- checkAccessorDeclaration(memberDecl);
+ ts.Debug.assert(memberDecl.kind === 152 /* GetAccessor */ || memberDecl.kind === 153 /* SetAccessor */);
+ checkNodeDeferred(memberDecl);
}
if (ts.hasDynamicName(memberDecl)) {
if (isNumericName(memberDecl.name)) {
@@ -34598,7 +37399,7 @@ var ts;
}
}
else {
- propertiesTable[member.name] = member;
+ propertiesTable.set(member.name, member);
}
propertiesArray.push(member);
}
@@ -34607,27 +37408,30 @@ var ts;
if (contextualTypeHasPattern) {
for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) {
var prop = _a[_i];
- if (!propertiesTable[prop.name]) {
- if (!(prop.flags & 536870912 /* Optional */)) {
+ if (!propertiesTable.get(prop.name)) {
+ if (!(prop.flags & 67108864 /* Optional */)) {
error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
}
- propertiesTable[prop.name] = prop;
+ propertiesTable.set(prop.name, prop);
propertiesArray.push(prop);
}
}
}
if (spread !== emptyObjectType) {
if (propertiesArray.length > 0) {
- spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true);
+ spread = getSpreadType(spread, createObjectLiteralType());
+ }
+ if (spread.flags & 32768 /* Object */) {
+ // only set the symbol and flags if this is a (fresh) object type
+ spread.flags |= propagatedFlags;
+ spread.symbol = node.symbol;
}
- spread.flags |= propagatedFlags;
- spread.symbol = node.symbol;
return spread;
}
return createObjectLiteralType();
function createObjectLiteralType() {
- var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined;
- var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined;
+ var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined;
+ var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined;
var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo);
var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */;
result.flags |= 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */);
@@ -34644,9 +37448,14 @@ var ts;
return result;
}
}
+ function isValidSpreadType(type) {
+ return !!(type.flags & (1 /* Any */ | 4096 /* Null */ | 2048 /* Undefined */ | 16777216 /* NonPrimitive */) ||
+ type.flags & 32768 /* Object */ && !isGenericMappedType(type) ||
+ type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); }));
+ }
function checkJsxSelfClosingElement(node) {
checkJsxOpeningLikeElement(node);
- return jsxElementType || anyType;
+ return getJsxGlobalElementType() || anyType;
}
function checkJsxElement(node) {
// Check attributes
@@ -34662,18 +37471,18 @@ var ts;
for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
var child = _a[_i];
switch (child.kind) {
- case 252 /* JsxExpression */:
+ case 255 /* JsxExpression */:
checkJsxExpression(child);
break;
- case 246 /* JsxElement */:
+ case 248 /* JsxElement */:
checkJsxElement(child);
break;
- case 247 /* JsxSelfClosingElement */:
+ case 249 /* JsxSelfClosingElement */:
checkJsxSelfClosingElement(child);
break;
}
}
- return jsxElementType || anyType;
+ return getJsxGlobalElementType() || anyType;
}
/**
* Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
@@ -34687,81 +37496,114 @@ var ts;
*/
function isJsxIntrinsicIdentifier(tagName) {
// TODO (yuisu): comment
- if (tagName.kind === 177 /* PropertyAccessExpression */ || tagName.kind === 98 /* ThisKeyword */) {
+ if (tagName.kind === 178 /* PropertyAccessExpression */ || tagName.kind === 98 /* ThisKeyword */) {
return false;
}
else {
return ts.isIntrinsicJsxName(tagName.text);
}
}
- function checkJsxAttribute(node, elementAttributesType, nameTable) {
- var correspondingPropType = undefined;
- // Look up the corresponding property for this attribute
- if (elementAttributesType === emptyObjectType && isUnhyphenatedJsxName(node.name.text)) {
- // If there is no 'props' property, you may not have non-"data-" attributes
- error(node.parent, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName());
- }
- else if (elementAttributesType && !isTypeAny(elementAttributesType)) {
- var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text);
- correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol);
- if (isUnhyphenatedJsxName(node.name.text)) {
- var attributeType = getTypeOfPropertyOfType(elementAttributesType, ts.getTextOfPropertyName(node.name)) || getIndexTypeOfType(elementAttributesType, 0 /* String */);
- if (attributeType) {
- correspondingPropType = attributeType;
+ /**
+ * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
+ *
+ * @param openingLikeElement a JSX opening-like element
+ * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
+ * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
+ * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
+ * which also calls getSpreadType.
+ */
+ function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) {
+ var attributes = openingLikeElement.attributes;
+ var attributesTable = ts.createMap();
+ var spread = emptyObjectType;
+ var attributesArray = [];
+ for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
+ var attributeDecl = _a[_i];
+ var member = attributeDecl.symbol;
+ if (ts.isJsxAttribute(attributeDecl)) {
+ var exprType = attributeDecl.initializer ?
+ checkExpression(attributeDecl.initializer, checkMode) :
+ trueType; // <Elem attr /> is sugar for <Elem attr={true} />
+ var attributeSymbol = createSymbol(4 /* Property */ | 134217728 /* Transient */ | member.flags, member.name);
+ attributeSymbol.declarations = member.declarations;
+ attributeSymbol.parent = member.parent;
+ if (member.valueDeclaration) {
+ attributeSymbol.valueDeclaration = member.valueDeclaration;
}
- else {
- // If there's no corresponding property with this name, error
- if (!correspondingPropType) {
- error(node.name, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.name.text, typeToString(elementAttributesType));
- return unknownType;
- }
+ attributeSymbol.type = exprType;
+ attributeSymbol.target = member;
+ attributesTable.set(attributeSymbol.name, attributeSymbol);
+ attributesArray.push(attributeSymbol);
+ }
+ else {
+ ts.Debug.assert(attributeDecl.kind === 254 /* JsxSpreadAttribute */);
+ if (attributesArray.length > 0) {
+ spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable));
+ attributesArray = [];
+ attributesTable = ts.createMap();
+ }
+ var exprType = checkExpression(attributeDecl.expression);
+ if (!isValidSpreadType(exprType)) {
+ error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
+ return anyType;
+ }
+ if (isTypeAny(exprType)) {
+ return anyType;
}
+ spread = getSpreadType(spread, exprType);
}
}
- var exprType;
- if (node.initializer) {
- exprType = checkExpression(node.initializer);
+ if (spread !== emptyObjectType) {
+ if (attributesArray.length > 0) {
+ spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable));
+ attributesArray = [];
+ attributesTable = ts.createMap();
+ }
+ attributesArray = getPropertiesOfType(spread);
}
- else {
- // <Elem attr /> is sugar for <Elem attr={true} />
- exprType = booleanType;
+ attributesTable = ts.createMap();
+ if (attributesArray) {
+ ts.forEach(attributesArray, function (attr) {
+ if (!filter || filter(attr)) {
+ attributesTable.set(attr.name, attr);
+ }
+ });
}
- if (correspondingPropType) {
- checkTypeAssignableTo(exprType, correspondingPropType, node);
+ return createJsxAttributesType(attributes.symbol, attributesTable);
+ /**
+ * Create anonymous type from given attributes symbol table.
+ * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
+ * @param attributesTable a symbol table of attributes property
+ */
+ function createJsxAttributesType(symbol, attributesTable) {
+ var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
+ var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */;
+ result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag;
+ result.objectFlags |= 128 /* ObjectLiteral */;
+ return result;
}
- nameTable[node.name.text] = true;
- return exprType;
}
- function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) {
- var type = checkExpression(node.expression);
- var props = getPropertiesOfType(type);
- for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
- var prop = props_2[_i];
- // Is there a corresponding property in the element attributes type? Skip checking of properties
- // that have already been assigned to, as these are not actually pushed into the resulting type
- if (!nameTable[prop.name]) {
- var targetPropSym = getPropertyOfType(elementAttributesType, prop.name);
- if (targetPropSym) {
- var msg = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property, prop.name);
- checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(targetPropSym), node, undefined, msg);
- }
- nameTable[prop.name] = true;
- }
- }
- return type;
+ /**
+ * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
+ * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
+ * @param node a JSXAttributes to be resolved of its type
+ */
+ function checkJsxAttributes(node, checkMode) {
+ return createJsxAttributesTypeFromAttributesProperty(node.parent, /*filter*/ undefined, checkMode);
}
function getJsxType(name) {
- if (jsxTypes[name] === undefined) {
- return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType;
+ var jsxType = jsxTypes.get(name);
+ if (jsxType === undefined) {
+ jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType);
}
- return jsxTypes[name];
+ return jsxType;
}
/**
- * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
- * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
- * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
- * May also return unknownSymbol if both of these lookups fail.
- */
+ * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
+ * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
+ * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
+ * May also return unknownSymbol if both of these lookups fail.
+ */
function getIntrinsicTagSymbol(node) {
var links = getNodeLinks(node);
if (!links.resolvedSymbol) {
@@ -34784,7 +37626,7 @@ var ts;
return links.resolvedSymbol = unknownSymbol;
}
else {
- if (compilerOptions.noImplicitAny) {
+ if (noImplicitAny) {
error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements);
}
return links.resolvedSymbol = unknownSymbol;
@@ -34849,28 +37691,133 @@ var ts;
}
}
/**
- * Given React element instance type and the class type, resolve the Jsx type
- * Pass elemType to handle individual type in the union typed element type.
- */
- function getResolvedJsxType(node, elemType, elemClassType) {
- if (!elemType) {
- elemType = checkExpression(node.tagName);
+ * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component.
+ * Return only attributes type of successfully resolved call signature.
+ * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component)
+ * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers.
+ * @param openingLikeElement a JSX opening-like element to find attributes type
+ * @param elementType a type of the opening-like element. This elementType can't be an union type
+ * @param elemInstanceType an element instance type (the result of newing or invoking this tag)
+ * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global
+ */
+ function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
+ ts.Debug.assert(!(elementType.flags & 65536 /* Union */));
+ if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
+ var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ if (jsxStatelessElementType) {
+ // We don't call getResolvedSignature here because we have already resolve the type of JSX Element.
+ var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined);
+ if (callSignature !== unknownSignature) {
+ var callReturnType = callSignature && getReturnTypeOfSignature(callSignature);
+ var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0]));
+ if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
+ // Intersect in JSX.IntrinsicAttributes if it exists
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ if (intrinsicAttributes !== unknownType) {
+ paramType = intersectTypes(intrinsicAttributes, paramType);
+ }
+ return paramType;
+ }
+ }
+ }
}
- if (elemType.flags & 65536 /* Union */) {
- var types = elemType.types;
- return getUnionType(ts.map(types, function (type) {
- return getResolvedJsxType(node, type, elemClassType);
+ return undefined;
+ }
+ /**
+ * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component.
+ * Return all attributes type of resolved call signature including candidate signatures.
+ * This function assumes that the caller handled other possible element type of the JSX element.
+ * This function is a behavior used by language service when looking up completion in JSX element.
+ * @param openingLikeElement a JSX opening-like element to find attributes type
+ * @param elementType a type of the opening-like element. This elementType can't be an union type
+ * @param elemInstanceType an element instance type (the result of newing or invoking this tag)
+ * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global
+ */
+ function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) {
+ ts.Debug.assert(!(elementType.flags & 65536 /* Union */));
+ if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
+ // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type
+ var jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ if (jsxStatelessElementType) {
+ // We don't call getResolvedSignature because here we have already resolve the type of JSX Element.
+ var candidatesOutArray = [];
+ getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray);
+ var result = void 0;
+ var allMatchingAttributesType = void 0;
+ for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) {
+ var candidate = candidatesOutArray_1[_i];
+ var callReturnType = getReturnTypeOfSignature(candidate);
+ var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0]));
+ if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
+ var shouldBeCandidate = true;
+ for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) {
+ var attribute = _b[_a];
+ if (ts.isJsxAttribute(attribute) &&
+ isUnhyphenatedJsxName(attribute.name.text) &&
+ !getPropertyOfType(paramType, attribute.name.text)) {
+ shouldBeCandidate = false;
+ break;
+ }
+ }
+ if (shouldBeCandidate) {
+ result = intersectTypes(result, paramType);
+ }
+ allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType);
+ }
+ }
+ // If we can't find any matching, just return everything.
+ if (!result) {
+ result = allMatchingAttributesType;
+ }
+ // Intersect in JSX.IntrinsicAttributes if it exists
+ var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
+ if (intrinsicAttributes !== unknownType) {
+ result = intersectTypes(intrinsicAttributes, result);
+ }
+ return result;
+ }
+ }
+ return undefined;
+ }
+ /**
+ * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType.
+ * For instance:
+ * declare function Foo(attr: { p1: string}): JSX.Element;
+ * <Foo p1={10} />; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }"
+ *
+ * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element..
+ * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component
+ *
+ * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement
+ * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature
+ * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname.
+ * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts)
+ * @return attributes type if able to resolve the type of node
+ * anyType if there is no type ElementAttributesProperty or there is an error
+ * emptyObjectType if there is no "prop" in the element instance type
+ */
+ function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) {
+ if (!elementType) {
+ elementType = checkExpression(openingLikeElement.tagName);
+ }
+ if (elementType.flags & 65536 /* Union */) {
+ var types = elementType.types;
+ return getUnionType(types.map(function (type) {
+ return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType);
}), /*subtypeReduction*/ true);
}
// If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type
- if (elemType.flags & 2 /* String */) {
+ if (elementType.flags & 2 /* String */) {
return anyType;
}
- else if (elemType.flags & 32 /* StringLiteral */) {
+ else if (elementType.flags & 32 /* StringLiteral */) {
// If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type
+ // For example:
+ // var CustomTag: "h1" = "h1";
+ // <CustomTag> Hello World </CustomTag>
var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements);
if (intrinsicElementsType !== unknownType) {
- var stringLiteralTypeName = elemType.text;
+ var stringLiteralTypeName = elementType.text;
var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName);
if (intrinsicProp) {
return getTypeOfSymbol(intrinsicProp);
@@ -34879,34 +37826,24 @@ var ts;
if (indexSignatureType) {
return indexSignatureType;
}
- error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements);
+ error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements);
}
// If we need to report an error, we already done so here. So just return any to prevent any more error downstream
return anyType;
}
// Get the element instance type (the result of newing or invoking this tag)
- var elemInstanceType = getJsxElementInstanceType(node, elemType);
- if (!elemClassType || !isTypeAssignableTo(elemInstanceType, elemClassType)) {
- // Is this is a stateless function component? See if its single signature's return type is
- // assignable to the JSX Element Type
- if (jsxElementType) {
- var callSignatures = elemType && getSignaturesOfType(elemType, 0 /* Call */);
- var callSignature = callSignatures && callSignatures.length > 0 && callSignatures[0];
- var callReturnType = callSignature && getReturnTypeOfSignature(callSignature);
- var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0]));
- if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) {
- // Intersect in JSX.IntrinsicAttributes if it exists
- var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
- if (intrinsicAttributes !== unknownType) {
- paramType = intersectTypes(intrinsicAttributes, paramType);
- }
- return paramType;
- }
- }
+ var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType);
+ // If we should include all stateless attributes type, then get all attributes type from all stateless function signature.
+ // Otherwise get only attributes type from the signature picked by choose-overload logic.
+ var statelessAttributesType = shouldIncludeAllStatelessAttributesType ?
+ tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) :
+ defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType);
+ if (statelessAttributesType) {
+ return statelessAttributesType;
}
// Issue an error if this return type isn't assignable to JSX.ElementClass
- if (elemClassType) {
- checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
+ if (elementClassType) {
+ checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements);
}
if (isTypeAny(elemInstanceType)) {
return elemInstanceType;
@@ -34930,11 +37867,6 @@ var ts;
// Props is of type 'any' or unknown
return attributesType;
}
- else if (attributesType.flags & 65536 /* Union */) {
- // Props cannot be a union type
- error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType));
- return anyType;
- }
else {
// Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
var apparentAttributesType = attributesType;
@@ -34959,30 +37891,68 @@ var ts;
}
}
/**
- * Given an opening/self-closing element, get the 'element attributes type', i.e. the type that tells
- * us which attributes are valid on a given element.
+ * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
+ * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
+ * @param node an intrinsic JSX opening-like element
*/
- function getJsxElementAttributesType(node) {
+ function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
+ ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
var links = getNodeLinks(node);
- if (!links.resolvedJsxType) {
- if (isJsxIntrinsicIdentifier(node.tagName)) {
- var symbol = getIntrinsicTagSymbol(node);
- if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
- return links.resolvedJsxType = getTypeOfSymbol(symbol);
- }
- else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
- return links.resolvedJsxType = getIndexInfoOfSymbol(symbol, 0 /* String */).type;
- }
- else {
- return links.resolvedJsxType = unknownType;
- }
+ if (!links.resolvedJsxElementAttributesType) {
+ var symbol = getIntrinsicTagSymbol(node);
+ if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
+ return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
+ }
+ else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
+ return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type;
}
else {
- var elemClassType = getJsxGlobalElementClassType();
- return links.resolvedJsxType = getResolvedJsxType(node, undefined, elemClassType);
+ return links.resolvedJsxElementAttributesType = unknownType;
}
}
- return links.resolvedJsxType;
+ return links.resolvedJsxElementAttributesType;
+ }
+ /**
+ * Get attributes type of the given custom opening-like JSX element.
+ * This function is intended to be called from a caller that handles intrinsic JSX element already.
+ * @param node a custom JSX opening-like element
+ * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component
+ */
+ function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) {
+ var links = getNodeLinks(node);
+ if (!links.resolvedJsxElementAttributesType) {
+ var elemClassType = getJsxGlobalElementClassType();
+ return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType);
+ }
+ return links.resolvedJsxElementAttributesType;
+ }
+ /**
+ * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element.
+ * This function is called by language service (see: completions-tryGetGlobalSymbols).
+ * @param node a JSX opening-like element to get attributes type for
+ */
+ function getAllAttributesTypeFromJsxOpeningLikeElement(node) {
+ if (isJsxIntrinsicIdentifier(node.tagName)) {
+ return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
+ }
+ else {
+ // Because in language service, the given JSX opening-like element may be incomplete and therefore,
+ // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads.
+ return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true);
+ }
+ }
+ /**
+ * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement.
+ * @param node a JSXOpeningLikeElement node
+ * @return an attributes type of the given node
+ */
+ function getAttributesTypeFromJsxOpeningLikeElement(node) {
+ if (isJsxIntrinsicIdentifier(node.tagName)) {
+ return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
+ }
+ else {
+ return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false);
+ }
}
/**
* Given a JSX attribute, returns the symbol for the corresponds property
@@ -34990,17 +37960,34 @@ var ts;
* that have no matching element attributes type property.
*/
function getJsxAttributePropertySymbol(attrib) {
- var attributesType = getJsxElementAttributesType(attrib.parent);
+ var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent);
var prop = getPropertyOfType(attributesType, attrib.name.text);
return prop || unknownSymbol;
}
function getJsxGlobalElementClassType() {
- if (!jsxElementClassType) {
- jsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass);
+ if (!deferredJsxElementClassType) {
+ deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass);
}
- return jsxElementClassType;
+ return deferredJsxElementClassType;
}
- /// Returns all the properties of the Jsx.IntrinsicElements interface
+ function getJsxGlobalElementType() {
+ if (!deferredJsxElementType) {
+ deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element);
+ }
+ return deferredJsxElementType;
+ }
+ function getJsxGlobalStatelessElementType() {
+ if (!deferredJsxStatelessElementType) {
+ var jsxElementType = getJsxGlobalElementType();
+ if (jsxElementType) {
+ deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]);
+ }
+ }
+ return deferredJsxStatelessElementType;
+ }
+ /**
+ * Returns all the properties of the Jsx.IntrinsicElements interface
+ */
function getJsxIntrinsicTagNames() {
var intrinsics = getJsxType(JsxNames.IntrinsicElements);
return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray;
@@ -35010,8 +37997,8 @@ var ts;
if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
}
- if (jsxElementType === undefined) {
- if (compilerOptions.noImplicitAny) {
+ if (getJsxGlobalElementType() === undefined) {
+ if (noImplicitAny) {
error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
}
}
@@ -35033,39 +38020,46 @@ var ts;
markAliasSymbolAsReferenced(reactSym);
}
}
- var targetAttributesType = getJsxElementAttributesType(node);
- var nameTable = ts.createMap();
- // Process this array in right-to-left order so we know which
- // attributes (mostly from spreads) are being overwritten and
- // thus should have their types ignored
- var sawSpreadedAny = false;
- for (var i = node.attributes.length - 1; i >= 0; i--) {
- if (node.attributes[i].kind === 250 /* JsxAttribute */) {
- checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable);
- }
- else {
- ts.Debug.assert(node.attributes[i].kind === 251 /* JsxSpreadAttribute */);
- var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable);
- if (isTypeAny(spreadType)) {
- sawSpreadedAny = true;
- }
- }
+ checkJsxAttributesAssignableToTagNameAttributes(node);
+ }
+ /**
+ * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes.
+ * Get the attributes type of the opening-like element through resolving the tagName, "target attributes"
+ * Check assignablity between given attributes property, "source attributes", and the "target attributes"
+ * @param openingLikeElement an opening-like JSX element to check its JSXAttributes
+ */
+ function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) {
+ // The function involves following steps:
+ // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType.
+ // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order)
+ // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element.
+ // 3. Check if the two are assignable to each other
+ // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element.
+ var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ?
+ getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) :
+ getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false);
+ // sourceAttributesType is a type of an attributes properties.
+ // i.e <div attr1={10} attr2="string" />
+ // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes".
+ var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) {
+ return isUnhyphenatedJsxName(attribute.name) || !!(getPropertyOfType(targetAttributesType, attribute.name));
+ });
+ // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type.
+ // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass.
+ if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) {
+ error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName());
}
- // Check that all required properties have been provided. If an 'any'
- // was spreaded in, though, assume that it provided all required properties
- if (targetAttributesType && !sawSpreadedAny) {
- var targetProperties = getPropertiesOfType(targetAttributesType);
- for (var i = 0; i < targetProperties.length; i++) {
- if (!(targetProperties[i].flags & 536870912 /* Optional */) &&
- !nameTable[targetProperties[i].name]) {
- error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType));
- }
- }
+ else {
+ checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement);
}
}
- function checkJsxExpression(node) {
+ function checkJsxExpression(node, checkMode) {
if (node.expression) {
- return checkExpression(node.expression);
+ var type = checkExpression(node.expression, checkMode);
+ if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
+ error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type));
+ }
+ return type;
}
else {
return unknownType;
@@ -35074,14 +38068,32 @@ var ts;
// If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized
// '.prototype' property as well as synthesized tuple index properties.
function getDeclarationKindFromSymbol(s) {
- return s.valueDeclaration ? s.valueDeclaration.kind : 147 /* PropertyDeclaration */;
+ return s.valueDeclaration ? s.valueDeclaration.kind : 148 /* PropertyDeclaration */;
}
function getDeclarationModifierFlagsFromSymbol(s) {
- return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0;
+ if (s.valueDeclaration) {
+ var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
+ return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
+ }
+ if (getCheckFlags(s) & 6 /* Synthetic */) {
+ var checkFlags = s.checkFlags;
+ var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ :
+ checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ :
+ 16 /* Protected */;
+ var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0;
+ return accessModifier | staticModifier;
+ }
+ if (s.flags & 16777216 /* Prototype */) {
+ return 4 /* Public */ | 32 /* Static */;
+ }
+ return 0;
}
function getDeclarationNodeFlagsFromSymbol(s) {
return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
}
+ function isMethodLike(symbol) {
+ return !!(symbol.flags & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */);
+ }
/**
* Check whether the requested property access is valid.
* Returns true if node is a valid property access, and false otherwise.
@@ -35090,12 +38102,16 @@ var ts;
* @param type The type of left.
* @param prop The symbol for the right hand side of the property access.
*/
- function checkClassPropertyAccess(node, left, type, prop) {
+ function checkPropertyAccessibility(node, left, type, prop) {
var flags = getDeclarationModifierFlagsFromSymbol(prop);
- var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop));
- var errorNode = node.kind === 177 /* PropertyAccessExpression */ || node.kind === 223 /* VariableDeclaration */ ?
+ var errorNode = node.kind === 178 /* PropertyAccessExpression */ || node.kind === 225 /* VariableDeclaration */ ?
node.name :
node.right;
+ if (getCheckFlags(prop) & 256 /* ContainsPrivate */) {
+ // Synthetic property with private constituent property
+ error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type));
+ return false;
+ }
if (left.kind === 96 /* SuperKeyword */) {
// TS 1.0 spec (April 2014): 4.8.2
// - In a constructor, instance member function, instance member accessor, or
@@ -35104,18 +38120,22 @@ var ts;
// - In a static member function or static member accessor
// where this references the constructor function object of a derived class,
// a super property access is permitted and must specify a public static member function of the base class.
- if (languageVersion < 2 /* ES2015 */ && getDeclarationKindFromSymbol(prop) !== 149 /* MethodDeclaration */) {
- // `prop` refers to a *property* declared in the super class
- // rather than a *method*, so it does not satisfy the above criteria.
- error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
- return false;
+ if (languageVersion < 2 /* ES2015 */) {
+ var hasNonMethodDeclaration = forEachProperty(prop, function (p) {
+ var propKind = getDeclarationKindFromSymbol(p);
+ return propKind !== 150 /* MethodDeclaration */ && propKind !== 149 /* MethodSignature */;
+ });
+ if (hasNonMethodDeclaration) {
+ error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
+ return false;
+ }
}
if (flags & 128 /* Abstract */) {
// A method cannot be accessed in a super property access if the method is abstract.
// This error could mask a private property access error. But, a member
// cannot simultaneously be private and abstract, so this will trigger an
// additional error elsewhere.
- error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass));
+ error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
return false;
}
}
@@ -35128,7 +38148,7 @@ var ts;
if (flags & 8 /* Private */) {
var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
if (!isNodeWithinClass(node, declaringClassDeclaration)) {
- error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass));
+ error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
return false;
}
return true;
@@ -35138,14 +38158,15 @@ var ts;
if (left.kind === 96 /* SuperKeyword */) {
return true;
}
- // Get the enclosing class that has the declaring class as its base type
+ // Find the first enclosing class that has the declaring classes of the protected constituents
+ // of the property as base classes
var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
- return hasBaseType(enclosingClass, declaringClass) ? enclosingClass : undefined;
+ return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
});
// A protected property is accessible if the property is within the declaring class or classes derived from it
if (!enclosingClass) {
- error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass));
+ error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
return false;
}
// No further restrictions for static properties
@@ -35157,7 +38178,6 @@ var ts;
// get the original type -- represented as the type constraint of the 'this' type
type = getConstraintOfTypeParameter(type);
}
- // TODO: why is the first part of this check here?
if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) {
error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
return false;
@@ -35165,16 +38185,17 @@ var ts;
return true;
}
function checkNonNullExpression(node) {
- var type = checkExpression(node);
- if (strictNullChecks) {
- var kind = getFalsyFlags(type) & 6144 /* Nullable */;
- if (kind) {
- error(node, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ?
- ts.Diagnostics.Object_is_possibly_null_or_undefined :
- ts.Diagnostics.Object_is_possibly_undefined :
- ts.Diagnostics.Object_is_possibly_null);
- }
- return getNonNullableType(type);
+ return checkNonNullType(checkExpression(node), node);
+ }
+ function checkNonNullType(type, errorNode) {
+ var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144 /* Nullable */;
+ if (kind) {
+ error(errorNode, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ?
+ ts.Diagnostics.Object_is_possibly_null_or_undefined :
+ ts.Diagnostics.Object_is_possibly_undefined :
+ ts.Diagnostics.Object_is_possibly_null);
+ var t = getNonNullableType(type);
+ return t.flags & (6144 /* Nullable */ | 8192 /* Never */) ? unknownType : t;
}
return type;
}
@@ -35203,7 +38224,7 @@ var ts;
noUnusedIdentifiers &&
(prop.flags & 106500 /* ClassMember */) &&
prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) {
- if (prop.flags & 16777216 /* Instantiated */) {
+ if (getCheckFlags(prop) & 1 /* Instantiated */) {
getSymbolLinks(prop).target.isReferenced = true;
}
else {
@@ -35211,6 +38232,15 @@ var ts;
}
}
}
+ function isInPropertyInitializer(node) {
+ while (node) {
+ if (node.parent && node.parent.kind === 148 /* PropertyDeclaration */ && node.parent.initializer === node) {
+ return true;
+ }
+ node = node.parent;
+ }
+ return false;
+ }
function checkPropertyAccessExpressionOrQualifiedName(node, left, right) {
var type = checkNonNullExpression(left);
if (isTypeAny(type) || type === silentNeverType) {
@@ -35223,16 +38253,30 @@ var ts;
}
var prop = getPropertyOfType(apparentType, right.text);
if (!prop) {
+ var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */);
+ if (stringIndexType) {
+ return stringIndexType;
+ }
if (right.text && !checkAndReportErrorForExtendingInterface(node)) {
reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type);
}
return unknownType;
}
+ if (prop.valueDeclaration) {
+ if (isInPropertyInitializer(node) &&
+ !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) {
+ error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text);
+ }
+ if (prop.valueDeclaration.kind === 228 /* ClassDeclaration */ &&
+ node.parent && node.parent.kind !== 158 /* TypeReference */ &&
+ !ts.isInAmbientContext(prop.valueDeclaration) &&
+ !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) {
+ error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text);
+ }
+ }
markPropertyAsReferenced(prop);
getNodeLinks(node).resolvedSymbol = prop;
- if (prop.parent && prop.parent.flags & 32 /* Class */) {
- checkClassPropertyAccess(node, left, apparentType, prop);
- }
+ checkPropertyAccessibility(node, left, apparentType, prop);
var propType = getTypeOfSymbol(prop);
var assignmentKind = ts.getAssignmentTargetKind(node);
if (assignmentKind) {
@@ -35244,23 +38288,23 @@ var ts;
// Only compute control flow type if this is a property access expression that isn't an
// assignment target, and the referenced property was declared as a variable, property,
// accessor, or optional method.
- if (node.kind !== 177 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ ||
+ if (node.kind !== 178 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ ||
!(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) &&
!(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) {
return propType;
}
- var flowType = getFlowTypeOfReference(node, propType, /*assumeInitialized*/ true, /*flowContainer*/ undefined);
+ var flowType = getFlowTypeOfReference(node, propType);
return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
}
function isValidPropertyAccess(node, propertyName) {
- var left = node.kind === 177 /* PropertyAccessExpression */
+ var left = node.kind === 178 /* PropertyAccessExpression */
? node.expression
: node.left;
var type = checkExpression(left);
if (type !== unknownType && !isTypeAny(type)) {
var prop = getPropertyOfType(getWidenedType(type), propertyName);
- if (prop && prop.parent && prop.parent.flags & 32 /* Class */) {
- return checkClassPropertyAccess(node, left, type, prop);
+ if (prop) {
+ return checkPropertyAccessibility(node, left, type, prop);
}
}
return true;
@@ -35270,7 +38314,7 @@ var ts;
*/
function getForInVariableSymbol(node) {
var initializer = node.initializer;
- if (initializer.kind === 224 /* VariableDeclarationList */) {
+ if (initializer.kind === 226 /* VariableDeclarationList */) {
var variable = initializer.declarations[0];
if (variable && !ts.isBindingPattern(variable.name)) {
return getSymbolOfNode(variable);
@@ -35299,7 +38343,7 @@ var ts;
var child = expr;
var node = expr.parent;
while (node) {
- if (node.kind === 212 /* ForInStatement */ &&
+ if (node.kind === 214 /* ForInStatement */ &&
child === node.statement &&
getForInVariableSymbol(node) === symbol &&
hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
@@ -35317,7 +38361,7 @@ var ts;
var indexExpression = node.argumentExpression;
if (!indexExpression) {
var sourceFile = ts.getSourceFileOfNode(node);
- if (node.parent.kind === 180 /* NewExpression */ && node.parent.expression === node) {
+ if (node.parent.kind === 181 /* NewExpression */ && node.parent.expression === node) {
var start = ts.skipTrivia(sourceFile.text, node.expression.end);
var end = node.end;
grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead);
@@ -35337,7 +38381,7 @@ var ts;
error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
return unknownType;
}
- return getIndexedAccessType(objectType, indexType, node);
+ return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node);
}
function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
if (expressionType === unknownType) {
@@ -35361,7 +38405,7 @@ var ts;
if (!leftHandSideSymbol) {
return false;
}
- var globalESSymbol = getGlobalESSymbolConstructorSymbol();
+ var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
if (!globalESSymbol) {
// Already errored when we tried to look up the symbol
return false;
@@ -35375,10 +38419,10 @@ var ts;
return true;
}
function resolveUntypedCall(node) {
- if (node.kind === 181 /* TaggedTemplateExpression */) {
+ if (node.kind === 182 /* TaggedTemplateExpression */) {
checkExpression(node.template);
}
- else if (node.kind !== 145 /* Decorator */) {
+ else if (node.kind !== 146 /* Decorator */) {
ts.forEach(node.arguments, function (argument) {
checkExpression(argument);
});
@@ -35405,16 +38449,16 @@ var ts;
var specializedIndex = -1;
var spliceIndex;
ts.Debug.assert(!result.length);
- for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
- var signature = signatures_2[_i];
+ for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
+ var signature = signatures_3[_i];
var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
- var parent_8 = signature.declaration && signature.declaration.parent;
+ var parent = signature.declaration && signature.declaration.parent;
if (!lastSymbol || symbol === lastSymbol) {
- if (lastParent && parent_8 === lastParent) {
+ if (lastParent && parent === lastParent) {
index++;
}
else {
- lastParent = parent_8;
+ lastParent = parent;
index = cutoffIndex;
}
}
@@ -35422,7 +38466,7 @@ var ts;
// current declaration belongs to a different symbol
// set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
index = cutoffIndex = result.length;
- lastParent = parent_8;
+ lastParent = parent;
}
lastSymbol = symbol;
// specialized signatures always need to be placed before non-specialized signatures regardless
@@ -35444,7 +38488,7 @@ var ts;
function getSpreadArgumentIndex(args) {
for (var i = 0; i < args.length; i++) {
var arg = args[i];
- if (arg && arg.kind === 196 /* SpreadElement */) {
+ if (arg && arg.kind === 197 /* SpreadElement */) {
return i;
}
}
@@ -35457,13 +38501,17 @@ var ts;
var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments
var isDecorator;
var spreadArgIndex = -1;
- if (node.kind === 181 /* TaggedTemplateExpression */) {
+ if (ts.isJsxOpeningLikeElement(node)) {
+ // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement".
+ return true;
+ }
+ if (node.kind === 182 /* TaggedTemplateExpression */) {
var tagExpression = node;
// Even if the call is incomplete, we'll have a missing expression as our last argument,
// so we can say the count is just the arg list length
argCount = args.length;
typeArguments = undefined;
- if (tagExpression.template.kind === 194 /* TemplateExpression */) {
+ if (tagExpression.template.kind === 195 /* TemplateExpression */) {
// If a tagged template expression lacks a tail literal, the call is incomplete.
// Specifically, a template only can end in a TemplateTail or a Missing literal.
var templateExpression = tagExpression.template;
@@ -35480,7 +38528,7 @@ var ts;
callIsIncomplete = !!templateLiteral.isUnterminated;
}
}
- else if (node.kind === 145 /* Decorator */) {
+ else if (node.kind === 146 /* Decorator */) {
isDecorator = true;
typeArguments = undefined;
argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature);
@@ -35489,19 +38537,21 @@ var ts;
var callExpression = node;
if (!callExpression.arguments) {
// This only happens when we have something of the form: 'new C'
- ts.Debug.assert(callExpression.kind === 180 /* NewExpression */);
+ ts.Debug.assert(callExpression.kind === 181 /* NewExpression */);
return signature.minArgumentCount === 0;
}
argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
- // If we are missing the close paren, the call is incomplete.
+ // If we are missing the close parenthesis, the call is incomplete.
callIsIncomplete = callExpression.arguments.end === callExpression.end;
typeArguments = callExpression.typeArguments;
spreadArgIndex = getSpreadArgumentIndex(args);
}
// If the user supplied type arguments, but the number of type arguments does not match
// the declared number of type parameters, the call has an incorrect arity.
+ var numTypeParameters = ts.length(signature.typeParameters);
+ var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
var hasRightNumberOfTypeArgs = !typeArguments ||
- (signature.typeParameters && typeArguments.length === signature.typeParameters.length);
+ (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
if (!hasRightNumberOfTypeArgs) {
return false;
}
@@ -35531,10 +38581,10 @@ var ts;
}
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) {
- var context = createInferenceContext(signature, /*inferUnionTypes*/ true);
+ var context = createInferenceContext(signature, /*inferUnionTypes*/ true, /*useAnyForNoInferences*/ false);
forEachMatchingParameterType(contextualSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
- inferTypes(context, instantiateType(source, contextualMapper), target);
+ inferTypesWithContext(context, instantiateType(source, contextualMapper), target);
});
return getSignatureInstantiation(signature, getInferredTypes(context));
}
@@ -35565,7 +38615,7 @@ var ts;
if (thisType) {
var thisArgumentNode = getThisArgumentOfCall(node);
var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
- inferTypes(context, thisArgumentType, thisType);
+ inferTypesWithContext(context, thisArgumentType, thisType);
}
// We perform two passes over the arguments. In the first pass we infer from all arguments, but use
// wildcards for all context sensitive function expressions.
@@ -35573,7 +38623,7 @@ var ts;
for (var i = 0; i < argCount; i++) {
var arg = getEffectiveArgument(node, args, i);
// If the effective argument is 'undefined', then it is an argument that is present but is synthetic.
- if (arg === undefined || arg.kind !== 198 /* OmittedExpression */) {
+ if (arg === undefined || arg.kind !== 199 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
var argType = getEffectiveArgumentType(node, i);
// If the effective argument type is 'undefined', there is no synthetic type
@@ -35584,7 +38634,7 @@ var ts;
var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper;
argType = checkExpressionWithContextualType(arg, paramType, mapper);
}
- inferTypes(context, argType, paramType);
+ inferTypesWithContext(context, argType, paramType);
}
}
// In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this
@@ -35598,7 +38648,7 @@ var ts;
if (excludeArgument[i] === false) {
var arg = args[i];
var paramType = getTypeAtPosition(signature, i);
- inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType);
+ inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType);
}
}
}
@@ -35608,7 +38658,7 @@ var ts;
var typeParameters = signature.typeParameters;
var typeArgumentsAreAssignable = true;
var mapper;
- for (var i = 0; i < typeParameters.length; i++) {
+ for (var i = 0; i < typeArgumentNodes.length; i++) {
if (typeArgumentsAreAssignable /* so far */) {
var constraint = getConstraintOfTypeParameter(typeParameters[i]);
if (constraint) {
@@ -35628,9 +38678,44 @@ var ts;
}
return typeArgumentsAreAssignable;
}
+ /**
+ * Check if the given signature can possibly be a signature called by the JSX opening-like element.
+ * @param node a JSX opening-like element we are trying to figure its call signature
+ * @param signature a candidate signature we are trying whether it is a call signature
+ * @param relation a relationship to check parameter and argument type
+ * @param excludeArgument
+ */
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) {
+ // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true:
+ // 1. callIsIncomplete
+ // 2. attributes property has same number of properties as the parameter object type.
+ // We can figure that out by resolving attributes property and check number of properties in the resolved type
+ // If the call has correct arity, we will then check if the argument type and parameter type is assignable
+ var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete
+ if (callIsIncomplete) {
+ return true;
+ }
+ var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
+ // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
+ // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
+ // can be specified by users through attributes property.
+ var paramType = getTypeAtPosition(signature, 0);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined);
+ var argProperties = getPropertiesOfType(attributesType);
+ for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) {
+ var arg = argProperties_1[_i];
+ if (!getPropertyOfType(paramType, arg.name) && isUnhyphenatedJsxName(arg.name)) {
+ return false;
+ }
+ }
+ return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage);
+ }
function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ if (ts.isJsxOpeningLikeElement(node)) {
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation);
+ }
var thisType = getThisTypeOfSignature(signature);
- if (thisType && thisType !== voidType && node.kind !== 180 /* NewExpression */) {
+ if (thisType && thisType !== voidType && node.kind !== 181 /* NewExpression */) {
// If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
// If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
// If the expression is a new expression, then the check is skipped.
@@ -35647,7 +38732,7 @@ var ts;
for (var i = 0; i < argCount; i++) {
var arg = getEffectiveArgument(node, args, i);
// If the effective argument is 'undefined', then it is an argument that is present but is synthetic.
- if (arg === undefined || arg.kind !== 198 /* OmittedExpression */) {
+ if (arg === undefined || arg.kind !== 199 /* OmittedExpression */) {
// Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter)
var paramType = getTypeAtPosition(signature, i);
var argType = getEffectiveArgumentType(node, i);
@@ -35669,12 +38754,12 @@ var ts;
* Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
*/
function getThisArgumentOfCall(node) {
- if (node.kind === 179 /* CallExpression */) {
+ if (node.kind === 180 /* CallExpression */) {
var callee = node.expression;
- if (callee.kind === 177 /* PropertyAccessExpression */) {
+ if (callee.kind === 178 /* PropertyAccessExpression */) {
return callee.expression;
}
- else if (callee.kind === 178 /* ElementAccessExpression */) {
+ else if (callee.kind === 179 /* ElementAccessExpression */) {
return callee.expression;
}
}
@@ -35690,53 +38775,56 @@ var ts;
*/
function getEffectiveCallArguments(node) {
var args;
- if (node.kind === 181 /* TaggedTemplateExpression */) {
+ if (node.kind === 182 /* TaggedTemplateExpression */) {
var template = node.template;
args = [undefined];
- if (template.kind === 194 /* TemplateExpression */) {
+ if (template.kind === 195 /* TemplateExpression */) {
ts.forEach(template.templateSpans, function (span) {
args.push(span.expression);
});
}
}
- else if (node.kind === 145 /* Decorator */) {
+ else if (node.kind === 146 /* Decorator */) {
// For a decorator, we return undefined as we will determine
// the number and types of arguments for a decorator using
// `getEffectiveArgumentCount` and `getEffectiveArgumentType` below.
return undefined;
}
+ else if (ts.isJsxOpeningLikeElement(node)) {
+ args = node.attributes.properties.length > 0 ? [node.attributes] : emptyArray;
+ }
else {
args = node.arguments || emptyArray;
}
return args;
}
/**
- * Returns the effective argument count for a node that works like a function invocation.
- * If 'node' is a Decorator, the number of arguments is derived from the decoration
- * target and the signature:
- * If 'node.target' is a class declaration or class expression, the effective argument
- * count is 1.
- * If 'node.target' is a parameter declaration, the effective argument count is 3.
- * If 'node.target' is a property declaration, the effective argument count is 2.
- * If 'node.target' is a method or accessor declaration, the effective argument count
- * is 3, although it can be 2 if the signature only accepts two arguments, allowing
- * us to match a property decorator.
- * Otherwise, the argument count is the length of the 'args' array.
- */
+ * Returns the effective argument count for a node that works like a function invocation.
+ * If 'node' is a Decorator, the number of arguments is derived from the decoration
+ * target and the signature:
+ * If 'node.target' is a class declaration or class expression, the effective argument
+ * count is 1.
+ * If 'node.target' is a parameter declaration, the effective argument count is 3.
+ * If 'node.target' is a property declaration, the effective argument count is 2.
+ * If 'node.target' is a method or accessor declaration, the effective argument count
+ * is 3, although it can be 2 if the signature only accepts two arguments, allowing
+ * us to match a property decorator.
+ * Otherwise, the argument count is the length of the 'args' array.
+ */
function getEffectiveArgumentCount(node, args, signature) {
- if (node.kind === 145 /* Decorator */) {
+ if (node.kind === 146 /* Decorator */) {
switch (node.parent.kind) {
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
// A class decorator will have one argument (see `ClassDecorator` in core.d.ts)
return 1;
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
// A property declaration decorator will have two arguments (see
// `PropertyDecorator` in core.d.ts)
return 2;
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
// A method or accessor declaration decorator will have two or three arguments (see
// `PropertyDecorator` and `MethodDecorator` in core.d.ts)
// If we are emitting decorators for ES3, we will only pass two arguments.
@@ -35746,7 +38834,7 @@ var ts;
// If the method decorator signature only accepts a target and a key, we will only
// type check those arguments.
return signature.parameters.length >= 3 ? 3 : 2;
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
// A parameter declaration decorator will have three arguments (see
// `ParameterDecorator` in core.d.ts)
return 3;
@@ -35757,38 +38845,38 @@ var ts;
}
}
/**
- * Returns the effective type of the first argument to a decorator.
- * If 'node' is a class declaration or class expression, the effective argument type
- * is the type of the static side of the class.
- * If 'node' is a parameter declaration, the effective argument type is either the type
- * of the static or instance side of the class for the parameter's parent method,
- * depending on whether the method is declared static.
- * For a constructor, the type is always the type of the static side of the class.
- * If 'node' is a property, method, or accessor declaration, the effective argument
- * type is the type of the static or instance side of the parent class for class
- * element, depending on whether the element is declared static.
- */
+ * Returns the effective type of the first argument to a decorator.
+ * If 'node' is a class declaration or class expression, the effective argument type
+ * is the type of the static side of the class.
+ * If 'node' is a parameter declaration, the effective argument type is either the type
+ * of the static or instance side of the class for the parameter's parent method,
+ * depending on whether the method is declared static.
+ * For a constructor, the type is always the type of the static side of the class.
+ * If 'node' is a property, method, or accessor declaration, the effective argument
+ * type is the type of the static or instance side of the parent class for class
+ * element, depending on whether the element is declared static.
+ */
function getEffectiveDecoratorFirstArgumentType(node) {
// The first argument to a decorator is its `target`.
- if (node.kind === 226 /* ClassDeclaration */) {
+ if (node.kind === 228 /* ClassDeclaration */) {
// For a class decorator, the `target` is the type of the class (e.g. the
// "static" or "constructor" side of the class)
var classSymbol = getSymbolOfNode(node);
return getTypeOfSymbol(classSymbol);
}
- if (node.kind === 144 /* Parameter */) {
+ if (node.kind === 145 /* Parameter */) {
// For a parameter decorator, the `target` is the parent type of the
// parameter's containing method.
node = node.parent;
- if (node.kind === 150 /* Constructor */) {
+ if (node.kind === 151 /* Constructor */) {
var classSymbol = getSymbolOfNode(node);
return getTypeOfSymbol(classSymbol);
}
}
- if (node.kind === 147 /* PropertyDeclaration */ ||
- node.kind === 149 /* MethodDeclaration */ ||
- node.kind === 151 /* GetAccessor */ ||
- node.kind === 152 /* SetAccessor */) {
+ if (node.kind === 148 /* PropertyDeclaration */ ||
+ node.kind === 150 /* MethodDeclaration */ ||
+ node.kind === 152 /* GetAccessor */ ||
+ node.kind === 153 /* SetAccessor */) {
// For a property or method decorator, the `target` is the
// "static"-side type of the parent of the member if the member is
// declared "static"; otherwise, it is the "instance"-side type of the
@@ -35799,37 +38887,39 @@ var ts;
return unknownType;
}
/**
- * Returns the effective type for the second argument to a decorator.
- * If 'node' is a parameter, its effective argument type is one of the following:
- * If 'node.parent' is a constructor, the effective argument type is 'any', as we
- * will emit `undefined`.
- * If 'node.parent' is a member with an identifier, numeric, or string literal name,
- * the effective argument type will be a string literal type for the member name.
- * If 'node.parent' is a computed property name, the effective argument type will
- * either be a symbol type or the string type.
- * If 'node' is a member with an identifier, numeric, or string literal name, the
- * effective argument type will be a string literal type for the member name.
- * If 'node' is a computed property name, the effective argument type will either
- * be a symbol type or the string type.
- * A class decorator does not have a second argument type.
- */
+ * Returns the effective type for the second argument to a decorator.
+ * If 'node' is a parameter, its effective argument type is one of the following:
+ * If 'node.parent' is a constructor, the effective argument type is 'any', as we
+ * will emit `undefined`.
+ * If 'node.parent' is a member with an identifier, numeric, or string literal name,
+ * the effective argument type will be a string literal type for the member name.
+ * If 'node.parent' is a computed property name, the effective argument type will
+ * either be a symbol type or the string type.
+ * If 'node' is a member with an identifier, numeric, or string literal name, the
+ * effective argument type will be a string literal type for the member name.
+ * If 'node' is a computed property name, the effective argument type will either
+ * be a symbol type or the string type.
+ * A class decorator does not have a second argument type.
+ */
function getEffectiveDecoratorSecondArgumentType(node) {
// The second argument to a decorator is its `propertyKey`
- if (node.kind === 226 /* ClassDeclaration */) {
+ if (node.kind === 228 /* ClassDeclaration */) {
ts.Debug.fail("Class decorators should not have a second synthetic argument.");
return unknownType;
}
- if (node.kind === 144 /* Parameter */) {
+ if (node.kind === 145 /* Parameter */) {
node = node.parent;
- if (node.kind === 150 /* Constructor */) {
+ if (node.kind === 151 /* Constructor */) {
// For a constructor parameter decorator, the `propertyKey` will be `undefined`.
return anyType;
}
+ // For a non-constructor parameter decorator, the `propertyKey` will be either
+ // a string or a symbol, based on the name of the parameter's containing method.
}
- if (node.kind === 147 /* PropertyDeclaration */ ||
- node.kind === 149 /* MethodDeclaration */ ||
- node.kind === 151 /* GetAccessor */ ||
- node.kind === 152 /* SetAccessor */) {
+ if (node.kind === 148 /* PropertyDeclaration */ ||
+ node.kind === 150 /* MethodDeclaration */ ||
+ node.kind === 152 /* GetAccessor */ ||
+ node.kind === 153 /* SetAccessor */) {
// The `propertyKey` for a property or method decorator will be a
// string literal type if the member name is an identifier, number, or string;
// otherwise, if the member name is a computed property name it will
@@ -35840,7 +38930,7 @@ var ts;
case 8 /* NumericLiteral */:
case 9 /* StringLiteral */:
return getLiteralTypeForText(32 /* StringLiteral */, element.name.text);
- case 142 /* ComputedPropertyName */:
+ case 143 /* ComputedPropertyName */:
var nameType = checkComputedPropertyName(element.name);
if (isTypeOfKind(nameType, 512 /* ESSymbol */)) {
return nameType;
@@ -35857,30 +38947,30 @@ var ts;
return unknownType;
}
/**
- * Returns the effective argument type for the third argument to a decorator.
- * If 'node' is a parameter, the effective argument type is the number type.
- * If 'node' is a method or accessor, the effective argument type is a
- * `TypedPropertyDescriptor<T>` instantiated with the type of the member.
- * Class and property decorators do not have a third effective argument.
- */
+ * Returns the effective argument type for the third argument to a decorator.
+ * If 'node' is a parameter, the effective argument type is the number type.
+ * If 'node' is a method or accessor, the effective argument type is a
+ * `TypedPropertyDescriptor<T>` instantiated with the type of the member.
+ * Class and property decorators do not have a third effective argument.
+ */
function getEffectiveDecoratorThirdArgumentType(node) {
// The third argument to a decorator is either its `descriptor` for a method decorator
// or its `parameterIndex` for a parameter decorator
- if (node.kind === 226 /* ClassDeclaration */) {
+ if (node.kind === 228 /* ClassDeclaration */) {
ts.Debug.fail("Class decorators should not have a third synthetic argument.");
return unknownType;
}
- if (node.kind === 144 /* Parameter */) {
+ if (node.kind === 145 /* Parameter */) {
// The `parameterIndex` for a parameter decorator is always a number
return numberType;
}
- if (node.kind === 147 /* PropertyDeclaration */) {
+ if (node.kind === 148 /* PropertyDeclaration */) {
ts.Debug.fail("Property decorators should not have a third synthetic argument.");
return unknownType;
}
- if (node.kind === 149 /* MethodDeclaration */ ||
- node.kind === 151 /* GetAccessor */ ||
- node.kind === 152 /* SetAccessor */) {
+ if (node.kind === 150 /* MethodDeclaration */ ||
+ node.kind === 152 /* GetAccessor */ ||
+ node.kind === 153 /* SetAccessor */) {
// The `descriptor` for a method decorator will be a `TypedPropertyDescriptor<T>`
// for the type of the member.
var propertyType = getTypeOfNode(node);
@@ -35890,8 +38980,8 @@ var ts;
return unknownType;
}
/**
- * Returns the effective argument type for the provided argument to a decorator.
- */
+ * Returns the effective argument type for the provided argument to a decorator.
+ */
function getEffectiveDecoratorArgumentType(node, argIndex) {
if (argIndex === 0) {
return getEffectiveDecoratorFirstArgumentType(node.parent);
@@ -35906,16 +38996,16 @@ var ts;
return unknownType;
}
/**
- * Gets the effective argument type for an argument in a call expression.
- */
+ * Gets the effective argument type for an argument in a call expression.
+ */
function getEffectiveArgumentType(node, argIndex) {
// Decorators provide special arguments, a tagged template expression provides
// a special first argument, and string literals get string literal types
// unless we're reporting errors
- if (node.kind === 145 /* Decorator */) {
+ if (node.kind === 146 /* Decorator */) {
return getEffectiveDecoratorArgumentType(node, argIndex);
}
- else if (argIndex === 0 && node.kind === 181 /* TaggedTemplateExpression */) {
+ else if (argIndex === 0 && node.kind === 182 /* TaggedTemplateExpression */) {
return getGlobalTemplateStringsArrayType();
}
// This is not a synthetic argument, so we return 'undefined'
@@ -35923,25 +39013,25 @@ var ts;
return undefined;
}
/**
- * Gets the effective argument expression for an argument in a call expression.
- */
+ * Gets the effective argument expression for an argument in a call expression.
+ */
function getEffectiveArgument(node, args, argIndex) {
// For a decorator or the first argument of a tagged template expression we return undefined.
- if (node.kind === 145 /* Decorator */ ||
- (argIndex === 0 && node.kind === 181 /* TaggedTemplateExpression */)) {
+ if (node.kind === 146 /* Decorator */ ||
+ (argIndex === 0 && node.kind === 182 /* TaggedTemplateExpression */)) {
return undefined;
}
return args[argIndex];
}
/**
- * Gets the error node to use when reporting errors for an effective argument.
- */
+ * Gets the error node to use when reporting errors for an effective argument.
+ */
function getEffectiveArgumentErrorNode(node, argIndex, arg) {
- if (node.kind === 145 /* Decorator */) {
+ if (node.kind === 146 /* Decorator */) {
// For a decorator, we use the expression of the decorator for error reporting.
return node.expression;
}
- else if (argIndex === 0 && node.kind === 181 /* TaggedTemplateExpression */) {
+ else if (argIndex === 0 && node.kind === 182 /* TaggedTemplateExpression */) {
// For a the first argument of a tagged template expression, we use the template of the tag for error reporting.
return node.template;
}
@@ -35950,16 +39040,31 @@ var ts;
}
}
function resolveCall(node, signatures, candidatesOutArray, headMessage) {
- var isTaggedTemplate = node.kind === 181 /* TaggedTemplateExpression */;
- var isDecorator = node.kind === 145 /* Decorator */;
+ var isTaggedTemplate = node.kind === 182 /* TaggedTemplateExpression */;
+ var isDecorator = node.kind === 146 /* Decorator */;
+ var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
var typeArguments;
- if (!isTaggedTemplate && !isDecorator) {
+ if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) {
typeArguments = node.typeArguments;
// We already perform checking on the type arguments on the class declaration itself.
if (node.expression.kind !== 96 /* SuperKeyword */) {
ts.forEach(typeArguments, checkSourceElement);
}
}
+ if (signatures.length === 1) {
+ var declaration = signatures[0].declaration;
+ if (declaration && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration)) {
+ if (containsArgumentsReference(declaration)) {
+ var signatureWithRest = cloneSignature(signatures[0]);
+ var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args");
+ syntheticArgsSymbol.type = anyArrayType;
+ syntheticArgsSymbol.isRestParameter = true;
+ signatureWithRest.parameters = ts.concatenate(signatureWithRest.parameters, [syntheticArgsSymbol]);
+ signatureWithRest.hasRestParameter = true;
+ signatures = [signatureWithRest];
+ }
+ }
+ }
var candidates = candidatesOutArray || [];
// reorderCandidates fills up the candidates array directly
reorderCandidates(signatures, candidates);
@@ -36022,7 +39127,7 @@ var ts;
var result;
// If we are in signature help, a trailing comma indicates that we intend to provide another argument,
// so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
- var signatureHelpTrailingComma = candidatesOutArray && node.kind === 179 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = candidatesOutArray && node.kind === 180 /* CallExpression */ && node.arguments.hasTrailingComma;
// Section 4.12.1:
// if the candidate list contains one or more signatures for which the type of each argument
// expression is a subtype of each corresponding parameter type, the return type of the first
@@ -36051,6 +39156,10 @@ var ts;
// If candidate is undefined, it means that no candidates had a suitable arity. In that case,
// skip the checkApplicableSignature check.
if (candidateForArgumentError) {
+ if (isJsxOpeningOrSelfClosingElement) {
+ // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType".
+ return candidateForArgumentError;
+ }
// excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
// The importance of excludeArgument is to prevent us from typing function expression parameters
// in arguments too early. If possible, we'd like to only type them once we know the correct
@@ -36072,7 +39181,7 @@ var ts;
if (headMessage) {
diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage);
}
- reportNoCommonSupertypeError(inferenceCandidates, node.expression || node.tag, diagnosticChainHead);
+ reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead);
}
}
else {
@@ -36113,20 +39222,20 @@ var ts;
var candidate = void 0;
var typeArgumentsAreValid = void 0;
var inferenceContext = originalCandidate.typeParameters
- ? createInferenceContext(originalCandidate, /*inferUnionTypes*/ false)
+ ? createInferenceContext(originalCandidate, /*inferUnionTypes*/ false, /*useAnyForNoInferences*/ ts.isInJavaScriptFile(node))
: undefined;
while (true) {
candidate = originalCandidate;
if (candidate.typeParameters) {
var typeArgumentTypes = void 0;
if (typeArguments) {
- typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode);
+ typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters));
typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false);
}
else {
inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined;
typeArgumentTypes = inferenceContext.inferredTypes;
+ typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined;
}
if (!typeArgumentsAreValid) {
break;
@@ -36136,7 +39245,7 @@ var ts;
if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
break;
}
- var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1;
+ var index = excludeArgument ? ts.indexOf(excludeArgument, /*value*/ true) : -1;
if (index < 0) {
return candidate;
}
@@ -36175,7 +39284,7 @@ var ts;
// with the type arguments specified in the extends clause.
var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node));
if (baseTypeNode) {
- var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments);
+ var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
return resolveCall(node, baseConstructors, candidatesOutArray);
}
}
@@ -36329,12 +39438,13 @@ var ts;
if (containingClass) {
var containingType = getTypeOfNode(containingClass);
var baseTypes = getBaseTypes(containingType);
- if (baseTypes.length) {
+ while (baseTypes.length) {
var baseType = baseTypes[0];
if (modifiers & 16 /* Protected */ &&
baseType.symbol === declaration.parent.symbol) {
return true;
}
+ baseTypes = getBaseTypes(baseType);
}
}
if (modifiers & 8 /* Private */) {
@@ -36366,26 +39476,26 @@ var ts;
return resolveCall(node, callSignatures, candidatesOutArray);
}
/**
- * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
- */
+ * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
+ */
function getDiagnosticHeadMessageForDecoratorResolution(node) {
switch (node.parent.kind) {
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
}
}
/**
- * Resolves a decorator as if it were a call expression.
- */
+ * Resolves a decorator as if it were a call expression.
+ */
function resolveDecorator(node, candidatesOutArray) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
@@ -36407,21 +39517,73 @@ var ts;
}
return resolveCall(node, callSignatures, candidatesOutArray, headMessage);
}
+ /**
+ * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component.
+ * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName
+ * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function)
+ * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not.
+ * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function
+ * @param elementType an element type of the opneing-like element by checking opening-like element's tagname.
+ * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
+ * the function will fill it up with appropriate candidate signatures
+ */
+ function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) {
+ ts.Debug.assert(!(elementType.flags & 65536 /* Union */));
+ var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray);
+ return callSignature;
+ }
+ /**
+ * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature.
+ * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible
+ * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element.
+ * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
+ * the function will fill it up with appropriate candidate signatures
+ * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions.
+ * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures
+ */
+ function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) {
+ // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType)
+ if (elementType.flags & 65536 /* Union */) {
+ var types = elementType.types;
+ var result = void 0;
+ for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
+ var type = types_18[_i];
+ result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray);
+ }
+ return result;
+ }
+ var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */);
+ if (callSignatures && callSignatures.length > 0) {
+ var callSignature = void 0;
+ callSignature = resolveCall(openingLikeElement, callSignatures, candidatesOutArray);
+ return callSignature;
+ }
+ return undefined;
+ }
function resolveSignature(node, candidatesOutArray) {
switch (node.kind) {
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
return resolveCallExpression(node, candidatesOutArray);
- case 180 /* NewExpression */:
+ case 181 /* NewExpression */:
return resolveNewExpression(node, candidatesOutArray);
- case 181 /* TaggedTemplateExpression */:
+ case 182 /* TaggedTemplateExpression */:
return resolveTaggedTemplateExpression(node, candidatesOutArray);
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
return resolveDecorator(node, candidatesOutArray);
+ case 250 /* JsxOpeningElement */:
+ case 249 /* JsxSelfClosingElement */:
+ // This code-path is called by language service
+ return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray);
}
ts.Debug.fail("Branch in 'resolveSignature' should be unreachable.");
}
- // candidatesOutArray is passed by signature help in the language service, and collectCandidates
- // must fill it up with the appropriate candidate signatures
+ /**
+ * Resolve a signature of a given call-like expression.
+ * @param node a call-like expression to try resolve a signature for
+ * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
+ * the function will fill it up with appropriate candidate signatures
+ * @return a signature of the call-like expression or undefined if one can't be found
+ */
function getResolvedSignature(node, candidatesOutArray) {
var links = getNodeLinks(node);
// If getResolvedSignature has already been called, we will have cached the resolvedSignature.
@@ -36464,12 +39626,12 @@ var ts;
if (node.expression.kind === 96 /* SuperKeyword */) {
return voidType;
}
- if (node.kind === 180 /* NewExpression */) {
+ if (node.kind === 181 /* NewExpression */) {
var declaration = signature.declaration;
if (declaration &&
- declaration.kind !== 150 /* Constructor */ &&
- declaration.kind !== 154 /* ConstructSignature */ &&
- declaration.kind !== 159 /* ConstructorType */ &&
+ declaration.kind !== 151 /* Constructor */ &&
+ declaration.kind !== 155 /* ConstructSignature */ &&
+ declaration.kind !== 160 /* ConstructorType */ &&
!ts.isJSDocConstructSignature(declaration)) {
// When resolved signature is a call signature (and not a construct signature) the result type is any, unless
// the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations
@@ -36479,10 +39641,13 @@ var ts;
var funcSymbol = node.expression.kind === 70 /* Identifier */ ?
getResolvedSymbol(node.expression) :
checkExpression(node.expression).symbol;
- if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) {
+ if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) {
+ funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer);
+ }
+ if (funcSymbol && funcSymbol.members && funcSymbol.flags & 16 /* Function */) {
return getInferredClassType(funcSymbol);
}
- else if (compilerOptions.noImplicitAny) {
+ else if (noImplicitAny) {
error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
}
return anyType;
@@ -36509,9 +39674,9 @@ var ts;
return false;
}
var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
- ? 225 /* FunctionDeclaration */
+ ? 227 /* FunctionDeclaration */
: resolvedRequire.flags & 3 /* Variable */
- ? 223 /* VariableDeclaration */
+ ? 225 /* VariableDeclaration */
: 0 /* Unknown */;
if (targetDeclarationKind !== 0 /* Unknown */) {
var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
@@ -36538,6 +39703,22 @@ var ts;
function checkNonNullAssertion(node) {
return getNonNullableType(checkExpression(node.expression));
}
+ function checkMetaProperty(node) {
+ checkGrammarMetaProperty(node);
+ var container = ts.getNewTargetContainer(node);
+ if (!container) {
+ error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
+ return unknownType;
+ }
+ else if (container.kind === 151 /* Constructor */) {
+ var symbol = getSymbolOfNode(container.parent);
+ return getTypeOfSymbol(symbol);
+ }
+ else {
+ var symbol = getSymbolOfNode(container);
+ return getTypeOfSymbol(symbol);
+ }
+ }
function getTypeOfParameter(symbol) {
var type = getTypeOfSymbol(symbol);
if (strictNullChecks) {
@@ -36553,13 +39734,16 @@ var ts;
pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) :
pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType;
}
- function assignContextualParameterTypes(signature, context, mapper) {
+ function getTypeOfFirstParameterOfSignature(signature) {
+ return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType;
+ }
+ function assignContextualParameterTypes(signature, context, mapper, checkMode) {
var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0);
- if (isInferentialContext(mapper)) {
+ if (checkMode === 2 /* Inferential */) {
for (var i = 0; i < len; i++) {
var declaration = signature.parameters[i].valueDeclaration;
if (declaration.type) {
- inferTypes(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i));
+ inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i));
}
}
}
@@ -36567,23 +39751,23 @@ var ts;
var parameter = signature.thisParameter;
if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
if (!parameter) {
- signature.thisParameter = createTransientSymbol(context.thisParameter, undefined);
+ signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
}
- assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper);
+ assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper, checkMode);
}
}
for (var i = 0; i < len; i++) {
var parameter = signature.parameters[i];
if (!parameter.valueDeclaration.type) {
var contextualParameterType = getTypeAtPosition(context, i);
- assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper);
+ assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode);
}
}
if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) {
var parameter = ts.lastOrUndefined(signature.parameters);
if (!parameter.valueDeclaration.type) {
var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters));
- assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper);
+ assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode);
}
}
}
@@ -36602,19 +39786,19 @@ var ts;
}
}
}
- function assignTypeToParameterAndFixTypeParameters(parameter, contextualType, mapper) {
+ function assignTypeToParameterAndFixTypeParameters(parameter, contextualType, mapper, checkMode) {
var links = getSymbolLinks(parameter);
if (!links.type) {
links.type = instantiateType(contextualType, mapper);
// if inference didn't come up with anything but {}, fall back to the binding pattern if present.
if (links.type === emptyObjectType &&
- (parameter.valueDeclaration.name.kind === 172 /* ObjectBindingPattern */ ||
- parameter.valueDeclaration.name.kind === 173 /* ArrayBindingPattern */)) {
+ (parameter.valueDeclaration.name.kind === 173 /* ObjectBindingPattern */ ||
+ parameter.valueDeclaration.name.kind === 174 /* ArrayBindingPattern */)) {
links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name);
}
assignBindingElementTypes(parameter.valueDeclaration);
}
- else if (isInferentialContext(mapper)) {
+ else if (checkMode === 2 /* Inferential */) {
// Even if the parameter already has a type, it might be because it was given a type while
// processing the function as an argument to a prior signature during overload resolution.
// If this was the case, it may have caused some type parameters to be fixed. So here,
@@ -36644,7 +39828,7 @@ var ts;
// T in the second overload so that we do not infer Base as a candidate for T
// (inferring Base would make type argument inference inconsistent between the two
// overloads).
- inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper));
+ inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper));
}
}
function getReturnTypeFromJSDocComment(func) {
@@ -36656,10 +39840,10 @@ var ts;
}
function createPromiseType(promisedType) {
// creates a `Promise<T>` type where `T` is the promisedType argument
- var globalPromiseType = getGlobalPromiseType();
+ var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
if (globalPromiseType !== emptyGenericType) {
// if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
- promisedType = getAwaitedType(promisedType);
+ promisedType = getAwaitedType(promisedType) || emptyObjectType;
return createTypeReference(globalPromiseType, [promisedType]);
}
return emptyObjectType;
@@ -36670,53 +39854,63 @@ var ts;
error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option);
return unknownType;
}
+ else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
+ error(func, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option);
+ }
return promiseType;
}
- function getReturnTypeFromBody(func, contextualMapper) {
+ function getReturnTypeFromBody(func, checkMode) {
var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
if (!func.body) {
return unknownType;
}
- var isAsync = ts.isAsyncFunctionLike(func);
+ var functionFlags = ts.getFunctionFlags(func);
var type;
- if (func.body.kind !== 204 /* Block */) {
- type = checkExpressionCached(func.body, contextualMapper);
- if (isAsync) {
+ if (func.body.kind !== 206 /* Block */) {
+ type = checkExpressionCached(func.body, checkMode);
+ if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
// return type of the body should be unwrapped to its awaited type, which we will wrap in
// the native Promise<T> type later in this function.
- type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member);
+ type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
}
}
else {
var types = void 0;
- var funcIsGenerator = !!func.asteriskToken;
- if (funcIsGenerator) {
- types = checkAndAggregateYieldOperandTypes(func, contextualMapper);
- if (types.length === 0) {
- var iterableIteratorAny = createIterableIteratorType(anyType);
- if (compilerOptions.noImplicitAny) {
+ if (functionFlags & 1 /* Generator */) {
+ types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode));
+ if (!types || types.length === 0) {
+ var iterableIteratorAny = functionFlags & 2 /* Async */
+ ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function
+ : createIterableIteratorType(anyType); // Generator function
+ if (noImplicitAny) {
error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny));
}
return iterableIteratorAny;
}
}
else {
- types = checkAndAggregateReturnExpressionTypes(func, contextualMapper);
+ types = checkAndAggregateReturnExpressionTypes(func, checkMode);
if (!types) {
// For an async function, the return type will not be never, but rather a Promise for never.
- return isAsync ? createPromiseReturnType(func, neverType) : neverType;
+ return functionFlags & 2 /* Async */
+ ? createPromiseReturnType(func, neverType) // Async function
+ : neverType; // Normal function
}
if (types.length === 0) {
// For an async function, the return type will not be void, but rather a Promise for void.
- return isAsync ? createPromiseReturnType(func, voidType) : voidType;
+ return functionFlags & 2 /* Async */
+ ? createPromiseReturnType(func, voidType) // Async function
+ : voidType; // Normal function
}
}
// Return a union of the return expression types.
type = getUnionType(types, /*subtypeReduction*/ true);
- if (funcIsGenerator) {
- type = createIterableIteratorType(type);
+ if (functionFlags & 1 /* Generator */) {
+ type = functionFlags & 2 /* Async */
+ ? createAsyncIterableIteratorType(type) // AsyncGenerator function
+ : createIterableIteratorType(type); // Generator function
}
}
if (!contextualSignature) {
@@ -36731,17 +39925,25 @@ var ts;
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
// return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
- return isAsync ? createPromiseReturnType(func, widenedType) : widenedType;
+ return (functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */
+ ? createPromiseReturnType(func, widenedType) // Async function
+ : widenedType; // Generator function, AsyncGenerator function, or normal function
}
- function checkAndAggregateYieldOperandTypes(func, contextualMapper) {
+ function checkAndAggregateYieldOperandTypes(func, checkMode) {
var aggregatedTypes = [];
+ var functionFlags = ts.getFunctionFlags(func);
ts.forEachYieldExpression(func.body, function (yieldExpression) {
var expr = yieldExpression.expression;
if (expr) {
- var type = checkExpressionCached(expr, contextualMapper);
+ var type = checkExpressionCached(expr, checkMode);
if (yieldExpression.asteriskToken) {
// A yield* expression effectively yields everything that its operand yields
- type = checkElementTypeOfIterable(type, yieldExpression.expression);
+ type = checkIteratedTypeOrElementType(type, yieldExpression.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0);
+ }
+ if (functionFlags & 2 /* Async */) {
+ type = checkAwaitedType(type, expr, yieldExpression.asteriskToken
+ ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
+ : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
}
if (!ts.contains(aggregatedTypes, type)) {
aggregatedTypes.push(type);
@@ -36762,33 +39964,33 @@ var ts;
if (!switchTypes.length) {
return false;
}
- return eachTypeContainedIn(type, switchTypes);
+ return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
}
function functionHasImplicitReturn(func) {
if (!(func.flags & 128 /* HasImplicitReturn */)) {
return false;
}
var lastStatement = ts.lastOrUndefined(func.body.statements);
- if (lastStatement && lastStatement.kind === 218 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) {
+ if (lastStatement && lastStatement.kind === 220 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) {
return false;
}
return true;
}
- function checkAndAggregateReturnExpressionTypes(func, contextualMapper) {
- var isAsync = ts.isAsyncFunctionLike(func);
+ function checkAndAggregateReturnExpressionTypes(func, checkMode) {
+ var functionFlags = ts.getFunctionFlags(func);
var aggregatedTypes = [];
var hasReturnWithNoExpression = functionHasImplicitReturn(func);
var hasReturnOfTypeNever = false;
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, contextualMapper);
- if (isAsync) {
+ var type = checkExpressionCached(expr, checkMode);
+ if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
// return type of the body should be unwrapped to its awaited type, which should be wrapped in
// the native Promise<T> type by the caller.
- type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member);
+ type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
}
if (type.flags & 8192 /* Never */) {
hasReturnOfTypeNever = true;
@@ -36802,7 +40004,7 @@ var ts;
}
});
if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever ||
- func.kind === 184 /* FunctionExpression */ || func.kind === 185 /* ArrowFunction */)) {
+ func.kind === 185 /* FunctionExpression */ || func.kind === 186 /* ArrowFunction */)) {
return undefined;
}
if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) {
@@ -36831,7 +40033,7 @@ var ts;
}
// If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
// also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
- if (ts.nodeIsMissing(func.body) || func.body.kind !== 204 /* Block */ || !functionHasImplicitReturn(func)) {
+ if (ts.nodeIsMissing(func.body) || func.body.kind !== 206 /* Block */ || !functionHasImplicitReturn(func)) {
return;
}
var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */;
@@ -36863,22 +40065,22 @@ var ts;
error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
}
}
- function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) {
- ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
+ function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
+ ts.Debug.assert(node.kind !== 150 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
// Grammar checking
var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
- if (!hasGrammarError && node.kind === 184 /* FunctionExpression */) {
+ if (!hasGrammarError && node.kind === 185 /* FunctionExpression */) {
checkGrammarForGenerator(node);
}
// The identityMapper object is used to indicate that function expressions are wildcards
- if (contextualMapper === identityMapper && isContextSensitive(node)) {
+ if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
checkNodeDeferred(node);
return anyFunctionType;
}
var links = getNodeLinks(node);
var type = getTypeOfSymbol(node.symbol);
var contextSensitive = isContextSensitive(node);
- var mightFixTypeParameters = contextSensitive && isInferentialContext(contextualMapper);
+ var mightFixTypeParameters = contextSensitive && checkMode === 2 /* Inferential */;
// Check if function expression is contextually typed and assign parameter types if so.
// See the comment in assignTypeToParameterAndFixTypeParameters to understand why we need to
// check mightFixTypeParameters.
@@ -36893,10 +40095,10 @@ var ts;
if (contextualSignature) {
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (contextSensitive) {
- assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper);
+ assignContextualParameterTypes(signature, contextualSignature, getContextualMapper(node), checkMode);
}
if (mightFixTypeParameters || !node.type && !signature.resolvedReturnType) {
- var returnType = getReturnTypeFromBody(node, contextualMapper);
+ var returnType = getReturnTypeFromBody(node, checkMode);
if (!signature.resolvedReturnType) {
signature.resolvedReturnType = returnType;
}
@@ -36908,17 +40110,21 @@ var ts;
}
}
}
- if (produceDiagnostics && node.kind !== 149 /* MethodDeclaration */) {
+ if (produceDiagnostics && node.kind !== 150 /* MethodDeclaration */) {
checkCollisionWithCapturedSuperVariable(node, node.name);
checkCollisionWithCapturedThisVariable(node, node.name);
+ checkCollisionWithCapturedNewTargetVariable(node, node.name);
}
return type;
}
function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
- ts.Debug.assert(node.kind !== 149 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
- var isAsync = ts.isAsyncFunctionLike(node);
- var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type));
- if (!node.asteriskToken) {
+ ts.Debug.assert(node.kind !== 150 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
+ var functionFlags = ts.getFunctionFlags(node);
+ var returnOrPromisedType = node.type &&
+ ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ ?
+ checkAsyncFunctionReturnType(node) :
+ getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function
+ if ((functionFlags & 1 /* Generator */) === 0) {
// return is not necessary in the body of generators
checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
}
@@ -36931,7 +40137,7 @@ var ts;
// checkFunctionExpressionBodies). So it must be done now.
getReturnTypeOfSignature(getSignatureFromDeclaration(node));
}
- if (node.body.kind === 204 /* Block */) {
+ if (node.body.kind === 206 /* Block */) {
checkSourceElement(node.body);
}
else {
@@ -36942,8 +40148,8 @@ var ts;
// its return type annotation.
var exprType = checkExpression(node.body);
if (returnOrPromisedType) {
- if (isAsync) {
- var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member);
+ if ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) {
+ var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body);
}
else {
@@ -36968,21 +40174,21 @@ var ts;
// Get accessors without matching set accessors
// Enum members
// Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
- return symbol.isReadonly ||
- symbol.flags & 4 /* Property */ && (getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */) !== 0 ||
- symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 ||
+ return !!(getCheckFlags(symbol) & 8 /* Readonly */ ||
+ symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
+ symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
- (symbol.flags & 8 /* EnumMember */) !== 0;
+ symbol.flags & 8 /* EnumMember */);
}
function isReferenceToReadonlyEntity(expr, symbol) {
if (isReadonlySymbol(symbol)) {
// Allow assignments to readonly properties within constructors of the same class declaration.
if (symbol.flags & 4 /* Property */ &&
- (expr.kind === 177 /* PropertyAccessExpression */ || expr.kind === 178 /* ElementAccessExpression */) &&
+ (expr.kind === 178 /* PropertyAccessExpression */ || expr.kind === 179 /* ElementAccessExpression */) &&
expr.expression.kind === 98 /* ThisKeyword */) {
// Look for if this is the constructor for the class that `symbol` is a property of.
var func = ts.getContainingFunction(expr);
- if (!(func && func.kind === 150 /* Constructor */))
+ if (!(func && func.kind === 151 /* Constructor */))
return true;
// If func.parent is a class and symbol is a (readonly) property of that class, or
// if func is a constructor and symbol is a (readonly) parameter property declared in it,
@@ -36994,13 +40200,13 @@ var ts;
return false;
}
function isReferenceThroughNamespaceImport(expr) {
- if (expr.kind === 177 /* PropertyAccessExpression */ || expr.kind === 178 /* ElementAccessExpression */) {
+ if (expr.kind === 178 /* PropertyAccessExpression */ || expr.kind === 179 /* ElementAccessExpression */) {
var node = ts.skipParentheses(expr.expression);
if (node.kind === 70 /* Identifier */) {
var symbol = getNodeLinks(node).resolvedSymbol;
if (symbol.flags & 8388608 /* Alias */) {
var declaration = getDeclarationOfAliasSymbol(symbol);
- return declaration && declaration.kind === 237 /* NamespaceImport */;
+ return declaration && declaration.kind === 239 /* NamespaceImport */;
}
}
}
@@ -37009,7 +40215,7 @@ var ts;
function checkReferenceExpression(expr, invalidReferenceMessage) {
// References are combinations of identifiers, parentheses, and property accesses.
var node = ts.skipParentheses(expr);
- if (node.kind !== 70 /* Identifier */ && node.kind !== 177 /* PropertyAccessExpression */ && node.kind !== 178 /* ElementAccessExpression */) {
+ if (node.kind !== 70 /* Identifier */ && node.kind !== 178 /* PropertyAccessExpression */ && node.kind !== 179 /* ElementAccessExpression */) {
error(expr, invalidReferenceMessage);
return false;
}
@@ -37017,11 +40223,21 @@ var ts;
}
function checkDeleteExpression(node) {
checkExpression(node.expression);
+ var expr = ts.skipParentheses(node.expression);
+ if (expr.kind !== 178 /* PropertyAccessExpression */ && expr.kind !== 179 /* ElementAccessExpression */) {
+ error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
+ return booleanType;
+ }
+ var links = getNodeLinks(expr);
+ var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
+ if (symbol && isReadonlySymbol(symbol)) {
+ error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
+ }
return booleanType;
}
function checkTypeOfExpression(node) {
checkExpression(node.expression);
- return stringType;
+ return typeofType;
}
function checkVoidExpression(node) {
checkExpression(node.expression);
@@ -37030,7 +40246,7 @@ var ts;
function checkAwaitExpression(node) {
// Grammar checking
if (produceDiagnostics) {
- if (!(node.flags & 524288 /* AwaitContext */)) {
+ if (!(node.flags & 16384 /* AwaitContext */)) {
grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function);
}
if (isInParameterInitializerBeforeContainingFunction(node)) {
@@ -37038,7 +40254,7 @@ var ts;
}
}
var operandType = checkExpression(node.expression);
- return checkAwaitedType(operandType, node);
+ return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
}
function checkPrefixUnaryExpression(node) {
var operandType = checkExpression(node.operand);
@@ -37052,6 +40268,7 @@ var ts;
case 36 /* PlusToken */:
case 37 /* MinusToken */:
case 51 /* TildeToken */:
+ checkNonNullType(operandType, node.operand);
if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) {
error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
}
@@ -37063,7 +40280,7 @@ var ts;
booleanType;
case 42 /* PlusPlusToken */:
case 43 /* MinusMinusToken */:
- var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type);
+ var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type);
if (ok) {
// run check only if former checks succeeded to avoid reporting cascading errors
checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access);
@@ -37077,7 +40294,7 @@ var ts;
if (operandType === silentNeverType) {
return silentNeverType;
}
- var ok = checkArithmeticOperandType(node.operand, getNonNullableType(operandType), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type);
+ var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type);
if (ok) {
// run check only if former checks succeeded to avoid reporting cascading errors
checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access);
@@ -37092,8 +40309,8 @@ var ts;
}
if (type.flags & 196608 /* UnionOrIntersection */) {
var types = type.types;
- for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
- var t = types_15[_i];
+ for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
+ var t = types_19[_i];
if (maybeTypeOfKind(t, kind)) {
return true;
}
@@ -37110,8 +40327,8 @@ var ts;
}
if (type.flags & 65536 /* Union */) {
var types = type.types;
- for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
- var t = types_16[_i];
+ for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
+ var t = types_20[_i];
if (!isTypeOfKind(t, kind)) {
return false;
}
@@ -37120,8 +40337,8 @@ var ts;
}
if (type.flags & 131072 /* Intersection */) {
var types = type.types;
- for (var _a = 0, types_17 = types; _a < types_17.length; _a++) {
- var t = types_17[_a];
+ for (var _a = 0, types_21 = types; _a < types_21.length; _a++) {
+ var t = types_21[_a];
if (isTypeOfKind(t, kind)) {
return true;
}
@@ -37141,14 +40358,17 @@ var ts;
}
// TypeScript 1.0 spec (April 2014): 4.15.4
// The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
- // and the right operand to be of type Any or a subtype of the 'Function' interface type.
+ // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
// The result is always of the Boolean primitive type.
// NOTE: do not raise error if leftType is unknown as related error was already reported
if (isTypeOfKind(leftType, 8190 /* Primitive */)) {
error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
}
// NOTE: do not raise error if right is unknown as related error was already reported
- if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
+ if (!(isTypeAny(rightType) ||
+ getSignaturesOfType(rightType, 0 /* Call */).length ||
+ getSignaturesOfType(rightType, 1 /* Construct */).length ||
+ isTypeSubtypeOf(rightType, globalFunctionType))) {
error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type);
}
return booleanType;
@@ -37157,6 +40377,8 @@ var ts;
if (leftType === silentNeverType || rightType === silentNeverType) {
return silentNeverType;
}
+ leftType = checkNonNullType(leftType, left);
+ rightType = checkNonNullType(rightType, right);
// TypeScript 1.0 spec (April 2014): 4.15.5
// The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
// and the right operand to be of type Any, an object type, or a type parameter type.
@@ -37164,37 +40386,37 @@ var ts;
if (!(isTypeComparableTo(leftType, stringType) || isTypeOfKind(leftType, 340 /* NumberLike */ | 512 /* ESSymbol */))) {
error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
}
- if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 16384 /* TypeParameter */ | 524288 /* IndexedAccess */)) {
+ if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) {
error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
}
return booleanType;
}
function checkObjectLiteralAssignment(node, sourceType) {
var properties = node.properties;
- for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) {
- var p = properties_5[_i];
+ for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) {
+ var p = properties_7[_i];
checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties);
}
return sourceType;
}
/** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) {
- if (property.kind === 257 /* PropertyAssignment */ || property.kind === 258 /* ShorthandPropertyAssignment */) {
- var name_20 = property.name;
- if (name_20.kind === 142 /* ComputedPropertyName */) {
- checkComputedPropertyName(name_20);
+ if (property.kind === 260 /* PropertyAssignment */ || property.kind === 261 /* ShorthandPropertyAssignment */) {
+ var name = property.name;
+ if (name.kind === 143 /* ComputedPropertyName */) {
+ checkComputedPropertyName(name);
}
- if (isComputedNonLiteralName(name_20)) {
+ if (isComputedNonLiteralName(name)) {
return undefined;
}
- var text = ts.getTextOfPropertyName(name_20);
+ var text = ts.getTextOfPropertyName(name);
var type = isTypeAny(objectLiteralType)
? objectLiteralType
: getTypeOfPropertyOfType(objectLiteralType, text) ||
isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) ||
getIndexTypeOfType(objectLiteralType, 0 /* String */);
if (type) {
- if (property.kind === 258 /* ShorthandPropertyAssignment */) {
+ if (property.kind === 261 /* ShorthandPropertyAssignment */) {
return checkDestructuringAssignment(property, type);
}
else {
@@ -37203,10 +40425,13 @@ var ts;
}
}
else {
- error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_20));
+ error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name));
}
}
- else if (property.kind === 259 /* SpreadAssignment */) {
+ else if (property.kind === 262 /* SpreadAssignment */) {
+ if (languageVersion < 5 /* ESNext */) {
+ checkExternalEmitHelpers(property, 4 /* Rest */);
+ }
var nonRestNames = [];
if (allProperties) {
for (var i = 0; i < allProperties.length - 1; i++) {
@@ -37220,22 +40445,25 @@ var ts;
error(property, ts.Diagnostics.Property_assignment_expected);
}
}
- function checkArrayLiteralAssignment(node, sourceType, contextualMapper) {
+ function checkArrayLiteralAssignment(node, sourceType, checkMode) {
+ if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
+ checkExternalEmitHelpers(node, 512 /* Read */);
+ }
// This elementType will be used if the specific property corresponding to this index is not
// present (aka the tuple element property). This call also checks that the parentType is in
// fact an iterable or array (depending on target language).
- var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false) || unknownType;
+ var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType;
var elements = node.elements;
for (var i = 0; i < elements.length; i++) {
- checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, contextualMapper);
+ checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
}
return sourceType;
}
- function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, contextualMapper) {
+ function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
var elements = node.elements;
var element = elements[elementIndex];
- if (element.kind !== 198 /* OmittedExpression */) {
- if (element.kind !== 196 /* SpreadElement */) {
+ if (element.kind !== 199 /* OmittedExpression */) {
+ if (element.kind !== 197 /* SpreadElement */) {
var propName = "" + elementIndex;
var type = isTypeAny(sourceType)
? sourceType
@@ -37243,7 +40471,7 @@ var ts;
? getTypeOfPropertyOfType(sourceType, propName)
: elementType;
if (type) {
- return checkDestructuringAssignment(element, type, contextualMapper);
+ return checkDestructuringAssignment(element, type, checkMode);
}
else {
// We still need to check element expression here because we may need to set appropriate flag on the expression
@@ -37263,20 +40491,20 @@ var ts;
}
else {
var restExpression = element.expression;
- if (restExpression.kind === 192 /* BinaryExpression */ && restExpression.operatorToken.kind === 57 /* EqualsToken */) {
+ if (restExpression.kind === 193 /* BinaryExpression */ && restExpression.operatorToken.kind === 57 /* EqualsToken */) {
error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
}
else {
- return checkDestructuringAssignment(restExpression, createArrayType(elementType), contextualMapper);
+ return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode);
}
}
}
}
return undefined;
}
- function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) {
+ function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) {
var target;
- if (exprOrAssignment.kind === 258 /* ShorthandPropertyAssignment */) {
+ if (exprOrAssignment.kind === 261 /* ShorthandPropertyAssignment */) {
var prop = exprOrAssignment;
if (prop.objectAssignmentInitializer) {
// In strict null checking mode, if a default value of a non-undefined type is specified, remove
@@ -37285,28 +40513,28 @@ var ts;
!(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) {
sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */);
}
- checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper);
+ checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
}
target = exprOrAssignment.name;
}
else {
target = exprOrAssignment;
}
- if (target.kind === 192 /* BinaryExpression */ && target.operatorToken.kind === 57 /* EqualsToken */) {
- checkBinaryExpression(target, contextualMapper);
+ if (target.kind === 193 /* BinaryExpression */ && target.operatorToken.kind === 57 /* EqualsToken */) {
+ checkBinaryExpression(target, checkMode);
target = target.left;
}
- if (target.kind === 176 /* ObjectLiteralExpression */) {
+ if (target.kind === 177 /* ObjectLiteralExpression */) {
return checkObjectLiteralAssignment(target, sourceType);
}
- if (target.kind === 175 /* ArrayLiteralExpression */) {
- return checkArrayLiteralAssignment(target, sourceType, contextualMapper);
+ if (target.kind === 176 /* ArrayLiteralExpression */) {
+ return checkArrayLiteralAssignment(target, sourceType, checkMode);
}
- return checkReferenceAssignment(target, sourceType, contextualMapper);
+ return checkReferenceAssignment(target, sourceType, checkMode);
}
- function checkReferenceAssignment(target, sourceType, contextualMapper) {
- var targetType = checkExpression(target, contextualMapper);
- var error = target.parent.kind === 259 /* SpreadAssignment */ ?
+ function checkReferenceAssignment(target, sourceType, checkMode) {
+ var targetType = checkExpression(target, checkMode);
+ var error = target.parent.kind === 262 /* SpreadAssignment */ ?
ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
if (checkReferenceExpression(target, error)) {
@@ -37328,35 +40556,35 @@ var ts;
case 70 /* Identifier */:
case 9 /* StringLiteral */:
case 11 /* RegularExpressionLiteral */:
- case 181 /* TaggedTemplateExpression */:
- case 194 /* TemplateExpression */:
+ case 182 /* TaggedTemplateExpression */:
+ case 195 /* TemplateExpression */:
case 12 /* NoSubstitutionTemplateLiteral */:
case 8 /* NumericLiteral */:
case 100 /* TrueKeyword */:
case 85 /* FalseKeyword */:
case 94 /* NullKeyword */:
- case 137 /* UndefinedKeyword */:
- case 184 /* FunctionExpression */:
- case 197 /* ClassExpression */:
- case 185 /* ArrowFunction */:
- case 175 /* ArrayLiteralExpression */:
- case 176 /* ObjectLiteralExpression */:
- case 187 /* TypeOfExpression */:
- case 201 /* NonNullExpression */:
- case 247 /* JsxSelfClosingElement */:
- case 246 /* JsxElement */:
+ case 138 /* UndefinedKeyword */:
+ case 185 /* FunctionExpression */:
+ case 198 /* ClassExpression */:
+ case 186 /* ArrowFunction */:
+ case 176 /* ArrayLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
+ case 188 /* TypeOfExpression */:
+ case 202 /* NonNullExpression */:
+ case 249 /* JsxSelfClosingElement */:
+ case 248 /* JsxElement */:
return true;
- case 193 /* ConditionalExpression */:
+ case 194 /* ConditionalExpression */:
return isSideEffectFree(node.whenTrue) &&
isSideEffectFree(node.whenFalse);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
if (ts.isAssignmentOperator(node.operatorToken.kind)) {
return false;
}
return isSideEffectFree(node.left) &&
isSideEffectFree(node.right);
- case 190 /* PrefixUnaryExpression */:
- case 191 /* PostfixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
// Unary operators ~, !, +, and - have no side effects.
// The rest do.
switch (node.operator) {
@@ -37368,9 +40596,9 @@ var ts;
}
return false;
// Some forms listed here for clarity
- case 188 /* VoidExpression */: // Explicit opt-out
- case 182 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
- case 200 /* AsExpression */: // Not SEF, but can produce useful type warnings
+ case 189 /* VoidExpression */: // Explicit opt-out
+ case 183 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
+ case 201 /* AsExpression */: // Not SEF, but can produce useful type warnings
default:
return false;
}
@@ -37385,16 +40613,16 @@ var ts;
firstAssignableToSecond && !secondAssignableToFirst ? type2 :
getUnionType([type1, type2], /*subtypeReduction*/ true);
}
- function checkBinaryExpression(node, contextualMapper) {
- return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node);
+ function checkBinaryExpression(node, checkMode) {
+ return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node);
}
- function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) {
+ function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
var operator = operatorToken.kind;
- if (operator === 57 /* EqualsToken */ && (left.kind === 176 /* ObjectLiteralExpression */ || left.kind === 175 /* ArrayLiteralExpression */)) {
- return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper);
+ if (operator === 57 /* EqualsToken */ && (left.kind === 177 /* ObjectLiteralExpression */ || left.kind === 176 /* ArrayLiteralExpression */)) {
+ return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode);
}
- var leftType = checkExpression(left, contextualMapper);
- var rightType = checkExpression(right, contextualMapper);
+ var leftType = checkExpression(left, checkMode);
+ var rightType = checkExpression(right, checkMode);
switch (operator) {
case 38 /* AsteriskToken */:
case 39 /* AsteriskAsteriskToken */:
@@ -37421,18 +40649,8 @@ var ts;
if (leftType === silentNeverType || rightType === silentNeverType) {
return silentNeverType;
}
- // TypeScript 1.0 spec (April 2014): 4.19.1
- // These operators require their operands to be of type Any, the Number primitive type,
- // or an enum type. Operands of an enum type are treated
- // as having the primitive type Number. If one operand is the null or undefined value,
- // it is treated as having the type of the other operand.
- // The result is always of the Number primitive type.
- if (leftType.flags & 6144 /* Nullable */)
- leftType = rightType;
- if (rightType.flags & 6144 /* Nullable */)
- rightType = leftType;
- leftType = getNonNullableType(leftType);
- rightType = getNonNullableType(rightType);
+ leftType = checkNonNullType(leftType, left);
+ rightType = checkNonNullType(rightType, right);
var suggestedOperator = void 0;
// if a user tries to apply a bitwise operator to 2 boolean operands
// try and return them a helpful suggestion
@@ -37455,16 +40673,10 @@ var ts;
if (leftType === silentNeverType || rightType === silentNeverType) {
return silentNeverType;
}
- // TypeScript 1.0 spec (April 2014): 4.19.2
- // The binary + operator requires both operands to be of the Number primitive type or an enum type,
- // or at least one of the operands to be of type Any or the String primitive type.
- // If one operand is the null or undefined value, it is treated as having the type of the other operand.
- if (leftType.flags & 6144 /* Nullable */)
- leftType = rightType;
- if (rightType.flags & 6144 /* Nullable */)
- rightType = leftType;
- leftType = getNonNullableType(leftType);
- rightType = getNonNullableType(rightType);
+ if (!isTypeOfKind(leftType, 1 /* Any */ | 262178 /* StringLike */) && !isTypeOfKind(rightType, 1 /* Any */ | 262178 /* StringLike */)) {
+ leftType = checkNonNullType(leftType, left);
+ rightType = checkNonNullType(rightType, right);
+ }
var resultType = void 0;
if (isTypeOfKind(leftType, 340 /* NumberLike */) && isTypeOfKind(rightType, 340 /* NumberLike */)) {
// Operands of an enum type are treated as having the primitive type Number.
@@ -37499,8 +40711,8 @@ var ts;
case 29 /* LessThanEqualsToken */:
case 30 /* GreaterThanEqualsToken */:
if (checkForDisallowedESSymbolOperand(operator)) {
- leftType = getBaseTypeOfLiteralType(leftType);
- rightType = getBaseTypeOfLiteralType(rightType);
+ leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
+ rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) {
reportOperatorError();
}
@@ -37536,11 +40748,14 @@ var ts;
checkAssignmentOperator(rightType);
return getRegularTypeOfObjectLiteral(rightType);
case 25 /* CommaToken */:
- if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left)) {
+ if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
}
return rightType;
}
+ function isEvalNode(node) {
+ return node.kind === 70 /* Identifier */ && node.text === "eval";
+ }
// Return true if there was no error, false if there was an error.
function checkForDisallowedESSymbolOperand(operator) {
var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left :
@@ -37603,7 +40818,7 @@ var ts;
function checkYieldExpression(node) {
// Grammar checking
if (produceDiagnostics) {
- if (!(node.flags & 131072 /* YieldContext */) || isYieldExpressionInClass(node)) {
+ if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) {
grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
}
if (isInParameterInitializerBeforeContainingFunction(node)) {
@@ -37614,23 +40829,40 @@ var ts;
var func = ts.getContainingFunction(node);
// If the user's code is syntactically correct, the func should always have a star. After all,
// we are in a yield context.
- if (func && func.asteriskToken) {
+ var functionFlags = func && ts.getFunctionFlags(func);
+ if (node.asteriskToken) {
+ if (functionFlags & 2 /* Async */) {
+ if (languageVersion < 4 /* ES2017 */) {
+ checkExternalEmitHelpers(node, 4096 /* AsyncDelegator */);
+ }
+ }
+ else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
+ checkExternalEmitHelpers(node, 256 /* Values */);
+ }
+ }
+ if (functionFlags & 1 /* Generator */) {
var expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined);
var expressionElementType = void 0;
var nodeIsYieldStar = !!node.asteriskToken;
if (nodeIsYieldStar) {
- expressionElementType = checkElementTypeOfIterable(expressionType, node.expression);
+ expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0);
}
// There is no point in doing an assignability check if the function
// has no explicit return type because the return type is directly computed
// from the yield expressions.
if (func.type) {
- var signatureElementType = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType;
+ var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(func.type), (functionFlags & 2 /* Async */) !== 0) || anyType;
if (nodeIsYieldStar) {
- checkTypeAssignableTo(expressionElementType, signatureElementType, node.expression, /*headMessage*/ undefined);
+ checkTypeAssignableTo(functionFlags & 2 /* Async */
+ ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)
+ : expressionElementType, signatureElementType, node.expression,
+ /*headMessage*/ undefined);
}
else {
- checkTypeAssignableTo(expressionType, signatureElementType, node.expression, /*headMessage*/ undefined);
+ checkTypeAssignableTo(functionFlags & 2 /* Async */
+ ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)
+ : expressionType, signatureElementType, node.expression,
+ /*headMessage*/ undefined);
}
}
}
@@ -37638,10 +40870,10 @@ var ts;
// Both yield and yield* expressions have type 'any'
return anyType;
}
- function checkConditionalExpression(node, contextualMapper) {
+ function checkConditionalExpression(node, checkMode) {
checkExpression(node.condition);
- var type1 = checkExpression(node.whenTrue, contextualMapper);
- var type2 = checkExpression(node.whenFalse, contextualMapper);
+ var type1 = checkExpression(node.whenTrue, checkMode);
+ var type2 = checkExpression(node.whenFalse, checkMode);
return getBestChoiceType(type1, type2);
}
function checkLiteralExpression(node) {
@@ -37672,12 +40904,17 @@ var ts;
}
function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
var saveContextualType = node.contextualType;
+ var saveContextualMapper = node.contextualMapper;
node.contextualType = contextualType;
- var result = checkExpression(node, contextualMapper);
+ node.contextualMapper = contextualMapper;
+ var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
+ contextualMapper ? 2 /* Inferential */ : 0 /* Normal */;
+ var result = checkExpression(node, checkMode);
node.contextualType = saveContextualType;
+ node.contextualMapper = saveContextualMapper;
return result;
}
- function checkExpressionCached(node, contextualMapper) {
+ function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -37685,83 +40922,87 @@ var ts;
// to the top of the stack ensures all transient types are computed from a known point.
var saveFlowLoopStart = flowLoopStart;
flowLoopStart = flowLoopCount;
- links.resolvedType = checkExpression(node, contextualMapper);
+ links.resolvedType = checkExpression(node, checkMode);
flowLoopStart = saveFlowLoopStart;
}
return links.resolvedType;
}
function isTypeAssertion(node) {
node = ts.skipParentheses(node);
- return node.kind === 182 /* TypeAssertionExpression */ || node.kind === 200 /* AsExpression */;
+ return node.kind === 183 /* TypeAssertionExpression */ || node.kind === 201 /* AsExpression */;
}
function checkDeclarationInitializer(declaration) {
- var type = checkExpressionCached(declaration.initializer);
+ var type = getTypeOfExpression(declaration.initializer, /*cache*/ true);
return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ ||
ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration) ||
isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type);
}
function isLiteralContextualType(contextualType) {
if (contextualType) {
- if (contextualType.flags & 16384 /* TypeParameter */) {
- var apparentType = getApparentTypeOfTypeParameter(contextualType);
+ if (contextualType.flags & 540672 /* TypeVariable */) {
+ var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType;
// If the type parameter is constrained to the base primitive type we're checking for,
// consider this a literal context. For example, given a type parameter 'T extends string',
// this causes us to infer string literal types for T.
- if (apparentType.flags & (2 /* String */ | 4 /* Number */ | 8 /* Boolean */ | 16 /* Enum */)) {
+ if (constraint.flags & (2 /* String */ | 4 /* Number */ | 8 /* Boolean */ | 16 /* Enum */)) {
return true;
}
- contextualType = apparentType;
+ contextualType = constraint;
}
return maybeTypeOfKind(contextualType, (480 /* Literal */ | 262144 /* Index */));
}
return false;
}
- function checkExpressionForMutableLocation(node, contextualMapper) {
- var type = checkExpression(node, contextualMapper);
+ function checkExpressionForMutableLocation(node, checkMode) {
+ var type = checkExpression(node, checkMode);
return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type);
}
- function checkPropertyAssignment(node, contextualMapper) {
+ function checkPropertyAssignment(node, checkMode) {
// Do not use hasDynamicName here, because that returns false for well known symbols.
// We want to perform checkComputedPropertyName for all computed properties, including
// well known symbols.
- if (node.name.kind === 142 /* ComputedPropertyName */) {
+ if (node.name.kind === 143 /* ComputedPropertyName */) {
checkComputedPropertyName(node.name);
}
- return checkExpressionForMutableLocation(node.initializer, contextualMapper);
+ return checkExpressionForMutableLocation(node.initializer, checkMode);
}
- function checkObjectLiteralMethod(node, contextualMapper) {
+ function checkObjectLiteralMethod(node, checkMode) {
// Grammar checking
checkGrammarMethod(node);
// Do not use hasDynamicName here, because that returns false for well known symbols.
// We want to perform checkComputedPropertyName for all computed properties, including
// well known symbols.
- if (node.name.kind === 142 /* ComputedPropertyName */) {
+ if (node.name.kind === 143 /* ComputedPropertyName */) {
checkComputedPropertyName(node.name);
}
- var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper);
- return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper);
+ var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
+ return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
- function instantiateTypeWithSingleGenericCallSignature(node, type, contextualMapper) {
- if (isInferentialContext(contextualMapper)) {
+ function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
+ if (checkMode === 2 /* Inferential */) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(contextualType);
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper));
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
}
}
}
}
return type;
}
- // Returns the type of an expression. Unlike checkExpression, this function is simply concerned
- // with computing the type and may not fully check all contained sub-expressions for errors.
- function getTypeOfExpression(node) {
+ /**
+ * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
+ * with computing the type and may not fully check all contained sub-expressions for errors.
+ * A cache argument of true indicates that if the function performs a full type check, it is ok
+ * to cache the result.
+ */
+ function getTypeOfExpression(node, cache) {
// Optimize for the common case of a call to a function with a single non-generic call
// signature where we can just fetch the return type without checking the arguments.
- if (node.kind === 179 /* CallExpression */ && node.expression.kind !== 96 /* SuperKeyword */) {
+ if (node.kind === 180 /* CallExpression */ && node.expression.kind !== 96 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
var funcType = checkNonNullExpression(node.expression);
var signature = getSingleCallSignature(funcType);
if (signature && !signature.typeParameters) {
@@ -37771,7 +41012,21 @@ var ts;
// Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions
// should have a parameter that indicates whether full error checking is required such that
// we can perform the optimizations locally.
- return checkExpression(node);
+ return cache ? checkExpressionCached(node) : checkExpression(node);
+ }
+ /**
+ * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
+ * with computing the type and may not fully check all contained sub-expressions for errors.
+ * It is intended for uses where you know there is no contextual type,
+ * and requesting the contextual type might cause a circularity or other bad behaviour.
+ * It sets the contextual type of the node to any before calling getTypeOfExpression.
+ */
+ function getContextFreeTypeOfExpression(node) {
+ var saveContextualType = node.contextualType;
+ node.contextualType = anyType;
+ var type = getTypeOfExpression(node);
+ node.contextualType = saveContextualType;
+ return type;
}
// Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When
// contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the
@@ -37780,30 +41035,30 @@ var ts;
// object, it serves as an indicator that all contained function and arrow expressions should be considered to
// have the wildcard function type; this form of type check is used during overload resolution to exclude
// contextually typed function and arrow expressions in the initial phase.
- function checkExpression(node, contextualMapper) {
+ function checkExpression(node, checkMode) {
var type;
- if (node.kind === 141 /* QualifiedName */) {
+ if (node.kind === 142 /* QualifiedName */) {
type = checkQualifiedName(node);
}
else {
- var uninstantiatedType = checkExpressionWorker(node, contextualMapper);
- type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper);
+ var uninstantiatedType = checkExpressionWorker(node, checkMode);
+ type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
if (isConstEnumObjectType(type)) {
// enum object type for const enums are only permitted in:
// - 'left' in property access
// - 'object' in indexed access
// - target in rhs of import statement
- var ok = (node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.expression === node) ||
- (node.parent.kind === 178 /* ElementAccessExpression */ && node.parent.expression === node) ||
- ((node.kind === 70 /* Identifier */ || node.kind === 141 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node));
+ var ok = (node.parent.kind === 178 /* PropertyAccessExpression */ && node.parent.expression === node) ||
+ (node.parent.kind === 179 /* ElementAccessExpression */ && node.parent.expression === node) ||
+ ((node.kind === 70 /* Identifier */ || node.kind === 142 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node));
if (!ok) {
error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment);
}
}
return type;
}
- function checkExpressionWorker(node, contextualMapper) {
+ function checkExpressionWorker(node, checkMode) {
switch (node.kind) {
case 70 /* Identifier */:
return checkIdentifier(node);
@@ -37818,66 +41073,70 @@ var ts;
case 100 /* TrueKeyword */:
case 85 /* FalseKeyword */:
return checkLiteralExpression(node);
- case 194 /* TemplateExpression */:
+ case 195 /* TemplateExpression */:
return checkTemplateExpression(node);
case 12 /* NoSubstitutionTemplateLiteral */:
return stringType;
case 11 /* RegularExpressionLiteral */:
return globalRegExpType;
- case 175 /* ArrayLiteralExpression */:
- return checkArrayLiteral(node, contextualMapper);
- case 176 /* ObjectLiteralExpression */:
- return checkObjectLiteral(node, contextualMapper);
- case 177 /* PropertyAccessExpression */:
+ case 176 /* ArrayLiteralExpression */:
+ return checkArrayLiteral(node, checkMode);
+ case 177 /* ObjectLiteralExpression */:
+ return checkObjectLiteral(node, checkMode);
+ case 178 /* PropertyAccessExpression */:
return checkPropertyAccessExpression(node);
- case 178 /* ElementAccessExpression */:
+ case 179 /* ElementAccessExpression */:
return checkIndexedAccess(node);
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
return checkCallExpression(node);
- case 181 /* TaggedTemplateExpression */:
+ case 182 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
- case 183 /* ParenthesizedExpression */:
- return checkExpression(node.expression, contextualMapper);
- case 197 /* ClassExpression */:
+ case 184 /* ParenthesizedExpression */:
+ return checkExpression(node.expression, checkMode);
+ case 198 /* ClassExpression */:
return checkClassExpression(node);
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper);
- case 187 /* TypeOfExpression */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
+ case 188 /* TypeOfExpression */:
return checkTypeOfExpression(node);
- case 182 /* TypeAssertionExpression */:
- case 200 /* AsExpression */:
+ case 183 /* TypeAssertionExpression */:
+ case 201 /* AsExpression */:
return checkAssertion(node);
- case 201 /* NonNullExpression */:
+ case 202 /* NonNullExpression */:
return checkNonNullAssertion(node);
- case 186 /* DeleteExpression */:
+ case 203 /* MetaProperty */:
+ return checkMetaProperty(node);
+ case 187 /* DeleteExpression */:
return checkDeleteExpression(node);
- case 188 /* VoidExpression */:
+ case 189 /* VoidExpression */:
return checkVoidExpression(node);
- case 189 /* AwaitExpression */:
+ case 190 /* AwaitExpression */:
return checkAwaitExpression(node);
- case 190 /* PrefixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
return checkPrefixUnaryExpression(node);
- case 191 /* PostfixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
return checkPostfixUnaryExpression(node);
- case 192 /* BinaryExpression */:
- return checkBinaryExpression(node, contextualMapper);
- case 193 /* ConditionalExpression */:
- return checkConditionalExpression(node, contextualMapper);
- case 196 /* SpreadElement */:
- return checkSpreadExpression(node, contextualMapper);
- case 198 /* OmittedExpression */:
+ case 193 /* BinaryExpression */:
+ return checkBinaryExpression(node, checkMode);
+ case 194 /* ConditionalExpression */:
+ return checkConditionalExpression(node, checkMode);
+ case 197 /* SpreadElement */:
+ return checkSpreadExpression(node, checkMode);
+ case 199 /* OmittedExpression */:
return undefinedWideningType;
- case 195 /* YieldExpression */:
+ case 196 /* YieldExpression */:
return checkYieldExpression(node);
- case 252 /* JsxExpression */:
- return checkJsxExpression(node);
- case 246 /* JsxElement */:
+ case 255 /* JsxExpression */:
+ return checkJsxExpression(node, checkMode);
+ case 248 /* JsxElement */:
return checkJsxElement(node);
- case 247 /* JsxSelfClosingElement */:
+ case 249 /* JsxSelfClosingElement */:
return checkJsxSelfClosingElement(node);
- case 248 /* JsxOpeningElement */:
+ case 253 /* JsxAttributes */:
+ return checkJsxAttributes(node, checkMode);
+ case 250 /* JsxOpeningElement */:
ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
}
return unknownType;
@@ -37889,7 +41148,16 @@ var ts;
grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
}
checkSourceElement(node.constraint);
- getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)));
+ checkSourceElement(node.default);
+ var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
+ if (!hasNonCircularBaseConstraint(typeParameter)) {
+ error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter));
+ }
+ var constraintType = getConstraintOfTypeParameter(typeParameter);
+ var defaultType = getDefaultFromTypeParameter(typeParameter);
+ if (constraintType && defaultType) {
+ checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
+ }
if (produceDiagnostics) {
checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
}
@@ -37905,7 +41173,7 @@ var ts;
var func = ts.getContainingFunction(node);
if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) {
func = ts.getContainingFunction(node);
- if (!(func.kind === 150 /* Constructor */ && ts.nodeIsPresent(func.body))) {
+ if (!(func.kind === 151 /* Constructor */ && ts.nodeIsPresent(func.body))) {
error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
}
}
@@ -37916,7 +41184,7 @@ var ts;
if (ts.indexOf(func.parameters, node) !== 0) {
error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter);
}
- if (func.kind === 150 /* Constructor */ || func.kind === 154 /* ConstructSignature */ || func.kind === 159 /* ConstructorType */) {
+ if (func.kind === 151 /* Constructor */ || func.kind === 155 /* ConstructSignature */ || func.kind === 160 /* ConstructorType */) {
error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
}
}
@@ -37926,14 +41194,6 @@ var ts;
error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
}
}
- function isSyntacticallyValidGenerator(node) {
- if (!node.asteriskToken || !node.body) {
- return false;
- }
- return node.kind === 149 /* MethodDeclaration */ ||
- node.kind === 225 /* FunctionDeclaration */ ||
- node.kind === 184 /* FunctionExpression */;
- }
function getTypePredicateParameterIndex(parameterList, parameter) {
if (parameterList) {
for (var i = 0; i < parameterList.length; i++) {
@@ -37967,7 +41227,7 @@ var ts;
error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
}
else {
- var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type);
+ var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type);
checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type,
/*headMessage*/ undefined, leadingError);
}
@@ -37975,9 +41235,9 @@ var ts;
else if (parameterName) {
var hasReportedError = false;
for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
- var name_21 = _a[_i].name;
- if (ts.isBindingPattern(name_21) &&
- checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, parameterName, typePredicate.parameterName)) {
+ var name = _a[_i].name;
+ if (ts.isBindingPattern(name) &&
+ checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
hasReportedError = true;
break;
}
@@ -37990,16 +41250,16 @@ var ts;
}
function getTypePredicateParent(node) {
switch (node.parent.kind) {
- case 185 /* ArrowFunction */:
- case 153 /* CallSignature */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 158 /* FunctionType */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- var parent_9 = node.parent;
- if (node === parent_9.type) {
- return parent_9;
+ case 186 /* ArrowFunction */:
+ case 154 /* CallSignature */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 159 /* FunctionType */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ var parent = node.parent;
+ if (node === parent.type) {
+ return parent;
}
}
}
@@ -38009,15 +41269,15 @@ var ts;
if (ts.isOmittedExpression(element)) {
continue;
}
- var name_22 = element.name;
- if (name_22.kind === 70 /* Identifier */ &&
- name_22.text === predicateVariableName) {
+ var name = element.name;
+ if (name.kind === 70 /* Identifier */ &&
+ name.text === predicateVariableName) {
error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
return true;
}
- else if (name_22.kind === 173 /* ArrayBindingPattern */ ||
- name_22.kind === 172 /* ObjectBindingPattern */) {
- if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_22, predicateVariableNode, predicateVariableName)) {
+ else if (name.kind === 174 /* ArrayBindingPattern */ ||
+ name.kind === 173 /* ObjectBindingPattern */) {
+ if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
return true;
}
}
@@ -38025,14 +41285,29 @@ var ts;
}
function checkSignatureDeclaration(node) {
// Grammar checking
- if (node.kind === 155 /* IndexSignature */) {
+ if (node.kind === 156 /* IndexSignature */) {
checkGrammarIndexSignature(node);
}
- else if (node.kind === 158 /* FunctionType */ || node.kind === 225 /* FunctionDeclaration */ || node.kind === 159 /* ConstructorType */ ||
- node.kind === 153 /* CallSignature */ || node.kind === 150 /* Constructor */ ||
- node.kind === 154 /* ConstructSignature */) {
+ else if (node.kind === 159 /* FunctionType */ || node.kind === 227 /* FunctionDeclaration */ || node.kind === 160 /* ConstructorType */ ||
+ node.kind === 154 /* CallSignature */ || node.kind === 151 /* Constructor */ ||
+ node.kind === 155 /* ConstructSignature */) {
checkGrammarFunctionLikeDeclaration(node);
}
+ var functionFlags = ts.getFunctionFlags(node);
+ if ((functionFlags & 7 /* InvalidAsyncOrAsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
+ checkExternalEmitHelpers(node, 64 /* Awaiter */);
+ if (languageVersion < 2 /* ES2015 */) {
+ checkExternalEmitHelpers(node, 128 /* Generator */);
+ }
+ }
+ if ((functionFlags & 5 /* InvalidGenerator */) === 1 /* Generator */) {
+ if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
+ checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */);
+ }
+ else if (languageVersion < 2 /* ES2015 */) {
+ checkExternalEmitHelpers(node, 128 /* Generator */);
+ }
+ }
checkTypeParameters(node.typeParameters);
ts.forEach(node.parameters, checkParameter);
if (node.type) {
@@ -38040,25 +41315,28 @@ var ts;
}
if (produceDiagnostics) {
checkCollisionWithArgumentsInGeneratedCode(node);
- if (compilerOptions.noImplicitAny && !node.type) {
+ if (noImplicitAny && !node.type) {
switch (node.kind) {
- case 154 /* ConstructSignature */:
+ case 155 /* ConstructSignature */:
error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
break;
- case 153 /* CallSignature */:
+ case 154 /* CallSignature */:
error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
break;
}
}
if (node.type) {
- if (languageVersion >= 2 /* ES2015 */ && isSyntacticallyValidGenerator(node)) {
+ var functionFlags_1 = ts.getFunctionFlags(node);
+ if ((functionFlags_1 & 5 /* InvalidGenerator */) === 1 /* Generator */) {
var returnType = getTypeFromTypeNode(node.type);
if (returnType === voidType) {
error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
}
else {
- var generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType;
- var iterableIteratorInstantiation = createIterableIteratorType(generatorElementType);
+ var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
+ var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */
+ ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function
+ : createIterableIteratorType(generatorElementType); // Generator function
// Naively, one could check that IterableIterator<any> is assignable to the return type annotation.
// However, that would not catch the error in the following case.
//
@@ -38068,7 +41346,7 @@ var ts;
checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type);
}
}
- else if (ts.isAsyncFunctionLike(node)) {
+ else if ((functionFlags_1 & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) {
checkAsyncFunctionReturnType(node);
}
}
@@ -38078,17 +41356,18 @@ var ts;
}
}
function checkClassForDuplicateDeclarations(node) {
- var Accessor;
- (function (Accessor) {
- Accessor[Accessor["Getter"] = 1] = "Getter";
- Accessor[Accessor["Setter"] = 2] = "Setter";
- Accessor[Accessor["Property"] = 3] = "Property";
- })(Accessor || (Accessor = {}));
+ var Declaration;
+ (function (Declaration) {
+ Declaration[Declaration["Getter"] = 1] = "Getter";
+ Declaration[Declaration["Setter"] = 2] = "Setter";
+ Declaration[Declaration["Method"] = 4] = "Method";
+ Declaration[Declaration["Property"] = 3] = "Property";
+ })(Declaration || (Declaration = {}));
var instanceNames = ts.createMap();
var staticNames = ts.createMap();
for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
var member = _a[_i];
- if (member.kind === 150 /* Constructor */) {
+ if (member.kind === 151 /* Constructor */) {
for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
var param = _c[_b];
if (ts.isParameterPropertyDeclaration(param)) {
@@ -38097,36 +41376,76 @@ var ts;
}
}
else {
- var isStatic = ts.forEach(member.modifiers, function (m) { return m.kind === 114 /* StaticKeyword */; });
+ var isStatic = ts.getModifierFlags(member) & 32 /* Static */;
var names = isStatic ? staticNames : instanceNames;
var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name);
if (memberName) {
switch (member.kind) {
- case 151 /* GetAccessor */:
+ case 152 /* GetAccessor */:
addName(names, member.name, memberName, 1 /* Getter */);
break;
- case 152 /* SetAccessor */:
+ case 153 /* SetAccessor */:
addName(names, member.name, memberName, 2 /* Setter */);
break;
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
addName(names, member.name, memberName, 3 /* Property */);
break;
+ case 150 /* MethodDeclaration */:
+ addName(names, member.name, memberName, 4 /* Method */);
+ break;
}
}
}
}
function addName(names, location, name, meaning) {
- var prev = names[name];
+ var prev = names.get(name);
if (prev) {
- if (prev & meaning) {
+ if (prev & 4 /* Method */) {
+ if (meaning !== 4 /* Method */) {
+ error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
+ }
+ }
+ else if (prev & meaning) {
error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
}
else {
- names[name] = prev | meaning;
+ names.set(name, prev | meaning);
}
}
else {
- names[name] = meaning;
+ names.set(name, meaning);
+ }
+ }
+ }
+ /**
+ * Static members being set on a constructor function may conflict with built-in properties
+ * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
+ * built-in properties. This check issues a transpile error when a class has a static
+ * member with the same name as a non-writable built-in property.
+ *
+ * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
+ * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
+ * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
+ * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
+ */
+ function checkClassForStaticPropertyNameConflicts(node) {
+ for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ var memberNameNode = member.name;
+ var isStatic = ts.getModifierFlags(member) & 32 /* Static */;
+ if (isStatic && memberNameNode) {
+ var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
+ switch (memberName) {
+ case "name":
+ case "length":
+ case "caller":
+ case "arguments":
+ case "prototype":
+ var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
+ var className = getNameOfSymbol(getSymbolOfNode(node));
+ error(memberNameNode, message, memberName, className);
+ break;
+ }
}
}
}
@@ -38134,7 +41453,7 @@ var ts;
var names = ts.createMap();
for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
var member = _a[_i];
- if (member.kind == 146 /* PropertySignature */) {
+ if (member.kind === 147 /* PropertySignature */) {
var memberName = void 0;
switch (member.name.kind) {
case 9 /* StringLiteral */:
@@ -38145,18 +41464,18 @@ var ts;
default:
continue;
}
- if (names[memberName]) {
+ if (names.get(memberName)) {
error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
}
else {
- names[memberName] = true;
+ names.set(memberName, true);
}
}
}
}
function checkTypeForDuplicateIndexSignatures(node) {
- if (node.kind === 227 /* InterfaceDeclaration */) {
+ if (node.kind === 229 /* InterfaceDeclaration */) {
var nodeSymbol = getSymbolOfNode(node);
// in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
// to prevent this run check only for the first declaration of a given kind
@@ -38176,7 +41495,7 @@ var ts;
var declaration = decl;
if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
switch (declaration.parameters[0].type.kind) {
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
if (!seenStringIndexer) {
seenStringIndexer = true;
}
@@ -38252,12 +41571,12 @@ var ts;
if (n.kind === 98 /* ThisKeyword */) {
error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
}
- else if (n.kind !== 184 /* FunctionExpression */ && n.kind !== 225 /* FunctionDeclaration */) {
+ else if (n.kind !== 185 /* FunctionExpression */ && n.kind !== 227 /* FunctionDeclaration */) {
ts.forEachChild(n, markThisReferencesAsErrors);
}
}
function isInstancePropertyWithInitializer(n) {
- return n.kind === 147 /* PropertyDeclaration */ &&
+ return n.kind === 148 /* PropertyDeclaration */ &&
!(ts.getModifierFlags(n) & 32 /* Static */) &&
!!n.initializer;
}
@@ -38287,7 +41606,7 @@ var ts;
var superCallStatement = void 0;
for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
var statement = statements_3[_i];
- if (statement.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
+ if (statement.kind === 209 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
superCallStatement = statement;
break;
}
@@ -38311,7 +41630,7 @@ var ts;
checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name);
checkDecorators(node);
checkSignatureDeclaration(node);
- if (node.kind === 151 /* GetAccessor */) {
+ if (node.kind === 152 /* GetAccessor */) {
if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) {
if (!(node.flags & 256 /* HasExplicitReturn */)) {
error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
@@ -38321,13 +41640,13 @@ var ts;
// Do not use hasDynamicName here, because that returns false for well known symbols.
// We want to perform checkComputedPropertyName for all computed properties, including
// well known symbols.
- if (node.name.kind === 142 /* ComputedPropertyName */) {
+ if (node.name.kind === 143 /* ComputedPropertyName */) {
checkComputedPropertyName(node.name);
}
if (!ts.hasDynamicName(node)) {
// TypeScript 1.0 spec (April 2014): 8.4.3
// Accessors for the same member name must specify the same accessibility.
- var otherKind = node.kind === 151 /* GetAccessor */ ? 152 /* SetAccessor */ : 151 /* GetAccessor */;
+ var otherKind = node.kind === 152 /* GetAccessor */ ? 153 /* SetAccessor */ : 152 /* GetAccessor */;
var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind);
if (otherAccessor) {
if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) {
@@ -38343,17 +41662,12 @@ var ts;
}
}
var returnType = getTypeOfAccessors(getSymbolOfNode(node));
- if (node.kind === 151 /* GetAccessor */) {
+ if (node.kind === 152 /* GetAccessor */) {
checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
}
}
- if (node.parent.kind !== 176 /* ObjectLiteralExpression */) {
- checkSourceElement(node.body);
- registerForUnusedIdentifiersCheck(node);
- }
- else {
- checkNodeDeferred(node);
- }
+ checkSourceElement(node.body);
+ registerForUnusedIdentifiersCheck(node);
}
function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
var firstType = getAnnotatedType(first);
@@ -38362,14 +41676,11 @@ var ts;
error(first, message);
}
}
- function checkAccessorDeferred(node) {
- checkSourceElement(node.body);
- registerForUnusedIdentifiersCheck(node);
- }
function checkMissingDeclaration(node) {
checkDecorators(node);
}
function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) {
+ var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
var typeArguments;
var mapper;
var result = true;
@@ -38377,7 +41688,7 @@ var ts;
var constraint = getConstraintOfTypeParameter(typeParameters[i]);
if (constraint) {
if (!typeArguments) {
- typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
+ typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount);
mapper = createTypeMapper(typeParameters, typeArguments);
}
var typeArgument = typeArguments[i];
@@ -38430,16 +41741,36 @@ var ts;
function checkUnionOrIntersectionType(node) {
ts.forEach(node.types, checkSourceElement);
}
+ function checkIndexedAccessIndexType(type, accessNode) {
+ if (!(type.flags & 524288 /* IndexedAccess */)) {
+ return type;
+ }
+ // Check if the index type is assignable to 'keyof T' for the object type.
+ var objectType = type.objectType;
+ var indexType = type.indexType;
+ if (isTypeAssignableTo(indexType, getIndexType(objectType))) {
+ return type;
+ }
+ // Check if we're indexing with a numeric type and the object type is a generic
+ // type with a constraint that has a numeric index signature.
+ if (maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && isTypeOfKind(indexType, 340 /* NumberLike */)) {
+ var constraint = getBaseConstraintOfType(objectType);
+ if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) {
+ return type;
+ }
+ }
+ error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
+ return type;
+ }
function checkIndexedAccessType(node) {
- getTypeFromIndexedAccessTypeNode(node);
+ checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
}
function checkMappedType(node) {
checkSourceElement(node.typeParameter);
checkSourceElement(node.type);
var type = getTypeFromMappedTypeNode(node);
var constraintType = getConstraintTypeFromMappedType(type);
- var keyType = constraintType.flags & 16384 /* TypeParameter */ ? getApparentTypeOfTypeParameter(constraintType) : constraintType;
- checkTypeAssignableTo(keyType, stringType, node.typeParameter.constraint);
+ checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint);
}
function isPrivateWithinAmbient(node) {
return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node);
@@ -38448,9 +41779,9 @@ var ts;
var flags = ts.getCombinedModifierFlags(n);
// children of classes (even ambient classes) should not be marked as ambient or export
// because those flags have no useful semantics there.
- if (n.parent.kind !== 227 /* InterfaceDeclaration */ &&
- n.parent.kind !== 226 /* ClassDeclaration */ &&
- n.parent.kind !== 197 /* ClassExpression */ &&
+ if (n.parent.kind !== 229 /* InterfaceDeclaration */ &&
+ n.parent.kind !== 228 /* ClassDeclaration */ &&
+ n.parent.kind !== 198 /* ClassExpression */ &&
ts.isInAmbientContext(n)) {
if (!(flags & 2 /* Ambient */)) {
// It is nested in an ambient context, which means it is automatically exported
@@ -38538,7 +41869,7 @@ var ts;
var errorNode_1 = subsequentNode.name || subsequentNode;
// TODO(jfreeman): These are methods, so handle computed name case
if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) {
- var reportError = (node.kind === 149 /* MethodDeclaration */ || node.kind === 148 /* MethodSignature */) &&
+ var reportError = (node.kind === 150 /* MethodDeclaration */ || node.kind === 149 /* MethodSignature */) &&
(ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */);
// we can get here in two cases
// 1. mixed static and instance class members
@@ -38573,11 +41904,11 @@ var ts;
}
var duplicateFunctionDeclaration = false;
var multipleConstructorImplementation = false;
- for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
- var current = declarations_4[_i];
+ for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
+ var current = declarations_5[_i];
var node = current;
var inAmbientContext = ts.isInAmbientContext(node);
- var inAmbientContextOrInterface = node.parent.kind === 227 /* InterfaceDeclaration */ || node.parent.kind === 161 /* TypeLiteral */ || inAmbientContext;
+ var inAmbientContextOrInterface = node.parent.kind === 229 /* InterfaceDeclaration */ || node.parent.kind === 162 /* TypeLiteral */ || inAmbientContext;
if (inAmbientContextOrInterface) {
// check if declarations are consecutive only if they are non-ambient
// 1. ambient declarations can be interleaved
@@ -38588,7 +41919,7 @@ var ts;
// 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
previousDeclaration = undefined;
}
- if (node.kind === 225 /* FunctionDeclaration */ || node.kind === 149 /* MethodDeclaration */ || node.kind === 148 /* MethodSignature */ || node.kind === 150 /* Constructor */) {
+ if (node.kind === 227 /* FunctionDeclaration */ || node.kind === 150 /* MethodDeclaration */ || node.kind === 149 /* MethodSignature */ || node.kind === 151 /* Constructor */) {
var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
someNodeFlags |= currentNodeFlags;
allNodeFlags &= currentNodeFlags;
@@ -38640,8 +41971,8 @@ var ts;
if (bodyDeclaration) {
var signatures = getSignaturesOfSymbol(symbol);
var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
- for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) {
- var signature = signatures_3[_a];
+ for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) {
+ var signature = signatures_4[_a];
if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation);
break;
@@ -38710,16 +42041,16 @@ var ts;
}
function getDeclarationSpaces(d) {
switch (d.kind) {
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
return 2097152 /* ExportType */;
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */
: 4194304 /* ExportNamespace */;
- case 226 /* ClassDeclaration */:
- case 229 /* EnumDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 231 /* EnumDeclaration */:
return 2097152 /* ExportType */ | 1048576 /* ExportValue */;
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
var result_3 = 0;
var target = resolveAlias(getSymbolOfNode(d));
ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); });
@@ -38729,25 +42060,16 @@ var ts;
}
}
}
- function checkNonThenableType(type, location, message) {
- type = getWidenedType(type);
- if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) {
- if (location) {
- if (!message) {
- message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member;
- }
- error(location, message);
- }
- return unknownType;
- }
- return type;
+ function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) {
+ var promisedType = getPromisedTypeOfPromise(type, errorNode);
+ return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage);
}
/**
- * Gets the "promised type" of a promise.
- * @param type The type of the promise.
- * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
- */
- function getPromisedType(promise) {
+ * Gets the "promised type" of a promise.
+ * @param type The type of the promise.
+ * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
+ */
+ function getPromisedTypeOfPromise(promise, errorNode) {
//
// { // promise
// then( // thenFunction
@@ -38760,127 +42082,140 @@ var ts;
if (isTypeAny(promise)) {
return undefined;
}
- if (getObjectFlags(promise) & 4 /* Reference */) {
- if (promise.target === tryGetGlobalPromiseType()
- || promise.target === getGlobalPromiseLikeType()) {
- return promise.typeArguments[0];
- }
+ var typeAsPromise = promise;
+ if (typeAsPromise.promisedTypeOfPromise) {
+ return typeAsPromise.promisedTypeOfPromise;
}
- var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType();
- if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) {
- return undefined;
+ if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) {
+ return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0];
}
var thenFunction = getTypeOfPropertyOfType(promise, "then");
- if (!thenFunction || isTypeAny(thenFunction)) {
+ if (isTypeAny(thenFunction)) {
return undefined;
}
- var thenSignatures = getSignaturesOfType(thenFunction, 0 /* Call */);
+ var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray;
if (thenSignatures.length === 0) {
+ if (errorNode) {
+ error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
+ }
return undefined;
}
- var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072 /* NEUndefined */);
+ var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */);
if (isTypeAny(onfulfilledParameterType)) {
return undefined;
}
var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
if (onfulfilledParameterSignatures.length === 0) {
+ if (errorNode) {
+ error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
+ }
return undefined;
}
- return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true);
- }
- function getTypeOfFirstParameterOfSignature(signature) {
- return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType;
+ return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true);
}
/**
- * Gets the "awaited type" of a type.
- * @param type The type to await.
- * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
- * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
- * The runtime behavior of the `await` keyword.
- */
- function getAwaitedType(type) {
- return checkAwaitedType(type, /*location*/ undefined, /*message*/ undefined);
+ * Gets the "awaited type" of a type.
+ * @param type The type to await.
+ * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
+ * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
+ * The runtime behavior of the `await` keyword.
+ */
+ function checkAwaitedType(type, errorNode, diagnosticMessage) {
+ return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType;
}
- function checkAwaitedType(type, location, message) {
- return checkAwaitedTypeWorker(type);
- function checkAwaitedTypeWorker(type) {
- if (type.flags & 65536 /* Union */) {
- var types = [];
- for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
- var constituentType = _a[_i];
- types.push(checkAwaitedTypeWorker(constituentType));
- }
- return getUnionType(types, /*subtypeReduction*/ true);
+ function getAwaitedType(type, errorNode, diagnosticMessage) {
+ var typeAsAwaitable = type;
+ if (typeAsAwaitable.awaitedTypeOfType) {
+ return typeAsAwaitable.awaitedTypeOfType;
+ }
+ if (isTypeAny(type)) {
+ return typeAsAwaitable.awaitedTypeOfType = type;
+ }
+ if (type.flags & 65536 /* Union */) {
+ var types = void 0;
+ for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
+ var constituentType = _a[_i];
+ types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage));
}
- else {
- var promisedType = getPromisedType(type);
- if (promisedType === undefined) {
- // The type was not a PromiseLike, so it could not be unwrapped any further.
- // As long as the type does not have a callable "then" property, it is
- // safe to return the type; otherwise, an error will have been reported in
- // the call to checkNonThenableType and we will return unknownType.
- //
- // An example of a non-promise "thenable" might be:
- //
- // await { then(): void {} }
- //
- // The "thenable" does not match the minimal definition for a PromiseLike. When
- // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
- // will never settle. We treat this as an error to help flag an early indicator
- // of a runtime problem. If the user wants to return this value from an async
- // function, they would need to wrap it in some other value. If they want it to
- // be treated as a promise, they can cast to <any>.
- return checkNonThenableType(type, location, message);
- }
- else {
- if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) {
- // We have a bad actor in the form of a promise whose promised type is
- // the same promise type, or a mutually recursive promise. Return the
- // unknown type as we cannot guess the shape. If this were the actual
- // case in the JavaScript, this Promise would never resolve.
- //
- // An example of a bad actor with a singly-recursive promise type might
- // be:
- //
- // interface BadPromise {
- // then(
- // onfulfilled: (value: BadPromise) => any,
- // onrejected: (error: any) => any): BadPromise;
- // }
- //
- // The above interface will pass the PromiseLike check, and return a
- // promised type of `BadPromise`. Since this is a self reference, we
- // don't want to keep recursing ad infinitum.
- //
- // An example of a bad actor in the form of a mutually-recursive
- // promise type might be:
- //
- // interface BadPromiseA {
- // then(
- // onfulfilled: (value: BadPromiseB) => any,
- // onrejected: (error: any) => any): BadPromiseB;
- // }
- //
- // interface BadPromiseB {
- // then(
- // onfulfilled: (value: BadPromiseA) => any,
- // onrejected: (error: any) => any): BadPromiseA;
- // }
- //
- if (location) {
- error(location, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method, symbolToString(type.symbol));
- }
- return unknownType;
- }
- // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
- // See the comments above for more information.
- awaitedTypeStack.push(type.id);
- var awaitedType = checkAwaitedTypeWorker(promisedType);
- awaitedTypeStack.pop();
- return awaitedType;
+ if (!types) {
+ return undefined;
+ }
+ return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, /*subtypeReduction*/ true);
+ }
+ var promisedType = getPromisedTypeOfPromise(type);
+ if (promisedType) {
+ if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) {
+ // Verify that we don't have a bad actor in the form of a promise whose
+ // promised type is the same as the promise type, or a mutually recursive
+ // promise. If so, we return undefined as we cannot guess the shape. If this
+ // were the actual case in the JavaScript, this Promise would never resolve.
+ //
+ // An example of a bad actor with a singly-recursive promise type might
+ // be:
+ //
+ // interface BadPromise {
+ // then(
+ // onfulfilled: (value: BadPromise) => any,
+ // onrejected: (error: any) => any): BadPromise;
+ // }
+ // The above interface will pass the PromiseLike check, and return a
+ // promised type of `BadPromise`. Since this is a self reference, we
+ // don't want to keep recursing ad infinitum.
+ //
+ // An example of a bad actor in the form of a mutually-recursive
+ // promise type might be:
+ //
+ // interface BadPromiseA {
+ // then(
+ // onfulfilled: (value: BadPromiseB) => any,
+ // onrejected: (error: any) => any): BadPromiseB;
+ // }
+ //
+ // interface BadPromiseB {
+ // then(
+ // onfulfilled: (value: BadPromiseA) => any,
+ // onrejected: (error: any) => any): BadPromiseA;
+ // }
+ //
+ if (errorNode) {
+ error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
}
+ return undefined;
+ }
+ // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
+ // See the comments above for more information.
+ awaitedTypeStack.push(type.id);
+ var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage);
+ awaitedTypeStack.pop();
+ if (!awaitedType) {
+ return undefined;
+ }
+ return typeAsAwaitable.awaitedTypeOfType = awaitedType;
+ }
+ // The type was not a promise, so it could not be unwrapped any further.
+ // As long as the type does not have a callable "then" property, it is
+ // safe to return the type; otherwise, an error will be reported in
+ // the call to getNonThenableType and we will return undefined.
+ //
+ // An example of a non-promise "thenable" might be:
+ //
+ // await { then(): void {} }
+ //
+ // The "thenable" does not match the minimal definition for a promise. When
+ // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
+ // will never settle. We treat this as an error to help flag an early indicator
+ // of a runtime problem. If the user wants to return this value from an async
+ // function, they would need to wrap it in some other value. If they want it to
+ // be treated as a promise, they can cast to <any>.
+ var thenFunction = getTypeOfPropertyOfType(type, "then");
+ if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) {
+ if (errorNode) {
+ ts.Debug.assert(!!diagnosticMessage);
+ error(errorNode, diagnosticMessage);
}
+ return undefined;
}
+ return typeAsAwaitable.awaitedTypeOfType = type;
}
/**
* Checks the return type of an async function to ensure it is a compatible
@@ -38925,8 +42260,8 @@ var ts;
if (returnType === unknownType) {
return unknownType;
}
- var globalPromiseType = getGlobalPromiseType();
- if (globalPromiseType !== emptyGenericType && globalPromiseType !== getTargetType(returnType)) {
+ var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
+ if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
// The promise type was not a valid type reference to the global promise type, so we
// report an error and return the unknown type.
error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
@@ -38947,10 +42282,15 @@ var ts;
var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455 /* Value */, /*ignoreErrors*/ true);
var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType;
if (promiseConstructorType === unknownType) {
- error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName));
+ if (promiseConstructorName.kind === 70 /* Identifier */ && promiseConstructorName.text === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
+ error(node.type, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option);
+ }
+ else {
+ error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName));
+ }
return unknownType;
}
- var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType();
+ var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
if (globalPromiseConstructorLikeType === emptyObjectType) {
// If we couldn't resolve the global PromiseConstructorLike type we cannot verify
// compatibility with __awaiter.
@@ -38969,7 +42309,7 @@ var ts;
}
}
// Get and return the awaited type of the return type.
- return checkAwaitedType(returnType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type);
+ return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
}
/** Check a decorator */
function checkDecorator(node) {
@@ -38982,22 +42322,22 @@ var ts;
var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
var errorInfo;
switch (node.parent.kind) {
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
var classSymbol = getSymbolOfNode(node.parent);
var classConstructorType = getTypeOfSymbol(classSymbol);
expectedReturnType = getUnionType([classConstructorType, voidType]);
break;
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
expectedReturnType = voidType;
errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
break;
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
expectedReturnType = voidType;
errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
break;
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
var methodType = getTypeOfNode(node.parent);
var descriptorType = createTypedPropertyDescriptorType(methodType);
expectedReturnType = getUnionType([descriptorType, voidType]);
@@ -39020,6 +42360,9 @@ var ts;
markAliasSymbolAsReferenced(rootSymbol);
}
}
+ function getParameterTypeNodeForDecoratorCheck(node) {
+ return node.dotDotDotToken ? ts.getRestParameterElementType(node.type) : node.type;
+ }
/** Check the decorators of a node */
function checkDecorators(node) {
if (!node.decorators) {
@@ -39033,29 +42376,37 @@ var ts;
if (!compilerOptions.experimentalDecorators) {
error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning);
}
+ var firstDecorator = node.decorators[0];
+ checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
+ if (node.kind === 145 /* Parameter */) {
+ checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
+ }
if (compilerOptions.emitDecoratorMetadata) {
+ checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
// we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
switch (node.kind) {
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
var constructor = ts.getFirstConstructorWithBody(node);
if (constructor) {
for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- markTypeNodeAsReferenced(parameter.type);
+ markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
}
}
break;
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
var parameter = _c[_b];
- markTypeNodeAsReferenced(parameter.type);
+ markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
}
markTypeNodeAsReferenced(node.type);
break;
- case 147 /* PropertyDeclaration */:
- case 144 /* Parameter */:
+ case 148 /* PropertyDeclaration */:
+ markTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
+ break;
+ case 145 /* Parameter */:
markTypeNodeAsReferenced(node.type);
break;
}
@@ -39067,6 +42418,7 @@ var ts;
checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node);
checkCollisionWithCapturedSuperVariable(node, node.name);
checkCollisionWithCapturedThisVariable(node, node.name);
+ checkCollisionWithCapturedNewTargetVariable(node, node.name);
checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
}
@@ -39074,11 +42426,11 @@ var ts;
function checkFunctionOrMethodDeclaration(node) {
checkDecorators(node);
checkSignatureDeclaration(node);
- var isAsync = ts.isAsyncFunctionLike(node);
+ var functionFlags = ts.getFunctionFlags(node);
// Do not use hasDynamicName here, because that returns false for well known symbols.
// We want to perform checkComputedPropertyName for all computed properties, including
// well known symbols.
- if (node.name && node.name.kind === 142 /* ComputedPropertyName */) {
+ if (node.name && node.name.kind === 143 /* ComputedPropertyName */) {
// This check will account for methods in class/interface declarations,
// as well as accessors in classes/object literals
checkComputedPropertyName(node.name);
@@ -39109,17 +42461,19 @@ var ts;
}
}
checkSourceElement(node.body);
- if (!node.asteriskToken) {
- var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type));
+ if ((functionFlags & 1 /* Generator */) === 0) {
+ var returnOrPromisedType = node.type && (functionFlags & 2 /* Async */
+ ? checkAsyncFunctionReturnType(node) // Async function
+ : getTypeFromTypeNode(node.type)); // normal function
checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType);
}
if (produceDiagnostics && !node.type) {
// Report an implicit any error if there is no body, no explicit return type, and node is not a private method
// in an ambient context
- if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) {
+ if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) {
reportImplicitAnyError(node, anyType);
}
- if (node.asteriskToken && ts.nodeIsPresent(node.body)) {
+ if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(node.body)) {
// A generator with a body and no type annotation can still cause errors. It can error if the
// yielded values have no common supertype, or it can give an implicit any error if it has no
// yielded values. The only way to trigger these errors is to try checking its return type.
@@ -39138,56 +42492,54 @@ var ts;
for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) {
var node = deferredUnusedIdentifierNodes_1[_i];
switch (node.kind) {
- case 261 /* SourceFile */:
- case 230 /* ModuleDeclaration */:
+ case 264 /* SourceFile */:
+ case 232 /* ModuleDeclaration */:
checkUnusedModuleMembers(node);
break;
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
checkUnusedClassMembers(node);
checkUnusedTypeParameters(node);
break;
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
checkUnusedTypeParameters(node);
break;
- case 204 /* Block */:
- case 232 /* CaseBlock */:
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
+ case 206 /* Block */:
+ case 234 /* CaseBlock */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
checkUnusedLocalsAndParameters(node);
break;
- case 150 /* Constructor */:
- case 184 /* FunctionExpression */:
- case 225 /* FunctionDeclaration */:
- case 185 /* ArrowFunction */:
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 151 /* Constructor */:
+ case 185 /* FunctionExpression */:
+ case 227 /* FunctionDeclaration */:
+ case 186 /* ArrowFunction */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
if (node.body) {
checkUnusedLocalsAndParameters(node);
}
checkUnusedTypeParameters(node);
break;
- case 148 /* MethodSignature */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
+ case 149 /* MethodSignature */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 156 /* IndexSignature */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
checkUnusedTypeParameters(node);
break;
}
- ;
}
}
}
function checkUnusedLocalsAndParameters(node) {
- if (node.parent.kind !== 227 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) {
- var _loop_3 = function (key) {
- var local = node.locals[key];
+ if (node.parent.kind !== 229 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) {
+ node.locals.forEach(function (local) {
if (!local.isReferenced) {
- if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 144 /* Parameter */) {
+ if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 145 /* Parameter */) {
var parameter = ts.getRootDeclaration(local.valueDeclaration);
if (compilerOptions.noUnusedParameters &&
!ts.isParameterPropertyDeclaration(parameter) &&
@@ -39200,22 +42552,28 @@ var ts;
ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); });
}
}
- };
- for (var key in node.locals) {
- _loop_3(key);
- }
+ });
+ }
+ }
+ function isRemovedPropertyFromObjectSpread(node) {
+ if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) {
+ var lastElement = ts.lastOrUndefined(node.parent.elements);
+ return lastElement !== node && !!lastElement.dotDotDotToken;
}
+ return false;
}
function errorUnusedLocal(node, name) {
if (isIdentifierThatStartsWithUnderScore(node)) {
var declaration = ts.getRootDeclaration(node.parent);
- if (declaration.kind === 223 /* VariableDeclaration */ &&
- (declaration.parent.parent.kind === 212 /* ForInStatement */ ||
- declaration.parent.parent.kind === 213 /* ForOfStatement */)) {
+ if (declaration.kind === 225 /* VariableDeclaration */ &&
+ (declaration.parent.parent.kind === 214 /* ForInStatement */ ||
+ declaration.parent.parent.kind === 215 /* ForOfStatement */)) {
return;
}
}
- error(node, ts.Diagnostics._0_is_declared_but_never_used, name);
+ if (!isRemovedPropertyFromObjectSpread(node.kind === 70 /* Identifier */ ? node.parent : node)) {
+ error(node, ts.Diagnostics._0_is_declared_but_never_used, name);
+ }
}
function parameterNameStartsWithUnderscore(parameterName) {
return parameterName && isIdentifierThatStartsWithUnderScore(parameterName);
@@ -39228,12 +42586,12 @@ var ts;
if (node.members) {
for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
var member = _a[_i];
- if (member.kind === 149 /* MethodDeclaration */ || member.kind === 147 /* PropertyDeclaration */) {
+ if (member.kind === 150 /* MethodDeclaration */ || member.kind === 148 /* PropertyDeclaration */) {
if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) {
error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name);
}
}
- else if (member.kind === 150 /* Constructor */) {
+ else if (member.kind === 151 /* Constructor */) {
for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
var parameter = _c[_b];
if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) {
@@ -39266,22 +42624,21 @@ var ts;
}
function checkUnusedModuleMembers(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
- for (var key in node.locals) {
- var local = node.locals[key];
+ node.locals.forEach(function (local) {
if (!local.isReferenced && !local.exportSymbol) {
for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (!ts.isAmbientModule(declaration)) {
- error(declaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name);
+ errorUnusedLocal(declaration.name, local.name);
}
}
}
- }
+ });
}
}
function checkBlock(node) {
// Grammar checking for SyntaxKind.Block
- if (node.kind === 204 /* Block */) {
+ if (node.kind === 206 /* Block */) {
checkGrammarStatementInAmbientContext(node);
}
ts.forEach(node.statements, checkSourceElement);
@@ -39304,12 +42661,12 @@ var ts;
if (!(identifier && identifier.text === name)) {
return false;
}
- if (node.kind === 147 /* PropertyDeclaration */ ||
- node.kind === 146 /* PropertySignature */ ||
- node.kind === 149 /* MethodDeclaration */ ||
- node.kind === 148 /* MethodSignature */ ||
- node.kind === 151 /* GetAccessor */ ||
- node.kind === 152 /* SetAccessor */) {
+ if (node.kind === 148 /* PropertyDeclaration */ ||
+ node.kind === 147 /* PropertySignature */ ||
+ node.kind === 150 /* MethodDeclaration */ ||
+ node.kind === 149 /* MethodSignature */ ||
+ node.kind === 152 /* GetAccessor */ ||
+ node.kind === 153 /* SetAccessor */) {
// it is ok to have member named '_super' or '_this' - member access is always qualified
return false;
}
@@ -39318,7 +42675,7 @@ var ts;
return false;
}
var root = ts.getRootDeclaration(node);
- if (root.kind === 144 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
+ if (root.kind === 145 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
// just an overload - no codegen impact
return false;
}
@@ -39329,10 +42686,14 @@ var ts;
potentialThisCollisions.push(node);
}
}
+ function checkCollisionWithCapturedNewTargetVariable(node, name) {
+ if (needCollisionCheckForIdentifier(node, name, "_newTarget")) {
+ potentialNewTargetCollisions.push(node);
+ }
+ }
// this function will run after checking the source file so 'CaptureThis' is correct for all nodes
function checkIfThisIsCapturedInEnclosingScope(node) {
- var current = node;
- while (current) {
+ ts.findAncestor(node, function (current) {
if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
var isDeclaration_1 = node.kind !== 70 /* Identifier */;
if (isDeclaration_1) {
@@ -39341,10 +42702,23 @@ var ts;
else {
error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
}
- return;
+ return true;
}
- current = current.parent;
- }
+ });
+ }
+ function checkIfNewTargetIsCapturedInEnclosingScope(node) {
+ ts.findAncestor(node, function (current) {
+ if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
+ var isDeclaration_2 = node.kind !== 70 /* Identifier */;
+ if (isDeclaration_2) {
+ error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
+ }
+ else {
+ error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
+ }
+ return true;
+ }
+ });
}
function checkCollisionWithCapturedSuperVariable(node, name) {
if (!needCollisionCheckForIdentifier(node, name, "_super")) {
@@ -39357,8 +42731,8 @@ var ts;
return;
}
if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) {
- var isDeclaration_2 = node.kind !== 70 /* Identifier */;
- if (isDeclaration_2) {
+ var isDeclaration_3 = node.kind !== 70 /* Identifier */;
+ if (isDeclaration_3) {
error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference);
}
else {
@@ -39375,27 +42749,27 @@ var ts;
return;
}
// Uninstantiated modules shouldnt do this check
- if (node.kind === 230 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
+ if (node.kind === 232 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
return;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 261 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 264 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
}
function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
- if (!needCollisionCheckForIdentifier(node, name, "Promise")) {
+ if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) {
return;
}
// Uninstantiated modules shouldnt do this check
- if (node.kind === 230 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
+ if (node.kind === 232 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
return;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 261 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 8192 /* HasAsyncFunctions */) {
+ if (parent.kind === 264 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
// If the declaration happens to be in external module, report error that Promise is a reserved identifier.
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -39430,7 +42804,7 @@ var ts;
// skip variable declarations that don't have initializers
// NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
// so we'll always treat binding elements as initialized
- if (node.kind === 223 /* VariableDeclaration */ && !node.initializer) {
+ if (node.kind === 225 /* VariableDeclaration */ && !node.initializer) {
return;
}
var symbol = getSymbolOfNode(node);
@@ -39440,24 +42814,24 @@ var ts;
localDeclarationSymbol !== symbol &&
localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
- var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 224 /* VariableDeclarationList */);
- var container = varDeclList.parent.kind === 205 /* VariableStatement */ && varDeclList.parent.parent
+ var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 226 /* VariableDeclarationList */);
+ var container = varDeclList.parent.kind === 207 /* VariableStatement */ && varDeclList.parent.parent
? varDeclList.parent.parent
: undefined;
// names of block-scoped and function scoped variables can collide only
// if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
var namesShareScope = container &&
- (container.kind === 204 /* Block */ && ts.isFunctionLike(container.parent) ||
- container.kind === 231 /* ModuleBlock */ ||
- container.kind === 230 /* ModuleDeclaration */ ||
- container.kind === 261 /* SourceFile */);
+ (container.kind === 206 /* Block */ && ts.isFunctionLike(container.parent) ||
+ container.kind === 233 /* ModuleBlock */ ||
+ container.kind === 232 /* ModuleDeclaration */ ||
+ container.kind === 264 /* SourceFile */);
// here we know that function scoped variable is shadowed by block scoped one
// if they are defined in the same scope - binder has already reported redeclaration error
// otherwise if variable has an initializer - show error that initialization will fail
// since LHS will be block scoped name instead of function scoped
if (!namesShareScope) {
- var name_23 = symbolToString(localDeclarationSymbol);
- error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_23, name_23);
+ var name = symbolToString(localDeclarationSymbol);
+ error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
}
}
}
@@ -39465,7 +42839,7 @@ var ts;
}
// Check that a parameter initializer contains no references to parameters declared to the right of itself
function checkParameterInitializer(node) {
- if (ts.getRootDeclaration(node).kind !== 144 /* Parameter */) {
+ if (ts.getRootDeclaration(node).kind !== 145 /* Parameter */) {
return;
}
var func = ts.getContainingFunction(node);
@@ -39476,7 +42850,7 @@ var ts;
// skip declaration names (i.e. in object literal expressions)
return;
}
- if (n.kind === 177 /* PropertyAccessExpression */) {
+ if (n.kind === 178 /* PropertyAccessExpression */) {
// skip property names in property access expression
return visit(n.expression);
}
@@ -39495,27 +42869,28 @@ var ts;
// so we need to do a bit of extra work to check if reference is legal
var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
if (enclosingContainer === func) {
- if (symbol.valueDeclaration.kind === 144 /* Parameter */) {
+ if (symbol.valueDeclaration.kind === 145 /* Parameter */ ||
+ symbol.valueDeclaration.kind === 175 /* BindingElement */) {
// it is ok to reference parameter in initializer if either
// - parameter is located strictly on the left of current parameter declaration
if (symbol.valueDeclaration.pos < node.pos) {
return;
}
// - parameter is wrapped in function-like entity
- var current = n;
- while (current !== node.initializer) {
- if (ts.isFunctionLike(current.parent)) {
- return;
+ if (ts.findAncestor(n, function (current) {
+ if (current === node.initializer) {
+ return "quit";
}
- // computed property names/initializers in instance property declaration of class like entities
- // are executed in constructor and thus deferred
- if (current.parent.kind === 147 /* PropertyDeclaration */ &&
- !(ts.hasModifier(current.parent, 32 /* Static */)) &&
- ts.isClassLike(current.parent.parent)) {
- return;
- }
- current = current.parent;
+ return ts.isFunctionLike(current.parent) ||
+ // computed property names/initializers in instance property declaration of class like entities
+ // are executed in constructor and thus deferred
+ (current.parent.kind === 148 /* PropertyDeclaration */ &&
+ !(ts.hasModifier(current.parent, 32 /* Static */)) &&
+ ts.isClassLike(current.parent.parent));
+ })) {
+ return;
}
+ // fall through to report error
}
error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n));
}
@@ -39536,40 +42911,46 @@ var ts;
// Do not use hasDynamicName here, because that returns false for well known symbols.
// We want to perform checkComputedPropertyName for all computed properties, including
// well known symbols.
- if (node.name.kind === 142 /* ComputedPropertyName */) {
+ if (node.name.kind === 143 /* ComputedPropertyName */) {
checkComputedPropertyName(node.name);
if (node.initializer) {
checkExpressionCached(node.initializer);
}
}
- if (node.kind === 174 /* BindingElement */) {
+ if (node.kind === 175 /* BindingElement */) {
+ if (node.parent.kind === 173 /* ObjectBindingPattern */ && languageVersion < 5 /* ESNext */) {
+ checkExternalEmitHelpers(node, 4 /* Rest */);
+ }
// check computed properties inside property names of binding elements
- if (node.propertyName && node.propertyName.kind === 142 /* ComputedPropertyName */) {
+ if (node.propertyName && node.propertyName.kind === 143 /* ComputedPropertyName */) {
checkComputedPropertyName(node.propertyName);
}
// check private/protected variable access
- var parent_10 = node.parent.parent;
- var parentType = getTypeForBindingElementParent(parent_10);
- var name_24 = node.propertyName || node.name;
- var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name_24));
+ var parent = node.parent.parent;
+ var parentType = getTypeForBindingElementParent(parent);
+ var name = node.propertyName || node.name;
+ var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name));
markPropertyAsReferenced(property);
- if (parent_10.initializer && property && getParentOfSymbol(property)) {
- checkClassPropertyAccess(parent_10, parent_10.initializer, parentType, property);
+ if (parent.initializer && property) {
+ checkPropertyAccessibility(parent, parent.initializer, parentType, property);
}
}
// For a binding pattern, check contained binding elements
if (ts.isBindingPattern(node.name)) {
+ if (node.name.kind === 174 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
+ checkExternalEmitHelpers(node, 512 /* Read */);
+ }
ts.forEach(node.name.elements, checkSourceElement);
}
// For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
- if (node.initializer && ts.getRootDeclaration(node).kind === 144 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
+ if (node.initializer && ts.getRootDeclaration(node).kind === 145 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
return;
}
// For a binding pattern, validate the initializer and exit
if (ts.isBindingPattern(node.name)) {
// Don't validate for-in initializer as it is already an error
- if (node.initializer && node.parent.parent.kind !== 212 /* ForInStatement */) {
+ if (node.initializer && node.parent.parent.kind !== 214 /* ForInStatement */) {
checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined);
checkParameterInitializer(node);
}
@@ -39580,7 +42961,7 @@ var ts;
if (node === symbol.valueDeclaration) {
// Node is the primary declaration of the symbol, just validate the initializer
// Don't validate for-in initializer as it is already an error
- if (node.initializer && node.parent.parent.kind !== 212 /* ForInStatement */) {
+ if (node.initializer && node.parent.parent.kind !== 214 /* ForInStatement */) {
checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined);
checkParameterInitializer(node);
}
@@ -39600,21 +42981,22 @@ var ts;
error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
}
}
- if (node.kind !== 147 /* PropertyDeclaration */ && node.kind !== 146 /* PropertySignature */) {
+ if (node.kind !== 148 /* PropertyDeclaration */ && node.kind !== 147 /* PropertySignature */) {
// We know we don't have a binding pattern or computed name here
checkExportsOnMergedDeclarations(node);
- if (node.kind === 223 /* VariableDeclaration */ || node.kind === 174 /* BindingElement */) {
+ if (node.kind === 225 /* VariableDeclaration */ || node.kind === 175 /* BindingElement */) {
checkVarDeclaredNamesNotShadowed(node);
}
checkCollisionWithCapturedSuperVariable(node, node.name);
checkCollisionWithCapturedThisVariable(node, node.name);
+ checkCollisionWithCapturedNewTargetVariable(node, node.name);
checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
}
}
function areDeclarationFlagsIdentical(left, right) {
- if ((left.kind === 144 /* Parameter */ && right.kind === 223 /* VariableDeclaration */) ||
- (left.kind === 223 /* VariableDeclaration */ && right.kind === 144 /* Parameter */)) {
+ if ((left.kind === 145 /* Parameter */ && right.kind === 225 /* VariableDeclaration */) ||
+ (left.kind === 225 /* VariableDeclaration */ && right.kind === 145 /* Parameter */)) {
// Differences in optionality between parameters and variables are allowed.
return true;
}
@@ -39644,8 +43026,8 @@ var ts;
}
function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) {
// We only disallow modifier on a method declaration if it is a property of object-literal-expression
- if (node.modifiers && node.parent.kind === 176 /* ObjectLiteralExpression */) {
- if (ts.isAsyncFunctionLike(node)) {
+ if (node.modifiers && node.parent.kind === 177 /* ObjectLiteralExpression */) {
+ if (ts.getFunctionFlags(node) & 2 /* Async */) {
if (node.modifiers.length > 1) {
return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
}
@@ -39665,7 +43047,7 @@ var ts;
checkGrammarStatementInAmbientContext(node);
checkExpression(node.expression);
checkSourceElement(node.thenStatement);
- if (node.thenStatement.kind === 206 /* EmptyStatement */) {
+ if (node.thenStatement.kind === 208 /* EmptyStatement */) {
error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
}
checkSourceElement(node.elseStatement);
@@ -39685,12 +43067,12 @@ var ts;
function checkForStatement(node) {
// Grammar checking
if (!checkGrammarStatementInAmbientContext(node)) {
- if (node.initializer && node.initializer.kind === 224 /* VariableDeclarationList */) {
+ if (node.initializer && node.initializer.kind === 226 /* VariableDeclarationList */) {
checkGrammarVariableDeclarationList(node.initializer);
}
}
if (node.initializer) {
- if (node.initializer.kind === 224 /* VariableDeclarationList */) {
+ if (node.initializer.kind === 226 /* VariableDeclarationList */) {
ts.forEach(node.initializer.declarations, checkVariableDeclaration);
}
else {
@@ -39708,19 +43090,29 @@ var ts;
}
function checkForOfStatement(node) {
checkGrammarForInOrForOfStatement(node);
+ if (node.kind === 215 /* ForOfStatement */) {
+ if (node.awaitModifier) {
+ if (languageVersion < 4 /* ES2017 */) {
+ checkExternalEmitHelpers(node, 8192 /* ForAwaitOfIncludes */);
+ }
+ }
+ else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
+ checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
+ }
+ }
// Check the LHS and RHS
// If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
// via checkRightHandSideOfForOf.
// If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
// Then check that the RHS is assignable to it.
- if (node.initializer.kind === 224 /* VariableDeclarationList */) {
+ if (node.initializer.kind === 226 /* VariableDeclarationList */) {
checkForInOrForOfVariableDeclaration(node);
}
else {
var varExpr = node.initializer;
- var iteratedType = checkRightHandSideOfForOf(node.expression);
+ var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier);
// There may be a destructuring assignment on the left side
- if (varExpr.kind === 175 /* ArrayLiteralExpression */ || varExpr.kind === 176 /* ObjectLiteralExpression */) {
+ if (varExpr.kind === 176 /* ArrayLiteralExpression */ || varExpr.kind === 177 /* ObjectLiteralExpression */) {
// iteratedType may be undefined. In this case, we still want to check the structure of
// varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
// to short circuit the type relation checking as much as possible, so we pass the unknownType.
@@ -39752,7 +43144,7 @@ var ts;
// for (let VarDecl in Expr) Statement
// VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
// and Expr must be an expression of type Any, an object type, or a type parameter type.
- if (node.initializer.kind === 224 /* VariableDeclarationList */) {
+ if (node.initializer.kind === 226 /* VariableDeclarationList */) {
var variable = node.initializer.declarations[0];
if (variable && ts.isBindingPattern(variable.name)) {
error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
@@ -39766,7 +43158,7 @@ var ts;
// and Expr must be an expression of type Any, an object type, or a type parameter type.
var varExpr = node.initializer;
var leftType = checkExpression(varExpr);
- if (varExpr.kind === 175 /* ArrayLiteralExpression */ || varExpr.kind === 176 /* ObjectLiteralExpression */) {
+ if (varExpr.kind === 176 /* ArrayLiteralExpression */ || varExpr.kind === 177 /* ObjectLiteralExpression */) {
error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
}
else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
@@ -39779,7 +43171,7 @@ var ts;
}
// unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
// in this case error about missing name is already reported - do not report extra one
- if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 16384 /* TypeParameter */ | 524288 /* IndexedAccess */)) {
+ if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) {
error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter);
}
checkSourceElement(node.statement);
@@ -39795,52 +43187,113 @@ var ts;
checkVariableDeclaration(decl);
}
}
- function checkRightHandSideOfForOf(rhsExpression) {
+ function checkRightHandSideOfForOf(rhsExpression, awaitModifier) {
var expressionType = checkNonNullExpression(rhsExpression);
- return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true);
+ return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined);
}
- function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput) {
+ function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable) {
if (isTypeAny(inputType)) {
return inputType;
}
- if (languageVersion >= 2 /* ES2015 */) {
- return checkElementTypeOfIterable(inputType, errorNode);
+ return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, /*checkAssignability*/ true) || anyType;
+ }
+ /**
+ * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
+ * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
+ * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
+ */
+ function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, checkAssignability) {
+ var uplevelIteration = languageVersion >= 2 /* ES2015 */;
+ var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
+ // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
+ // or higher, when inside of an async generator or for-await-if, or when
+ // downlevelIteration is requested.
+ if (uplevelIteration || downlevelIteration || allowAsyncIterable) {
+ // We only report errors for an invalid iterable type in ES2015 or higher.
+ var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterable, allowAsyncIterable, checkAssignability);
+ if (iteratedType || uplevelIteration) {
+ return iteratedType;
+ }
}
+ var arrayType = inputType;
+ var reportedError = false;
+ var hasStringConstituent = false;
+ // If strings are permitted, remove any string-like constituents from the array type.
+ // This allows us to find other non-string element types from an array unioned with
+ // a string.
if (allowStringInput) {
- return checkElementTypeOfArrayOrString(inputType, errorNode);
- }
- if (isArrayLikeType(inputType)) {
- var indexType = getIndexTypeOfType(inputType, 1 /* Number */);
- if (indexType) {
- return indexType;
+ if (arrayType.flags & 65536 /* Union */) {
+ // After we remove all types that are StringLike, we will know if there was a string constituent
+ // based on whether the result of filter is a new array.
+ var arrayTypes = inputType.types;
+ var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178 /* StringLike */); });
+ if (filteredTypes !== arrayTypes) {
+ arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true);
+ }
+ }
+ else if (arrayType.flags & 262178 /* StringLike */) {
+ arrayType = neverType;
+ }
+ hasStringConstituent = arrayType !== inputType;
+ if (hasStringConstituent) {
+ if (languageVersion < 1 /* ES5 */) {
+ if (errorNode) {
+ error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
+ reportedError = true;
+ }
+ }
+ // Now that we've removed all the StringLike types, if no constituents remain, then the entire
+ // arrayOrStringType was a string.
+ if (arrayType.flags & 8192 /* Never */) {
+ return stringType;
+ }
}
}
- if (errorNode) {
- error(errorNode, ts.Diagnostics.Type_0_is_not_an_array_type, typeToString(inputType));
+ if (!isArrayLikeType(arrayType)) {
+ if (errorNode && !reportedError) {
+ // Which error we report depends on whether we allow strings or if there was a
+ // string constituent. For example, if the input type is number | string, we
+ // want to say that number is not an array type. But if the input was just
+ // number and string input is allowed, we want to say that number is not an
+ // array type or a string type.
+ var diagnostic = !allowStringInput || hasStringConstituent
+ ? downlevelIteration
+ ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator
+ : ts.Diagnostics.Type_0_is_not_an_array_type
+ : downlevelIteration
+ ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator
+ : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type;
+ error(errorNode, diagnostic, typeToString(arrayType));
+ }
+ return hasStringConstituent ? stringType : undefined;
}
- return unknownType;
- }
- /**
- * When errorNode is undefined, it means we should not report any errors.
- */
- function checkElementTypeOfIterable(iterable, errorNode) {
- var elementType = getElementTypeOfIterable(iterable, errorNode);
- // Now even though we have extracted the iteratedType, we will have to validate that the type
- // passed in is actually an Iterable.
- if (errorNode && elementType) {
- checkTypeAssignableTo(iterable, createIterableType(elementType), errorNode);
+ var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
+ if (hasStringConstituent && arrayElementType) {
+ // This is just an optimization for the case where arrayOrStringType is string | string[]
+ if (arrayElementType.flags & 262178 /* StringLike */) {
+ return stringType;
+ }
+ return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true);
}
- return elementType || anyType;
+ return arrayElementType;
}
/**
* We want to treat type as an iterable, and get the type it is an iterable of. The iterable
* must have the following structure (annotated with the names of the variables below):
*
- * { // iterable
- * [Symbol.iterator]: { // iteratorFunction
- * (): Iterator<T>
+ * { // iterable
+ * [Symbol.iterator]: { // iteratorMethod
+ * (): Iterator<T>
+ * }
+ * }
+ *
+ * For an async iterable, we expect the following structure:
+ *
+ * { // iterable
+ * [Symbol.asyncIterator]: { // iteratorMethod
+ * (): AsyncIterator<T>
+ * }
* }
- * }
*
* T is the type we are after. At every level that involves analyzing return types
* of signatures, we union the return types of all the signatures.
@@ -39852,166 +43305,170 @@ var ts;
* caller requested it. Then the caller can decide what to do in the case where there is no iterated
* type. This is different from returning anyType, because that would signify that we have matched the
* whole pattern and that T (above) is 'any'.
+ *
+ * For a **for-of** statement, `yield*` (in a normal generator), spread, array
+ * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
+ * method.
+ *
+ * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
+ *
+ * For a **for-await-of** statement or a `yield*` in an async generator we will look for
+ * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
*/
- function getElementTypeOfIterable(type, errorNode) {
+ function getIteratedTypeOfIterable(type, errorNode, isAsyncIterable, allowNonAsyncIterables, checkAssignability) {
if (isTypeAny(type)) {
return undefined;
}
var typeAsIterable = type;
- if (!typeAsIterable.iterableElementType) {
- // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable<number>),
- // then just grab its type argument.
- if ((getObjectFlags(type) & 4 /* Reference */) && type.target === getGlobalIterableType()) {
- typeAsIterable.iterableElementType = type.typeArguments[0];
+ if (isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable) {
+ return isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable;
+ }
+ if (isAsyncIterable) {
+ // As an optimization, if the type is an instantiation of the global `AsyncIterable<T>`
+ // or the global `AsyncIterableIterator<T>` then just grab its type argument.
+ if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) ||
+ isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) {
+ return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0];
+ }
+ }
+ if (!isAsyncIterable || allowNonAsyncIterables) {
+ // As an optimization, if the type is an instantiation of the global `Iterable<T>` or
+ // `IterableIterator<T>` then just grab its type argument.
+ if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) ||
+ isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) {
+ return isAsyncIterable
+ ? typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]
+ : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0];
+ }
+ }
+ var iteratorMethodSignatures;
+ var mayBeIterable = false;
+ if (isAsyncIterable) {
+ var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator"));
+ if (isTypeAny(iteratorMethod)) {
+ return undefined;
}
- else {
- var iteratorFunction = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"));
- if (isTypeAny(iteratorFunction)) {
- return undefined;
- }
- var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0 /* Call */) : emptyArray;
- if (iteratorFunctionSignatures.length === 0) {
- if (errorNode) {
- error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator);
- }
- return undefined;
- }
- typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true), errorNode);
+ iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0 /* Call */);
+ }
+ if (!isAsyncIterable || (allowNonAsyncIterables && !ts.some(iteratorMethodSignatures))) {
+ var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"));
+ if (isTypeAny(iteratorMethod)) {
+ return undefined;
}
+ iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0 /* Call */);
+ mayBeIterable = true;
+ }
+ if (ts.some(iteratorMethodSignatures)) {
+ var iteratorMethodReturnType = getUnionType(ts.map(iteratorMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true);
+ var iteratedType = getIteratedTypeOfIterator(iteratorMethodReturnType, errorNode, /*isAsyncIterator*/ false);
+ if (checkAssignability && errorNode && iteratedType) {
+ // If `checkAssignability` was specified, we were called from
+ // `checkIteratedTypeOrElementType`. As such, we need to validate that
+ // the type passed in is actually an Iterable.
+ checkTypeAssignableTo(type, mayBeIterable
+ ? createIterableType(iteratedType)
+ : createAsyncIterableType(iteratedType), errorNode);
+ }
+ return isAsyncIterable
+ ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType
+ : typeAsIterable.iteratedTypeOfIterable = iteratedType;
+ }
+ if (errorNode) {
+ error(errorNode, isAsyncIterable
+ ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
+ : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator);
}
- return typeAsIterable.iterableElementType;
+ return undefined;
}
/**
- * This function has very similar logic as getElementTypeOfIterable, except that it operates on
+ * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on
* Iterators instead of Iterables. Here is the structure:
*
* { // iterator
- * next: { // iteratorNextFunction
- * (): { // iteratorNextResult
- * value: T // iteratorNextValue
+ * next: { // nextMethod
+ * (): { // nextResult
+ * value: T // nextValue
* }
* }
* }
*
+ * For an async iterator, we expect the following structure:
+ *
+ * { // iterator
+ * next: { // nextMethod
+ * (): PromiseLike<{ // nextResult
+ * value: T // nextValue
+ * }>
+ * }
+ * }
*/
- function getElementTypeOfIterator(type, errorNode) {
+ function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) {
if (isTypeAny(type)) {
return undefined;
}
var typeAsIterator = type;
- if (!typeAsIterator.iteratorElementType) {
- // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator<number>),
- // then just grab its type argument.
- if ((getObjectFlags(type) & 4 /* Reference */) && type.target === getGlobalIteratorType()) {
- typeAsIterator.iteratorElementType = type.typeArguments[0];
- }
- else {
- var iteratorNextFunction = getTypeOfPropertyOfType(type, "next");
- if (isTypeAny(iteratorNextFunction)) {
- return undefined;
- }
- var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0 /* Call */) : emptyArray;
- if (iteratorNextFunctionSignatures.length === 0) {
- if (errorNode) {
- error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method);
- }
- return undefined;
- }
- var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true);
- if (isTypeAny(iteratorNextResult)) {
- return undefined;
- }
- var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value");
- if (!iteratorNextValue) {
- if (errorNode) {
- error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property);
- }
- return undefined;
- }
- typeAsIterator.iteratorElementType = iteratorNextValue;
- }
+ if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) {
+ return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator;
+ }
+ // As an optimization, if the type is an instantiation of the global `Iterator<T>` (for
+ // a non-async iterator) or the global `AsyncIterator<T>` (for an async-iterator) then
+ // just grab its type argument.
+ var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType;
+ if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) {
+ return isAsyncIterator
+ ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0]
+ : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0];
+ }
+ // Both async and non-async iterators must have a `next` method.
+ var nextMethod = getTypeOfPropertyOfType(type, "next");
+ if (isTypeAny(nextMethod)) {
+ return undefined;
}
- return typeAsIterator.iteratorElementType;
- }
- function getElementTypeOfIterableIterator(type) {
- if (isTypeAny(type)) {
+ var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : emptyArray;
+ if (nextMethodSignatures.length === 0) {
+ if (errorNode) {
+ error(errorNode, isAsyncIterator
+ ? ts.Diagnostics.An_async_iterator_must_have_a_next_method
+ : ts.Diagnostics.An_iterator_must_have_a_next_method);
+ }
return undefined;
}
- // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator<number>),
- // then just grab its type argument.
- if ((getObjectFlags(type) & 4 /* Reference */) && type.target === getGlobalIterableIteratorType()) {
- return type.typeArguments[0];
+ var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true);
+ if (isTypeAny(nextResult)) {
+ return undefined;
}
- return getElementTypeOfIterable(type, /*errorNode*/ undefined) ||
- getElementTypeOfIterator(type, /*errorNode*/ undefined);
- }
- /**
- * This function does the following steps:
- * 1. Break up arrayOrStringType (possibly a union) into its string constituents and array constituents.
- * 2. Take the element types of the array constituents.
- * 3. Return the union of the element types, and string if there was a string constituent.
- *
- * For example:
- * string -> string
- * number[] -> number
- * string[] | number[] -> string | number
- * string | number[] -> string | number
- * string | string[] | number[] -> string | number
- *
- * It also errors if:
- * 1. Some constituent is neither a string nor an array.
- * 2. Some constituent is a string and target is less than ES5 (because in ES3 string is not indexable).
- */
- function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) {
- ts.Debug.assert(languageVersion < 2 /* ES2015 */);
- var arrayType = arrayOrStringType;
- if (arrayOrStringType.flags & 65536 /* Union */) {
- // After we remove all types that are StringLike, we will know if there was a string constituent
- // based on whether the result of filter is a new array.
- var arrayTypes = arrayOrStringType.types;
- var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178 /* StringLike */); });
- if (filteredTypes !== arrayTypes) {
- arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true);
- }
- }
- else if (arrayOrStringType.flags & 262178 /* StringLike */) {
- arrayType = neverType;
- }
- var hasStringConstituent = arrayOrStringType !== arrayType;
- var reportedError = false;
- if (hasStringConstituent) {
- if (languageVersion < 1 /* ES5 */) {
- error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
- reportedError = true;
- }
- // Now that we've removed all the StringLike types, if no constituents remain, then the entire
- // arrayOrStringType was a string.
- if (arrayType.flags & 8192 /* Never */) {
- return stringType;
+ // For an async iterator, we must get the awaited type of the return type.
+ if (isAsyncIterator) {
+ nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property);
+ if (isTypeAny(nextResult)) {
+ return undefined;
}
}
- if (!isArrayLikeType(arrayType)) {
- if (!reportedError) {
- // Which error we report depends on whether there was a string constituent. For example,
- // if the input type is number | string, we want to say that number is not an array type.
- // But if the input was just number, we want to say that number is not an array type
- // or a string type.
- var diagnostic = hasStringConstituent
- ? ts.Diagnostics.Type_0_is_not_an_array_type
- : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type;
- error(errorNode, diagnostic, typeToString(arrayType));
+ var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value");
+ if (!nextValue) {
+ if (errorNode) {
+ error(errorNode, isAsyncIterator
+ ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property
+ : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property);
}
- return hasStringConstituent ? stringType : unknownType;
+ return undefined;
}
- var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */) || unknownType;
- if (hasStringConstituent) {
- // This is just an optimization for the case where arrayOrStringType is string | string[]
- if (arrayElementType.flags & 262178 /* StringLike */) {
- return stringType;
- }
- return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true);
+ return isAsyncIterator
+ ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue
+ : typeAsIterator.iteratedTypeOfIterator = nextValue;
+ }
+ /**
+ * A generator may have a return type of `Iterator<T>`, `Iterable<T>`, or
+ * `IterableIterator<T>`. An async generator may have a return type of `AsyncIterator<T>`,
+ * `AsyncIterable<T>`, or `AsyncIterableIterator<T>`. This function can be used to extract
+ * the iterated type from this return type for contextual typing and verifying signatures.
+ */
+ function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) {
+ if (isTypeAny(returnType)) {
+ return undefined;
}
- return arrayElementType;
+ return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, isAsyncGenerator, /*allowNonAsyncIterables*/ false, /*checkAssignability*/ false)
+ || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator);
}
function checkBreakOrContinueStatement(node) {
// Grammar checking
@@ -40019,10 +43476,12 @@ var ts;
// TODO: Check that target label is valid
}
function isGetAccessorWithAnnotatedSetAccessor(node) {
- return !!(node.kind === 151 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 152 /* SetAccessor */)));
+ return !!(node.kind === 152 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 153 /* SetAccessor */)));
}
function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
- var unwrappedReturnType = ts.isAsyncFunctionLike(func) ? getPromisedType(returnType) : returnType;
+ var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */
+ ? getPromisedTypeOfPromise(returnType) // Async function
+ : returnType; // AsyncGenerator function, Generator function, or normal function
return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */);
}
function checkReturnStatement(node) {
@@ -40039,40 +43498,41 @@ var ts;
var returnType = getReturnTypeOfSignature(signature);
if (strictNullChecks || node.expression || returnType.flags & 8192 /* Never */) {
var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
- if (func.asteriskToken) {
+ var functionFlags = ts.getFunctionFlags(func);
+ if (functionFlags & 1 /* Generator */) {
// A generator does not need its return expressions checked against its return type.
// Instead, the yield expressions are checked against the element type.
// TODO: Check return expressions of generators when return type tracking is added
// for generators.
return;
}
- if (func.kind === 152 /* SetAccessor */) {
+ if (func.kind === 153 /* SetAccessor */) {
if (node.expression) {
- error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value);
+ error(node, ts.Diagnostics.Setters_cannot_return_a_value);
}
}
- else if (func.kind === 150 /* Constructor */) {
- if (node.expression && !checkTypeAssignableTo(exprType, returnType, node.expression)) {
- error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
+ else if (func.kind === 151 /* Constructor */) {
+ if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) {
+ error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
}
}
else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) {
- if (ts.isAsyncFunctionLike(func)) {
- var promisedType = getPromisedType(returnType);
- var awaitedType = checkAwaitedType(exprType, node.expression || node, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member);
+ if (functionFlags & 2 /* Async */) {
+ var promisedType = getPromisedTypeOfPromise(returnType);
+ var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
if (promisedType) {
// If the function has a return type, but promisedType is
// undefined, an error will be reported in checkAsyncFunctionReturnType
// so we don't need to report one here.
- checkTypeAssignableTo(awaitedType, promisedType, node.expression || node);
+ checkTypeAssignableTo(awaitedType, promisedType, node);
}
}
else {
- checkTypeAssignableTo(exprType, returnType, node.expression || node);
+ checkTypeAssignableTo(exprType, returnType, node);
}
}
}
- else if (func.kind !== 150 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
+ else if (func.kind !== 151 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
// The function has a return type, but the return statement doesn't have an expression.
error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
}
@@ -40081,7 +43541,7 @@ var ts;
function checkWithStatement(node) {
// Grammar checking for withStatement
if (!checkGrammarStatementInAmbientContext(node)) {
- if (node.flags & 524288 /* AwaitContext */) {
+ if (node.flags & 16384 /* AwaitContext */) {
grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
}
}
@@ -40102,7 +43562,7 @@ var ts;
var expressionIsLiteral = isLiteralType(expressionType);
ts.forEach(node.caseBlock.clauses, function (clause) {
// Grammar check for duplicate default clauses, skip if we already report duplicate default clause
- if (clause.kind === 254 /* DefaultClause */ && !hasDuplicateDefaultClause) {
+ if (clause.kind === 257 /* DefaultClause */ && !hasDuplicateDefaultClause) {
if (firstDefaultClause === undefined) {
firstDefaultClause = clause;
}
@@ -40114,7 +43574,7 @@ var ts;
hasDuplicateDefaultClause = true;
}
}
- if (produceDiagnostics && clause.kind === 253 /* CaseClause */) {
+ if (produceDiagnostics && clause.kind === 256 /* CaseClause */) {
var caseClause = clause;
// TypeScript 1.0 spec (April 2014): 5.9
// In a 'switch' statement, each 'case' expression must be of a type that is comparable
@@ -40140,18 +43600,16 @@ var ts;
function checkLabeledStatement(node) {
// Grammar checking
if (!checkGrammarStatementInAmbientContext(node)) {
- var current = node.parent;
- while (current) {
+ ts.findAncestor(node.parent, function (current) {
if (ts.isFunctionLike(current)) {
- break;
+ return "quit";
}
- if (current.kind === 219 /* LabeledStatement */ && current.label.text === node.label.text) {
+ if (current.kind === 221 /* LabeledStatement */ && current.label.text === node.label.text) {
var sourceFile = ts.getSourceFileOfNode(node);
grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label));
- break;
+ return true;
}
- current = current.parent;
- }
+ });
}
// ensure that label is unique
checkSourceElement(node.statement);
@@ -40182,14 +43640,14 @@ var ts;
grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
}
else {
- var blockLocals = catchClause.block.locals;
- if (blockLocals) {
- for (var caughtName in catchClause.locals) {
- var blockLocal = blockLocals[caughtName];
+ var blockLocals_1 = catchClause.block.locals;
+ if (blockLocals_1) {
+ ts.forEachKey(catchClause.locals, function (caughtName) {
+ var blockLocal = blockLocals_1.get(caughtName);
if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
}
- }
+ });
}
}
}
@@ -40241,15 +43699,16 @@ var ts;
if (!indexType) {
return;
}
+ var propDeclaration = prop.valueDeclaration;
// index is numeric and property name is not valid numeric literal
- if (indexKind === 1 /* Number */ && !isNumericName(prop.valueDeclaration.name)) {
+ if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) {
return;
}
// perform property check if property or indexer is declared in 'type'
// this allows to rule out cases when both property and indexer are inherited from the base class
var errorNode;
- if (prop.valueDeclaration.name.kind === 142 /* ComputedPropertyName */ || prop.parent === containingType.symbol) {
- errorNode = prop.valueDeclaration;
+ if (propDeclaration && (propDeclaration.name.kind === 143 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) {
+ errorNode = propDeclaration;
}
else if (indexDeclaration) {
errorNode = indexDeclaration;
@@ -40279,16 +43738,26 @@ var ts;
case "string":
case "symbol":
case "void":
+ case "object":
error(name, message, name.text);
}
}
- /** Check each type parameter and check that type parameters have no duplicate type parameter declarations */
+ /**
+ * Check each type parameter and check that type parameters have no duplicate type parameter declarations
+ */
function checkTypeParameters(typeParameterDeclarations) {
if (typeParameterDeclarations) {
- for (var i = 0, n = typeParameterDeclarations.length; i < n; i++) {
+ var seenDefault = false;
+ for (var i = 0; i < typeParameterDeclarations.length; i++) {
var node = typeParameterDeclarations[i];
checkTypeParameter(node);
if (produceDiagnostics) {
+ if (node.default) {
+ seenDefault = true;
+ }
+ else if (seenDefault) {
+ error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
+ }
for (var j = 0; j < i; j++) {
if (typeParameterDeclarations[j].symbol === node.symbol) {
error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
@@ -40299,22 +43768,64 @@ var ts;
}
}
/** Check that type parameter lists are identical across multiple declarations */
- function checkTypeParameterListsIdentical(node, symbol) {
+ function checkTypeParameterListsIdentical(symbol) {
if (symbol.declarations.length === 1) {
return;
}
- var firstDecl;
- for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
- var declaration = _a[_i];
- if (declaration.kind === 226 /* ClassDeclaration */ || declaration.kind === 227 /* InterfaceDeclaration */) {
- if (!firstDecl) {
- firstDecl = declaration;
+ var links = getSymbolLinks(symbol);
+ if (!links.typeParametersChecked) {
+ links.typeParametersChecked = true;
+ var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
+ if (declarations.length <= 1) {
+ return;
+ }
+ var type = getDeclaredTypeOfSymbol(symbol);
+ if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
+ // Report an error on every conflicting declaration.
+ var name = symbolToString(symbol);
+ for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
+ var declaration = declarations_6[_i];
+ error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
+ }
+ }
+ }
+ }
+ function areTypeParametersIdentical(declarations, typeParameters) {
+ var maxTypeArgumentCount = ts.length(typeParameters);
+ var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
+ for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
+ var declaration = declarations_7[_i];
+ // If this declaration has too few or too many type parameters, we report an error
+ var numTypeParameters = ts.length(declaration.typeParameters);
+ if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
+ return false;
+ }
+ for (var i = 0; i < numTypeParameters; i++) {
+ var source = declaration.typeParameters[i];
+ var target = typeParameters[i];
+ // If the type parameter node does not have the same as the resolved type
+ // parameter at this position, we report an error.
+ if (source.name.text !== target.symbol.name) {
+ return false;
}
- else if (!areTypeParametersIdentical(firstDecl.typeParameters, node.typeParameters)) {
- error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, node.name.text);
+ // If the type parameter node does not have an identical constraint as the resolved
+ // type parameter at this position, we report an error.
+ var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint);
+ var targetConstraint = getConstraintFromTypeParameter(target);
+ if ((sourceConstraint || targetConstraint) &&
+ (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) {
+ return false;
+ }
+ // If the type parameter node has a default and it is not identical to the default
+ // for the type parameter at this position, we report an error.
+ var sourceDefault = source.default && getTypeFromTypeNode(source.default);
+ var targetDefault = getDefaultFromTypeParameter(target);
+ if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
+ return false;
}
}
}
+ return true;
}
function checkClassExpression(node) {
checkClassLikeDeclaration(node);
@@ -40334,11 +43845,12 @@ var ts;
registerForUnusedIdentifiersCheck(node);
}
function checkClassLikeDeclaration(node) {
- checkGrammarClassDeclarationHeritageClauses(node);
+ checkGrammarClassLikeDeclaration(node);
checkDecorators(node);
if (node.name) {
checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
checkCollisionWithCapturedThisVariable(node, node.name);
+ checkCollisionWithCapturedNewTargetVariable(node, node.name);
checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
}
@@ -40348,19 +43860,27 @@ var ts;
var type = getDeclaredTypeOfSymbol(symbol);
var typeWithThis = getTypeWithThisArgument(type);
var staticType = getTypeOfSymbol(symbol);
- checkTypeParameterListsIdentical(node, symbol);
+ checkTypeParameterListsIdentical(symbol);
checkClassForDuplicateDeclarations(node);
+ // Only check for reserved static identifiers on non-ambient context.
+ if (!ts.isInAmbientContext(node)) {
+ checkClassForStaticPropertyNameConflicts(node);
+ }
var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node);
if (baseTypeNode) {
+ if (languageVersion < 2 /* ES2015 */) {
+ checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
+ }
var baseTypes = getBaseTypes(type);
if (baseTypes.length && produceDiagnostics) {
var baseType_1 = baseTypes[0];
- var staticBaseType = getBaseConstructorTypeOfClass(type);
+ var baseConstructorType = getBaseConstructorTypeOfClass(type);
+ var staticBaseType = getApparentType(baseConstructorType);
checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
checkSourceElement(baseTypeNode.expression);
if (baseTypeNode.typeArguments) {
ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
- for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); _i < _a.length; _i++) {
+ for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
var constructor = _a[_i];
if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) {
break;
@@ -40369,19 +43889,15 @@ var ts;
}
checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
- if (baseType_1.symbol.valueDeclaration &&
- !ts.isInAmbientContext(baseType_1.symbol.valueDeclaration) &&
- baseType_1.symbol.valueDeclaration.kind === 226 /* ClassDeclaration */) {
- if (!isBlockScopedNameDeclaredBeforeUse(baseType_1.symbol.valueDeclaration, node)) {
- error(baseTypeNode, ts.Diagnostics.A_class_must_be_declared_after_its_base_class);
- }
+ if (baseConstructorType.flags & 540672 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
+ error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
}
- if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */)) {
+ if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 540672 /* TypeVariable */)) {
// When the static base type is a "class-like" constructor function (but not actually a class), we verify
// that all instantiated base constructor signatures return the same type. We can simply compare the type
// references (as opposed to checking the structure of the types) because elsewhere we have already checked
// that the base type is a class or interface type (and not, for example, an anonymous object type).
- var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments);
+ var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) {
error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
}
@@ -40400,8 +43916,7 @@ var ts;
if (produceDiagnostics) {
var t = getTypeFromTypeNode(typeRefNode);
if (t !== unknownType) {
- var declaredType = getObjectFlags(t) & 4 /* Reference */ ? t.target : t;
- if (getObjectFlags(declaredType) & 3 /* ClassOrInterface */) {
+ if (isValidBaseType(t)) {
checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1);
}
else {
@@ -40431,11 +43946,16 @@ var ts;
function getTargetSymbol(s) {
// if symbol is instantiated its flags are not copied from the 'target'
// so we'll need to get back original 'target' symbol to work with correct set of flags
- return s.flags & 16777216 /* Instantiated */ ? getSymbolLinks(s).target : s;
+ return getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
}
function getClassLikeDeclarationOfSymbol(symbol) {
return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; });
}
+ function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
+ return ts.filter(symbol.declarations, function (d) {
+ return d.kind === 228 /* ClassDeclaration */ || d.kind === 229 /* InterfaceDeclaration */;
+ });
+ }
function checkKindsOfPropertyMemberOverrides(type, baseType) {
// TypeScript 1.0 spec (April 2014): 8.2.3
// A derived class inherits all members from its base class it doesn't override.
@@ -40451,11 +43971,11 @@ var ts;
// Base class instance member variables and accessors can be overridden by
// derived class instance member variables and accessors, but not by other kinds of members.
// NOTE: assignability is checked in checkClassDeclaration
- var baseProperties = getPropertiesOfObjectType(baseType);
+ var baseProperties = getPropertiesOfType(baseType);
for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
var baseProperty = baseProperties_1[_i];
var base = getTargetSymbol(baseProperty);
- if (base.flags & 134217728 /* Prototype */) {
+ if (base.flags & 16777216 /* Prototype */) {
continue;
}
var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name));
@@ -40472,7 +43992,7 @@ var ts;
// If there is no declaration for the derived class (as in the case of class expressions),
// then the class cannot be declared abstract.
if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) {
- if (derivedClassDecl.kind === 197 /* ClassExpression */) {
+ if (derivedClassDecl.kind === 198 /* ClassExpression */) {
error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
}
else {
@@ -40483,7 +44003,7 @@ var ts;
else {
// derived overrides base.
var derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived);
- if ((baseDeclarationFlags & 8 /* Private */) || (derivedDeclarationFlags & 8 /* Private */)) {
+ if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
// either base or derived property is private - not override, skip it
continue;
}
@@ -40491,64 +44011,32 @@ var ts;
// value of 'static' is not the same for properties - not override, skip it
continue;
}
- if ((base.flags & derived.flags & 8192 /* Method */) || ((base.flags & 98308 /* PropertyOrAccessor */) && (derived.flags & 98308 /* PropertyOrAccessor */))) {
+ if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) {
// method is overridden with method or property/accessor is overridden with property/accessor - correct case
continue;
}
var errorMessage = void 0;
- if (base.flags & 8192 /* Method */) {
+ if (isMethodLike(base)) {
if (derived.flags & 98304 /* Accessor */) {
errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
}
else {
- ts.Debug.assert((derived.flags & 4 /* Property */) !== 0);
errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property;
}
}
else if (base.flags & 4 /* Property */) {
- ts.Debug.assert((derived.flags & 8192 /* Method */) !== 0);
errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
}
else {
- ts.Debug.assert((base.flags & 98304 /* Accessor */) !== 0);
- ts.Debug.assert((derived.flags & 8192 /* Method */) !== 0);
errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
}
- error(derived.valueDeclaration.name, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
+ error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
}
}
}
}
function isAccessor(kind) {
- return kind === 151 /* GetAccessor */ || kind === 152 /* SetAccessor */;
- }
- function areTypeParametersIdentical(list1, list2) {
- if (!list1 && !list2) {
- return true;
- }
- if (!list1 || !list2 || list1.length !== list2.length) {
- return false;
- }
- // TypeScript 1.0 spec (April 2014):
- // When a generic interface has multiple declarations, all declarations must have identical type parameter
- // lists, i.e. identical type parameter names with identical constraints in identical order.
- for (var i = 0, len = list1.length; i < len; i++) {
- var tp1 = list1[i];
- var tp2 = list2[i];
- if (tp1.name.text !== tp2.name.text) {
- return false;
- }
- if (!tp1.constraint && !tp2.constraint) {
- continue;
- }
- if (!tp1.constraint || !tp2.constraint) {
- return false;
- }
- if (!isTypeIdenticalTo(getTypeFromTypeNode(tp1.constraint), getTypeFromTypeNode(tp2.constraint))) {
- return false;
- }
- }
- return true;
+ return kind === 152 /* GetAccessor */ || kind === 153 /* SetAccessor */;
}
function checkInheritedPropertiesAreIdentical(type, typeNode) {
var baseTypes = getBaseTypes(type);
@@ -40556,16 +44044,16 @@ var ts;
return true;
}
var seen = ts.createMap();
- ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; });
+ ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.name, { prop: p, containingType: type }); });
var ok = true;
for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
var base = baseTypes_2[_i];
- var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType));
- for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
- var prop = properties_6[_a];
- var existing = seen[prop.name];
+ var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
+ for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) {
+ var prop = properties_8[_a];
+ var existing = seen.get(prop.name);
if (!existing) {
- seen[prop.name] = { prop: prop, containingType: base };
+ seen.set(prop.name, { prop: prop, containingType: base });
}
else {
var isInheritedProperty = existing.containingType !== type;
@@ -40573,7 +44061,7 @@ var ts;
ok = false;
var typeName1 = typeToString(existing.containingType);
var typeName2 = typeToString(base);
- var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
+ var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
}
@@ -40590,9 +44078,9 @@ var ts;
checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
checkExportsOnMergedDeclarations(node);
var symbol = getSymbolOfNode(node);
- checkTypeParameterListsIdentical(node, symbol);
+ checkTypeParameterListsIdentical(symbol);
// Only check this symbol once
- var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 227 /* InterfaceDeclaration */);
+ var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 229 /* InterfaceDeclaration */);
if (node === firstInterfaceDecl) {
var type = getDeclaredTypeOfSymbol(symbol);
var typeWithThis = getTypeWithThisArgument(type);
@@ -40699,7 +44187,7 @@ var ts;
return value;
function evalConstant(e) {
switch (e.kind) {
- case 190 /* PrefixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
var value_1 = evalConstant(e.operand);
if (value_1 === undefined) {
return undefined;
@@ -40710,7 +44198,7 @@ var ts;
case 51 /* TildeToken */: return ~value_1;
}
return undefined;
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
var left = evalConstant(e.left);
if (left === undefined) {
return undefined;
@@ -40734,12 +44222,13 @@ var ts;
}
return undefined;
case 8 /* NumericLiteral */:
+ checkGrammarNumericLiteral(e);
return +e.text;
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return evalConstant(e.expression);
case 70 /* Identifier */:
- case 178 /* ElementAccessExpression */:
- case 177 /* PropertyAccessExpression */:
+ case 179 /* ElementAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
var member = initializer.parent;
var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent));
var enumType_1;
@@ -40752,7 +44241,7 @@ var ts;
}
else {
var expression = void 0;
- if (e.kind === 178 /* ElementAccessExpression */) {
+ if (e.kind === 179 /* ElementAccessExpression */) {
if (e.argumentExpression === undefined ||
e.argumentExpression.kind !== 9 /* StringLiteral */) {
return undefined;
@@ -40770,7 +44259,7 @@ var ts;
if (current.kind === 70 /* Identifier */) {
break;
}
- else if (current.kind === 177 /* PropertyAccessExpression */) {
+ else if (current.kind === 178 /* PropertyAccessExpression */) {
current = current.expression;
}
else {
@@ -40814,6 +44303,7 @@ var ts;
checkGrammarDecorators(node) || checkGrammarModifiers(node);
checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
checkCollisionWithCapturedThisVariable(node, node.name);
+ checkCollisionWithCapturedNewTargetVariable(node, node.name);
checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
@@ -40842,7 +44332,7 @@ var ts;
var seenEnumMissingInitialInitializer_1 = false;
ts.forEach(enumSymbol.declarations, function (declaration) {
// return true if we hit a violation of the rule, false otherwise
- if (declaration.kind !== 229 /* EnumDeclaration */) {
+ if (declaration.kind !== 231 /* EnumDeclaration */) {
return false;
}
var enumDeclaration = declaration;
@@ -40863,10 +44353,10 @@ var ts;
}
function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
var declarations = symbol.declarations;
- for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
- var declaration = declarations_5[_i];
- if ((declaration.kind === 226 /* ClassDeclaration */ ||
- (declaration.kind === 225 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
+ for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
+ var declaration = declarations_8[_i];
+ if ((declaration.kind === 228 /* ClassDeclaration */ ||
+ (declaration.kind === 227 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
!ts.isInAmbientContext(declaration)) {
return declaration;
}
@@ -40930,7 +44420,7 @@ var ts;
}
// if the module merges with a class declaration in the same lexical scope,
// we need to track this to ensure the correct emit.
- var mergedClass = ts.getDeclarationOfKind(symbol, 226 /* ClassDeclaration */);
+ var mergedClass = ts.getDeclarationOfKind(symbol, 228 /* ClassDeclaration */);
if (mergedClass &&
inSameLexicalScope(node, mergedClass)) {
getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
@@ -40943,7 +44433,7 @@ var ts;
// We can detect if augmentation was applied using following rules:
// - augmentation for a global scope is always applied
// - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
- var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Merged */);
+ var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728 /* Transient */);
if (checkBody && node.body) {
// body of ambient external module is always a module block
for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
@@ -40981,39 +44471,39 @@ var ts;
}
function checkModuleAugmentationElement(node, isGlobalAugmentation) {
switch (node.kind) {
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
// error each individual name in variable statement instead of marking the entire variable statement
for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
checkModuleAugmentationElement(decl, isGlobalAugmentation);
}
break;
- case 240 /* ExportAssignment */:
- case 241 /* ExportDeclaration */:
+ case 242 /* ExportAssignment */:
+ case 243 /* ExportDeclaration */:
grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
break;
- case 234 /* ImportEqualsDeclaration */:
- case 235 /* ImportDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 237 /* ImportDeclaration */:
grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
break;
- case 174 /* BindingElement */:
- case 223 /* VariableDeclaration */:
- var name_25 = node.name;
- if (ts.isBindingPattern(name_25)) {
- for (var _b = 0, _c = name_25.elements; _b < _c.length; _b++) {
+ case 175 /* BindingElement */:
+ case 225 /* VariableDeclaration */:
+ var name = node.name;
+ if (ts.isBindingPattern(name)) {
+ for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
var el = _c[_b];
// mark individual names in binding pattern
checkModuleAugmentationElement(el, isGlobalAugmentation);
}
break;
}
- // fallthrough
- case 226 /* ClassDeclaration */:
- case 229 /* EnumDeclaration */:
- case 225 /* FunctionDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 230 /* ModuleDeclaration */:
- case 228 /* TypeAliasDeclaration */:
+ // falls through
+ case 228 /* ClassDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 227 /* FunctionDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
if (isGlobalAugmentation) {
return;
}
@@ -41023,7 +44513,7 @@ var ts;
// this is done it two steps
// 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
// 2. main check - report error if value declaration of the parent symbol is module augmentation)
- var reportError = !(symbol.flags & 33554432 /* Merged */);
+ var reportError = !(symbol.flags & 134217728 /* Transient */);
if (!reportError) {
// symbol should not originate in augmentation
reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
@@ -41036,12 +44526,12 @@ var ts;
switch (node.kind) {
case 70 /* Identifier */:
return node;
- case 141 /* QualifiedName */:
+ case 142 /* QualifiedName */:
do {
node = node.left;
} while (node.kind !== 70 /* Identifier */);
return node;
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
do {
node = node.expression;
} while (node.kind !== 70 /* Identifier */);
@@ -41054,9 +44544,9 @@ var ts;
error(moduleName, ts.Diagnostics.String_literal_expected);
return false;
}
- var inAmbientExternalModule = node.parent.kind === 231 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 261 /* SourceFile */ && !inAmbientExternalModule) {
- error(moduleName, node.kind === 241 /* ExportDeclaration */ ?
+ var inAmbientExternalModule = node.parent.kind === 233 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
+ if (node.parent.kind !== 264 /* SourceFile */ && !inAmbientExternalModule) {
+ error(moduleName, node.kind === 243 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
return false;
@@ -41089,7 +44579,7 @@ var ts;
(symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) |
(symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
if (target.flags & excludedMeanings) {
- var message = node.kind === 243 /* ExportSpecifier */ ?
+ var message = node.kind === 245 /* ExportSpecifier */ ?
ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
error(node, message, symbolToString(symbol));
@@ -41117,7 +44607,7 @@ var ts;
checkImportBinding(importClause);
}
if (importClause.namedBindings) {
- if (importClause.namedBindings.kind === 237 /* NamespaceImport */) {
+ if (importClause.namedBindings.kind === 239 /* NamespaceImport */) {
checkImportBinding(importClause.namedBindings);
}
else {
@@ -41174,8 +44664,10 @@ var ts;
// export { x, y }
// export { x, y } from "foo"
ts.forEach(node.exportClause.elements, checkExportSpecifier);
- var inAmbientExternalModule = node.parent.kind === 231 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 261 /* SourceFile */ && !inAmbientExternalModule) {
+ var inAmbientExternalModule = node.parent.kind === 233 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
+ var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 233 /* ModuleBlock */ &&
+ !node.moduleSpecifier && ts.isInAmbientContext(node);
+ if (node.parent.kind !== 264 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -41189,7 +44681,7 @@ var ts;
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 261 /* SourceFile */ || node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 230 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 264 /* SourceFile */ || node.parent.kind === 233 /* ModuleBlock */ || node.parent.kind === 232 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -41215,9 +44707,14 @@ var ts;
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 261 /* SourceFile */ ? node.parent : node.parent.parent;
- if (container.kind === 230 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
- error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
+ var container = node.parent.kind === 264 /* SourceFile */ ? node.parent : node.parent.parent;
+ if (container.kind === 232 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
+ if (node.isExportEquals) {
+ error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
+ }
+ else {
+ error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
+ }
return;
}
// Grammar checking
@@ -41243,18 +44740,13 @@ var ts;
}
}
function hasExportedMembers(moduleSymbol) {
- for (var id in moduleSymbol.exports) {
- if (id !== "export=") {
- return true;
- }
- }
- return false;
+ return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
}
function checkExternalModuleExports(node) {
var moduleSymbol = getSymbolOfNode(node);
var links = getSymbolLinks(moduleSymbol);
if (!links.exportsChecked) {
- var exportEqualsSymbol = moduleSymbol.exports["export="];
+ var exportEqualsSymbol = moduleSymbol.exports.get("export=");
if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
if (!isTopLevelInExternalModuleAugmentation(declaration)) {
@@ -41263,35 +44755,35 @@ var ts;
}
// Checks for export * conflicts
var exports = getExportsOfModule(moduleSymbol);
- for (var id in exports) {
+ exports && exports.forEach(function (_a, id) {
+ var declarations = _a.declarations, flags = _a.flags;
if (id === "__export") {
- continue;
+ return;
}
- var _a = exports[id], declarations = _a.declarations, flags = _a.flags;
// ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
// (TS Exceptions: namespaces, function overloads, enums, and interfaces)
if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
- continue;
+ return;
}
var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload);
if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
// it is legal to merge type alias with other values
// so count should be either 1 (just type alias) or 2 (type alias + merged value)
- continue;
+ return;
}
if (exportedDeclarationsCount > 1) {
- for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
- var declaration = declarations_6[_i];
+ for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
+ var declaration = declarations_9[_i];
if (isNotOverload(declaration)) {
diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id));
}
}
}
- }
+ });
links.exportsChecked = true;
}
function isNotOverload(declaration) {
- return (declaration.kind !== 225 /* FunctionDeclaration */ && declaration.kind !== 149 /* MethodDeclaration */) ||
+ return (declaration.kind !== 227 /* FunctionDeclaration */ && declaration.kind !== 150 /* MethodDeclaration */) ||
!!declaration.body;
}
}
@@ -41304,123 +44796,123 @@ var ts;
// Only bother checking on a few construct kinds. We don't want to be excessively
// hitting the cancellation token on every node we check.
switch (kind) {
- case 230 /* ModuleDeclaration */:
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 225 /* FunctionDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 227 /* FunctionDeclaration */:
cancellationToken.throwIfCancellationRequested();
}
}
switch (kind) {
- case 143 /* TypeParameter */:
+ case 144 /* TypeParameter */:
return checkTypeParameter(node);
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
return checkParameter(node);
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
return checkPropertyDeclaration(node);
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
return checkSignatureDeclaration(node);
- case 155 /* IndexSignature */:
+ case 156 /* IndexSignature */:
return checkSignatureDeclaration(node);
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
return checkMethodDeclaration(node);
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
return checkConstructorDeclaration(node);
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
return checkAccessorDeclaration(node);
- case 157 /* TypeReference */:
+ case 158 /* TypeReference */:
return checkTypeReferenceNode(node);
- case 156 /* TypePredicate */:
+ case 157 /* TypePredicate */:
return checkTypePredicate(node);
- case 160 /* TypeQuery */:
+ case 161 /* TypeQuery */:
return checkTypeQuery(node);
- case 161 /* TypeLiteral */:
+ case 162 /* TypeLiteral */:
return checkTypeLiteral(node);
- case 162 /* ArrayType */:
+ case 163 /* ArrayType */:
return checkArrayType(node);
- case 163 /* TupleType */:
+ case 164 /* TupleType */:
return checkTupleType(node);
- case 164 /* UnionType */:
- case 165 /* IntersectionType */:
+ case 165 /* UnionType */:
+ case 166 /* IntersectionType */:
return checkUnionOrIntersectionType(node);
- case 166 /* ParenthesizedType */:
- case 168 /* TypeOperator */:
+ case 167 /* ParenthesizedType */:
+ case 169 /* TypeOperator */:
return checkSourceElement(node.type);
- case 169 /* IndexedAccessType */:
+ case 170 /* IndexedAccessType */:
return checkIndexedAccessType(node);
- case 170 /* MappedType */:
+ case 171 /* MappedType */:
return checkMappedType(node);
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return checkFunctionDeclaration(node);
- case 204 /* Block */:
- case 231 /* ModuleBlock */:
+ case 206 /* Block */:
+ case 233 /* ModuleBlock */:
return checkBlock(node);
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
return checkVariableStatement(node);
- case 207 /* ExpressionStatement */:
+ case 209 /* ExpressionStatement */:
return checkExpressionStatement(node);
- case 208 /* IfStatement */:
+ case 210 /* IfStatement */:
return checkIfStatement(node);
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
return checkDoStatement(node);
- case 210 /* WhileStatement */:
+ case 212 /* WhileStatement */:
return checkWhileStatement(node);
- case 211 /* ForStatement */:
+ case 213 /* ForStatement */:
return checkForStatement(node);
- case 212 /* ForInStatement */:
+ case 214 /* ForInStatement */:
return checkForInStatement(node);
- case 213 /* ForOfStatement */:
+ case 215 /* ForOfStatement */:
return checkForOfStatement(node);
- case 214 /* ContinueStatement */:
- case 215 /* BreakStatement */:
+ case 216 /* ContinueStatement */:
+ case 217 /* BreakStatement */:
return checkBreakOrContinueStatement(node);
- case 216 /* ReturnStatement */:
+ case 218 /* ReturnStatement */:
return checkReturnStatement(node);
- case 217 /* WithStatement */:
+ case 219 /* WithStatement */:
return checkWithStatement(node);
- case 218 /* SwitchStatement */:
+ case 220 /* SwitchStatement */:
return checkSwitchStatement(node);
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
return checkLabeledStatement(node);
- case 220 /* ThrowStatement */:
+ case 222 /* ThrowStatement */:
return checkThrowStatement(node);
- case 221 /* TryStatement */:
+ case 223 /* TryStatement */:
return checkTryStatement(node);
- case 223 /* VariableDeclaration */:
+ case 225 /* VariableDeclaration */:
return checkVariableDeclaration(node);
- case 174 /* BindingElement */:
+ case 175 /* BindingElement */:
return checkBindingElement(node);
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
return checkClassDeclaration(node);
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
return checkInterfaceDeclaration(node);
- case 228 /* TypeAliasDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
return checkTypeAliasDeclaration(node);
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
return checkEnumDeclaration(node);
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return checkModuleDeclaration(node);
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
return checkImportDeclaration(node);
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
return checkImportEqualsDeclaration(node);
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
return checkExportDeclaration(node);
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
return checkExportAssignment(node);
- case 206 /* EmptyStatement */:
+ case 208 /* EmptyStatement */:
checkGrammarStatementInAmbientContext(node);
return;
- case 222 /* DebuggerStatement */:
+ case 224 /* DebuggerStatement */:
checkGrammarStatementInAmbientContext(node);
return;
- case 244 /* MissingDeclaration */:
+ case 246 /* MissingDeclaration */:
return checkMissingDeclaration(node);
}
}
@@ -41442,17 +44934,17 @@ var ts;
for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) {
var node = deferredNodes_1[_i];
switch (node.kind) {
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
break;
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- checkAccessorDeferred(node);
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ checkAccessorDeclaration(node);
break;
- case 197 /* ClassExpression */:
+ case 198 /* ClassExpression */:
checkClassExpressionDeferred(node);
break;
}
@@ -41477,6 +44969,7 @@ var ts;
// Grammar checking
checkGrammarSourceFile(node);
potentialThisCollisions.length = 0;
+ potentialNewTargetCollisions.length = 0;
deferredNodes = [];
deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined;
ts.forEach(node.statements, checkSourceElement);
@@ -41496,6 +44989,10 @@ var ts;
ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
potentialThisCollisions.length = 0;
}
+ if (potentialNewTargetCollisions.length) {
+ ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
+ potentialNewTargetCollisions.length = 0;
+ }
links.flags |= 1 /* TypeChecked */;
}
}
@@ -41553,7 +45050,7 @@ var ts;
function isInsideWithStatementBody(node) {
if (node) {
while (node.parent) {
- if (node.parent.kind === 217 /* WithStatement */ && node.parent.statement === node) {
+ if (node.parent.kind === 219 /* WithStatement */ && node.parent.statement === node) {
return true;
}
node = node.parent;
@@ -41562,12 +45059,12 @@ var ts;
return false;
}
function getSymbolsInScope(location, meaning) {
- var symbols = ts.createMap();
- var memberFlags = 0 /* None */;
if (isInsideWithStatementBody(location)) {
// We cannot answer semantic questions within a with block, do not proceed any further
return [];
}
+ var symbols = ts.createMap();
+ var memberFlags = 0 /* None */;
populateSymbols();
return symbolsToArray(symbols);
function populateSymbols() {
@@ -41576,25 +45073,27 @@ var ts;
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
- case 230 /* ModuleDeclaration */:
+ // falls through
+ case 232 /* ModuleDeclaration */:
copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */);
break;
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
break;
- case 197 /* ClassExpression */:
+ case 198 /* ClassExpression */:
var className = location.name;
if (className) {
copySymbol(location.symbol, meaning);
}
- // fall through; this fall-through is necessary because we would like to handle
+ // falls through
+ // this fall-through is necessary because we would like to handle
// type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
// If we didn't come from static member of class or interface,
// add the type parameters into the symbol table
// (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
@@ -41603,7 +45102,7 @@ var ts;
copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */);
}
break;
- case 184 /* FunctionExpression */:
+ case 185 /* FunctionExpression */:
var funcName = location.name;
if (funcName) {
copySymbol(location.symbol, meaning);
@@ -41631,17 +45130,16 @@ var ts;
// We will copy all symbol regardless of its reserved name because
// symbolsToArray will check whether the key is a reserved name and
// it will not copy symbol with reserved name to the array
- if (!symbols[id]) {
- symbols[id] = symbol;
+ if (!symbols.has(id)) {
+ symbols.set(id, symbol);
}
}
}
function copySymbols(source, meaning) {
if (meaning) {
- for (var id in source) {
- var symbol = source[id];
+ source.forEach(function (symbol) {
copySymbol(symbol, meaning);
- }
+ });
}
}
}
@@ -41652,28 +45150,28 @@ var ts;
}
function isTypeDeclaration(node) {
switch (node.kind) {
- case 143 /* TypeParameter */:
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 228 /* TypeAliasDeclaration */:
- case 229 /* EnumDeclaration */:
+ case 144 /* TypeParameter */:
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
+ case 231 /* EnumDeclaration */:
return true;
}
}
// True if the given identifier is part of a type reference
function isTypeReferenceIdentifier(entityName) {
var node = entityName;
- while (node.parent && node.parent.kind === 141 /* QualifiedName */) {
+ while (node.parent && node.parent.kind === 142 /* QualifiedName */) {
node = node.parent;
}
- return node.parent && (node.parent.kind === 157 /* TypeReference */ || node.parent.kind === 272 /* JSDocTypeReference */);
+ return node.parent && (node.parent.kind === 158 /* TypeReference */ || node.parent.kind === 276 /* JSDocTypeReference */);
}
function isHeritageClauseElementIdentifier(entityName) {
var node = entityName;
- while (node.parent && node.parent.kind === 177 /* PropertyAccessExpression */) {
+ while (node.parent && node.parent.kind === 178 /* PropertyAccessExpression */) {
node = node.parent;
}
- return node.parent && node.parent.kind === 199 /* ExpressionWithTypeArguments */;
+ return node.parent && node.parent.kind === 200 /* ExpressionWithTypeArguments */;
}
function forEachEnclosingClass(node, callback) {
var result;
@@ -41690,13 +45188,13 @@ var ts;
return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
}
function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
- while (nodeOnRightSide.parent.kind === 141 /* QualifiedName */) {
+ while (nodeOnRightSide.parent.kind === 142 /* QualifiedName */) {
nodeOnRightSide = nodeOnRightSide.parent;
}
- if (nodeOnRightSide.parent.kind === 234 /* ImportEqualsDeclaration */) {
+ if (nodeOnRightSide.parent.kind === 236 /* ImportEqualsDeclaration */) {
return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent;
}
- if (nodeOnRightSide.parent.kind === 240 /* ExportAssignment */) {
+ if (nodeOnRightSide.parent.kind === 242 /* ExportAssignment */) {
return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent;
}
return undefined;
@@ -41704,29 +45202,38 @@ var ts;
function isInRightSideOfImportOrExportAssignment(node) {
return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
}
+ function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
+ var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent);
+ switch (specialPropertyAssignmentKind) {
+ case 1 /* ExportsProperty */:
+ case 3 /* PrototypeProperty */:
+ return getSymbolOfNode(entityName.parent);
+ case 4 /* ThisProperty */:
+ case 2 /* ModuleExports */:
+ case 5 /* Property */:
+ return getSymbolOfNode(entityName.parent.parent);
+ }
+ }
function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) {
if (ts.isDeclarationName(entityName)) {
return getSymbolOfNode(entityName.parent);
}
- if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 177 /* PropertyAccessExpression */) {
- var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent);
- switch (specialPropertyAssignmentKind) {
- case 1 /* ExportsProperty */:
- case 3 /* PrototypeProperty */:
- return getSymbolOfNode(entityName.parent);
- case 4 /* ThisProperty */:
- case 2 /* ModuleExports */:
- return getSymbolOfNode(entityName.parent.parent);
- default:
+ if (ts.isInJavaScriptFile(entityName) &&
+ entityName.parent.kind === 178 /* PropertyAccessExpression */ &&
+ entityName.parent === entityName.parent.parent.left) {
+ // Check if this is a special property assignment
+ var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName);
+ if (specialPropertyAssignmentSymbol) {
+ return specialPropertyAssignmentSymbol;
}
}
- if (entityName.parent.kind === 240 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) {
+ if (entityName.parent.kind === 242 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) {
return resolveEntityName(entityName,
/*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */);
}
- if (entityName.kind !== 177 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) {
+ if (entityName.kind !== 178 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) {
// Since we already checked for ExportAssignment, this really could only be an Import
- var importEqualsDeclaration = ts.getAncestor(entityName, 234 /* ImportEqualsDeclaration */);
+ var importEqualsDeclaration = ts.getAncestor(entityName, 236 /* ImportEqualsDeclaration */);
ts.Debug.assert(importEqualsDeclaration !== undefined);
return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true);
}
@@ -41736,7 +45243,7 @@ var ts;
if (isHeritageClauseElementIdentifier(entityName)) {
var meaning = 0 /* None */;
// In an interface or class, we're definitely interested in a type.
- if (entityName.parent.kind === 199 /* ExpressionWithTypeArguments */) {
+ if (entityName.parent.kind === 200 /* ExpressionWithTypeArguments */) {
meaning = 793064 /* Type */;
// In a class 'extends' clause we are also looking for a value.
if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) {
@@ -41747,9 +45254,12 @@ var ts;
meaning = 1920 /* Namespace */;
}
meaning |= 8388608 /* Alias */;
- return resolveEntityName(entityName, meaning);
+ var entityNameSymbol = resolveEntityName(entityName, meaning);
+ if (entityNameSymbol) {
+ return entityNameSymbol;
+ }
}
- else if (ts.isPartOfExpression(entityName)) {
+ if (ts.isPartOfExpression(entityName)) {
if (ts.nodeIsMissing(entityName)) {
// Missing entity name.
return undefined;
@@ -41760,14 +45270,14 @@ var ts;
}
return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
}
- else if (entityName.kind === 177 /* PropertyAccessExpression */) {
+ else if (entityName.kind === 178 /* PropertyAccessExpression */) {
var symbol = getNodeLinks(entityName).resolvedSymbol;
if (!symbol) {
checkPropertyAccessExpression(entityName);
}
return getNodeLinks(entityName).resolvedSymbol;
}
- else if (entityName.kind === 141 /* QualifiedName */) {
+ else if (entityName.kind === 142 /* QualifiedName */) {
var symbol = getNodeLinks(entityName).resolvedSymbol;
if (!symbol) {
checkQualifiedName(entityName);
@@ -41776,20 +45286,20 @@ var ts;
}
}
else if (isTypeReferenceIdentifier(entityName)) {
- var meaning = (entityName.parent.kind === 157 /* TypeReference */ || entityName.parent.kind === 272 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */;
+ var meaning = (entityName.parent.kind === 158 /* TypeReference */ || entityName.parent.kind === 276 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */;
return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
}
- else if (entityName.parent.kind === 250 /* JsxAttribute */) {
+ else if (entityName.parent.kind === 252 /* JsxAttribute */) {
return getJsxAttributePropertySymbol(entityName.parent);
}
- if (entityName.parent.kind === 156 /* TypePredicate */) {
+ if (entityName.parent.kind === 157 /* TypePredicate */) {
return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */);
}
// Do we want to return undefined here?
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 261 /* SourceFile */) {
+ if (node.kind === 264 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
if (isInsideWithStatementBody(node)) {
@@ -41807,8 +45317,8 @@ var ts;
if (isInRightSideOfImportOrExportAssignment(node)) {
return getSymbolOfEntityNameOrPropertyAccessExpression(node);
}
- else if (node.parent.kind === 174 /* BindingElement */ &&
- node.parent.parent.kind === 172 /* ObjectBindingPattern */ &&
+ else if (node.parent.kind === 175 /* BindingElement */ &&
+ node.parent.parent.kind === 173 /* ObjectBindingPattern */ &&
node === node.parent.propertyName) {
var typeOfPattern = getTypeOfNode(node.parent.parent);
var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text);
@@ -41819,8 +45329,8 @@ var ts;
}
switch (node.kind) {
case 70 /* Identifier */:
- case 177 /* PropertyAccessExpression */:
- case 141 /* QualifiedName */:
+ case 178 /* PropertyAccessExpression */:
+ case 142 /* QualifiedName */:
return getSymbolOfEntityNameOrPropertyAccessExpression(node);
case 98 /* ThisKeyword */:
var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
@@ -41830,16 +45340,16 @@ var ts;
return sig.thisParameter;
}
}
- // fallthrough
+ // falls through
case 96 /* SuperKeyword */:
var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node);
return type.symbol;
- case 167 /* ThisType */:
+ case 168 /* ThisType */:
return getTypeFromTypeNode(node).symbol;
case 122 /* ConstructorKeyword */:
// constructor keyword for an overload, should take us to the definition if it exist
var constructorDeclaration = node.parent;
- if (constructorDeclaration && constructorDeclaration.kind === 150 /* Constructor */) {
+ if (constructorDeclaration && constructorDeclaration.kind === 151 /* Constructor */) {
return constructorDeclaration.parent.symbol;
}
return undefined;
@@ -41847,17 +45357,17 @@ var ts;
// External module name in an import declaration
if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) &&
ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
- ((node.parent.kind === 235 /* ImportDeclaration */ || node.parent.kind === 241 /* ExportDeclaration */) &&
+ ((node.parent.kind === 237 /* ImportDeclaration */ || node.parent.kind === 243 /* ExportDeclaration */) &&
node.parent.moduleSpecifier === node)) {
return resolveExternalModuleName(node, node);
}
if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) {
return resolveExternalModuleName(node, node);
}
- // Fall through
+ // falls through
case 8 /* NumericLiteral */:
// index access
- if (node.parent.kind === 178 /* ElementAccessExpression */ && node.parent.argumentExpression === node) {
+ if (node.parent.kind === 179 /* ElementAccessExpression */ && node.parent.argumentExpression === node) {
var objectType = getTypeOfExpression(node.parent.expression);
if (objectType === unknownType)
return undefined;
@@ -41874,7 +45384,7 @@ var ts;
// The function returns a value symbol of an identifier in the short-hand property assignment.
// This is necessary as an identifier in short-hand property assignment can contains two meaning:
// property name and property value.
- if (location && location.kind === 258 /* ShorthandPropertyAssignment */) {
+ if (location && location.kind === 261 /* ShorthandPropertyAssignment */) {
return resolveEntityName(location.name, 107455 /* Value */ | 8388608 /* Alias */);
}
return undefined;
@@ -41891,7 +45401,13 @@ var ts;
return unknownType;
}
if (ts.isPartOfTypeNode(node)) {
- return getTypeFromTypeNode(node);
+ var typeFromTypeNode = getTypeFromTypeNode(node);
+ if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) {
+ var containingClass = ts.getContainingClass(node);
+ var classType = getTypeOfNode(containingClass);
+ typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType);
+ }
+ return typeFromTypeNode;
}
if (ts.isPartOfExpression(node)) {
return getRegularTypeOfExpression(node);
@@ -41899,7 +45415,10 @@ var ts;
if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) {
// A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
// extends clause of a class. We handle that case here.
- return getBaseTypes(getDeclaredTypeOfSymbol(getSymbolOfNode(node.parent.parent)))[0];
+ var classNode = ts.getContainingClass(node);
+ var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode));
+ var baseType = getBaseTypes(classType)[0];
+ return baseType && getTypeWithThisArgument(baseType, classType.thisType);
}
if (isTypeDeclaration(node)) {
// In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
@@ -41936,31 +45455,31 @@ var ts;
// [ a ] from
// [a] = [ some array ...]
function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) {
- ts.Debug.assert(expr.kind === 176 /* ObjectLiteralExpression */ || expr.kind === 175 /* ArrayLiteralExpression */);
+ ts.Debug.assert(expr.kind === 177 /* ObjectLiteralExpression */ || expr.kind === 176 /* ArrayLiteralExpression */);
// If this is from "for of"
// for ( { a } of elems) {
// }
- if (expr.parent.kind === 213 /* ForOfStatement */) {
- var iteratedType = checkRightHandSideOfForOf(expr.parent.expression);
+ if (expr.parent.kind === 215 /* ForOfStatement */) {
+ var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier);
return checkDestructuringAssignment(expr, iteratedType || unknownType);
}
// If this is from "for" initializer
// for ({a } = elems[0];.....) { }
- if (expr.parent.kind === 192 /* BinaryExpression */) {
+ if (expr.parent.kind === 193 /* BinaryExpression */) {
var iteratedType = getTypeOfExpression(expr.parent.right);
return checkDestructuringAssignment(expr, iteratedType || unknownType);
}
// If this is from nested object binding pattern
// for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
- if (expr.parent.kind === 257 /* PropertyAssignment */) {
+ if (expr.parent.kind === 260 /* PropertyAssignment */) {
var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent);
return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent);
}
// Array literal assignment - array destructuring pattern
- ts.Debug.assert(expr.parent.kind === 175 /* ArrayLiteralExpression */);
+ ts.Debug.assert(expr.parent.kind === 176 /* ArrayLiteralExpression */);
// [{ property1: p1, property2 }] = elems;
var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent);
- var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false) || unknownType;
+ var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType;
return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType);
}
// Gets the property symbol corresponding to the property in destructuring assignment
@@ -41981,9 +45500,9 @@ var ts;
return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
}
/**
- * Gets either the static or instance type of a class element, based on
- * whether the element is declared as "static".
- */
+ * Gets either the static or instance type of a class element, based on
+ * whether the element is declared as "static".
+ */
function getParentTypeOfClassElement(node) {
var classSymbol = getSymbolOfNode(node.parent);
return ts.getModifierFlags(node) & 32 /* Static */
@@ -41997,29 +45516,32 @@ var ts;
var propsByName = createSymbolTable(getPropertiesOfType(type));
if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) {
ts.forEach(getPropertiesOfType(globalFunctionType), function (p) {
- if (!propsByName[p.name]) {
- propsByName[p.name] = p;
+ if (!propsByName.has(p.name)) {
+ propsByName.set(p.name, p);
}
});
}
return getNamedMembers(propsByName);
}
function getRootSymbols(symbol) {
- if (symbol.flags & 268435456 /* SyntheticProperty */) {
+ if (getCheckFlags(symbol) & 6 /* Synthetic */) {
var symbols_3 = [];
- var name_26 = symbol.name;
+ var name_2 = symbol.name;
ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) {
- var symbol = getPropertyOfType(t, name_26);
+ var symbol = getPropertyOfType(t, name_2);
if (symbol) {
symbols_3.push(symbol);
}
});
return symbols_3;
}
- else if (symbol.flags & 67108864 /* Transient */) {
+ else if (symbol.flags & 134217728 /* Transient */) {
if (symbol.leftSpread) {
var links = symbol;
- return [links.leftSpread, links.rightSpread];
+ return getRootSymbols(links.leftSpread).concat(getRootSymbols(links.rightSpread));
+ }
+ if (symbol.syntheticOrigin) {
+ return getRootSymbols(symbol.syntheticOrigin);
}
var target = void 0;
var next = symbol;
@@ -42037,7 +45559,8 @@ var ts;
if (!ts.isGeneratedIdentifier(node)) {
node = ts.getParseTreeNode(node, ts.isIdentifier);
if (node) {
- return getReferencedValueSymbol(node) === argumentsSymbol;
+ var isPropertyName_1 = node.parent.kind === 178 /* PropertyAccessExpression */ && node.parent.name === node;
+ return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol;
}
}
return false;
@@ -42058,7 +45581,7 @@ var ts;
// otherwise - check if at least one export is value
symbolLinks.exportsSomeValue = hasExportAssignment
? !!(moduleSymbol.flags & 107455 /* Value */)
- : ts.forEachProperty(getExportsOfModule(moduleSymbol), isValue);
+ : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
}
return symbolLinks.exportsSomeValue;
function isValue(s) {
@@ -42091,20 +45614,16 @@ var ts;
}
symbol = exportSymbol;
}
- var parentSymbol = getParentOfSymbol(symbol);
- if (parentSymbol) {
- if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 261 /* SourceFile */) {
- var symbolFile = parentSymbol.valueDeclaration;
+ var parentSymbol_1 = getParentOfSymbol(symbol);
+ if (parentSymbol_1) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 264 /* SourceFile */) {
+ var symbolFile = parentSymbol_1.valueDeclaration;
var referenceFile = ts.getSourceFileOfNode(node);
// If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
var symbolIsUmdExport = symbolFile !== referenceFile;
return symbolIsUmdExport ? undefined : symbolFile;
}
- for (var n = node.parent; n; n = n.parent) {
- if (ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol) {
- return n;
- }
- }
+ return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
}
}
}
@@ -42150,7 +45669,7 @@ var ts;
// they will not collide with anything
var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */;
var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
- var inLoopBodyBlock = container.kind === 204 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
+ var inLoopBodyBlock = container.kind === 206 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
}
else {
@@ -42190,22 +45709,17 @@ var ts;
return false;
}
function isValueAliasDeclaration(node) {
- node = ts.getParseTreeNode(node);
- if (node === undefined) {
- // A synthesized node comes from an emit transformation and is always a value.
- return true;
- }
switch (node.kind) {
- case 234 /* ImportEqualsDeclaration */:
- case 236 /* ImportClause */:
- case 237 /* NamespaceImport */:
- case 239 /* ImportSpecifier */:
- case 243 /* ExportSpecifier */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 238 /* ImportClause */:
+ case 239 /* NamespaceImport */:
+ case 241 /* ImportSpecifier */:
+ case 245 /* ExportSpecifier */:
return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
var exportClause = node.exportClause;
return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration);
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
return node.expression
&& node.expression.kind === 70 /* Identifier */
? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol)
@@ -42215,7 +45729,7 @@ var ts;
}
function isTopLevelValueImportEqualsWithEntityName(node) {
node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 261 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 264 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -42236,11 +45750,6 @@ var ts;
return isConstEnumSymbol(s) || s.constEnumOnlyModule;
}
function isReferencedAliasDeclaration(node, checkChildren) {
- node = ts.getParseTreeNode(node);
- // Purely synthesized nodes are always emitted.
- if (node === undefined) {
- return true;
- }
if (ts.isAliasSymbolDeclaration(node)) {
var symbol = getSymbolOfNode(node);
if (symbol && getSymbolLinks(symbol).referenced) {
@@ -42272,16 +45781,30 @@ var ts;
}
return false;
}
+ function isRequiredInitializedParameter(parameter) {
+ return strictNullChecks &&
+ !isOptionalParameter(parameter) &&
+ parameter.initializer &&
+ !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */);
+ }
function getNodeCheckFlags(node) {
- node = ts.getParseTreeNode(node);
- return node ? getNodeLinks(node).flags : undefined;
+ return getNodeLinks(node).flags;
}
function getEnumMemberValue(node) {
computeEnumMemberValues(node.parent);
return getNodeLinks(node).enumMemberValue;
}
+ function canHaveConstantValue(node) {
+ switch (node.kind) {
+ case 263 /* EnumMember */:
+ case 178 /* PropertyAccessExpression */:
+ case 179 /* ElementAccessExpression */:
+ return true;
+ }
+ return false;
+ }
function getConstantValue(node) {
- if (node.kind === 260 /* EnumMember */) {
+ if (node.kind === 263 /* EnumMember */) {
return getEnumMemberValue(node);
}
var symbol = getNodeLinks(node).resolvedSymbol;
@@ -42299,16 +45822,18 @@ var ts;
function getTypeReferenceSerializationKind(typeName, location) {
// Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
- var globalPromiseSymbol = tryGetGlobalPromiseConstructorSymbol();
- if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
- return ts.TypeReferenceSerializationKind.Promise;
- }
- var constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined;
- if (constructorType && isConstructorType(constructorType)) {
- return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
- }
// Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
var typeSymbol = resolveEntityName(typeName, 793064 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
+ if (valueSymbol && valueSymbol === typeSymbol) {
+ var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
+ if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
+ return ts.TypeReferenceSerializationKind.Promise;
+ }
+ var constructorType = getTypeOfSymbol(valueSymbol);
+ if (constructorType && isConstructorType(constructorType)) {
+ return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
+ }
+ }
// We might not be able to resolve type symbol so use unknown type in that case (eg error case)
if (!typeSymbol) {
return ts.TypeReferenceSerializationKind.ObjectType;
@@ -42354,6 +45879,9 @@ var ts;
var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
? getWidenedLiteralType(getTypeOfSymbol(symbol))
: unknownType;
+ if (flags & 4096 /* AddUndefined */) {
+ type = includeFalsyTypes(type, 2048 /* Undefined */);
+ }
getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags);
}
function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) {
@@ -42368,10 +45896,13 @@ var ts;
var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node));
resolveBaseTypesOfClass(classType);
var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType;
+ if (!baseType.symbol) {
+ writer.reportIllegalExtends();
+ }
getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags);
}
function hasGlobalName(name) {
- return !!globals[name];
+ return globals.has(name);
}
function getReferencedValueSymbol(reference, startInDeclarationContainer) {
var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
@@ -42382,9 +45913,9 @@ var ts;
if (startInDeclarationContainer) {
// When resolving the name of a declaration as a value, we need to start resolution
// at a point outside of the declaration.
- var parent_11 = reference.parent;
- if (ts.isDeclaration(parent_11) && reference === parent_11.name) {
- location = getDeclarationContainer(parent_11);
+ var parent = reference.parent;
+ if (ts.isDeclaration(parent) && reference === parent.name) {
+ location = getDeclarationContainer(parent);
}
}
return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined);
@@ -42420,34 +45951,48 @@ var ts;
if (resolvedTypeReferenceDirectives) {
// populate reverse mapping: file path -> type reference directive that was resolved to this file
fileToDirective = ts.createFileMap();
- for (var key in resolvedTypeReferenceDirectives) {
- var resolvedDirective = resolvedTypeReferenceDirectives[key];
+ resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
if (!resolvedDirective) {
- continue;
+ return;
}
var file = host.getSourceFile(resolvedDirective.resolvedFileName);
fileToDirective.set(file.path, key);
- }
+ });
}
return {
getReferencedExportContainer: getReferencedExportContainer,
getReferencedImportDeclaration: getReferencedImportDeclaration,
getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
isDeclarationWithCollidingName: isDeclarationWithCollidingName,
- isValueAliasDeclaration: isValueAliasDeclaration,
+ isValueAliasDeclaration: function (node) {
+ node = ts.getParseTreeNode(node);
+ // Synthesized nodes are always treated like values.
+ return node ? isValueAliasDeclaration(node) : true;
+ },
hasGlobalName: hasGlobalName,
- isReferencedAliasDeclaration: isReferencedAliasDeclaration,
- getNodeCheckFlags: getNodeCheckFlags,
+ isReferencedAliasDeclaration: function (node, checkChildren) {
+ node = ts.getParseTreeNode(node);
+ // Synthesized nodes are always treated as referenced.
+ return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
+ },
+ getNodeCheckFlags: function (node) {
+ node = ts.getParseTreeNode(node);
+ return node ? getNodeCheckFlags(node) : undefined;
+ },
isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
isDeclarationVisible: isDeclarationVisible,
isImplementationOfOverload: isImplementationOfOverload,
+ isRequiredInitializedParameter: isRequiredInitializedParameter,
writeTypeOfDeclaration: writeTypeOfDeclaration,
writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration,
writeTypeOfExpression: writeTypeOfExpression,
writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass,
isSymbolAccessible: isSymbolAccessible,
isEntityNameVisible: isEntityNameVisible,
- getConstantValue: getConstantValue,
+ getConstantValue: function (node) {
+ node = ts.getParseTreeNode(node, canHaveConstantValue);
+ return node ? getConstantValue(node) : undefined;
+ },
collectLinkedAliases: collectLinkedAliases,
getReferencedValueDeclaration: getReferencedValueDeclaration,
getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
@@ -42470,7 +46015,7 @@ var ts;
// property access can only be used as values
// qualified names can only be used as types\namespaces
// identifiers are treated as values only if they appear in type queries
- var meaning = (node.kind === 177 /* PropertyAccessExpression */) || (node.kind === 70 /* Identifier */ && isInTypeQuery(node))
+ var meaning = (node.kind === 178 /* PropertyAccessExpression */) || (node.kind === 70 /* Identifier */ && isInTypeQuery(node))
? 107455 /* Value */ | 1048576 /* ExportValue */
: 793064 /* Type */ | 1920 /* Namespace */;
var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
@@ -42513,15 +46058,15 @@ var ts;
// external modules cannot define or contribute to type declaration files
var current = symbol;
while (true) {
- var parent_12 = getParentOfSymbol(current);
- if (parent_12) {
- current = parent_12;
+ var parent = getParentOfSymbol(current);
+ if (parent) {
+ current = parent;
}
else {
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 261 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 264 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -42541,7 +46086,7 @@ var ts;
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 261 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 264 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -42551,8 +46096,6 @@ var ts;
}
// Initialize global symbol table
var augmentations;
- var requestedExternalEmitHelpers = 0;
- var firstFileRequestingExternalHelpers;
for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
var file = _c[_b];
if (!ts.isExternalOrCommonJsModule(file)) {
@@ -42567,20 +46110,11 @@ var ts;
if (file.symbol && file.symbol.globalExports) {
// Merge in UMD exports with first-in-wins semantics (see #9771)
var source = file.symbol.globalExports;
- for (var id in source) {
- if (!(id in globals)) {
- globals[id] = source[id];
- }
- }
- }
- if ((compilerOptions.isolatedModules || ts.isExternalModule(file)) && !file.isDeclarationFile) {
- var fileRequestedExternalEmitHelpers = file.flags & 64512 /* EmitHelperFlags */;
- if (fileRequestedExternalEmitHelpers) {
- requestedExternalEmitHelpers |= fileRequestedExternalEmitHelpers;
- if (firstFileRequestingExternalHelpers === undefined) {
- firstFileRequestingExternalHelpers = file;
+ source.forEach(function (sourceSymbol, id) {
+ if (!globals.has(id)) {
+ globals.set(id, sourceSymbol);
}
- }
+ });
}
}
if (augmentations) {
@@ -42597,110 +46131,67 @@ var ts;
// Setup global builtins
addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
- getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments");
+ getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
getSymbolLinks(unknownSymbol).type = unknownType;
// Initialize special types
- globalArrayType = getGlobalType("Array", /*arity*/ 1);
- globalObjectType = getGlobalType("Object");
- globalFunctionType = getGlobalType("Function");
- globalStringType = getGlobalType("String");
- globalNumberType = getGlobalType("Number");
- globalBooleanType = getGlobalType("Boolean");
- globalRegExpType = getGlobalType("RegExp");
- jsxElementType = getExportedTypeFromNamespace("JSX", JsxNames.Element);
- getGlobalClassDecoratorType = ts.memoize(function () { return getGlobalType("ClassDecorator"); });
- getGlobalPropertyDecoratorType = ts.memoize(function () { return getGlobalType("PropertyDecorator"); });
- getGlobalMethodDecoratorType = ts.memoize(function () { return getGlobalType("MethodDecorator"); });
- getGlobalParameterDecoratorType = ts.memoize(function () { return getGlobalType("ParameterDecorator"); });
- getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", /*arity*/ 1); });
- getGlobalESSymbolConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Symbol"); });
- getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", /*arity*/ 1); });
- tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793064 /* Type */, /*diagnostic*/ undefined) && getGlobalPromiseType(); });
- getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", /*arity*/ 1); });
- getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType);
- getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); });
- tryGetGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalSymbol("Promise", 107455 /* Value */, /*diagnostic*/ undefined) && getGlobalPromiseConstructorSymbol(); });
- getGlobalPromiseConstructorLikeType = ts.memoize(function () { return getGlobalType("PromiseConstructorLike"); });
- getGlobalThenableType = ts.memoize(createThenableType);
- getGlobalTemplateStringsArrayType = ts.memoize(function () { return getGlobalType("TemplateStringsArray"); });
- if (languageVersion >= 2 /* ES2015 */) {
- getGlobalESSymbolType = ts.memoize(function () { return getGlobalType("Symbol"); });
- getGlobalIterableType = ts.memoize(function () { return getGlobalType("Iterable", /*arity*/ 1); });
- getGlobalIteratorType = ts.memoize(function () { return getGlobalType("Iterator", /*arity*/ 1); });
- getGlobalIterableIteratorType = ts.memoize(function () { return getGlobalType("IterableIterator", /*arity*/ 1); });
- }
- else {
- getGlobalESSymbolType = ts.memoize(function () { return emptyObjectType; });
- getGlobalIterableType = ts.memoize(function () { return emptyGenericType; });
- getGlobalIteratorType = ts.memoize(function () { return emptyGenericType; });
- getGlobalIterableIteratorType = ts.memoize(function () { return emptyGenericType; });
- }
+ globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
+ globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
+ globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
+ globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
+ globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
+ globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
+ globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
anyArrayType = createArrayType(anyType);
autoArrayType = createArrayType(autoType);
- var symbol = getGlobalSymbol("ReadonlyArray", 793064 /* Type */, /*diagnostic*/ undefined);
- globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1);
+ globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1);
anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
- // If we have specified that we are importing helpers, we should report global
- // errors if we cannot resolve the helpers external module, or if it does not have
- // the necessary helpers exported.
- if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) {
- // Find the first reference to the helpers module.
- var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0,
- /*errorNode*/ undefined);
- // If we found the module, report errors if it does not have the necessary exports.
- if (helpersModule) {
- var exports = helpersModule.exports;
- if (requestedExternalEmitHelpers & 1024 /* HasClassExtends */ && languageVersion < 2 /* ES2015 */) {
- verifyHelperSymbol(exports, "__extends", 107455 /* Value */);
- }
- if (requestedExternalEmitHelpers & 16384 /* HasSpreadAttribute */ &&
- (languageVersion < 5 /* ESNext */ || compilerOptions.jsx === 2 /* React */)) {
- verifyHelperSymbol(exports, "__assign", 107455 /* Value */);
- }
- if (languageVersion < 5 /* ESNext */ && requestedExternalEmitHelpers & 32768 /* HasRestAttribute */) {
- verifyHelperSymbol(exports, "__rest", 107455 /* Value */);
- }
- if (requestedExternalEmitHelpers & 2048 /* HasDecorators */) {
- verifyHelperSymbol(exports, "__decorate", 107455 /* Value */);
- if (compilerOptions.emitDecoratorMetadata) {
- verifyHelperSymbol(exports, "__metadata", 107455 /* Value */);
- }
- }
- if (requestedExternalEmitHelpers & 4096 /* HasParamDecorators */) {
- verifyHelperSymbol(exports, "__param", 107455 /* Value */);
- }
- if (requestedExternalEmitHelpers & 8192 /* HasAsyncFunctions */) {
- verifyHelperSymbol(exports, "__awaiter", 107455 /* Value */);
- if (languageVersion < 2 /* ES2015 */) {
- verifyHelperSymbol(exports, "__generator", 107455 /* Value */);
+ globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
+ }
+ function checkExternalEmitHelpers(location, helpers) {
+ if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
+ var sourceFile = ts.getSourceFileOfNode(location);
+ if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) {
+ var helpersModule = resolveHelpersModule(sourceFile, location);
+ if (helpersModule !== unknownSymbol) {
+ var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
+ for (var helper = 1 /* FirstEmitHelper */; helper <= 8192 /* LastEmitHelper */; helper <<= 1) {
+ if (uncheckedHelpers & helper) {
+ var name = getHelperName(helper);
+ var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455 /* Value */);
+ if (!symbol) {
+ error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name);
+ }
+ }
}
}
+ requestedExternalEmitHelpers |= helpers;
}
}
}
- function verifyHelperSymbol(symbols, name, meaning) {
- var symbol = getSymbol(symbols, ts.escapeIdentifier(name), meaning);
- if (!symbol) {
- error(/*location*/ undefined, ts.Diagnostics.Module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name);
+ function getHelperName(helper) {
+ switch (helper) {
+ case 1 /* Extends */: return "__extends";
+ case 2 /* Assign */: return "__assign";
+ case 4 /* Rest */: return "__rest";
+ case 8 /* Decorate */: return "__decorate";
+ case 16 /* Metadata */: return "__metadata";
+ case 32 /* Param */: return "__param";
+ case 64 /* Awaiter */: return "__awaiter";
+ case 128 /* Generator */: return "__generator";
+ case 256 /* Values */: return "__values";
+ case 512 /* Read */: return "__read";
+ case 1024 /* Spread */: return "__spread";
+ case 2048 /* AsyncGenerator */: return "__asyncGenerator";
+ case 4096 /* AsyncDelegator */: return "__asyncDelegator";
+ case 8192 /* AsyncValues */: return "__asyncValues";
+ default: ts.Debug.fail("Unrecognized helper.");
}
}
- function createInstantiatedPromiseLikeType() {
- var promiseLikeType = getGlobalPromiseLikeType();
- if (promiseLikeType !== emptyGenericType) {
- return createTypeReference(promiseLikeType, [anyType]);
+ function resolveHelpersModule(node, errorNode) {
+ if (!externalHelpersModule) {
+ externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
}
- return emptyObjectType;
- }
- function createThenableType() {
- // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`.
- var thenPropertySymbol = createSymbol(67108864 /* Transient */ | 4 /* Property */, "then");
- getSymbolLinks(thenPropertySymbol).type = globalFunctionType;
- var thenableType = createObjectType(16 /* Anonymous */);
- thenableType.properties = [thenPropertySymbol];
- thenableType.members = createSymbolTable(thenableType.properties);
- thenableType.callSignatures = [];
- thenableType.constructSignatures = [];
- return thenableType;
+ return externalHelpersModule;
}
// GRAMMAR CHECKING
function checkGrammarDecorators(node) {
@@ -42708,14 +46199,14 @@ var ts;
return false;
}
if (!ts.nodeCanBeDecorated(node)) {
- if (node.kind === 149 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
+ if (node.kind === 150 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
}
else {
return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
}
}
- else if (node.kind === 151 /* GetAccessor */ || node.kind === 152 /* SetAccessor */) {
+ else if (node.kind === 152 /* GetAccessor */ || node.kind === 153 /* SetAccessor */) {
var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
@@ -42733,16 +46224,16 @@ var ts;
for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
var modifier = _a[_i];
if (modifier.kind !== 130 /* ReadonlyKeyword */) {
- if (node.kind === 146 /* PropertySignature */ || node.kind === 148 /* MethodSignature */) {
+ if (node.kind === 147 /* PropertySignature */ || node.kind === 149 /* MethodSignature */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
}
- if (node.kind === 155 /* IndexSignature */) {
+ if (node.kind === 156 /* IndexSignature */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
}
}
switch (modifier.kind) {
case 75 /* ConstKeyword */:
- if (node.kind !== 229 /* EnumDeclaration */ && node.parent.kind === 226 /* ClassDeclaration */) {
+ if (node.kind !== 231 /* EnumDeclaration */ && node.parent.kind === 228 /* ClassDeclaration */) {
return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(75 /* ConstKeyword */));
}
break;
@@ -42768,7 +46259,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) {
+ else if (node.parent.kind === 233 /* ModuleBlock */ || node.parent.kind === 264 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -42791,10 +46282,10 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) {
+ else if (node.parent.kind === 233 /* ModuleBlock */ || node.parent.kind === 264 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
- else if (node.kind === 144 /* Parameter */) {
+ else if (node.kind === 145 /* Parameter */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
}
else if (flags & 128 /* Abstract */) {
@@ -42807,7 +46298,7 @@ var ts;
if (flags & 64 /* Readonly */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
}
- else if (node.kind !== 147 /* PropertyDeclaration */ && node.kind !== 146 /* PropertySignature */ && node.kind !== 155 /* IndexSignature */ && node.kind !== 144 /* Parameter */) {
+ else if (node.kind !== 148 /* PropertyDeclaration */ && node.kind !== 147 /* PropertySignature */ && node.kind !== 156 /* IndexSignature */ && node.kind !== 145 /* Parameter */) {
// If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
}
@@ -42827,10 +46318,10 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
}
- else if (node.parent.kind === 226 /* ClassDeclaration */) {
+ else if (node.parent.kind === 228 /* ClassDeclaration */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
}
- else if (node.kind === 144 /* Parameter */) {
+ else if (node.kind === 145 /* Parameter */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
}
flags |= 1 /* Export */;
@@ -42842,13 +46333,13 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
}
- else if (node.parent.kind === 226 /* ClassDeclaration */) {
+ else if (node.parent.kind === 228 /* ClassDeclaration */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
}
- else if (node.kind === 144 /* Parameter */) {
+ else if (node.kind === 145 /* Parameter */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
}
- else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 231 /* ModuleBlock */) {
+ else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 233 /* ModuleBlock */) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
}
flags |= 2 /* Ambient */;
@@ -42858,14 +46349,14 @@ var ts;
if (flags & 128 /* Abstract */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
}
- if (node.kind !== 226 /* ClassDeclaration */) {
- if (node.kind !== 149 /* MethodDeclaration */ &&
- node.kind !== 147 /* PropertyDeclaration */ &&
- node.kind !== 151 /* GetAccessor */ &&
- node.kind !== 152 /* SetAccessor */) {
+ if (node.kind !== 228 /* ClassDeclaration */) {
+ if (node.kind !== 150 /* MethodDeclaration */ &&
+ node.kind !== 148 /* PropertyDeclaration */ &&
+ node.kind !== 152 /* GetAccessor */ &&
+ node.kind !== 153 /* SetAccessor */) {
return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
}
- if (!(node.parent.kind === 226 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) {
+ if (!(node.parent.kind === 228 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
}
if (flags & 32 /* Static */) {
@@ -42884,7 +46375,7 @@ var ts;
else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
}
- else if (node.kind === 144 /* Parameter */) {
+ else if (node.kind === 145 /* Parameter */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
}
flags |= 256 /* Async */;
@@ -42892,7 +46383,7 @@ var ts;
break;
}
}
- if (node.kind === 150 /* Constructor */) {
+ if (node.kind === 151 /* Constructor */) {
if (flags & 32 /* Static */) {
return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
}
@@ -42907,13 +46398,13 @@ var ts;
}
return;
}
- else if ((node.kind === 235 /* ImportDeclaration */ || node.kind === 234 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
+ else if ((node.kind === 237 /* ImportDeclaration */ || node.kind === 236 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
}
- else if (node.kind === 144 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
+ else if (node.kind === 145 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
}
- else if (node.kind === 144 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
+ else if (node.kind === 145 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
}
if (flags & 256 /* Async */) {
@@ -42933,37 +46424,37 @@ var ts;
}
function shouldReportBadModifier(node) {
switch (node.kind) {
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 150 /* Constructor */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 155 /* IndexSignature */:
- case 230 /* ModuleDeclaration */:
- case 235 /* ImportDeclaration */:
- case 234 /* ImportEqualsDeclaration */:
- case 241 /* ExportDeclaration */:
- case 240 /* ExportAssignment */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 144 /* Parameter */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 151 /* Constructor */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 156 /* IndexSignature */:
+ case 232 /* ModuleDeclaration */:
+ case 237 /* ImportDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 243 /* ExportDeclaration */:
+ case 242 /* ExportAssignment */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 145 /* Parameter */:
return false;
default:
- if (node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) {
+ if (node.parent.kind === 233 /* ModuleBlock */ || node.parent.kind === 264 /* SourceFile */) {
return false;
}
switch (node.kind) {
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return nodeHasAnyModifiersExcept(node, 119 /* AsyncKeyword */);
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
return nodeHasAnyModifiersExcept(node, 116 /* AbstractKeyword */);
- case 227 /* InterfaceDeclaration */:
- case 205 /* VariableStatement */:
- case 228 /* TypeAliasDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 207 /* VariableStatement */:
+ case 230 /* TypeAliasDeclaration */:
return true;
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
return nodeHasAnyModifiersExcept(node, 75 /* ConstKeyword */);
default:
ts.Debug.fail();
@@ -42976,14 +46467,11 @@ var ts;
}
function checkGrammarAsyncModifier(node, asyncModifier) {
switch (node.kind) {
- case 149 /* MethodDeclaration */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- if (!node.asteriskToken) {
- return false;
- }
- break;
+ case 150 /* MethodDeclaration */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ return false;
}
return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
}
@@ -43041,8 +46529,12 @@ var ts;
return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file);
}
+ function checkGrammarClassLikeDeclaration(node) {
+ var file = ts.getSourceFileOfNode(node);
+ return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
+ }
function checkGrammarArrowFunction(node, file) {
- if (node.kind === 185 /* ArrowFunction */) {
+ if (node.kind === 186 /* ArrowFunction */) {
var arrowFunction = node;
var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line;
var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line;
@@ -43077,7 +46569,7 @@ var ts;
if (!parameter.type) {
return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
}
- if (parameter.type.kind !== 134 /* StringKeyword */ && parameter.type.kind !== 132 /* NumberKeyword */) {
+ if (parameter.type.kind !== 135 /* StringKeyword */ && parameter.type.kind !== 132 /* NumberKeyword */) {
return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number);
}
if (!node.type) {
@@ -43105,7 +46597,7 @@ var ts;
var sourceFile = ts.getSourceFileOfNode(node);
for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
var arg = args_4[_i];
- if (arg.kind === 198 /* OmittedExpression */) {
+ if (arg.kind === 199 /* OmittedExpression */) {
return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
}
}
@@ -43178,28 +46670,25 @@ var ts;
}
function checkGrammarComputedPropertyName(node) {
// If node is not a computedPropertyName, just skip the grammar checking
- if (node.kind !== 142 /* ComputedPropertyName */) {
+ if (node.kind !== 143 /* ComputedPropertyName */) {
return false;
}
var computedPropertyName = node;
- if (computedPropertyName.expression.kind === 192 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 25 /* CommaToken */) {
+ if (computedPropertyName.expression.kind === 193 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 25 /* CommaToken */) {
return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
}
}
function checkGrammarForGenerator(node) {
if (node.asteriskToken) {
- ts.Debug.assert(node.kind === 225 /* FunctionDeclaration */ ||
- node.kind === 184 /* FunctionExpression */ ||
- node.kind === 149 /* MethodDeclaration */);
+ ts.Debug.assert(node.kind === 227 /* FunctionDeclaration */ ||
+ node.kind === 185 /* FunctionExpression */ ||
+ node.kind === 150 /* MethodDeclaration */);
if (ts.isInAmbientContext(node)) {
return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
}
if (!node.body) {
return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
}
- if (languageVersion < 2 /* ES2015 */) {
- return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher);
- }
}
}
function checkGrammarForInvalidQuestionMark(questionToken, message) {
@@ -43215,15 +46704,15 @@ var ts;
var GetOrSetAccessor = GetAccessor | SetAccessor;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var prop = _a[_i];
- if (prop.kind === 259 /* SpreadAssignment */) {
+ if (prop.kind === 262 /* SpreadAssignment */) {
continue;
}
- var name_27 = prop.name;
- if (name_27.kind === 142 /* ComputedPropertyName */) {
+ var name = prop.name;
+ if (name.kind === 143 /* ComputedPropertyName */) {
// If the name is not a ComputedPropertyName, the grammar checking will skip it
- checkGrammarComputedPropertyName(name_27);
+ checkGrammarComputedPropertyName(name);
}
- if (prop.kind === 258 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
+ if (prop.kind === 261 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
// having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
// outside of destructuring it is a syntax error
return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
@@ -43232,7 +46721,7 @@ var ts;
if (prop.modifiers) {
for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) {
var mod = _c[_b];
- if (mod.kind !== 119 /* AsyncKeyword */ || prop.kind !== 149 /* MethodDeclaration */) {
+ if (mod.kind !== 119 /* AsyncKeyword */ || prop.kind !== 150 /* MethodDeclaration */) {
grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
}
}
@@ -43246,69 +46735,69 @@ var ts;
// d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
// and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
var currentKind = void 0;
- if (prop.kind === 257 /* PropertyAssignment */ || prop.kind === 258 /* ShorthandPropertyAssignment */) {
+ if (prop.kind === 260 /* PropertyAssignment */ || prop.kind === 261 /* ShorthandPropertyAssignment */) {
// Grammar checking for computedPropertyName and shorthandPropertyAssignment
checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
- if (name_27.kind === 8 /* NumericLiteral */) {
- checkGrammarNumericLiteral(name_27);
+ if (name.kind === 8 /* NumericLiteral */) {
+ checkGrammarNumericLiteral(name);
}
currentKind = Property;
}
- else if (prop.kind === 149 /* MethodDeclaration */) {
+ else if (prop.kind === 150 /* MethodDeclaration */) {
currentKind = Property;
}
- else if (prop.kind === 151 /* GetAccessor */) {
+ else if (prop.kind === 152 /* GetAccessor */) {
currentKind = GetAccessor;
}
- else if (prop.kind === 152 /* SetAccessor */) {
+ else if (prop.kind === 153 /* SetAccessor */) {
currentKind = SetAccessor;
}
else {
ts.Debug.fail("Unexpected syntax kind:" + prop.kind);
}
- var effectiveName = ts.getPropertyNameForPropertyNameNode(name_27);
+ var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
if (effectiveName === undefined) {
continue;
}
- if (!seen[effectiveName]) {
- seen[effectiveName] = currentKind;
+ var existingKind = seen.get(effectiveName);
+ if (!existingKind) {
+ seen.set(effectiveName, currentKind);
}
else {
- var existingKind = seen[effectiveName];
if (currentKind === Property && existingKind === Property) {
- grammarErrorOnNode(name_27, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_27));
+ grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
}
else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) {
if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) {
- seen[effectiveName] = currentKind | existingKind;
+ seen.set(effectiveName, currentKind | existingKind);
}
else {
- return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
+ return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
}
}
else {
- return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
+ return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
}
}
}
}
function checkGrammarJsxElement(node) {
var seen = ts.createMap();
- for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) {
+ for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
var attr = _a[_i];
- if (attr.kind === 251 /* JsxSpreadAttribute */) {
+ if (attr.kind === 254 /* JsxSpreadAttribute */) {
continue;
}
var jsxAttr = attr;
- var name_28 = jsxAttr.name;
- if (!seen[name_28.text]) {
- seen[name_28.text] = true;
+ var name = jsxAttr.name;
+ if (!seen.get(name.text)) {
+ seen.set(name.text, true);
}
else {
- return grammarErrorOnNode(name_28, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
+ return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
}
var initializer = jsxAttr.initializer;
- if (initializer && initializer.kind === 252 /* JsxExpression */ && !initializer.expression) {
+ if (initializer && initializer.kind === 255 /* JsxExpression */ && !initializer.expression) {
return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
}
}
@@ -43317,7 +46806,12 @@ var ts;
if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
return true;
}
- if (forInOrOfStatement.initializer.kind === 224 /* VariableDeclarationList */) {
+ if (forInOrOfStatement.kind === 215 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
+ if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) {
+ return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
+ }
+ }
+ if (forInOrOfStatement.initializer.kind === 226 /* VariableDeclarationList */) {
var variableList = forInOrOfStatement.initializer;
if (!checkGrammarVariableDeclarationList(variableList)) {
var declarations = variableList.declarations;
@@ -43332,20 +46826,20 @@ var ts;
return false;
}
if (declarations.length > 1) {
- var diagnostic = forInOrOfStatement.kind === 212 /* ForInStatement */
+ var diagnostic = forInOrOfStatement.kind === 214 /* ForInStatement */
? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
: ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
}
var firstDeclaration = declarations[0];
if (firstDeclaration.initializer) {
- var diagnostic = forInOrOfStatement.kind === 212 /* ForInStatement */
+ var diagnostic = forInOrOfStatement.kind === 214 /* ForInStatement */
? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
: ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
return grammarErrorOnNode(firstDeclaration.name, diagnostic);
}
if (firstDeclaration.type) {
- var diagnostic = forInOrOfStatement.kind === 212 /* ForInStatement */
+ var diagnostic = forInOrOfStatement.kind === 214 /* ForInStatement */
? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
: ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
return grammarErrorOnNode(firstDeclaration, diagnostic);
@@ -43365,15 +46859,18 @@ var ts;
else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) {
return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
}
+ else if (accessor.body && ts.getModifierFlags(accessor) & 128 /* Abstract */) {
+ return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
+ }
else if (accessor.typeParameters) {
return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
}
else if (!doesAccessorHaveCorrectParameterCount(accessor)) {
- return grammarErrorOnNode(accessor.name, kind === 151 /* GetAccessor */ ?
+ return grammarErrorOnNode(accessor.name, kind === 152 /* GetAccessor */ ?
ts.Diagnostics.A_get_accessor_cannot_have_parameters :
ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
}
- else if (kind === 152 /* SetAccessor */) {
+ else if (kind === 153 /* SetAccessor */) {
if (accessor.type) {
return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
}
@@ -43392,14 +46889,14 @@ var ts;
}
}
/** Does the accessor have the right number of parameters?
-
- A get accessor has no parameters or a single `this` parameter.
- A set accessor has one parameter or a `this` parameter and one more parameter */
+ * A get accessor has no parameters or a single `this` parameter.
+ * A set accessor has one parameter or a `this` parameter and one more parameter.
+ */
function doesAccessorHaveCorrectParameterCount(accessor) {
- return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 151 /* GetAccessor */ ? 0 : 1);
+ return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 152 /* GetAccessor */ ? 0 : 1);
}
function getAccessorThisParameter(accessor) {
- if (accessor.parameters.length === (accessor.kind === 151 /* GetAccessor */ ? 1 : 2)) {
+ if (accessor.parameters.length === (accessor.kind === 152 /* GetAccessor */ ? 1 : 2)) {
return ts.getThisParameter(accessor);
}
}
@@ -43414,7 +46911,7 @@ var ts;
checkGrammarForGenerator(node)) {
return true;
}
- if (node.parent.kind === 176 /* ObjectLiteralExpression */) {
+ if (node.parent.kind === 177 /* ObjectLiteralExpression */) {
if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
return true;
}
@@ -43435,10 +46932,10 @@ var ts;
return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol);
}
}
- else if (node.parent.kind === 227 /* InterfaceDeclaration */) {
+ else if (node.parent.kind === 229 /* InterfaceDeclaration */) {
return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol);
}
- else if (node.parent.kind === 161 /* TypeLiteral */) {
+ else if (node.parent.kind === 162 /* TypeLiteral */) {
return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol);
}
}
@@ -43449,11 +46946,11 @@ var ts;
return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
}
switch (current.kind) {
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
if (node.label && current.label.text === node.label.text) {
// found matching label - verify that label usage is correct
// continue can only target labels that are on iteration statements
- var isMisplacedContinueLabel = node.kind === 214 /* ContinueStatement */
+ var isMisplacedContinueLabel = node.kind === 216 /* ContinueStatement */
&& !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
if (isMisplacedContinueLabel) {
return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
@@ -43461,8 +46958,8 @@ var ts;
return false;
}
break;
- case 218 /* SwitchStatement */:
- if (node.kind === 215 /* BreakStatement */ && !node.label) {
+ case 220 /* SwitchStatement */:
+ if (node.kind === 217 /* BreakStatement */ && !node.label) {
// unlabeled break within switch statement - ok
return false;
}
@@ -43477,13 +46974,13 @@ var ts;
current = current.parent;
}
if (node.label) {
- var message = node.kind === 215 /* BreakStatement */
+ var message = node.kind === 217 /* BreakStatement */
? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
: ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
return grammarErrorOnNode(node, message);
}
else {
- var message = node.kind === 215 /* BreakStatement */
+ var message = node.kind === 217 /* BreakStatement */
? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
: ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
return grammarErrorOnNode(node, message);
@@ -43495,7 +46992,7 @@ var ts;
if (node !== ts.lastOrUndefined(elements)) {
return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
}
- if (node.name.kind === 173 /* ArrayBindingPattern */ || node.name.kind === 172 /* ObjectBindingPattern */) {
+ if (node.name.kind === 174 /* ArrayBindingPattern */ || node.name.kind === 173 /* ObjectBindingPattern */) {
return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
}
if (node.initializer) {
@@ -43506,11 +47003,11 @@ var ts;
}
function isStringOrNumberLiteralExpression(expr) {
return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ ||
- expr.kind === 190 /* PrefixUnaryExpression */ && expr.operator === 37 /* MinusToken */ &&
+ expr.kind === 191 /* PrefixUnaryExpression */ && expr.operator === 37 /* MinusToken */ &&
expr.operand.kind === 8 /* NumericLiteral */;
}
function checkGrammarVariableDeclaration(node) {
- if (node.parent.parent.kind !== 212 /* ForInStatement */ && node.parent.parent.kind !== 213 /* ForOfStatement */) {
+ if (node.parent.parent.kind !== 214 /* ForInStatement */ && node.parent.parent.kind !== 215 /* ForOfStatement */) {
if (ts.isInAmbientContext(node)) {
if (node.initializer) {
if (ts.isConst(node) && !node.type) {
@@ -43539,6 +47036,10 @@ var ts;
}
}
}
+ if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit &&
+ !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) {
+ checkESModuleMarker(node.name);
+ }
var checkLetConstNames = (ts.isLet(node) || ts.isConst(node));
// 1. LexicalDeclaration : LetOrConst BindingList ;
// It is a Syntax Error if the BoundNames of BindingList contains "let".
@@ -43548,6 +47049,22 @@ var ts;
// and its Identifier is eval or arguments
return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
}
+ function checkESModuleMarker(name) {
+ if (name.kind === 70 /* Identifier */) {
+ if (ts.unescapeIdentifier(name.text) === "__esModule") {
+ return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
+ }
+ }
+ else {
+ var elements = name.elements;
+ for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
+ var element = elements_2[_i];
+ if (!ts.isOmittedExpression(element)) {
+ return checkESModuleMarker(element.name);
+ }
+ }
+ }
+ }
function checkGrammarNameInLetOrConstDeclarations(name) {
if (name.kind === 70 /* Identifier */) {
if (name.originalKeywordKind === 109 /* LetKeyword */) {
@@ -43556,8 +47073,8 @@ var ts;
}
else {
var elements = name.elements;
- for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
- var element = elements_2[_i];
+ for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
+ var element = elements_3[_i];
if (!ts.isOmittedExpression(element)) {
checkGrammarNameInLetOrConstDeclarations(element.name);
}
@@ -43575,15 +47092,15 @@ var ts;
}
function allowLetAndConstDeclarations(parent) {
switch (parent.kind) {
- case 208 /* IfStatement */:
- case 209 /* DoStatement */:
- case 210 /* WhileStatement */:
- case 217 /* WithStatement */:
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
+ case 210 /* IfStatement */:
+ case 211 /* DoStatement */:
+ case 212 /* WhileStatement */:
+ case 219 /* WithStatement */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
return false;
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
return allowLetAndConstDeclarations(parent.parent);
}
return true;
@@ -43598,6 +47115,13 @@ var ts;
}
}
}
+ function checkGrammarMetaProperty(node) {
+ if (node.keywordToken === 93 /* NewKeyword */) {
+ if (node.name.text !== "target") {
+ return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.text, ts.tokenToString(node.keywordToken), "target");
+ }
+ }
+ }
function hasParseDiagnostics(sourceFile) {
return sourceFile.parseDiagnostics.length > 0;
}
@@ -43638,7 +47162,7 @@ var ts;
return true;
}
}
- else if (node.parent.kind === 227 /* InterfaceDeclaration */) {
+ else if (node.parent.kind === 229 /* InterfaceDeclaration */) {
if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) {
return true;
}
@@ -43646,7 +47170,7 @@ var ts;
return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
}
}
- else if (node.parent.kind === 161 /* TypeLiteral */) {
+ else if (node.parent.kind === 162 /* TypeLiteral */) {
if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) {
return true;
}
@@ -43671,13 +47195,13 @@ var ts;
// export_opt AmbientDeclaration
//
// TODO: The spec needs to be amended to reflect this grammar.
- if (node.kind === 227 /* InterfaceDeclaration */ ||
- node.kind === 228 /* TypeAliasDeclaration */ ||
- node.kind === 235 /* ImportDeclaration */ ||
- node.kind === 234 /* ImportEqualsDeclaration */ ||
- node.kind === 241 /* ExportDeclaration */ ||
- node.kind === 240 /* ExportAssignment */ ||
- node.kind === 233 /* NamespaceExportDeclaration */ ||
+ if (node.kind === 229 /* InterfaceDeclaration */ ||
+ node.kind === 230 /* TypeAliasDeclaration */ ||
+ node.kind === 237 /* ImportDeclaration */ ||
+ node.kind === 236 /* ImportEqualsDeclaration */ ||
+ node.kind === 243 /* ExportDeclaration */ ||
+ node.kind === 242 /* ExportAssignment */ ||
+ node.kind === 235 /* NamespaceExportDeclaration */ ||
ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
return false;
}
@@ -43686,7 +47210,7 @@ var ts;
function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
var decl = _a[_i];
- if (ts.isDeclaration(decl) || decl.kind === 205 /* VariableStatement */) {
+ if (ts.isDeclaration(decl) || decl.kind === 207 /* VariableStatement */) {
if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
return true;
}
@@ -43712,7 +47236,7 @@ var ts;
// to prevent noisiness. So use a bit on the block to indicate if
// this has already been reported, and don't report if it has.
//
- if (node.parent.kind === 204 /* Block */ || node.parent.kind === 231 /* ModuleBlock */ || node.parent.kind === 261 /* SourceFile */) {
+ if (node.parent.kind === 206 /* Block */ || node.parent.kind === 233 /* ModuleBlock */ || node.parent.kind === 264 /* SourceFile */) {
var links_1 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_1.hasReportedStatementInAmbientContext) {
@@ -43720,13 +47244,30 @@ var ts;
}
}
else {
+ // We must be parented by a statement. If so, there's no need
+ // to report the error as our parent will have already done it.
+ // Debug.assert(isStatement(node.parent));
}
}
}
function checkGrammarNumericLiteral(node) {
// Grammar checking
- if (node.isOctalLiteral && languageVersion >= 1 /* ES5 */) {
- return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher);
+ if (node.numericLiteralFlags & 4 /* Octal */) {
+ var diagnosticMessage = void 0;
+ if (languageVersion >= 1 /* ES5 */) {
+ diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
+ }
+ else if (ts.isChildOfNodeWithKind(node, 172 /* LiteralType */)) {
+ diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
+ }
+ else if (ts.isChildOfNodeWithKind(node, 263 /* EnumMember */)) {
+ diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
+ }
+ if (diagnosticMessage) {
+ var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 37 /* MinusToken */;
+ var literal = (withMinus ? "-" : "") + "0o" + node.text;
+ return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
+ }
}
}
function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
@@ -43739,11 +47280,11 @@ var ts;
}
function getAmbientModules() {
var result = [];
- for (var sym in globals) {
+ globals.forEach(function (global, sym) {
if (ambientModuleSymbolRegex.test(sym)) {
- result.push(globals[sym]);
+ result.push(global);
}
- }
+ });
return result;
}
}
@@ -43752,73 +47293,408 @@ var ts;
/// <reference path="checker.ts" />
/// <reference path="factory.ts" />
/// <reference path="utilities.ts" />
-/* @internal */
var ts;
(function (ts) {
- ;
+ function visitNode(node, visitor, test, lift) {
+ if (node === undefined || visitor === undefined) {
+ return node;
+ }
+ ts.aggregateTransformFlags(node);
+ var visited = visitor(node);
+ if (visited === node) {
+ return node;
+ }
+ var visitedNode;
+ if (visited === undefined) {
+ return undefined;
+ }
+ else if (ts.isArray(visited)) {
+ visitedNode = (lift || extractSingleNode)(visited);
+ }
+ else {
+ visitedNode = visited;
+ }
+ ts.Debug.assertNode(visitedNode, test);
+ ts.aggregateTransformFlags(visitedNode);
+ return visitedNode;
+ }
+ ts.visitNode = visitNode;
/**
- * This map contains information about the shape of each Node in "types.ts" pertaining to how
- * each node should be traversed during a transformation.
+ * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
*
- * Each edge corresponds to a property in a Node subtype that should be traversed when visiting
- * each child. The properties are assigned in the order in which traversal should occur.
- *
- * We only add entries for nodes that do not have a create/update pair defined in factory.ts
+ * @param nodes The NodeArray to visit.
+ * @param visitor The callback used to visit a Node.
+ * @param test A node test to execute for each node.
+ * @param start An optional value indicating the starting offset at which to start visiting.
+ * @param count An optional value indicating the maximum number of nodes to visit.
+ */
+ function visitNodes(nodes, visitor, test, start, count) {
+ if (nodes === undefined || visitor === undefined) {
+ return nodes;
+ }
+ var updated;
+ // Ensure start and count have valid values
+ var length = nodes.length;
+ if (start === undefined || start < 0) {
+ start = 0;
+ }
+ if (count === undefined || count > length - start) {
+ count = length - start;
+ }
+ if (start > 0 || count < length) {
+ // If we are not visiting all of the original nodes, we must always create a new array.
+ // Since this is a fragment of a node array, we do not copy over the previous location
+ // and will only copy over `hasTrailingComma` if we are including the last element.
+ updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
+ }
+ // Visit each original node.
+ for (var i = 0; i < count; i++) {
+ var node = nodes[i + start];
+ ts.aggregateTransformFlags(node);
+ var visited = node !== undefined ? visitor(node) : undefined;
+ if (updated !== undefined || visited === undefined || visited !== node) {
+ if (updated === undefined) {
+ // Ensure we have a copy of `nodes`, up to the current index.
+ updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
+ ts.setTextRange(updated, nodes);
+ }
+ if (visited) {
+ if (ts.isArray(visited)) {
+ for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
+ var visitedNode = visited_1[_i];
+ ts.Debug.assertNode(visitedNode, test);
+ ts.aggregateTransformFlags(visitedNode);
+ updated.push(visitedNode);
+ }
+ }
+ else {
+ ts.Debug.assertNode(visited, test);
+ ts.aggregateTransformFlags(visited);
+ updated.push(visited);
+ }
+ }
+ }
+ }
+ return updated || nodes;
+ }
+ ts.visitNodes = visitNodes;
+ /**
+ * Starts a new lexical environment and visits a statement list, ending the lexical environment
+ * and merging hoisted declarations upon completion.
+ */
+ function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
+ context.startLexicalEnvironment();
+ statements = visitNodes(statements, visitor, ts.isStatement, start);
+ if (ensureUseStrict && !ts.startsWithUseStrict(statements)) {
+ statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements);
+ }
+ var declarations = context.endLexicalEnvironment();
+ return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements);
+ }
+ ts.visitLexicalEnvironment = visitLexicalEnvironment;
+ /**
+ * Starts a new lexical environment and visits a parameter list, suspending the lexical
+ * environment upon completion.
+ */
+ function visitParameterList(nodes, visitor, context, nodesVisitor) {
+ if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
+ context.startLexicalEnvironment();
+ var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
+ context.suspendLexicalEnvironment();
+ return updated;
+ }
+ ts.visitParameterList = visitParameterList;
+ function visitFunctionBody(node, visitor, context) {
+ context.resumeLexicalEnvironment();
+ var updated = visitNode(node, visitor, ts.isConciseBody);
+ var declarations = context.endLexicalEnvironment();
+ if (ts.some(declarations)) {
+ var block = ts.convertToFunctionBody(updated);
+ var statements = ts.mergeLexicalEnvironment(block.statements, declarations);
+ return ts.updateBlock(block, statements);
+ }
+ return updated;
+ }
+ ts.visitFunctionBody = visitFunctionBody;
+ function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) {
+ if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
+ if (node === undefined) {
+ return undefined;
+ }
+ var kind = node.kind;
+ // No need to visit nodes with no children.
+ if ((kind > 0 /* FirstToken */ && kind <= 141 /* LastToken */) || kind === 168 /* ThisType */) {
+ return node;
+ }
+ switch (node.kind) {
+ case 205 /* SemicolonClassElement */:
+ case 208 /* EmptyStatement */:
+ case 199 /* OmittedExpression */:
+ case 224 /* DebuggerStatement */:
+ case 297 /* EndOfDeclarationMarker */:
+ case 246 /* MissingDeclaration */:
+ // No need to visit nodes with no children.
+ return node;
+ // Names
+ case 142 /* QualifiedName */:
+ return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier));
+ case 143 /* ComputedPropertyName */:
+ return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
+ // Signatures and Signature Elements
+ case 159 /* FunctionType */:
+ return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode));
+ case 160 /* ConstructorType */:
+ return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode));
+ case 154 /* CallSignature */:
+ return ts.updateCallSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode));
+ case 155 /* ConstructSignature */:
+ return ts.updateConstructSignatureDeclaration(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode));
+ case 149 /* MethodSignature */:
+ return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken));
+ case 156 /* IndexSignature */:
+ return ts.updateIndexSignatureDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode));
+ case 145 /* Parameter */:
+ return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
+ case 146 /* Decorator */:
+ return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
+ // Types
+ case 158 /* TypeReference */:
+ return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
+ case 157 /* TypePredicate */:
+ return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode));
+ case 161 /* TypeQuery */:
+ return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName));
+ case 162 /* TypeLiteral */:
+ return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor));
+ case 163 /* ArrayType */:
+ return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode));
+ case 164 /* TupleType */:
+ return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode));
+ case 165 /* UnionType */:
+ case 166 /* IntersectionType */:
+ return ts.updateUnionOrIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
+ case 167 /* ParenthesizedType */:
+ throw ts.Debug.fail("not implemented.");
+ case 169 /* TypeOperator */:
+ return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode));
+ case 170 /* IndexedAccessType */:
+ return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode));
+ case 171 /* MappedType */:
+ return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameter), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode));
+ case 172 /* LiteralType */:
+ return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression));
+ // Type Declarations
+ case 144 /* TypeParameter */:
+ return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode));
+ // Type members
+ case 147 /* PropertySignature */:
+ return ts.updatePropertySignature(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
+ case 148 /* PropertyDeclaration */:
+ return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
+ case 150 /* MethodDeclaration */:
+ return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
+ case 151 /* Constructor */:
+ return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
+ case 152 /* GetAccessor */:
+ return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
+ case 153 /* SetAccessor */:
+ return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
+ // Binding patterns
+ case 173 /* ObjectBindingPattern */:
+ return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
+ case 174 /* ArrayBindingPattern */:
+ return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
+ case 175 /* BindingElement */:
+ return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression));
+ // Expression
+ case 176 /* ArrayLiteralExpression */:
+ return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression));
+ case 177 /* ObjectLiteralExpression */:
+ return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
+ case 178 /* PropertyAccessExpression */:
+ return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier));
+ case 179 /* ElementAccessExpression */:
+ return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
+ case 180 /* CallExpression */:
+ return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
+ case 181 /* NewExpression */:
+ return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
+ case 182 /* TaggedTemplateExpression */:
+ return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
+ case 183 /* TypeAssertionExpression */:
+ return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
+ case 184 /* ParenthesizedExpression */:
+ return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
+ case 185 /* FunctionExpression */:
+ return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
+ case 186 /* ArrowFunction */:
+ return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
+ case 187 /* DeleteExpression */:
+ return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
+ case 188 /* TypeOfExpression */:
+ return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
+ case 189 /* VoidExpression */:
+ return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
+ case 190 /* AwaitExpression */:
+ return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
+ case 193 /* BinaryExpression */:
+ return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression));
+ case 191 /* PrefixUnaryExpression */:
+ return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
+ case 192 /* PostfixUnaryExpression */:
+ return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
+ case 194 /* ConditionalExpression */:
+ return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression));
+ case 195 /* TemplateExpression */:
+ return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
+ case 196 /* YieldExpression */:
+ return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression));
+ case 197 /* SpreadElement */:
+ return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
+ case 198 /* ClassExpression */:
+ return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
+ case 200 /* ExpressionWithTypeArguments */:
+ return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
+ case 201 /* AsExpression */:
+ return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode));
+ case 202 /* NonNullExpression */:
+ return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression));
+ // Misc
+ case 204 /* TemplateSpan */:
+ return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
+ // Element
+ case 206 /* Block */:
+ return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
+ case 207 /* VariableStatement */:
+ return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
+ case 209 /* ExpressionStatement */:
+ return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression));
+ case 210 /* IfStatement */:
+ return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock));
+ case 211 /* DoStatement */:
+ return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
+ case 212 /* WhileStatement */:
+ return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
+ case 213 /* ForStatement */:
+ return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
+ case 214 /* ForInStatement */:
+ return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
+ case 215 /* ForOfStatement */:
+ return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
+ case 216 /* ContinueStatement */:
+ return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier));
+ case 217 /* BreakStatement */:
+ return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier));
+ case 218 /* ReturnStatement */:
+ return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression));
+ case 219 /* WithStatement */:
+ return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
+ case 220 /* SwitchStatement */:
+ return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
+ case 221 /* LabeledStatement */:
+ return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
+ case 222 /* ThrowStatement */:
+ return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
+ case 223 /* TryStatement */:
+ return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock));
+ case 225 /* VariableDeclaration */:
+ return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
+ case 226 /* VariableDeclarationList */:
+ return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
+ case 227 /* FunctionDeclaration */:
+ return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
+ case 228 /* ClassDeclaration */:
+ return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
+ case 231 /* EnumDeclaration */:
+ return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember));
+ case 232 /* ModuleDeclaration */:
+ return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody));
+ case 233 /* ModuleBlock */:
+ return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
+ case 234 /* CaseBlock */:
+ return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
+ case 236 /* ImportEqualsDeclaration */:
+ return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference));
+ case 237 /* ImportDeclaration */:
+ return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression));
+ case 238 /* ImportClause */:
+ return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings));
+ case 239 /* NamespaceImport */:
+ return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
+ case 240 /* NamedImports */:
+ return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
+ case 241 /* ImportSpecifier */:
+ return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
+ case 242 /* ExportAssignment */:
+ return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
+ case 243 /* ExportDeclaration */:
+ return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression));
+ case 244 /* NamedExports */:
+ return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
+ case 245 /* ExportSpecifier */:
+ return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
+ // Module references
+ case 247 /* ExternalModuleReference */:
+ return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression));
+ // JSX
+ case 248 /* JsxElement */:
+ return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
+ case 253 /* JsxAttributes */:
+ return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
+ case 249 /* JsxSelfClosingElement */:
+ return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes));
+ case 250 /* JsxOpeningElement */:
+ return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes));
+ case 251 /* JsxClosingElement */:
+ return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
+ case 252 /* JsxAttribute */:
+ return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
+ case 254 /* JsxSpreadAttribute */:
+ return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
+ case 255 /* JsxExpression */:
+ return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
+ // Clauses
+ case 256 /* CaseClause */:
+ return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
+ case 257 /* DefaultClause */:
+ return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
+ case 258 /* HeritageClause */:
+ return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
+ case 259 /* CatchClause */:
+ return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
+ // Property assignments
+ case 260 /* PropertyAssignment */:
+ return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
+ case 261 /* ShorthandPropertyAssignment */:
+ return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
+ case 262 /* SpreadAssignment */:
+ return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
+ // Enum
+ case 263 /* EnumMember */:
+ return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
+ // Top-level nodes
+ case 264 /* SourceFile */:
+ return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
+ // Transformation nodes
+ case 295 /* PartiallyEmittedExpression */:
+ return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
+ default:
+ return node;
+ }
+ }
+ ts.visitEachChild = visitEachChild;
+ /**
+ * Extracts the single node from a NodeArray.
*
- * NOTE: This needs to be kept up to date with changes to nodes in "types.ts". Currently, this
- * map is not comprehensive. Only node edges relevant to tree transformation are
- * currently defined. We may extend this to be more comprehensive, and eventually
- * supplant the existing `forEachChild` implementation if performance is not
- * significantly impacted.
+ * @param nodes The NodeArray.
*/
- var nodeEdgeTraversalMap = ts.createMap((_a = {},
- _a[141 /* QualifiedName */] = [
- { name: "left", test: ts.isEntityName },
- { name: "right", test: ts.isIdentifier }
- ],
- _a[145 /* Decorator */] = [
- { name: "expression", test: ts.isLeftHandSideExpression }
- ],
- _a[182 /* TypeAssertionExpression */] = [
- { name: "type", test: ts.isTypeNode },
- { name: "expression", test: ts.isUnaryExpression }
- ],
- _a[200 /* AsExpression */] = [
- { name: "expression", test: ts.isExpression },
- { name: "type", test: ts.isTypeNode }
- ],
- _a[201 /* NonNullExpression */] = [
- { name: "expression", test: ts.isLeftHandSideExpression }
- ],
- _a[229 /* EnumDeclaration */] = [
- { name: "decorators", test: ts.isDecorator },
- { name: "modifiers", test: ts.isModifier },
- { name: "name", test: ts.isIdentifier },
- { name: "members", test: ts.isEnumMember }
- ],
- _a[230 /* ModuleDeclaration */] = [
- { name: "decorators", test: ts.isDecorator },
- { name: "modifiers", test: ts.isModifier },
- { name: "name", test: ts.isModuleName },
- { name: "body", test: ts.isModuleBody }
- ],
- _a[231 /* ModuleBlock */] = [
- { name: "statements", test: ts.isStatement }
- ],
- _a[234 /* ImportEqualsDeclaration */] = [
- { name: "decorators", test: ts.isDecorator },
- { name: "modifiers", test: ts.isModifier },
- { name: "name", test: ts.isIdentifier },
- { name: "moduleReference", test: ts.isModuleReference }
- ],
- _a[245 /* ExternalModuleReference */] = [
- { name: "expression", test: ts.isExpression, optional: true }
- ],
- _a[260 /* EnumMember */] = [
- { name: "name", test: ts.isPropertyName },
- { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList }
- ],
- _a));
+ function extractSingleNode(nodes) {
+ ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
+ return ts.singleOrUndefined(nodes);
+ }
+})(ts || (ts = {}));
+/* @internal */
+(function (ts) {
function reduceNode(node, f, initial) {
return node ? f(initial, node) : initial;
}
@@ -43827,8 +47703,7 @@ var ts;
}
/**
* Similar to `reduceLeft`, performs a reduction against each child of a node.
- * NOTE: Unlike `forEachChild`, this does *not* visit every node. Only nodes added to the
- * `nodeEdgeTraversalMap` above will be visited.
+ * NOTE: Unlike `forEachChild`, this does *not* visit every node.
*
* @param node The node containing the children to reduce.
* @param initial The initial value to supply to the reduction.
@@ -43842,47 +47717,51 @@ var ts;
var cbNodes = cbNodeArray || cbNode;
var kind = node.kind;
// No need to visit nodes with no children.
- if ((kind > 0 /* FirstToken */ && kind <= 140 /* LastToken */)) {
+ if ((kind > 0 /* FirstToken */ && kind <= 141 /* LastToken */)) {
return initial;
}
// We do not yet support types.
- if ((kind >= 156 /* TypePredicate */ && kind <= 171 /* LiteralType */)) {
+ if ((kind >= 157 /* TypePredicate */ && kind <= 172 /* LiteralType */)) {
return initial;
}
var result = initial;
switch (node.kind) {
// Leaf nodes
- case 203 /* SemicolonClassElement */:
- case 206 /* EmptyStatement */:
- case 198 /* OmittedExpression */:
- case 222 /* DebuggerStatement */:
- case 293 /* NotEmittedStatement */:
+ case 205 /* SemicolonClassElement */:
+ case 208 /* EmptyStatement */:
+ case 199 /* OmittedExpression */:
+ case 224 /* DebuggerStatement */:
+ case 294 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
- case 142 /* ComputedPropertyName */:
+ case 142 /* QualifiedName */:
+ result = reduceNode(node.left, cbNode, result);
+ result = reduceNode(node.right, cbNode, result);
+ break;
+ case 143 /* ComputedPropertyName */:
result = reduceNode(node.expression, cbNode, result);
break;
// Signature elements
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.initializer, cbNode, result);
break;
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
result = reduceNode(node.expression, cbNode, result);
break;
// Type member
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.initializer, cbNode, result);
break;
- case 149 /* MethodDeclaration */:
+ case 150 /* MethodDeclaration */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
@@ -43891,12 +47770,12 @@ var ts;
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.body, cbNode, result);
break;
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNodes(node.parameters, cbNodes, result);
result = reduceNode(node.body, cbNode, result);
break;
- case 151 /* GetAccessor */:
+ case 152 /* GetAccessor */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
@@ -43904,7 +47783,7 @@ var ts;
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.body, cbNode, result);
break;
- case 152 /* SetAccessor */:
+ case 153 /* SetAccessor */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
@@ -43912,45 +47791,49 @@ var ts;
result = reduceNode(node.body, cbNode, result);
break;
// Binding patterns
- case 172 /* ObjectBindingPattern */:
- case 173 /* ArrayBindingPattern */:
+ case 173 /* ObjectBindingPattern */:
+ case 174 /* ArrayBindingPattern */:
result = reduceNodes(node.elements, cbNodes, result);
break;
- case 174 /* BindingElement */:
+ case 175 /* BindingElement */:
result = reduceNode(node.propertyName, cbNode, result);
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.initializer, cbNode, result);
break;
// Expression
- case 175 /* ArrayLiteralExpression */:
+ case 176 /* ArrayLiteralExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
result = reduceNodes(node.properties, cbNodes, result);
break;
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
result = reduceNode(node.expression, cbNode, result);
result = reduceNode(node.name, cbNode, result);
break;
- case 178 /* ElementAccessExpression */:
+ case 179 /* ElementAccessExpression */:
result = reduceNode(node.expression, cbNode, result);
result = reduceNode(node.argumentExpression, cbNode, result);
break;
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
result = reduceNode(node.expression, cbNode, result);
result = reduceNodes(node.typeArguments, cbNodes, result);
result = reduceNodes(node.arguments, cbNodes, result);
break;
- case 180 /* NewExpression */:
+ case 181 /* NewExpression */:
result = reduceNode(node.expression, cbNode, result);
result = reduceNodes(node.typeArguments, cbNodes, result);
result = reduceNodes(node.arguments, cbNodes, result);
break;
- case 181 /* TaggedTemplateExpression */:
+ case 182 /* TaggedTemplateExpression */:
result = reduceNode(node.tag, cbNode, result);
result = reduceNode(node.template, cbNode, result);
break;
- case 184 /* FunctionExpression */:
+ case 183 /* TypeAssertionExpression */:
+ result = reduceNode(node.type, cbNode, result);
+ result = reduceNode(node.expression, cbNode, result);
+ break;
+ case 185 /* FunctionExpression */:
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
result = reduceNodes(node.typeParameters, cbNodes, result);
@@ -43958,119 +47841,126 @@ var ts;
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.body, cbNode, result);
break;
- case 185 /* ArrowFunction */:
+ case 186 /* ArrowFunction */:
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNodes(node.typeParameters, cbNodes, result);
result = reduceNodes(node.parameters, cbNodes, result);
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.body, cbNode, result);
break;
- case 183 /* ParenthesizedExpression */:
- case 186 /* DeleteExpression */:
- case 187 /* TypeOfExpression */:
- case 188 /* VoidExpression */:
- case 189 /* AwaitExpression */:
- case 195 /* YieldExpression */:
- case 196 /* SpreadElement */:
- case 201 /* NonNullExpression */:
+ case 184 /* ParenthesizedExpression */:
+ case 187 /* DeleteExpression */:
+ case 188 /* TypeOfExpression */:
+ case 189 /* VoidExpression */:
+ case 190 /* AwaitExpression */:
+ case 196 /* YieldExpression */:
+ case 197 /* SpreadElement */:
+ case 202 /* NonNullExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 190 /* PrefixUnaryExpression */:
- case 191 /* PostfixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
result = reduceNode(node.operand, cbNode, result);
break;
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
result = reduceNode(node.left, cbNode, result);
result = reduceNode(node.right, cbNode, result);
break;
- case 193 /* ConditionalExpression */:
+ case 194 /* ConditionalExpression */:
result = reduceNode(node.condition, cbNode, result);
result = reduceNode(node.whenTrue, cbNode, result);
result = reduceNode(node.whenFalse, cbNode, result);
break;
- case 194 /* TemplateExpression */:
+ case 195 /* TemplateExpression */:
result = reduceNode(node.head, cbNode, result);
result = reduceNodes(node.templateSpans, cbNodes, result);
break;
- case 197 /* ClassExpression */:
+ case 198 /* ClassExpression */:
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
result = reduceNodes(node.typeParameters, cbNodes, result);
result = reduceNodes(node.heritageClauses, cbNodes, result);
result = reduceNodes(node.members, cbNodes, result);
break;
- case 199 /* ExpressionWithTypeArguments */:
+ case 200 /* ExpressionWithTypeArguments */:
result = reduceNode(node.expression, cbNode, result);
result = reduceNodes(node.typeArguments, cbNodes, result);
break;
+ case 201 /* AsExpression */:
+ result = reduceNode(node.expression, cbNode, result);
+ result = reduceNode(node.type, cbNode, result);
+ break;
+ case 202 /* NonNullExpression */:
+ result = reduceNode(node.expression, cbNode, result);
+ break;
// Misc
- case 202 /* TemplateSpan */:
+ case 204 /* TemplateSpan */:
result = reduceNode(node.expression, cbNode, result);
result = reduceNode(node.literal, cbNode, result);
break;
// Element
- case 204 /* Block */:
+ case 206 /* Block */:
result = reduceNodes(node.statements, cbNodes, result);
break;
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.declarationList, cbNode, result);
break;
- case 207 /* ExpressionStatement */:
+ case 209 /* ExpressionStatement */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 208 /* IfStatement */:
+ case 210 /* IfStatement */:
result = reduceNode(node.expression, cbNode, result);
result = reduceNode(node.thenStatement, cbNode, result);
result = reduceNode(node.elseStatement, cbNode, result);
break;
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
result = reduceNode(node.statement, cbNode, result);
result = reduceNode(node.expression, cbNode, result);
break;
- case 210 /* WhileStatement */:
- case 217 /* WithStatement */:
+ case 212 /* WhileStatement */:
+ case 219 /* WithStatement */:
result = reduceNode(node.expression, cbNode, result);
result = reduceNode(node.statement, cbNode, result);
break;
- case 211 /* ForStatement */:
+ case 213 /* ForStatement */:
result = reduceNode(node.initializer, cbNode, result);
result = reduceNode(node.condition, cbNode, result);
result = reduceNode(node.incrementor, cbNode, result);
result = reduceNode(node.statement, cbNode, result);
break;
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
result = reduceNode(node.initializer, cbNode, result);
result = reduceNode(node.expression, cbNode, result);
result = reduceNode(node.statement, cbNode, result);
break;
- case 216 /* ReturnStatement */:
- case 220 /* ThrowStatement */:
+ case 218 /* ReturnStatement */:
+ case 222 /* ThrowStatement */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 218 /* SwitchStatement */:
+ case 220 /* SwitchStatement */:
result = reduceNode(node.expression, cbNode, result);
result = reduceNode(node.caseBlock, cbNode, result);
break;
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
result = reduceNode(node.label, cbNode, result);
result = reduceNode(node.statement, cbNode, result);
break;
- case 221 /* TryStatement */:
+ case 223 /* TryStatement */:
result = reduceNode(node.tryBlock, cbNode, result);
result = reduceNode(node.catchClause, cbNode, result);
result = reduceNode(node.finallyBlock, cbNode, result);
break;
- case 223 /* VariableDeclaration */:
+ case 225 /* VariableDeclaration */:
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.initializer, cbNode, result);
break;
- case 224 /* VariableDeclarationList */:
+ case 226 /* VariableDeclarationList */:
result = reduceNodes(node.declarations, cbNodes, result);
break;
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
@@ -44079,7 +47969,7 @@ var ts;
result = reduceNode(node.type, cbNode, result);
result = reduceNode(node.body, cbNode, result);
break;
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.name, cbNode, result);
@@ -44087,484 +47977,148 @@ var ts;
result = reduceNodes(node.heritageClauses, cbNodes, result);
result = reduceNodes(node.members, cbNodes, result);
break;
- case 232 /* CaseBlock */:
+ case 231 /* EnumDeclaration */:
+ result = reduceNodes(node.decorators, cbNodes, result);
+ result = reduceNodes(node.modifiers, cbNodes, result);
+ result = reduceNode(node.name, cbNode, result);
+ result = reduceNodes(node.members, cbNodes, result);
+ break;
+ case 232 /* ModuleDeclaration */:
+ result = reduceNodes(node.decorators, cbNodes, result);
+ result = reduceNodes(node.modifiers, cbNodes, result);
+ result = reduceNode(node.name, cbNode, result);
+ result = reduceNode(node.body, cbNode, result);
+ break;
+ case 233 /* ModuleBlock */:
+ result = reduceNodes(node.statements, cbNodes, result);
+ break;
+ case 234 /* CaseBlock */:
result = reduceNodes(node.clauses, cbNodes, result);
break;
- case 235 /* ImportDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
+ result = reduceNodes(node.decorators, cbNodes, result);
+ result = reduceNodes(node.modifiers, cbNodes, result);
+ result = reduceNode(node.name, cbNode, result);
+ result = reduceNode(node.moduleReference, cbNode, result);
+ break;
+ case 237 /* ImportDeclaration */:
result = reduceNodes(node.decorators, cbNodes, result);
result = reduceNodes(node.modifiers, cbNodes, result);
result = reduceNode(node.importClause, cbNode, result);
result = reduceNode(node.moduleSpecifier, cbNode, result);
break;
- case 236 /* ImportClause */:
+ case 238 /* ImportClause */:
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.namedBindings, cbNode, result);
break;
- case 237 /* NamespaceImport */:
+ case 239 /* NamespaceImport */:
result = reduceNode(node.name, cbNode, result);
break;
- case 238 /* NamedImports */:
- case 242 /* NamedExports */:
+ case 240 /* NamedImports */:
+ case 244 /* NamedExports */:
result = reduceNodes(node.elements, cbNodes, result);
break;
- case 239 /* ImportSpecifier */:
- case 243 /* ExportSpecifier */:
+ case 241 /* ImportSpecifier */:
+ case 245 /* ExportSpecifier */:
result = reduceNode(node.propertyName, cbNode, result);
result = reduceNode(node.name, cbNode, result);
break;
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
result = ts.reduceLeft(node.decorators, cbNode, result);
result = ts.reduceLeft(node.modifiers, cbNode, result);
result = reduceNode(node.expression, cbNode, result);
break;
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
result = ts.reduceLeft(node.decorators, cbNode, result);
result = ts.reduceLeft(node.modifiers, cbNode, result);
result = reduceNode(node.exportClause, cbNode, result);
result = reduceNode(node.moduleSpecifier, cbNode, result);
break;
+ // Module references
+ case 247 /* ExternalModuleReference */:
+ result = reduceNode(node.expression, cbNode, result);
+ break;
// JSX
- case 246 /* JsxElement */:
+ case 248 /* JsxElement */:
result = reduceNode(node.openingElement, cbNode, result);
result = ts.reduceLeft(node.children, cbNode, result);
result = reduceNode(node.closingElement, cbNode, result);
break;
- case 247 /* JsxSelfClosingElement */:
- case 248 /* JsxOpeningElement */:
+ case 249 /* JsxSelfClosingElement */:
+ case 250 /* JsxOpeningElement */:
result = reduceNode(node.tagName, cbNode, result);
- result = reduceNodes(node.attributes, cbNodes, result);
+ result = reduceNode(node.attributes, cbNode, result);
+ break;
+ case 253 /* JsxAttributes */:
+ result = reduceNodes(node.properties, cbNodes, result);
break;
- case 249 /* JsxClosingElement */:
+ case 251 /* JsxClosingElement */:
result = reduceNode(node.tagName, cbNode, result);
break;
- case 250 /* JsxAttribute */:
+ case 252 /* JsxAttribute */:
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.initializer, cbNode, result);
break;
- case 251 /* JsxSpreadAttribute */:
+ case 254 /* JsxSpreadAttribute */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 252 /* JsxExpression */:
+ case 255 /* JsxExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
// Clauses
- case 253 /* CaseClause */:
+ case 256 /* CaseClause */:
result = reduceNode(node.expression, cbNode, result);
- // fall-through
- case 254 /* DefaultClause */:
+ // falls through
+ case 257 /* DefaultClause */:
result = reduceNodes(node.statements, cbNodes, result);
break;
- case 255 /* HeritageClause */:
+ case 258 /* HeritageClause */:
result = reduceNodes(node.types, cbNodes, result);
break;
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
result = reduceNode(node.variableDeclaration, cbNode, result);
result = reduceNode(node.block, cbNode, result);
break;
// Property assignments
- case 257 /* PropertyAssignment */:
+ case 260 /* PropertyAssignment */:
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.initializer, cbNode, result);
break;
- case 258 /* ShorthandPropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.objectAssignmentInitializer, cbNode, result);
break;
- case 259 /* SpreadAssignment */:
+ case 262 /* SpreadAssignment */:
result = reduceNode(node.expression, cbNode, result);
break;
+ // Enum
+ case 263 /* EnumMember */:
+ result = reduceNode(node.name, cbNode, result);
+ result = reduceNode(node.initializer, cbNode, result);
+ break;
// Top-level nodes
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
- case 294 /* PartiallyEmittedExpression */:
+ // Transformation nodes
+ case 295 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
default:
- var edgeTraversalPath = nodeEdgeTraversalMap[kind];
- if (edgeTraversalPath) {
- for (var _i = 0, edgeTraversalPath_1 = edgeTraversalPath; _i < edgeTraversalPath_1.length; _i++) {
- var edge = edgeTraversalPath_1[_i];
- var value = node[edge.name];
- if (value !== undefined) {
- result = ts.isArray(value)
- ? reduceNodes(value, cbNodes, result)
- : cbNode(result, value);
- }
- }
- }
break;
}
return result;
}
ts.reduceEachChild = reduceEachChild;
- function visitNode(node, visitor, test, optional, lift, parenthesize, parentNode) {
- if (node === undefined || visitor === undefined) {
- return node;
- }
- aggregateTransformFlags(node);
- var visited = visitor(node);
- if (visited === node) {
- return node;
- }
- var visitedNode;
- if (visited === undefined) {
- if (!optional) {
- Debug.failNotOptional();
- }
- return undefined;
- }
- else if (ts.isArray(visited)) {
- visitedNode = (lift || extractSingleNode)(visited);
- }
- else {
- visitedNode = visited;
- }
- if (parenthesize !== undefined) {
- visitedNode = parenthesize(visitedNode, parentNode);
- }
- Debug.assertNode(visitedNode, test);
- aggregateTransformFlags(visitedNode);
- return visitedNode;
- }
- ts.visitNode = visitNode;
- function visitNodes(nodes, visitor, test, start, count, parenthesize, parentNode) {
- if (nodes === undefined) {
- return undefined;
- }
- var updated;
- // Ensure start and count have valid values
- var length = nodes.length;
- if (start === undefined || start < 0) {
- start = 0;
- }
- if (count === undefined || count > length - start) {
- count = length - start;
- }
- if (start > 0 || count < length) {
- // If we are not visiting all of the original nodes, we must always create a new array.
- // Since this is a fragment of a node array, we do not copy over the previous location
- // and will only copy over `hasTrailingComma` if we are including the last element.
- updated = ts.createNodeArray([], /*location*/ undefined,
- /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
- }
- // Visit each original node.
- for (var i = 0; i < count; i++) {
- var node = nodes[i + start];
- aggregateTransformFlags(node);
- var visited = node !== undefined ? visitor(node) : undefined;
- if (updated !== undefined || visited === undefined || visited !== node) {
- if (updated === undefined) {
- // Ensure we have a copy of `nodes`, up to the current index.
- updated = ts.createNodeArray(nodes.slice(0, i), /*location*/ nodes, nodes.hasTrailingComma);
- }
- if (visited) {
- if (ts.isArray(visited)) {
- for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
- var visitedNode = visited_1[_i];
- visitedNode = parenthesize
- ? parenthesize(visitedNode, parentNode)
- : visitedNode;
- Debug.assertNode(visitedNode, test);
- aggregateTransformFlags(visitedNode);
- updated.push(visitedNode);
- }
- }
- else {
- var visitedNode = parenthesize
- ? parenthesize(visited, parentNode)
- : visited;
- Debug.assertNode(visitedNode, test);
- aggregateTransformFlags(visitedNode);
- updated.push(visitedNode);
- }
- }
- }
- }
- return updated || nodes;
- }
- ts.visitNodes = visitNodes;
- /**
- * Starts a new lexical environment and visits a statement list, ending the lexical environment
- * and merging hoisted declarations upon completion.
- */
- function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
- context.startLexicalEnvironment();
- statements = visitNodes(statements, visitor, ts.isStatement, start);
- if (ensureUseStrict && !ts.startsWithUseStrict(statements)) {
- statements = ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements), statements);
- }
- var declarations = context.endLexicalEnvironment();
- return ts.createNodeArray(ts.concatenate(statements, declarations), statements);
- }
- ts.visitLexicalEnvironment = visitLexicalEnvironment;
- /**
- * Starts a new lexical environment and visits a parameter list, suspending the lexical
- * environment upon completion.
- */
- function visitParameterList(nodes, visitor, context) {
- context.startLexicalEnvironment();
- var updated = visitNodes(nodes, visitor, ts.isParameterDeclaration);
- context.suspendLexicalEnvironment();
- return updated;
- }
- ts.visitParameterList = visitParameterList;
- function visitFunctionBody(node, visitor, context) {
- context.resumeLexicalEnvironment();
- var updated = visitNode(node, visitor, ts.isConciseBody);
- var declarations = context.endLexicalEnvironment();
- if (ts.some(declarations)) {
- var block = ts.convertToFunctionBody(updated);
- var statements = mergeLexicalEnvironment(block.statements, declarations);
- return ts.updateBlock(block, statements);
- }
- return updated;
- }
- ts.visitFunctionBody = visitFunctionBody;
- function visitEachChild(node, visitor, context) {
- if (node === undefined) {
- return undefined;
- }
- var kind = node.kind;
- // No need to visit nodes with no children.
- if ((kind > 0 /* FirstToken */ && kind <= 140 /* LastToken */)) {
- return node;
- }
- // We do not yet support types.
- if ((kind >= 156 /* TypePredicate */ && kind <= 171 /* LiteralType */)) {
- return node;
- }
- switch (node.kind) {
- case 203 /* SemicolonClassElement */:
- case 206 /* EmptyStatement */:
- case 198 /* OmittedExpression */:
- case 222 /* DebuggerStatement */:
- // No need to visit nodes with no children.
- return node;
- // Names
- case 142 /* ComputedPropertyName */:
- return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
- // Signature elements
- case 144 /* Parameter */:
- return ts.updateParameter(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), node.dotDotDotToken, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true));
- // Type member
- case 147 /* PropertyDeclaration */:
- return ts.updateProperty(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true));
- case 149 /* MethodDeclaration */:
- return ts.updateMethod(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context));
- case 150 /* Constructor */:
- return ts.updateConstructor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context));
- case 151 /* GetAccessor */:
- return ts.updateGetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context));
- case 152 /* SetAccessor */:
- return ts.updateSetAccessor(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context), visitFunctionBody(node.body, visitor, context));
- // Binding patterns
- case 172 /* ObjectBindingPattern */:
- return ts.updateObjectBindingPattern(node, visitNodes(node.elements, visitor, ts.isBindingElement));
- case 173 /* ArrayBindingPattern */:
- return ts.updateArrayBindingPattern(node, visitNodes(node.elements, visitor, ts.isArrayBindingElement));
- case 174 /* BindingElement */:
- return ts.updateBindingElement(node, node.dotDotDotToken, visitNode(node.propertyName, visitor, ts.isPropertyName, /*optional*/ true), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true));
- // Expression
- case 175 /* ArrayLiteralExpression */:
- return ts.updateArrayLiteral(node, visitNodes(node.elements, visitor, ts.isExpression));
- case 176 /* ObjectLiteralExpression */:
- return ts.updateObjectLiteral(node, visitNodes(node.properties, visitor, ts.isObjectLiteralElementLike));
- case 177 /* PropertyAccessExpression */:
- return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier));
- case 178 /* ElementAccessExpression */:
- return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
- case 179 /* CallExpression */:
- return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression));
- case 180 /* NewExpression */:
- return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression));
- case 181 /* TaggedTemplateExpression */:
- return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
- case 183 /* ParenthesizedExpression */:
- return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
- case 184 /* FunctionExpression */:
- return ts.updateFunctionExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context));
- case 185 /* ArrowFunction */:
- return ts.updateArrowFunction(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context));
- case 186 /* DeleteExpression */:
- return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
- case 187 /* TypeOfExpression */:
- return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
- case 188 /* VoidExpression */:
- return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
- case 189 /* AwaitExpression */:
- return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
- case 192 /* BinaryExpression */:
- return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression));
- case 190 /* PrefixUnaryExpression */:
- return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
- case 191 /* PostfixUnaryExpression */:
- return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
- case 193 /* ConditionalExpression */:
- return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression));
- case 194 /* TemplateExpression */:
- return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan));
- case 195 /* YieldExpression */:
- return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression));
- case 196 /* SpreadElement */:
- return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
- case 197 /* ClassExpression */:
- return ts.updateClassExpression(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement));
- case 199 /* ExpressionWithTypeArguments */:
- return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
- // Misc
- case 202 /* TemplateSpan */:
- return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
- // Element
- case 204 /* Block */:
- return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement));
- case 205 /* VariableStatement */:
- return ts.updateVariableStatement(node, visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
- case 207 /* ExpressionStatement */:
- return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression));
- case 208 /* IfStatement */:
- return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, /*optional*/ false, liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, /*optional*/ true, liftToBlock));
- case 209 /* DoStatement */:
- return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
- case 210 /* WhileStatement */:
- return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock));
- case 211 /* ForStatement */:
- return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock));
- case 212 /* ForInStatement */:
- return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock));
- case 213 /* ForOfStatement */:
- return ts.updateForOf(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock));
- case 214 /* ContinueStatement */:
- return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier, /*optional*/ true));
- case 215 /* BreakStatement */:
- return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier, /*optional*/ true));
- case 216 /* ReturnStatement */:
- return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true));
- case 217 /* WithStatement */:
- return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock));
- case 218 /* SwitchStatement */:
- return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
- case 219 /* LabeledStatement */:
- return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, liftToBlock));
- case 220 /* ThrowStatement */:
- return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
- case 221 /* TryStatement */:
- return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause, /*optional*/ true), visitNode(node.finallyBlock, visitor, ts.isBlock, /*optional*/ true));
- case 223 /* VariableDeclaration */:
- return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitNode(node.initializer, visitor, ts.isExpression, /*optional*/ true));
- case 224 /* VariableDeclarationList */:
- return ts.updateVariableDeclarationList(node, visitNodes(node.declarations, visitor, ts.isVariableDeclaration));
- case 225 /* FunctionDeclaration */:
- return ts.updateFunctionDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context), visitNode(node.type, visitor, ts.isTypeNode, /*optional*/ true), visitFunctionBody(node.body, visitor, context));
- case 226 /* ClassDeclaration */:
- return ts.updateClassDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNodes(node.typeParameters, visitor, ts.isTypeParameter), visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), visitNodes(node.members, visitor, ts.isClassElement));
- case 232 /* CaseBlock */:
- return ts.updateCaseBlock(node, visitNodes(node.clauses, visitor, ts.isCaseOrDefaultClause));
- case 235 /* ImportDeclaration */:
- return ts.updateImportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause, /*optional*/ true), visitNode(node.moduleSpecifier, visitor, ts.isExpression));
- case 236 /* ImportClause */:
- return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings, /*optional*/ true));
- case 237 /* NamespaceImport */:
- return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
- case 238 /* NamedImports */:
- return ts.updateNamedImports(node, visitNodes(node.elements, visitor, ts.isImportSpecifier));
- case 239 /* ImportSpecifier */:
- return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.name, visitor, ts.isIdentifier));
- case 240 /* ExportAssignment */:
- return ts.updateExportAssignment(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
- case 241 /* ExportDeclaration */:
- return ts.updateExportDeclaration(node, visitNodes(node.decorators, visitor, ts.isDecorator), visitNodes(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports, /*optional*/ true), visitNode(node.moduleSpecifier, visitor, ts.isExpression, /*optional*/ true));
- case 242 /* NamedExports */:
- return ts.updateNamedExports(node, visitNodes(node.elements, visitor, ts.isExportSpecifier));
- case 243 /* ExportSpecifier */:
- return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier, /*optional*/ true), visitNode(node.name, visitor, ts.isIdentifier));
- // JSX
- case 246 /* JsxElement */:
- return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), visitNodes(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
- case 247 /* JsxSelfClosingElement */:
- return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike));
- case 248 /* JsxOpeningElement */:
- return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNodes(node.attributes, visitor, ts.isJsxAttributeLike));
- case 249 /* JsxClosingElement */:
- return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
- case 250 /* JsxAttribute */:
- return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
- case 251 /* JsxSpreadAttribute */:
- return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
- case 252 /* JsxExpression */:
- return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- // Clauses
- case 253 /* CaseClause */:
- return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.statements, visitor, ts.isStatement));
- case 254 /* DefaultClause */:
- return ts.updateDefaultClause(node, visitNodes(node.statements, visitor, ts.isStatement));
- case 255 /* HeritageClause */:
- return ts.updateHeritageClause(node, visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments));
- case 256 /* CatchClause */:
- return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
- // Property assignments
- case 257 /* PropertyAssignment */:
- return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
- case 258 /* ShorthandPropertyAssignment */:
- return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
- case 259 /* SpreadAssignment */:
- return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
- // Top-level nodes
- case 261 /* SourceFile */:
- return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
- // Transformation nodes
- case 294 /* PartiallyEmittedExpression */:
- return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- default:
- var updated = void 0;
- var edgeTraversalPath = nodeEdgeTraversalMap[kind];
- if (edgeTraversalPath) {
- for (var _i = 0, edgeTraversalPath_2 = edgeTraversalPath; _i < edgeTraversalPath_2.length; _i++) {
- var edge = edgeTraversalPath_2[_i];
- var value = node[edge.name];
- if (value !== undefined) {
- var visited = ts.isArray(value)
- ? visitNodes(value, visitor, edge.test, 0, value.length, edge.parenthesize, node)
- : visitNode(value, visitor, edge.test, edge.optional, edge.lift, edge.parenthesize, node);
- if (updated !== undefined || visited !== value) {
- if (updated === undefined) {
- updated = ts.getMutableClone(node);
- }
- if (visited !== value) {
- updated[edge.name] = visited;
- }
- }
- }
- }
- }
- return updated ? ts.updateNode(updated, node) : node;
- }
- // return node;
- }
- ts.visitEachChild = visitEachChild;
function mergeLexicalEnvironment(statements, declarations) {
if (!ts.some(declarations)) {
return statements;
}
return ts.isNodeArray(statements)
- ? ts.createNodeArray(ts.concatenate(statements, declarations), statements)
+ ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements)
: ts.addRange(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
- function mergeFunctionBodyLexicalEnvironment(body, declarations) {
- if (body && declarations !== undefined && declarations.length > 0) {
- if (ts.isBlock(body)) {
- return ts.updateBlock(body, ts.createNodeArray(ts.concatenate(body.statements, declarations), body.statements));
- }
- else {
- return ts.createBlock(ts.createNodeArray([ts.createReturn(body, /*location*/ body)].concat(declarations), body),
- /*location*/ body,
- /*multiLine*/ true);
- }
- }
- return body;
- }
- ts.mergeFunctionBodyLexicalEnvironment = mergeFunctionBodyLexicalEnvironment;
/**
* Lifts a NodeArray containing only Statement nodes to a block.
*
@@ -44576,15 +48130,6 @@ var ts;
}
ts.liftToBlock = liftToBlock;
/**
- * Extracts the single node from a NodeArray.
- *
- * @param nodes The NodeArray.
- */
- function extractSingleNode(nodes) {
- Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
- return ts.singleOrUndefined(nodes);
- }
- /**
* Aggregates the TransformFlags for a Node and its subtree.
*/
function aggregateTransformFlags(node) {
@@ -44629,7 +48174,7 @@ var ts;
function aggregateTransformFlagsForSubtree(node) {
// We do not transform ambient declarations or types, so there is no need to
// recursively aggregate transform flags.
- if (ts.hasModifier(node, 2 /* Ambient */) || ts.isTypeNode(node)) {
+ if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 200 /* ExpressionWithTypeArguments */)) {
return 0 /* None */;
}
// Aggregate the transform flags of each child.
@@ -44647,9 +48192,6 @@ var ts;
}
var Debug;
(function (Debug) {
- Debug.failNotOptional = Debug.shouldAssert(1 /* Normal */)
- ? function (message) { return Debug.assert(false, message || "Node not optional."); }
- : ts.noop;
Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */)
? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); }
: ts.noop;
@@ -44682,7 +48224,6 @@ var ts;
}
}
})(Debug = ts.Debug || (ts.Debug = {}));
- var _a;
})(ts || (ts = {}));
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
@@ -44710,7 +48251,7 @@ var ts;
var value;
if (ts.isDestructuringAssignment(node)) {
value = node.right;
- while (ts.isEmptyObjectLiteralOrArrayLiteral(node.left)) {
+ while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
if (ts.isDestructuringAssignment(value)) {
location = node = value;
value = node.right;
@@ -44724,6 +48265,7 @@ var ts;
var flattenContext = {
context: context,
level: level,
+ downlevelIteration: context.getCompilerOptions().downlevelIteration,
hoistTempVariables: true,
emitExpression: emitExpression,
emitBindingOrAssignment: emitBindingOrAssignment,
@@ -44772,7 +48314,7 @@ var ts;
ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
var expression = createAssignmentCallback
? createAssignmentCallback(target, value, location)
- : ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value, location);
+ : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
expression.original = original;
emitExpression(expression);
}
@@ -44796,6 +48338,7 @@ var ts;
var flattenContext = {
context: context,
level: level,
+ downlevelIteration: context.getCompilerOptions().downlevelIteration,
hoistTempVariables: hoistTempVariables,
emitExpression: emitExpression,
emitBindingOrAssignment: emitBindingOrAssignment,
@@ -44821,11 +48364,12 @@ var ts;
}
}
for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
- var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name_29 = _a.name, value = _a.value, location_2 = _a.location, original = _a.original;
- var variable = ts.createVariableDeclaration(name_29,
- /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value, location_2);
+ var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
+ var variable = ts.createVariableDeclaration(name,
+ /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
variable.original = original;
- if (ts.isIdentifier(name_29)) {
+ ts.setTextRange(variable, location);
+ if (ts.isIdentifier(name)) {
ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */);
}
ts.aggregateTransformFlags(variable);
@@ -44947,7 +48491,14 @@ var ts;
function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
var numElements = elements.length;
- if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)) {
+ if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
+ // Read the elements of the iterable into an array
+ value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
+ ? undefined
+ : numElements, location),
+ /*reuseIdentifierExpressions*/ false, location);
+ }
+ else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)) {
// For anything other than a single-element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once. Additionally, if we have zero elements
// we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
@@ -45029,8 +48580,8 @@ var ts;
return ts.createElementAccess(value, argumentExpression);
}
else {
- var name_30 = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text));
- return ts.createPropertyAccess(value, name_30);
+ var name = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text));
+ return ts.createPropertyAccess(value, name);
}
}
/**
@@ -45052,7 +48603,7 @@ var ts;
var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
if (flattenContext.hoistTempVariables) {
flattenContext.context.hoistVariableDeclaration(temp);
- flattenContext.emitExpression(ts.createAssignment(temp, value, location));
+ flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location));
}
else {
flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
@@ -45075,7 +48626,7 @@ var ts;
return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement));
}
function makeBindingElement(name) {
- return ts.createBindingElement(/*propertyName*/ undefined, /*dotDotDotToken*/ undefined, name);
+ return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
}
function makeAssignmentElement(name) {
return name;
@@ -45083,10 +48634,11 @@ var ts;
var restHelper = {
name: "typescript:rest",
scoped: false,
- text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
+ text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
};
/** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
- * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`*/
+ * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
+ */
function createRestCall(context, value, elements, computedTempVariables, location) {
context.requestEmitHelper(restHelper);
var propertyNames = [];
@@ -45105,7 +48657,11 @@ var ts;
}
}
}
- return ts.createCall(ts.getHelperName("__rest"), undefined, [value, ts.createArrayLiteral(propertyNames, location)]);
+ return ts.createCall(ts.getHelperName("__rest"),
+ /*typeArguments*/ undefined, [
+ value,
+ ts.setTextRange(ts.createArrayLiteral(propertyNames), location)
+ ]);
}
})(ts || (ts = {}));
/// <reference path="../factory.ts" />
@@ -45140,8 +48696,8 @@ var ts;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
// Enable substitution for property/element access to emit const enum values.
- context.enableSubstitution(177 /* PropertyAccessExpression */);
- context.enableSubstitution(178 /* ElementAccessExpression */);
+ context.enableSubstitution(178 /* PropertyAccessExpression */);
+ context.enableSubstitution(179 /* ElementAccessExpression */);
// These variables contain state that changes as we descend into the tree.
var currentSourceFile;
var currentNamespace;
@@ -45205,15 +48761,15 @@ var ts;
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 261 /* SourceFile */:
- case 232 /* CaseBlock */:
- case 231 /* ModuleBlock */:
- case 204 /* Block */:
+ case 264 /* SourceFile */:
+ case 234 /* CaseBlock */:
+ case 233 /* ModuleBlock */:
+ case 206 /* Block */:
currentScope = node;
currentScopeFirstDeclarationsOfName = undefined;
break;
- case 226 /* ClassDeclaration */:
- case 225 /* FunctionDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 227 /* FunctionDeclaration */:
if (ts.hasModifier(node, 2 /* Ambient */)) {
break;
}
@@ -45260,13 +48816,13 @@ var ts;
*/
function sourceElementVisitorWorker(node) {
switch (node.kind) {
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
return visitImportDeclaration(node);
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
return visitImportEqualsDeclaration(node);
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
return visitExportAssignment(node);
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
return visitExportDeclaration(node);
default:
return visitorWorker(node);
@@ -45286,11 +48842,11 @@ var ts;
* @param node The node to visit.
*/
function namespaceElementVisitorWorker(node) {
- if (node.kind === 241 /* ExportDeclaration */ ||
- node.kind === 235 /* ImportDeclaration */ ||
- node.kind === 236 /* ImportClause */ ||
- (node.kind === 234 /* ImportEqualsDeclaration */ &&
- node.moduleReference.kind === 245 /* ExternalModuleReference */)) {
+ if (node.kind === 243 /* ExportDeclaration */ ||
+ node.kind === 237 /* ImportDeclaration */ ||
+ node.kind === 238 /* ImportClause */ ||
+ (node.kind === 236 /* ImportEqualsDeclaration */ &&
+ node.moduleReference.kind === 247 /* ExternalModuleReference */)) {
// do not emit ES6 imports and exports since they are illegal inside a namespace
return undefined;
}
@@ -45320,19 +48876,19 @@ var ts;
*/
function classElementVisitorWorker(node) {
switch (node.kind) {
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
// TypeScript constructors are transformed in `visitClassDeclaration`.
// We elide them here as `visitorWorker` checks transform flags, which could
// erronously include an ES6 constructor without TypeScript syntax.
return undefined;
- case 147 /* PropertyDeclaration */:
- case 155 /* IndexSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 149 /* MethodDeclaration */:
+ case 148 /* PropertyDeclaration */:
+ case 156 /* IndexSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 150 /* MethodDeclaration */:
// Fallback to the default visit behavior.
return visitorWorker(node);
- case 203 /* SemicolonClassElement */:
+ case 205 /* SemicolonClassElement */:
return node;
default:
ts.Debug.failBadSyntaxKind(node);
@@ -45372,46 +48928,47 @@ var ts;
case 123 /* DeclareKeyword */:
case 130 /* ReadonlyKeyword */:
// TypeScript accessibility and readonly modifiers are elided.
- case 162 /* ArrayType */:
- case 163 /* TupleType */:
- case 161 /* TypeLiteral */:
- case 156 /* TypePredicate */:
- case 143 /* TypeParameter */:
+ case 163 /* ArrayType */:
+ case 164 /* TupleType */:
+ case 162 /* TypeLiteral */:
+ case 157 /* TypePredicate */:
+ case 144 /* TypeParameter */:
case 118 /* AnyKeyword */:
case 121 /* BooleanKeyword */:
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
case 132 /* NumberKeyword */:
case 129 /* NeverKeyword */:
case 104 /* VoidKeyword */:
- case 135 /* SymbolKeyword */:
- case 159 /* ConstructorType */:
- case 158 /* FunctionType */:
- case 160 /* TypeQuery */:
- case 157 /* TypeReference */:
- case 164 /* UnionType */:
- case 165 /* IntersectionType */:
- case 166 /* ParenthesizedType */:
- case 167 /* ThisType */:
- case 168 /* TypeOperator */:
- case 169 /* IndexedAccessType */:
- case 170 /* MappedType */:
- case 171 /* LiteralType */:
+ case 136 /* SymbolKeyword */:
+ case 160 /* ConstructorType */:
+ case 159 /* FunctionType */:
+ case 161 /* TypeQuery */:
+ case 158 /* TypeReference */:
+ case 165 /* UnionType */:
+ case 166 /* IntersectionType */:
+ case 167 /* ParenthesizedType */:
+ case 168 /* ThisType */:
+ case 169 /* TypeOperator */:
+ case 170 /* IndexedAccessType */:
+ case 171 /* MappedType */:
+ case 172 /* LiteralType */:
// TypeScript type nodes are elided.
- case 155 /* IndexSignature */:
+ case 156 /* IndexSignature */:
// TypeScript index signatures are elided.
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
// TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
- case 228 /* TypeAliasDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
// TypeScript type-only declarations are elided.
- case 147 /* PropertyDeclaration */:
- // TypeScript property declarations are elided.
- case 150 /* Constructor */:
+ case 148 /* PropertyDeclaration */:
+ // TypeScript property declarations are elided.
+ return undefined;
+ case 151 /* Constructor */:
return visitConstructor(node);
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
// TypeScript interfaces are elided, but some comments may be preserved.
// See the implementation of `getLeadingComments` in comments.ts for more details.
return ts.createNotEmittedStatement(node);
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
// This is a class declaration with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
@@ -45422,7 +48979,7 @@ var ts;
// - index signatures
// - method overload signatures
return visitClassDeclaration(node);
- case 197 /* ClassExpression */:
+ case 198 /* ClassExpression */:
// This is a class expression with TypeScript syntax extensions.
//
// TypeScript class syntax extensions include:
@@ -45433,35 +48990,35 @@ var ts;
// - index signatures
// - method overload signatures
return visitClassExpression(node);
- case 255 /* HeritageClause */:
+ case 258 /* HeritageClause */:
// This is a heritage clause with TypeScript syntax extensions.
//
// TypeScript heritage clause extensions include:
// - `implements` clause
return visitHeritageClause(node);
- case 199 /* ExpressionWithTypeArguments */:
+ case 200 /* ExpressionWithTypeArguments */:
// TypeScript supports type arguments on an expression in an `extends` heritage clause.
return visitExpressionWithTypeArguments(node);
- case 149 /* MethodDeclaration */:
+ case 150 /* MethodDeclaration */:
// TypeScript method declarations may have decorators, modifiers
// or type annotations.
return visitMethodDeclaration(node);
- case 151 /* GetAccessor */:
+ case 152 /* GetAccessor */:
// Get Accessors can have TypeScript modifiers, decorators, and type annotations.
return visitGetAccessor(node);
- case 152 /* SetAccessor */:
+ case 153 /* SetAccessor */:
// Set Accessors can have TypeScript modifiers and type annotations.
return visitSetAccessor(node);
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
// Typescript function declarations can have modifiers, decorators, and type annotations.
return visitFunctionDeclaration(node);
- case 184 /* FunctionExpression */:
+ case 185 /* FunctionExpression */:
// TypeScript function expressions can have modifiers and type annotations.
return visitFunctionExpression(node);
- case 185 /* ArrowFunction */:
+ case 186 /* ArrowFunction */:
// TypeScript arrow functions can have modifiers and type annotations.
return visitArrowFunction(node);
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
// This is a parameter declaration with TypeScript syntax extensions.
//
// TypeScript parameter declaration syntax extensions include:
@@ -45471,33 +49028,33 @@ var ts;
// - type annotations
// - this parameters
return visitParameter(node);
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
// ParenthesizedExpressions are TypeScript if their expression is a
// TypeAssertion or AsExpression
return visitParenthesizedExpression(node);
- case 182 /* TypeAssertionExpression */:
- case 200 /* AsExpression */:
+ case 183 /* TypeAssertionExpression */:
+ case 201 /* AsExpression */:
// TypeScript type assertions are removed, but their subtrees are preserved.
return visitAssertionExpression(node);
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
return visitCallExpression(node);
- case 180 /* NewExpression */:
+ case 181 /* NewExpression */:
return visitNewExpression(node);
- case 201 /* NonNullExpression */:
+ case 202 /* NonNullExpression */:
// TypeScript non-null expressions are removed, but their subtrees are preserved.
return visitNonNullExpression(node);
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
// TypeScript enum declarations do not exist in ES6 and must be rewritten.
return visitEnumDeclaration(node);
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
// TypeScript namespace exports for variable statements must be transformed.
return visitVariableStatement(node);
- case 223 /* VariableDeclaration */:
+ case 225 /* VariableDeclaration */:
return visitVariableDeclaration(node);
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
// TypeScript namespace declarations must be transformed.
return visitModuleDeclaration(node);
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
// TypeScript namespace or external module import.
return visitImportEqualsDeclaration(node);
default:
@@ -45506,7 +49063,8 @@ var ts;
}
}
function visitSourceFile(node) {
- var alwaysStrict = compilerOptions.alwaysStrict && !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015);
+ var alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) &&
+ !(ts.isExternalModule(node) && moduleKind === ts.ModuleKind.ES2015);
return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
}
/**
@@ -45602,13 +49160,14 @@ var ts;
// }
var classDeclaration = ts.createClassDeclaration(
/*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name,
- /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node);
- var emitFlags = ts.getEmitFlags(node);
+ /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause));
// To better align with the old emitter, we should not emit a trailing source map
// entry if the class has static properties.
+ var emitFlags = ts.getEmitFlags(node);
if (hasStaticProperties) {
emitFlags |= 32 /* NoTrailingSourceMap */;
}
+ ts.setTextRange(classDeclaration, node);
ts.setOriginalNode(classDeclaration, node);
ts.setEmitFlags(classDeclaration, emitFlags);
return classDeclaration;
@@ -45716,12 +49275,18 @@ var ts;
// }
var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
var members = transformClassMembers(node, hasExtendsClause);
- var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members, location);
+ var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
ts.setOriginalNode(classExpression, node);
+ ts.setTextRange(classExpression, location);
// let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
// or decoratedClassAlias if the class contain self-reference.
- var statement = ts.createLetStatement(declName, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression, location);
+ var statement = ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList([
+ ts.createVariableDeclaration(declName,
+ /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression)
+ ], 1 /* Let */));
ts.setOriginalNode(statement, node);
+ ts.setTextRange(statement, location);
ts.setCommentRange(statement, node);
return statement;
}
@@ -45738,10 +49303,11 @@ var ts;
var staticProperties = getInitializedProperties(node, /*isStatic*/ true);
var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
var members = transformClassMembers(node, ts.some(heritageClauses, function (c) { return c.token === 84 /* ExtendsKeyword */; }));
- var classExpression = ts.setOriginalNode(ts.createClassExpression(
+ var classExpression = ts.createClassExpression(
/*modifiers*/ undefined, node.name,
- /*typeParameters*/ undefined, heritageClauses, members,
- /*location*/ node), node);
+ /*typeParameters*/ undefined, heritageClauses, members);
+ ts.setOriginalNode(classExpression, node);
+ ts.setTextRange(classExpression, node);
if (staticProperties.length > 0) {
var expressions = [];
var temp = ts.createTempVariable(hoistVariableDeclaration);
@@ -45773,7 +49339,7 @@ var ts;
members.push(constructor);
}
ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
- return ts.createNodeArray(members, /*location*/ node.members);
+ return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
}
/**
* Transforms (or creates) a constructor for a class.
@@ -45798,10 +49364,9 @@ var ts;
// constructor(${parameters}) {
// ${body}
// }
- return ts.startOnNewLine(ts.setOriginalNode(ts.createConstructor(
+ return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(
/*decorators*/ undefined,
- /*modifiers*/ undefined, parameters, body,
- /*location*/ constructor || node), constructor));
+ /*modifiers*/ undefined, parameters, body), constructor || node), constructor));
}
/**
* Transforms (or creates) the parameters for the constructor of a class with
@@ -45883,11 +49448,11 @@ var ts;
ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
}
// End the lexical environment.
- ts.addRange(statements, endLexicalEnvironment());
- return ts.createBlock(ts.createNodeArray(statements,
+ statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
+ return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
/*location*/ constructor ? constructor.body.statements : node.members),
- /*location*/ constructor ? constructor.body : undefined,
- /*multiLine*/ true);
+ /*multiLine*/ true),
+ /*location*/ constructor ? constructor.body : undefined);
}
/**
* Adds super call and preceding prologue directives into the list of statements.
@@ -45899,13 +49464,13 @@ var ts;
if (ctor.body) {
var statements = ctor.body.statements;
// add prologue directives to the list (if any)
- var index = ts.addPrologueDirectives(result, statements, /*ensureUseStrict*/ false, visitor);
+ var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
if (index === statements.length) {
// list contains nothing but prologue directives (or empty) - exit
return index;
}
var statement = statements[index];
- if (statement.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
+ if (statement.kind === 209 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
result.push(ts.visitNode(statement, visitor, ts.isStatement));
return index + 1;
}
@@ -45942,9 +49507,7 @@ var ts;
ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
var localName = ts.getMutableClone(name);
ts.setEmitFlags(localName, 1536 /* NoComments */);
- return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName,
- /*location*/ node.name), localName),
- /*location*/ ts.moveRangePos(node, -1)));
+ return ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)));
}
/**
* Gets all property declarations with initializers on either the static or instance side of a class.
@@ -45978,7 +49541,7 @@ var ts;
* @param isStatic A value indicating whether the member should be a static or instance member.
*/
function isInitializedProperty(member, isStatic) {
- return member.kind === 147 /* PropertyDeclaration */
+ return member.kind === 148 /* PropertyDeclaration */
&& isStatic === ts.hasModifier(member, 32 /* Static */)
&& member.initializer !== undefined;
}
@@ -45989,8 +49552,8 @@ var ts;
* @param receiver The receiver on which each property should be assigned.
*/
function addInitializedPropertyStatements(statements, properties, receiver) {
- for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) {
- var property = properties_7[_i];
+ for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
+ var property = properties_9[_i];
var statement = ts.createStatement(transformInitializedProperty(property, receiver));
ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
ts.setCommentRange(statement, property);
@@ -46005,8 +49568,8 @@ var ts;
*/
function generateInitializedPropertyExpressions(properties, receiver) {
var expressions = [];
- for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
- var property = properties_8[_i];
+ for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) {
+ var property = properties_10[_i];
var expression = transformInitializedProperty(property, receiver);
expression.startsOnNewLine = true;
ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
@@ -46113,12 +49676,12 @@ var ts;
*/
function getAllDecoratorsOfClassElement(node, member) {
switch (member.kind) {
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
return getAllDecoratorsOfAccessors(node, member);
- case 149 /* MethodDeclaration */:
+ case 150 /* MethodDeclaration */:
return getAllDecoratorsOfMethod(member);
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
return getAllDecoratorsOfProperty(member);
default:
return undefined;
@@ -46135,10 +49698,11 @@ var ts;
return undefined;
}
var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
- if (accessor !== firstAccessor) {
+ var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
+ if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
return undefined;
}
- var decorators = firstAccessor.decorators || (secondAccessor && secondAccessor.decorators);
+ var decorators = firstAccessorWithDecorators.decorators;
var parameters = getDecoratorsOfParameters(setAccessor);
if (!decorators && !parameters) {
return undefined;
@@ -46179,14 +49743,14 @@ var ts;
* @param node The declaration node.
* @param allDecorators An object containing all of the decorators for the declaration.
*/
- function transformAllDecoratorsOfDeclaration(node, allDecorators) {
+ function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
if (!allDecorators) {
return undefined;
}
var decoratorExpressions = [];
ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
- addTypeMetadata(node, decoratorExpressions);
+ addTypeMetadata(node, container, decoratorExpressions);
return decoratorExpressions;
}
/**
@@ -46233,7 +49797,7 @@ var ts;
*/
function generateClassElementDecorationExpression(node, member) {
var allDecorators = getAllDecoratorsOfClassElement(node, member);
- var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, allDecorators);
+ var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
if (!decoratorExpressions) {
return undefined;
}
@@ -46270,7 +49834,7 @@ var ts;
var prefix = getClassMemberPrefix(node, member);
var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
var descriptor = languageVersion > 0 /* ES3 */
- ? member.kind === 147 /* PropertyDeclaration */
+ ? member.kind === 148 /* PropertyDeclaration */
? ts.createVoidZero()
: ts.createNull()
: undefined;
@@ -46296,7 +49860,7 @@ var ts;
*/
function generateConstructorDecorationExpression(node) {
var allDecorators = getAllDecoratorsOfConstructor(node);
- var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, allDecorators);
+ var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
if (!decoratorExpressions) {
return undefined;
}
@@ -46342,41 +49906,41 @@ var ts;
* @param node The declaration node.
* @param decoratorExpressions The destination array to which to add new decorator expressions.
*/
- function addTypeMetadata(node, decoratorExpressions) {
+ function addTypeMetadata(node, container, decoratorExpressions) {
if (USE_NEW_TYPE_METADATA_FORMAT) {
- addNewTypeMetadata(node, decoratorExpressions);
+ addNewTypeMetadata(node, container, decoratorExpressions);
}
else {
- addOldTypeMetadata(node, decoratorExpressions);
+ addOldTypeMetadata(node, container, decoratorExpressions);
}
}
- function addOldTypeMetadata(node, decoratorExpressions) {
+ function addOldTypeMetadata(node, container, decoratorExpressions) {
if (compilerOptions.emitDecoratorMetadata) {
if (shouldAddTypeMetadata(node)) {
decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
}
if (shouldAddParamTypesMetadata(node)) {
- decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node)));
+ decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container)));
}
if (shouldAddReturnTypeMetadata(node)) {
decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
}
}
}
- function addNewTypeMetadata(node, decoratorExpressions) {
+ function addNewTypeMetadata(node, container, decoratorExpressions) {
if (compilerOptions.emitDecoratorMetadata) {
var properties = void 0;
if (shouldAddTypeMetadata(node)) {
(properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
}
if (shouldAddParamTypesMetadata(node)) {
- (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node))));
+ (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
}
if (shouldAddReturnTypeMetadata(node)) {
(properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(35 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
}
if (properties) {
- decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true)));
+ decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true)));
}
}
}
@@ -46389,10 +49953,10 @@ var ts;
*/
function shouldAddTypeMetadata(node) {
var kind = node.kind;
- return kind === 149 /* MethodDeclaration */
- || kind === 151 /* GetAccessor */
- || kind === 152 /* SetAccessor */
- || kind === 147 /* PropertyDeclaration */;
+ return kind === 150 /* MethodDeclaration */
+ || kind === 152 /* GetAccessor */
+ || kind === 153 /* SetAccessor */
+ || kind === 148 /* PropertyDeclaration */;
}
/**
* Determines whether to emit the "design:returntype" metadata based on the node's kind.
@@ -46402,7 +49966,7 @@ var ts;
* @param node The node to test.
*/
function shouldAddReturnTypeMetadata(node) {
- return node.kind === 149 /* MethodDeclaration */;
+ return node.kind === 150 /* MethodDeclaration */;
}
/**
* Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
@@ -46412,12 +49976,16 @@ var ts;
* @param node The node to test.
*/
function shouldAddParamTypesMetadata(node) {
- var kind = node.kind;
- return kind === 226 /* ClassDeclaration */
- || kind === 197 /* ClassExpression */
- || kind === 149 /* MethodDeclaration */
- || kind === 151 /* GetAccessor */
- || kind === 152 /* SetAccessor */;
+ switch (node.kind) {
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ return ts.getFirstConstructorWithBody(node) !== undefined;
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ return true;
+ }
+ return false;
}
/**
* Serializes the type of a node for use with decorator type metadata.
@@ -46426,43 +49994,26 @@ var ts;
*/
function serializeTypeOfNode(node) {
switch (node.kind) {
- case 147 /* PropertyDeclaration */:
- case 144 /* Parameter */:
- case 151 /* GetAccessor */:
+ case 148 /* PropertyDeclaration */:
+ case 145 /* Parameter */:
+ case 152 /* GetAccessor */:
return serializeTypeNode(node.type);
- case 152 /* SetAccessor */:
+ case 153 /* SetAccessor */:
return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node));
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 149 /* MethodDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 150 /* MethodDeclaration */:
return ts.createIdentifier("Function");
default:
return ts.createVoidZero();
}
}
/**
- * Gets the most likely element type for a TypeNode. This is not an exhaustive test
- * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
- *
- * @param node The type node.
- */
- function getRestParameterElementType(node) {
- if (node && node.kind === 162 /* ArrayType */) {
- return node.elementType;
- }
- else if (node && node.kind === 157 /* TypeReference */) {
- return ts.singleOrUndefined(node.typeArguments);
- }
- else {
- return undefined;
- }
- }
- /**
* Serializes the types of the parameters of a node for use with decorator type metadata.
*
* @param node The node that should have its parameter types serialized.
*/
- function serializeParameterTypesOfNode(node) {
+ function serializeParameterTypesOfNode(node, container) {
var valueDeclaration = ts.isClassLike(node)
? ts.getFirstConstructorWithBody(node)
: ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
@@ -46470,7 +50021,7 @@ var ts;
: undefined;
var expressions = [];
if (valueDeclaration) {
- var parameters = valueDeclaration.parameters;
+ var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
var numParameters = parameters.length;
for (var i = 0; i < numParameters; i++) {
var parameter = parameters[i];
@@ -46478,7 +50029,7 @@ var ts;
continue;
}
if (parameter.dotDotDotToken) {
- expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type)));
+ expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
}
else {
expressions.push(serializeTypeOfNode(parameter));
@@ -46487,6 +50038,15 @@ var ts;
}
return ts.createArrayLiteral(expressions);
}
+ function getParametersOfDecoratedDeclaration(node, container) {
+ if (container && node.kind === 152 /* GetAccessor */) {
+ var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
+ if (setAccessor) {
+ return setAccessor.parameters;
+ }
+ }
+ return node.parameters;
+ }
/**
* Serializes the return type of a node for use with decorator type metadata.
*
@@ -46496,7 +50056,7 @@ var ts;
if (ts.isFunctionLike(node) && node.type) {
return serializeTypeNode(node.type);
}
- else if (ts.isAsyncFunctionLike(node)) {
+ else if (ts.isAsyncFunction(node)) {
return ts.createIdentifier("Promise");
}
return ts.createVoidZero();
@@ -46525,21 +50085,26 @@ var ts;
}
switch (node.kind) {
case 104 /* VoidKeyword */:
+ case 138 /* UndefinedKeyword */:
+ case 94 /* NullKeyword */:
+ case 129 /* NeverKeyword */:
return ts.createVoidZero();
- case 166 /* ParenthesizedType */:
+ case 167 /* ParenthesizedType */:
return serializeTypeNode(node.type);
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
return ts.createIdentifier("Function");
- case 162 /* ArrayType */:
- case 163 /* TupleType */:
+ case 163 /* ArrayType */:
+ case 164 /* TupleType */:
return ts.createIdentifier("Array");
- case 156 /* TypePredicate */:
+ case 157 /* TypePredicate */:
case 121 /* BooleanKeyword */:
return ts.createIdentifier("Boolean");
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
return ts.createIdentifier("String");
- case 171 /* LiteralType */:
+ case 133 /* ObjectKeyword */:
+ return ts.createIdentifier("Object");
+ case 172 /* LiteralType */:
switch (node.literal.kind) {
case 9 /* StringLiteral */:
return ts.createIdentifier("String");
@@ -46555,49 +50120,22 @@ var ts;
break;
case 132 /* NumberKeyword */:
return ts.createIdentifier("Number");
- case 135 /* SymbolKeyword */:
+ case 136 /* SymbolKeyword */:
return languageVersion < 2 /* ES2015 */
? getGlobalSymbolNameWithFallback()
: ts.createIdentifier("Symbol");
- case 157 /* TypeReference */:
+ case 158 /* TypeReference */:
return serializeTypeReferenceNode(node);
- case 165 /* IntersectionType */:
- case 164 /* UnionType */:
- {
- var unionOrIntersection = node;
- var serializedUnion = void 0;
- for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) {
- var typeNode = _a[_i];
- var serializedIndividual = serializeTypeNode(typeNode);
- // Non identifier
- if (serializedIndividual.kind !== 70 /* Identifier */) {
- serializedUnion = undefined;
- break;
- }
- // One of the individual is global object, return immediately
- if (serializedIndividual.text === "Object") {
- return serializedIndividual;
- }
- // Different types
- if (serializedUnion && serializedUnion.text !== serializedIndividual.text) {
- serializedUnion = undefined;
- break;
- }
- serializedUnion = serializedIndividual;
- }
- // If we were able to find common type
- if (serializedUnion) {
- return serializedUnion;
- }
- }
- // Fallthrough
- case 160 /* TypeQuery */:
- case 168 /* TypeOperator */:
- case 169 /* IndexedAccessType */:
- case 170 /* MappedType */:
- case 161 /* TypeLiteral */:
+ case 166 /* IntersectionType */:
+ case 165 /* UnionType */:
+ return serializeUnionOrIntersectionType(node);
+ case 161 /* TypeQuery */:
+ case 169 /* TypeOperator */:
+ case 170 /* IndexedAccessType */:
+ case 171 /* MappedType */:
+ case 162 /* TypeLiteral */:
case 118 /* AnyKeyword */:
- case 167 /* ThisType */:
+ case 168 /* ThisType */:
break;
default:
ts.Debug.failBadSyntaxKind(node);
@@ -46605,6 +50143,37 @@ var ts;
}
return ts.createIdentifier("Object");
}
+ function serializeUnionOrIntersectionType(node) {
+ var serializedUnion;
+ for (var _i = 0, _a = node.types; _i < _a.length; _i++) {
+ var typeNode = _a[_i];
+ var serializedIndividual = serializeTypeNode(typeNode);
+ if (ts.isVoidExpression(serializedIndividual)) {
+ // If we dont have any other type already set, set the initial type
+ if (!serializedUnion) {
+ serializedUnion = serializedIndividual;
+ }
+ }
+ else if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") {
+ // One of the individual is global object, return immediately
+ return serializedIndividual;
+ }
+ else if (serializedUnion && !ts.isVoidExpression(serializedUnion)) {
+ // Different types
+ if (!ts.isIdentifier(serializedUnion) ||
+ !ts.isIdentifier(serializedIndividual) ||
+ serializedUnion.text !== serializedIndividual.text) {
+ return ts.createIdentifier("Object");
+ }
+ }
+ else {
+ // Initialize the union type
+ serializedUnion = serializedIndividual;
+ }
+ }
+ // If we were able to find common type, use it
+ return serializedUnion;
+ }
/**
* Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
* decorator type metadata.
@@ -46654,15 +50223,15 @@ var ts;
case 70 /* Identifier */:
// Create a clone of the name with a new parent, and treat it as if it were
// a source tree node for the purposes of the checker.
- var name_31 = ts.getMutableClone(node);
- name_31.flags &= ~8 /* Synthesized */;
- name_31.original = undefined;
- name_31.parent = currentScope;
+ var name = ts.getMutableClone(node);
+ name.flags &= ~8 /* Synthesized */;
+ name.original = undefined;
+ name.parent = currentScope;
if (useFallback) {
- return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_31), ts.createLiteral("undefined")), name_31);
+ return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name);
}
- return name_31;
- case 141 /* QualifiedName */:
+ return name;
+ case 142 /* QualifiedName */:
return serializeQualifiedNameAsExpression(node, useFallback);
}
}
@@ -46708,7 +50277,7 @@ var ts;
: name.expression;
}
else if (ts.isIdentifier(name)) {
- return ts.createLiteral(name.text);
+ return ts.createLiteral(ts.unescapeIdentifier(name.text));
}
else {
return ts.getSynthesizedClone(name);
@@ -46730,7 +50299,7 @@ var ts;
hoistVariableDeclaration(generatedName);
expression = ts.createAssignment(generatedName, expression);
}
- return ts.setOriginalNode(ts.createComputedPropertyName(expression, /*location*/ name), name);
+ return ts.updateComputedPropertyName(name, expression);
}
else {
return name;
@@ -46748,7 +50317,7 @@ var ts;
function visitHeritageClause(node) {
if (node.token === 84 /* ExtendsKeyword */) {
var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1);
- return ts.createHeritageClause(84 /* ExtendsKeyword */, types, node);
+ return ts.setTextRange(ts.createHeritageClause(84 /* ExtendsKeyword */, types), node);
}
return undefined;
}
@@ -46761,9 +50330,8 @@ var ts;
* @param node The ExpressionWithTypeArguments to transform.
*/
function visitExpressionWithTypeArguments(node) {
- var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
- return ts.createExpressionWithTypeArguments(
- /*typeArguments*/ undefined, expression, node);
+ return ts.updateExpressionWithTypeArguments(node,
+ /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
}
/**
* Determines whether to emit a function-like declaration. We should not emit the
@@ -46778,7 +50346,7 @@ var ts;
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
}
- return ts.visitEachChild(node, visitor, context);
+ return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context));
}
/**
* Visits a method declaration of a class.
@@ -46795,7 +50363,8 @@ var ts;
return undefined;
}
var updated = ts.updateMethod(node,
- /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node),
+ /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node),
+ /*questionToken*/ undefined,
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
if (updated !== node) {
@@ -46877,7 +50446,7 @@ var ts;
return ts.createNotEmittedStatement(node);
}
var updated = ts.updateFunctionDeclaration(node,
- /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name,
+ /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name,
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
if (isNamespaceExport(node)) {
@@ -46896,12 +50465,12 @@ var ts;
* @param node The function expression node.
*/
function visitFunctionExpression(node) {
- if (ts.nodeIsMissing(node.body)) {
+ if (!shouldEmitFunctionLikeDeclaration(node)) {
return ts.createOmittedExpression();
}
- var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.name,
+ var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name,
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
+ /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
return updated;
}
/**
@@ -46933,11 +50502,11 @@ var ts;
/*decorators*/ undefined,
/*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName),
/*questionToken*/ undefined,
- /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression),
- /*location*/ ts.moveRangePastModifiers(node));
+ /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
// While we emit the source map for the node after skipping decorators and modifiers,
// we need to emit the comments for the original range.
ts.setOriginalNode(parameter, node);
+ ts.setTextRange(parameter, ts.moveRangePastModifiers(node));
ts.setCommentRange(parameter, node);
ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node));
ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */);
@@ -46956,8 +50525,7 @@ var ts;
// elide statement if there are no initialized variables.
return undefined;
}
- return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable)),
- /*location*/ node);
+ return ts.setTextRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
}
else {
return ts.visitEachChild(node, visitor, context);
@@ -46970,7 +50538,7 @@ var ts;
/*needsValue*/ false, createNamespaceExportExpression);
}
else {
- return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression),
+ return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)),
/*location*/ node);
}
}
@@ -46996,13 +50564,13 @@ var ts;
// code if the casted expression has a lower precedence than the rest of the
// expression.
//
+ // To preserve comments, we return a "PartiallyEmittedExpression" here which will
+ // preserve the position information of the original expression.
+ //
// Due to the auto-parenthesization rules used by the visitor and factory functions
// we can safely elide the parentheses here, as a new synthetic
// ParenthesizedExpression will be inserted if we remove parentheses too
// aggressively.
- //
- // To preserve comments, we return a "PartiallyEmittedExpression" here which will
- // preserve the position information of the original expression.
return ts.createPartiallyEmittedExpression(expression, node);
}
return ts.visitEachChild(node, visitor, context);
@@ -47084,9 +50652,9 @@ var ts;
/*name*/ undefined,
/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
/*type*/ undefined, transformEnumBody(node, containerName)),
- /*typeArguments*/ undefined, [moduleArg]),
- /*location*/ node);
+ /*typeArguments*/ undefined, [moduleArg]));
ts.setOriginalNode(enumStatement, node);
+ ts.setTextRange(enumStatement, node);
ts.setEmitFlags(enumStatement, emitFlags);
statements.push(enumStatement);
// Add a DeclarationMarker for the enum to preserve trailing comments and mark
@@ -47107,8 +50675,7 @@ var ts;
ts.addRange(statements, ts.map(node.members, transformEnumMember));
ts.addRange(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
- return ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members),
- /*location*/ undefined,
+ return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
/*multiLine*/ true);
}
/**
@@ -47121,9 +50688,7 @@ var ts;
// we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
// old emitter always generate 'expression' part of the name as-is.
var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
- return ts.createStatement(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name,
- /*location*/ member),
- /*location*/ member);
+ return ts.setTextRange(ts.createStatement(ts.setTextRange(ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), transformEnumMemberDeclarationValue(member))), name), member)), member);
}
/**
* Transforms the value of an enum member.
@@ -47176,8 +50741,8 @@ var ts;
if (!currentScopeFirstDeclarationsOfName) {
currentScopeFirstDeclarationsOfName = ts.createMap();
}
- if (!(name in currentScopeFirstDeclarationsOfName)) {
- currentScopeFirstDeclarationsOfName[name] = node;
+ if (!currentScopeFirstDeclarationsOfName.has(name)) {
+ currentScopeFirstDeclarationsOfName.set(name, node);
}
}
}
@@ -47187,9 +50752,9 @@ var ts;
*/
function isFirstEmittedDeclarationInScope(node) {
if (currentScopeFirstDeclarationsOfName) {
- var name_32 = node.symbol && node.symbol.name;
- if (name_32) {
- return currentScopeFirstDeclarationsOfName[name_32] === node;
+ var name = node.symbol && node.symbol.name;
+ if (name) {
+ return currentScopeFirstDeclarationsOfName.get(name) === node;
}
}
return false;
@@ -47206,7 +50771,7 @@ var ts;
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
// Adjust the source map emit to match the old emitter.
- if (node.kind === 229 /* EnumDeclaration */) {
+ if (node.kind === 231 /* EnumDeclaration */) {
ts.setSourceMapRange(statement.declarationList, node);
}
else {
@@ -47298,9 +50863,9 @@ var ts;
/*name*/ undefined,
/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
/*type*/ undefined, transformModuleBody(node, containerName)),
- /*typeArguments*/ undefined, [moduleArg]),
- /*location*/ node);
+ /*typeArguments*/ undefined, [moduleArg]));
ts.setOriginalNode(moduleStatement, node);
+ ts.setTextRange(moduleStatement, node);
ts.setEmitFlags(moduleStatement, emitFlags);
statements.push(moduleStatement);
// Add a DeclarationMarker for the namespace to preserve trailing comments and mark
@@ -47325,8 +50890,8 @@ var ts;
var statementsLocation;
var blockLocation;
var body = node.body;
- if (body.kind === 231 /* ModuleBlock */) {
- ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement));
+ if (body.kind === 233 /* ModuleBlock */) {
+ saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
statementsLocation = body.statements;
blockLocation = body;
}
@@ -47347,10 +50912,10 @@ var ts;
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
- var block = ts.createBlock(ts.createNodeArray(statements,
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
/*location*/ statementsLocation),
- /*location*/ blockLocation,
/*multiLine*/ true);
+ ts.setTextRange(block, blockLocation);
// namespace hello.hi.world {
// function foo() {}
//
@@ -47371,13 +50936,13 @@ var ts;
// })(hi = hello.hi || (hello.hi = {}));
// })(hello || (hello = {}));
// We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
- if (body.kind !== 231 /* ModuleBlock */) {
+ if (body.kind !== 233 /* ModuleBlock */) {
ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
}
return block;
}
function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
- if (moduleDeclaration.body.kind === 230 /* ModuleDeclaration */) {
+ if (moduleDeclaration.body.kind === 232 /* ModuleDeclaration */) {
var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
return recursiveInnerModule || moduleDeclaration.body;
}
@@ -47394,7 +50959,7 @@ var ts;
return node;
}
// Elide the declaration if the import clause was elided.
- var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause, /*optional*/ true);
+ var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
return importClause
? ts.updateImportDeclaration(node,
/*decorators*/ undefined,
@@ -47409,7 +50974,7 @@ var ts;
function visitImportClause(node) {
// Elide the import clause if we elide both its name and its named bindings.
var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
- var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings, /*optional*/ true);
+ var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings) : undefined;
}
/**
@@ -47418,7 +50983,7 @@ var ts;
* @param node The named import bindings node.
*/
function visitNamedImportBindings(node) {
- if (node.kind === 237 /* NamespaceImport */) {
+ if (node.kind === 239 /* NamespaceImport */) {
// Elide a namespace import if it is not referenced.
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
@@ -47465,7 +51030,7 @@ var ts;
return undefined;
}
// Elide the export declaration if all of its named exports are elided.
- var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports, /*optional*/ true);
+ var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports);
return exportClause
? ts.updateExportDeclaration(node,
/*decorators*/ undefined,
@@ -47525,10 +51090,10 @@ var ts;
if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) {
// export var ${name} = ${moduleReference};
// var ${name} = ${moduleReference};
- return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
+ return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
ts.setOriginalNode(ts.createVariableDeclaration(node.name,
/*type*/ undefined, moduleReference), node)
- ]), node), node);
+ ])), node), node);
}
else {
// exports.${name} = ${moduleReference};
@@ -47573,7 +51138,7 @@ var ts;
* Creates a statement for the provided expression. This is used in calls to `map`.
*/
function expressionToStatement(expression) {
- return ts.createStatement(expression, /*location*/ undefined);
+ return ts.createStatement(expression);
}
function addExportMemberAssignment(statements, node) {
var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node));
@@ -47583,10 +51148,10 @@ var ts;
statements.push(statement);
}
function createNamespaceExport(exportName, exportValue, location) {
- return ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue), location);
+ return ts.setTextRange(ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
}
function createNamespaceExportExpression(exportName, exportValue, location) {
- return ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue, location);
+ return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
}
function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
@@ -47614,7 +51179,7 @@ var ts;
function getClassAliasIfNeeded(node) {
if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) {
enableSubstitutionForClassAliases();
- var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? node.name.text : "default");
+ var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeIdentifier(node.name.text) : "default");
classAliases[ts.getOriginalNodeId(node)] = classAlias;
hoistVariableDeclaration(classAlias);
return classAlias;
@@ -47641,7 +51206,7 @@ var ts;
// substitute class names inside of a class declaration.
context.enableSubstitution(70 /* Identifier */);
// Keep track of class aliases.
- classAliases = ts.createMap();
+ classAliases = [];
}
}
function enableSubstitutionForNamespaceExports() {
@@ -47650,44 +51215,49 @@ var ts;
// We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
// substitute the names of exported members of a namespace.
context.enableSubstitution(70 /* Identifier */);
- context.enableSubstitution(258 /* ShorthandPropertyAssignment */);
+ context.enableSubstitution(261 /* ShorthandPropertyAssignment */);
// We need to be notified when entering and exiting namespaces.
- context.enableEmitNotification(230 /* ModuleDeclaration */);
+ context.enableEmitNotification(232 /* ModuleDeclaration */);
}
}
function isTransformedModuleDeclaration(node) {
- return ts.getOriginalNode(node).kind === 230 /* ModuleDeclaration */;
+ return ts.getOriginalNode(node).kind === 232 /* ModuleDeclaration */;
}
function isTransformedEnumDeclaration(node) {
- return ts.getOriginalNode(node).kind === 229 /* EnumDeclaration */;
+ return ts.getOriginalNode(node).kind === 231 /* EnumDeclaration */;
}
/**
* Hook for node emit.
*
- * @param emitContext A context hint for the emitter.
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emit A callback used to emit the node in the printer.
*/
- function onEmitNode(emitContext, node, emitCallback) {
+ function onEmitNode(hint, node, emitCallback) {
var savedApplicableSubstitutions = applicableSubstitutions;
+ var savedCurrentSourceFile = currentSourceFile;
+ if (ts.isSourceFile(node)) {
+ currentSourceFile = node;
+ }
if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
applicableSubstitutions |= 2 /* NamespaceExports */;
}
if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
}
- previousOnEmitNode(emitContext, node, emitCallback);
+ previousOnEmitNode(hint, node, emitCallback);
applicableSubstitutions = savedApplicableSubstitutions;
+ currentSourceFile = savedCurrentSourceFile;
}
/**
* Hooks node substitutions.
*
- * @param emitContext A context hint for the emitter.
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
- function onSubstituteNode(emitContext, node) {
- node = previousOnSubstituteNode(emitContext, node);
- if (emitContext === 1 /* Expression */) {
+ function onSubstituteNode(hint, node) {
+ node = previousOnSubstituteNode(hint, node);
+ if (hint === 1 /* Expression */) {
return substituteExpression(node);
}
else if (ts.isShorthandPropertyAssignment(node)) {
@@ -47697,16 +51267,16 @@ var ts;
}
function substituteShorthandPropertyAssignment(node) {
if (enabledSubstitutions & 2 /* NamespaceExports */) {
- var name_33 = node.name;
- var exportedName = trySubstituteNamespaceExportedName(name_33);
+ var name = node.name;
+ var exportedName = trySubstituteNamespaceExportedName(name);
if (exportedName) {
// A shorthand property with an assignment initializer is probably part of a
// destructuring assignment
if (node.objectAssignmentInitializer) {
var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
- return ts.createPropertyAssignment(name_33, initializer, /*location*/ node);
+ return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
}
- return ts.createPropertyAssignment(name_33, exportedName, /*location*/ node);
+ return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node);
}
}
return node;
@@ -47715,9 +51285,9 @@ var ts;
switch (node.kind) {
case 70 /* Identifier */:
return substituteExpressionIdentifier(node);
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
return substitutePropertyAccessExpression(node);
- case 178 /* ElementAccessExpression */:
+ case 179 /* ElementAccessExpression */:
return substituteElementAccessExpression(node);
}
return node;
@@ -47755,11 +51325,12 @@ var ts;
// If we are nested within a namespace declaration, we may need to qualifiy
// an identifier that is exported from a merged namespace.
var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
- if (container && container.kind !== 261 /* SourceFile */) {
- var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 230 /* ModuleDeclaration */) ||
- (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 229 /* EnumDeclaration */);
+ if (container && container.kind !== 264 /* SourceFile */) {
+ var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 232 /* ModuleDeclaration */) ||
+ (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 231 /* EnumDeclaration */);
if (substitute) {
- return ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node, /*location*/ node);
+ return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node),
+ /*location*/ node);
}
}
}
@@ -47774,16 +51345,15 @@ var ts;
function substituteConstantValue(node) {
var constantValue = tryGetConstEnumValue(node);
if (constantValue !== undefined) {
+ // track the constant value on the node for the printer in needsDotDotForPropertyAccess
+ ts.setConstantValue(node, constantValue);
var substitute = ts.createLiteral(constantValue);
- ts.setSourceMapRange(substitute, node);
- ts.setCommentRange(substitute, node);
if (!compilerOptions.removeComments) {
var propertyName = ts.isPropertyAccessExpression(node)
? ts.declarationNameToString(node.name)
: ts.getTextOfNode(node.argumentExpression);
- substitute.trailingComment = " " + propertyName + " ";
+ ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
}
- ts.setConstantValue(node, constantValue);
return substitute;
}
return node;
@@ -47798,19 +51368,33 @@ var ts;
}
}
ts.transformTypeScript = transformTypeScript;
- var paramHelper = {
- name: "typescript:param",
+ function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
+ var argumentsArray = [];
+ argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true));
+ argumentsArray.push(target);
+ if (memberName) {
+ argumentsArray.push(memberName);
+ if (descriptor) {
+ argumentsArray.push(descriptor);
+ }
+ }
+ context.requestEmitHelper(decorateHelper);
+ return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
+ /*typeArguments*/ undefined, argumentsArray), location);
+ }
+ var decorateHelper = {
+ name: "typescript:decorate",
scoped: false,
- priority: 4,
- text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };"
+ priority: 2,
+ text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
- function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
- return ts.createCall(ts.getHelperName("__param"),
+ function createMetadataHelper(context, metadataKey, metadataValue) {
+ context.requestEmitHelper(metadataHelper);
+ return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
- ts.createLiteral(parameterOffset),
- expression
- ], location);
+ ts.createLiteral(metadataKey),
+ metadataValue
+ ]);
}
var metadataHelper = {
name: "typescript:metadata",
@@ -47818,41 +51402,391 @@ var ts;
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
- function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
- return ts.createCall(ts.getHelperName("__metadata"),
+ function createParamHelper(context, expression, parameterOffset, location) {
+ context.requestEmitHelper(paramHelper);
+ return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
- ts.createLiteral(metadataKey),
- metadataValue
- ]);
+ ts.createLiteral(parameterOffset),
+ expression
+ ]), location);
}
- var decorateHelper = {
- name: "typescript:decorate",
+ var paramHelper = {
+ name: "typescript:param",
scoped: false,
- priority: 2,
- text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
+ priority: 4,
+ text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };"
};
- function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
- context.requestEmitHelper(decorateHelper);
- var argumentsArray = [];
- argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*location*/ undefined, /*multiLine*/ true));
- argumentsArray.push(target);
- if (memberName) {
- argumentsArray.push(memberName);
- if (descriptor) {
- argumentsArray.push(descriptor);
+})(ts || (ts = {}));
+/// <reference path="../factory.ts" />
+/// <reference path="../visitor.ts" />
+/*@internal*/
+var ts;
+(function (ts) {
+ var ES2017SubstitutionFlags;
+ (function (ES2017SubstitutionFlags) {
+ /** Enables substitutions for async methods with `super` calls. */
+ ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
+ })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
+ function transformES2017(context) {
+ var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment;
+ var resolver = context.getEmitResolver();
+ var compilerOptions = context.getCompilerOptions();
+ var languageVersion = ts.getEmitScriptTarget(compilerOptions);
+ // These variables contain state that changes as we descend into the tree.
+ var currentSourceFile;
+ /**
+ * Keeps track of whether expression substitution has been enabled for specific edge cases.
+ * They are persisted between each SourceFile transformation and should not be reset.
+ */
+ var enabledSubstitutions;
+ /**
+ * This keeps track of containers where `super` is valid, for use with
+ * just-in-time substitution for `super` expressions inside of async methods.
+ */
+ var enclosingSuperContainerFlags = 0;
+ // Save the previous transformation hooks.
+ var previousOnEmitNode = context.onEmitNode;
+ var previousOnSubstituteNode = context.onSubstituteNode;
+ // Set new transformation hooks.
+ context.onEmitNode = onEmitNode;
+ context.onSubstituteNode = onSubstituteNode;
+ return transformSourceFile;
+ function transformSourceFile(node) {
+ if (ts.isDeclarationFile(node)) {
+ return node;
+ }
+ currentSourceFile = node;
+ var visited = ts.visitEachChild(node, visitor, context);
+ ts.addEmitHelpers(visited, context.readEmitHelpers());
+ currentSourceFile = undefined;
+ return visited;
+ }
+ function visitor(node) {
+ if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) {
+ return node;
+ }
+ switch (node.kind) {
+ case 119 /* AsyncKeyword */:
+ // ES2017 async modifier should be elided for targets < ES2017
+ return undefined;
+ case 190 /* AwaitExpression */:
+ return visitAwaitExpression(node);
+ case 150 /* MethodDeclaration */:
+ return visitMethodDeclaration(node);
+ case 227 /* FunctionDeclaration */:
+ return visitFunctionDeclaration(node);
+ case 185 /* FunctionExpression */:
+ return visitFunctionExpression(node);
+ case 186 /* ArrowFunction */:
+ return visitArrowFunction(node);
+ default:
+ return ts.visitEachChild(node, visitor, context);
}
}
- return ts.createCall(ts.getHelperName("__decorate"), /*typeArguments*/ undefined, argumentsArray, location);
+ /**
+ * Visits an AwaitExpression node.
+ *
+ * This function will be called any time a ES2017 await expression is encountered.
+ *
+ * @param node The node to visit.
+ */
+ function visitAwaitExpression(node) {
+ return ts.setOriginalNode(ts.setTextRange(ts.createYield(
+ /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
+ }
+ /**
+ * Visits a MethodDeclaration node.
+ *
+ * This function will be called when one of the following conditions are met:
+ * - The node is marked as async
+ *
+ * @param node The node to visit.
+ */
+ function visitMethodDeclaration(node) {
+ return ts.updateMethod(node,
+ /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
+ /*questionToken*/ undefined,
+ /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
+ /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
+ ? transformAsyncFunctionBody(node)
+ : ts.visitFunctionBody(node.body, visitor, context));
+ }
+ /**
+ * Visits a FunctionDeclaration node.
+ *
+ * This function will be called when one of the following conditions are met:
+ * - The node is marked async
+ *
+ * @param node The node to visit.
+ */
+ function visitFunctionDeclaration(node) {
+ return ts.updateFunctionDeclaration(node,
+ /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
+ /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
+ /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
+ ? transformAsyncFunctionBody(node)
+ : ts.visitFunctionBody(node.body, visitor, context));
+ }
+ /**
+ * Visits a FunctionExpression node.
+ *
+ * This function will be called when one of the following conditions are met:
+ * - The node is marked async
+ *
+ * @param node The node to visit.
+ */
+ function visitFunctionExpression(node) {
+ return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name,
+ /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
+ /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
+ ? transformAsyncFunctionBody(node)
+ : ts.visitFunctionBody(node.body, visitor, context));
+ }
+ /**
+ * Visits an ArrowFunction.
+ *
+ * This function will be called when one of the following conditions are met:
+ * - The node is marked async
+ *
+ * @param node The node to visit.
+ */
+ function visitArrowFunction(node) {
+ return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier),
+ /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
+ /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
+ ? transformAsyncFunctionBody(node)
+ : ts.visitFunctionBody(node.body, visitor, context));
+ }
+ function transformAsyncFunctionBody(node) {
+ resumeLexicalEnvironment();
+ var original = ts.getOriginalNode(node, ts.isFunctionLike);
+ var nodeType = original.type;
+ var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
+ var isArrowFunction = node.kind === 186 /* ArrowFunction */;
+ var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
+ // An async function is emit as an outer function that calls an inner
+ // generator function. To preserve lexical bindings, we pass the current
+ // `this` and `arguments` objects to `__awaiter`. The generator function
+ // passed to `__awaiter` is executed inside of the callback to the
+ // promise constructor.
+ if (!isArrowFunction) {
+ var statements = [];
+ var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
+ statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset))));
+ ts.addRange(statements, endLexicalEnvironment());
+ var block = ts.createBlock(statements, /*multiLine*/ true);
+ ts.setTextRange(block, node.body);
+ // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
+ // This step isn't needed if we eventually transform this to ES5.
+ if (languageVersion >= 2 /* ES2015 */) {
+ if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
+ enableSubstitutionForAsyncMethodsWithSuper();
+ ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
+ }
+ else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
+ enableSubstitutionForAsyncMethodsWithSuper();
+ ts.addEmitHelper(block, ts.asyncSuperHelper);
+ }
+ }
+ return block;
+ }
+ else {
+ var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body));
+ var declarations = endLexicalEnvironment();
+ if (ts.some(declarations)) {
+ var block = ts.convertToFunctionBody(expression);
+ return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements));
+ }
+ return expression;
+ }
+ }
+ function transformFunctionBodyWorker(body, start) {
+ if (ts.isBlock(body)) {
+ return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start));
+ }
+ else {
+ startLexicalEnvironment();
+ var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody));
+ var declarations = endLexicalEnvironment();
+ return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements));
+ }
+ }
+ function getPromiseConstructor(type) {
+ var typeName = type && ts.getEntityNameFromTypeNode(type);
+ if (typeName && ts.isEntityName(typeName)) {
+ var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
+ if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
+ || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
+ return typeName;
+ }
+ }
+ return undefined;
+ }
+ function enableSubstitutionForAsyncMethodsWithSuper() {
+ if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
+ enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
+ // We need to enable substitutions for call, property access, and element access
+ // if we need to rewrite super calls.
+ context.enableSubstitution(180 /* CallExpression */);
+ context.enableSubstitution(178 /* PropertyAccessExpression */);
+ context.enableSubstitution(179 /* ElementAccessExpression */);
+ // We need to be notified when entering and exiting declarations that bind super.
+ context.enableEmitNotification(228 /* ClassDeclaration */);
+ context.enableEmitNotification(150 /* MethodDeclaration */);
+ context.enableEmitNotification(152 /* GetAccessor */);
+ context.enableEmitNotification(153 /* SetAccessor */);
+ context.enableEmitNotification(151 /* Constructor */);
+ }
+ }
+ /**
+ * Hook for node emit.
+ *
+ * @param hint A hint as to the intended usage of the node.
+ * @param node The node to emit.
+ * @param emit A callback used to emit the node in the printer.
+ */
+ function onEmitNode(hint, node, emitCallback) {
+ // If we need to support substitutions for `super` in an async method,
+ // we should track it here.
+ if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
+ var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
+ if (superContainerFlags !== enclosingSuperContainerFlags) {
+ var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
+ enclosingSuperContainerFlags = superContainerFlags;
+ previousOnEmitNode(hint, node, emitCallback);
+ enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
+ return;
+ }
+ }
+ previousOnEmitNode(hint, node, emitCallback);
+ }
+ /**
+ * Hooks node substitutions.
+ *
+ * @param hint A hint as to the intended usage of the node.
+ * @param node The node to substitute.
+ */
+ function onSubstituteNode(hint, node) {
+ node = previousOnSubstituteNode(hint, node);
+ if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
+ return substituteExpression(node);
+ }
+ return node;
+ }
+ function substituteExpression(node) {
+ switch (node.kind) {
+ case 178 /* PropertyAccessExpression */:
+ return substitutePropertyAccessExpression(node);
+ case 179 /* ElementAccessExpression */:
+ return substituteElementAccessExpression(node);
+ case 180 /* CallExpression */:
+ return substituteCallExpression(node);
+ }
+ return node;
+ }
+ function substitutePropertyAccessExpression(node) {
+ if (node.expression.kind === 96 /* SuperKeyword */) {
+ return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node);
+ }
+ return node;
+ }
+ function substituteElementAccessExpression(node) {
+ if (node.expression.kind === 96 /* SuperKeyword */) {
+ return createSuperAccessInAsyncMethod(node.argumentExpression, node);
+ }
+ return node;
+ }
+ function substituteCallExpression(node) {
+ var expression = node.expression;
+ if (ts.isSuperProperty(expression)) {
+ var argumentExpression = ts.isPropertyAccessExpression(expression)
+ ? substitutePropertyAccessExpression(expression)
+ : substituteElementAccessExpression(expression);
+ return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"),
+ /*typeArguments*/ undefined, [
+ ts.createThis()
+ ].concat(node.arguments));
+ }
+ return node;
+ }
+ function isSuperContainer(node) {
+ var kind = node.kind;
+ return kind === 228 /* ClassDeclaration */
+ || kind === 151 /* Constructor */
+ || kind === 150 /* MethodDeclaration */
+ || kind === 152 /* GetAccessor */
+ || kind === 153 /* SetAccessor */;
+ }
+ function createSuperAccessInAsyncMethod(argumentExpression, location) {
+ if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
+ return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"),
+ /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
+ }
+ else {
+ return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"),
+ /*typeArguments*/ undefined, [argumentExpression]), location);
+ }
+ }
+ }
+ ts.transformES2017 = transformES2017;
+ var awaiterHelper = {
+ name: "typescript:awaiter",
+ scoped: false,
+ priority: 5,
+ text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
+ };
+ function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
+ context.requestEmitHelper(awaiterHelper);
+ var generatorFunc = ts.createFunctionExpression(
+ /*modifiers*/ undefined, ts.createToken(38 /* AsteriskToken */),
+ /*name*/ undefined,
+ /*typeParameters*/ undefined,
+ /*parameters*/ [],
+ /*type*/ undefined, body);
+ // Mark this node as originally an async function
+ (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072 /* AsyncFunctionBody */;
+ return ts.createCall(ts.getHelperName("__awaiter"),
+ /*typeArguments*/ undefined, [
+ ts.createThis(),
+ hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
+ promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
+ generatorFunc
+ ]);
}
+ ts.asyncSuperHelper = {
+ name: "typescript:async-super",
+ scoped: true,
+ text: "\n const _super = name => super[name];\n "
+ };
+ ts.advancedAsyncSuperHelper = {
+ name: "typescript:advanced-async-super",
+ scoped: true,
+ text: "\n const _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);\n "
+ };
})(ts || (ts = {}));
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
+/// <reference path="es2017.ts" />
/*@internal*/
var ts;
(function (ts) {
+ var ESNextSubstitutionFlags;
+ (function (ESNextSubstitutionFlags) {
+ /** Enables substitutions for async methods with `super` calls. */
+ ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
+ })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
function transformESNext(context) {
- var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment;
+ var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
+ var resolver = context.getEmitResolver();
+ var compilerOptions = context.getCompilerOptions();
+ var languageVersion = ts.getEmitScriptTarget(compilerOptions);
+ var previousOnEmitNode = context.onEmitNode;
+ context.onEmitNode = onEmitNode;
+ var previousOnSubstituteNode = context.onSubstituteNode;
+ context.onSubstituteNode = onSubstituteNode;
+ var enabledSubstitutions;
+ var enclosingFunctionFlags;
+ var enclosingSuperContainerFlags = 0;
return transformSourceFile;
function transformSourceFile(node) {
if (ts.isDeclarationFile(node)) {
@@ -47868,53 +51802,95 @@ var ts;
function visitorNoDestructuringValue(node) {
return visitorWorker(node, /*noDestructuringValue*/ true);
}
+ function visitorNoAsyncModifier(node) {
+ if (node.kind === 119 /* AsyncKeyword */) {
+ return undefined;
+ }
+ return node;
+ }
function visitorWorker(node, noDestructuringValue) {
if ((node.transformFlags & 8 /* ContainsESNext */) === 0) {
return node;
}
switch (node.kind) {
- case 176 /* ObjectLiteralExpression */:
+ case 190 /* AwaitExpression */:
+ return visitAwaitExpression(node);
+ case 196 /* YieldExpression */:
+ return visitYieldExpression(node);
+ case 221 /* LabeledStatement */:
+ return visitLabeledStatement(node);
+ case 177 /* ObjectLiteralExpression */:
return visitObjectLiteralExpression(node);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return visitBinaryExpression(node, noDestructuringValue);
- case 223 /* VariableDeclaration */:
+ case 225 /* VariableDeclaration */:
return visitVariableDeclaration(node);
- case 213 /* ForOfStatement */:
- return visitForOfStatement(node);
- case 211 /* ForStatement */:
+ case 215 /* ForOfStatement */:
+ return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
+ case 213 /* ForStatement */:
return visitForStatement(node);
- case 188 /* VoidExpression */:
+ case 189 /* VoidExpression */:
return visitVoidExpression(node);
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
return visitConstructorDeclaration(node);
- case 149 /* MethodDeclaration */:
+ case 150 /* MethodDeclaration */:
return visitMethodDeclaration(node);
- case 151 /* GetAccessor */:
+ case 152 /* GetAccessor */:
return visitGetAccessorDeclaration(node);
- case 152 /* SetAccessor */:
+ case 153 /* SetAccessor */:
return visitSetAccessorDeclaration(node);
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return visitFunctionDeclaration(node);
- case 184 /* FunctionExpression */:
+ case 185 /* FunctionExpression */:
return visitFunctionExpression(node);
- case 185 /* ArrowFunction */:
+ case 186 /* ArrowFunction */:
return visitArrowFunction(node);
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
return visitParameter(node);
- case 207 /* ExpressionStatement */:
+ case 209 /* ExpressionStatement */:
return visitExpressionStatement(node);
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return visitParenthesizedExpression(node, noDestructuringValue);
default:
return ts.visitEachChild(node, visitor, context);
}
}
+ function visitAwaitExpression(node) {
+ if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
+ var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
+ return ts.setOriginalNode(ts.setTextRange(ts.createYield(
+ /*asteriskToken*/ undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])),
+ /*location*/ node), node);
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitYieldExpression(node) {
+ if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
+ var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
+ return ts.updateYield(node, node.asteriskToken, node.asteriskToken
+ ? createAsyncDelegatorHelper(context, expression, expression)
+ : ts.createArrayLiteral(expression
+ ? [ts.createLiteral("yield"), expression]
+ : [ts.createLiteral("yield")]));
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitLabeledStatement(node) {
+ if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
+ var statement = ts.unwrapInnermostStatementOfLabel(node);
+ if (statement.kind === 215 /* ForOfStatement */ && statement.awaitModifier) {
+ return visitForOfStatement(statement, node);
+ }
+ return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), node);
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
function chunkObjectLiteralElements(elements) {
var chunkObject;
var objects = [];
- for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
- var e = elements_3[_i];
- if (e.kind === 259 /* SpreadAssignment */) {
+ for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
+ var e = elements_4[_i];
+ if (e.kind === 262 /* SpreadAssignment */) {
if (chunkObject) {
objects.push(ts.createObjectLiteral(chunkObject));
chunkObject = undefined;
@@ -47926,7 +51902,7 @@ var ts;
if (!chunkObject) {
chunkObject = [];
}
- if (e.kind === 257 /* PropertyAssignment */) {
+ if (e.kind === 260 /* PropertyAssignment */) {
var p = e;
chunkObject.push(ts.createPropertyAssignment(p.name, ts.visitNode(p.initializer, visitor, ts.isExpression)));
}
@@ -47948,7 +51924,7 @@ var ts;
// If the first element is a spread element, then the first argument to __assign is {}:
// { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2)
var objects = chunkObjectLiteralElements(node.properties);
- if (objects.length && objects[0].kind !== 176 /* ObjectLiteralExpression */) {
+ if (objects.length && objects[0].kind !== 177 /* ObjectLiteralExpression */) {
objects.unshift(ts.createObjectLiteral());
}
return createAssignHelper(context, objects);
@@ -47998,41 +51974,101 @@ var ts;
*
* @param node A ForOfStatement.
*/
- function visitForOfStatement(node) {
- var leadingStatements;
- var temp;
- var initializer = ts.skipParentheses(node.initializer);
- if (initializer.transformFlags & 1048576 /* ContainsObjectRest */) {
- if (ts.isVariableDeclarationList(initializer)) {
- temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
- var firstDeclaration = ts.firstOrUndefined(initializer.declarations);
- var declarations = ts.flattenDestructuringBinding(firstDeclaration, visitor, context, 1 /* ObjectRest */, temp,
- /*doNotRecordTempVariablesInLine*/ false,
- /*skipInitializer*/ true);
- if (ts.some(declarations)) {
- var statement = ts.createVariableStatement(
- /*modifiers*/ undefined, ts.updateVariableDeclarationList(initializer, declarations),
- /*location*/ initializer);
- leadingStatements = ts.append(leadingStatements, statement);
- }
- }
- else if (ts.isAssignmentPattern(initializer)) {
- temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
- var expression = ts.flattenDestructuringAssignment(ts.aggregateTransformFlags(ts.createAssignment(initializer, temp, /*location*/ node.initializer)), visitor, context, 1 /* ObjectRest */);
- leadingStatements = ts.append(leadingStatements, ts.createStatement(expression, /*location*/ node.initializer));
- }
+ function visitForOfStatement(node, outermostLabeledStatement) {
+ if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) {
+ node = transformForOfStatementWithObjectRest(node);
}
- if (temp) {
- var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
- var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
- var block = ts.isBlock(statement)
- ? ts.updateBlock(statement, ts.createNodeArray(ts.concatenate(leadingStatements, statement.statements), statement.statements))
- : ts.createBlock(ts.append(leadingStatements, statement), statement, /*multiLine*/ true);
- return ts.updateForOf(node, ts.createVariableDeclarationList([
- ts.createVariableDeclaration(temp, /*type*/ undefined, /*initializer*/ undefined, node.initializer)
- ], node.initializer, 1 /* Let */), expression, block);
+ if (node.awaitModifier) {
+ return transformForAwaitOfStatement(node, outermostLabeledStatement);
}
- return ts.visitEachChild(node, visitor, context);
+ else {
+ return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
+ }
+ }
+ function transformForOfStatementWithObjectRest(node) {
+ var initializerWithoutParens = ts.skipParentheses(node.initializer);
+ if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
+ var bodyLocation = void 0;
+ var statementsLocation = void 0;
+ var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
+ var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)];
+ if (ts.isBlock(node.statement)) {
+ ts.addRange(statements, node.statement.statements);
+ bodyLocation = node.statement;
+ statementsLocation = node.statement.statements;
+ }
+ return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([
+ ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer)
+ ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation),
+ /*multiLine*/ true), bodyLocation));
+ }
+ return node;
+ }
+ function convertForOfStatementHead(node, boundValue) {
+ var binding = ts.createForOfBindingStatement(node.initializer, boundValue);
+ var bodyLocation;
+ var statementsLocation;
+ var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
+ var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
+ if (ts.isBlock(statement)) {
+ ts.addRange(statements, statement.statements);
+ bodyLocation = statement;
+ statementsLocation = statement.statements;
+ }
+ else {
+ statements.push(statement);
+ }
+ return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation),
+ /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
+ }
+ function transformForAwaitOfStatement(node, outermostLabeledStatement) {
+ var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
+ var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
+ var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
+ var errorRecord = ts.createUniqueName("e");
+ var catchVariable = ts.getGeneratedNameForNode(errorRecord);
+ var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
+ var values = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
+ var next = ts.createYield(
+ /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */
+ ? ts.createArrayLiteral([
+ ts.createLiteral("await"),
+ ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, [])
+ ])
+ : ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []));
+ hoistVariableDeclaration(errorRecord);
+ hoistVariableDeclaration(returnMethod);
+ var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
+ /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
+ ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression),
+ ts.createVariableDeclaration(result, /*type*/ undefined, next)
+ ]), node.expression), 1048576 /* NoHoisting */),
+ /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")),
+ /*incrementor*/ ts.createAssignment(result, next),
+ /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))),
+ /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
+ return ts.createTry(ts.createBlock([
+ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
+ ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
+ ts.createStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
+ ts.createPropertyAssignment("error", catchVariable)
+ ])))
+ ]), 1 /* SingleLine */)), ts.createBlock([
+ ts.createTry(
+ /*tryBlock*/ ts.createBlock([
+ ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(
+ /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */
+ ? ts.createArrayLiteral([
+ ts.createLiteral("await"),
+ ts.createFunctionCall(returnMethod, iterator, [])
+ ])
+ : ts.createFunctionCall(returnMethod, iterator, [])))), 1 /* SingleLine */)
+ ]),
+ /*catchClause*/ undefined,
+ /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
+ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
+ ]), 1 /* SingleLine */))
+ ]));
}
function visitParameter(node) {
if (node.transformFlags & 1048576 /* ContainsObjectRest */) {
@@ -48041,48 +52077,137 @@ var ts;
return ts.updateParameter(node,
/*decorators*/ undefined,
/*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node),
+ /*questionToken*/ undefined,
/*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
}
return ts.visitEachChild(node, visitor, context);
}
function visitConstructorDeclaration(node) {
- return ts.updateConstructor(node,
+ var savedEnclosingFunctionFlags = enclosingFunctionFlags;
+ enclosingFunctionFlags = 0 /* Normal */;
+ var updated = ts.updateConstructor(node,
/*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
+ enclosingFunctionFlags = savedEnclosingFunctionFlags;
+ return updated;
}
function visitGetAccessorDeclaration(node) {
- return ts.updateGetAccessor(node,
+ var savedEnclosingFunctionFlags = enclosingFunctionFlags;
+ enclosingFunctionFlags = 0 /* Normal */;
+ var updated = ts.updateGetAccessor(node,
/*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, transformFunctionBody(node));
+ enclosingFunctionFlags = savedEnclosingFunctionFlags;
+ return updated;
}
function visitSetAccessorDeclaration(node) {
- return ts.updateSetAccessor(node,
+ var savedEnclosingFunctionFlags = enclosingFunctionFlags;
+ enclosingFunctionFlags = 0 /* Normal */;
+ var updated = ts.updateSetAccessor(node,
/*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
+ enclosingFunctionFlags = savedEnclosingFunctionFlags;
+ return updated;
}
function visitMethodDeclaration(node) {
- return ts.updateMethod(node,
- /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName),
+ var savedEnclosingFunctionFlags = enclosingFunctionFlags;
+ enclosingFunctionFlags = ts.getFunctionFlags(node);
+ var updated = ts.updateMethod(node,
+ /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
+ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
+ : node.modifiers, enclosingFunctionFlags & 2 /* Async */
+ ? undefined
+ : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken),
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, transformFunctionBody(node));
+ /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
+ ? transformAsyncGeneratorFunctionBody(node)
+ : transformFunctionBody(node));
+ enclosingFunctionFlags = savedEnclosingFunctionFlags;
+ return updated;
}
function visitFunctionDeclaration(node) {
- return ts.updateFunctionDeclaration(node,
- /*decorators*/ undefined, node.modifiers, node.name,
+ var savedEnclosingFunctionFlags = enclosingFunctionFlags;
+ enclosingFunctionFlags = ts.getFunctionFlags(node);
+ var updated = ts.updateFunctionDeclaration(node,
+ /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
+ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
+ : node.modifiers, enclosingFunctionFlags & 2 /* Async */
+ ? undefined
+ : node.asteriskToken, node.name,
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, transformFunctionBody(node));
+ /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
+ ? transformAsyncGeneratorFunctionBody(node)
+ : transformFunctionBody(node));
+ enclosingFunctionFlags = savedEnclosingFunctionFlags;
+ return updated;
}
function visitArrowFunction(node) {
- return ts.updateArrowFunction(node, node.modifiers,
+ var savedEnclosingFunctionFlags = enclosingFunctionFlags;
+ enclosingFunctionFlags = ts.getFunctionFlags(node);
+ var updated = ts.updateArrowFunction(node, node.modifiers,
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
/*type*/ undefined, transformFunctionBody(node));
+ enclosingFunctionFlags = savedEnclosingFunctionFlags;
+ return updated;
}
function visitFunctionExpression(node) {
- return ts.updateFunctionExpression(node, node.modifiers, node.name,
+ var savedEnclosingFunctionFlags = enclosingFunctionFlags;
+ enclosingFunctionFlags = ts.getFunctionFlags(node);
+ var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
+ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
+ : node.modifiers, enclosingFunctionFlags & 2 /* Async */
+ ? undefined
+ : node.asteriskToken, node.name,
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, transformFunctionBody(node));
+ /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
+ ? transformAsyncGeneratorFunctionBody(node)
+ : transformFunctionBody(node));
+ enclosingFunctionFlags = savedEnclosingFunctionFlags;
+ return updated;
+ }
+ function transformAsyncGeneratorFunctionBody(node) {
+ resumeLexicalEnvironment();
+ var statements = [];
+ var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
+ appendObjectRestAssignmentsIfNeeded(statements, node);
+ statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(
+ /*modifiers*/ undefined, ts.createToken(38 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name),
+ /*typeParameters*/ undefined,
+ /*parameters*/ [],
+ /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))));
+ ts.addRange(statements, endLexicalEnvironment());
+ var block = ts.updateBlock(node.body, statements);
+ // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
+ // This step isn't needed if we eventually transform this to ES5.
+ if (languageVersion >= 2 /* ES2015 */) {
+ if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
+ enableSubstitutionForAsyncMethodsWithSuper();
+ ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
+ }
+ else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
+ enableSubstitutionForAsyncMethodsWithSuper();
+ ts.addEmitHelper(block, ts.asyncSuperHelper);
+ }
+ }
+ return block;
}
function transformFunctionBody(node) {
resumeLexicalEnvironment();
- var leadingStatements;
+ var statementOffset = 0;
+ var statements = [];
+ var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
+ if (ts.isBlock(body)) {
+ statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
+ }
+ ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
+ var trailingStatements = endLexicalEnvironment();
+ if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) {
+ var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
+ ts.addRange(statements, block.statements.slice(statementOffset));
+ ts.addRange(statements, trailingStatements);
+ return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
+ }
+ return body;
+ }
+ function appendObjectRestAssignmentsIfNeeded(statements, node) {
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) {
@@ -48094,17 +52219,116 @@ var ts;
var statement = ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList(declarations));
ts.setEmitFlags(statement, 524288 /* CustomPrologue */);
- leadingStatements = ts.append(leadingStatements, statement);
+ statements = ts.append(statements, statement);
}
}
}
- var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
- var trailingStatements = endLexicalEnvironment();
- if (ts.some(leadingStatements) || ts.some(trailingStatements)) {
- var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
- return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(ts.concatenate(leadingStatements, block.statements), trailingStatements), block.statements));
+ return statements;
+ }
+ function enableSubstitutionForAsyncMethodsWithSuper() {
+ if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
+ enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
+ // We need to enable substitutions for call, property access, and element access
+ // if we need to rewrite super calls.
+ context.enableSubstitution(180 /* CallExpression */);
+ context.enableSubstitution(178 /* PropertyAccessExpression */);
+ context.enableSubstitution(179 /* ElementAccessExpression */);
+ // We need to be notified when entering and exiting declarations that bind super.
+ context.enableEmitNotification(228 /* ClassDeclaration */);
+ context.enableEmitNotification(150 /* MethodDeclaration */);
+ context.enableEmitNotification(152 /* GetAccessor */);
+ context.enableEmitNotification(153 /* SetAccessor */);
+ context.enableEmitNotification(151 /* Constructor */);
+ }
+ }
+ /**
+ * Called by the printer just before a node is printed.
+ *
+ * @param hint A hint as to the intended usage of the node.
+ * @param node The node to be printed.
+ * @param emitCallback The callback used to emit the node.
+ */
+ function onEmitNode(hint, node, emitCallback) {
+ // If we need to support substitutions for `super` in an async method,
+ // we should track it here.
+ if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
+ var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
+ if (superContainerFlags !== enclosingSuperContainerFlags) {
+ var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
+ enclosingSuperContainerFlags = superContainerFlags;
+ previousOnEmitNode(hint, node, emitCallback);
+ enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
+ return;
+ }
+ }
+ previousOnEmitNode(hint, node, emitCallback);
+ }
+ /**
+ * Hooks node substitutions.
+ *
+ * @param hint The context for the emitter.
+ * @param node The node to substitute.
+ */
+ function onSubstituteNode(hint, node) {
+ node = previousOnSubstituteNode(hint, node);
+ if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
+ return substituteExpression(node);
+ }
+ return node;
+ }
+ function substituteExpression(node) {
+ switch (node.kind) {
+ case 178 /* PropertyAccessExpression */:
+ return substitutePropertyAccessExpression(node);
+ case 179 /* ElementAccessExpression */:
+ return substituteElementAccessExpression(node);
+ case 180 /* CallExpression */:
+ return substituteCallExpression(node);
+ }
+ return node;
+ }
+ function substitutePropertyAccessExpression(node) {
+ if (node.expression.kind === 96 /* SuperKeyword */) {
+ return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node);
+ }
+ return node;
+ }
+ function substituteElementAccessExpression(node) {
+ if (node.expression.kind === 96 /* SuperKeyword */) {
+ return createSuperAccessInAsyncMethod(node.argumentExpression, node);
+ }
+ return node;
+ }
+ function substituteCallExpression(node) {
+ var expression = node.expression;
+ if (ts.isSuperProperty(expression)) {
+ var argumentExpression = ts.isPropertyAccessExpression(expression)
+ ? substitutePropertyAccessExpression(expression)
+ : substituteElementAccessExpression(expression);
+ return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"),
+ /*typeArguments*/ undefined, [
+ ts.createThis()
+ ].concat(node.arguments));
+ }
+ return node;
+ }
+ function isSuperContainer(node) {
+ var kind = node.kind;
+ return kind === 228 /* ClassDeclaration */
+ || kind === 151 /* Constructor */
+ || kind === 150 /* MethodDeclaration */
+ || kind === 152 /* GetAccessor */
+ || kind === 153 /* SetAccessor */;
+ }
+ function createSuperAccessInAsyncMethod(argumentExpression, location) {
+ if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
+ return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"),
+ /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
+ }
+ else {
+ return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"),
+ /*typeArguments*/ undefined, [argumentExpression]), location);
}
- return body;
}
}
ts.transformESNext = transformESNext;
@@ -48115,11 +52339,51 @@ var ts;
text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };"
};
function createAssignHelper(context, attributesSegments) {
+ if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
+ return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
+ /*typeArguments*/ undefined, attributesSegments);
+ }
context.requestEmitHelper(assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
+ var asyncGeneratorHelper = {
+ name: "typescript:asyncGenerator",
+ scoped: false,
+ text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? _yield : r.value[0] === \"delegate\" ? delegate : fulfill, reject); }\n function _yield(value) { settle(c[2], { value: value, done: false }); }\n function delegate(r) { step(r.done ? r : { value: [\"yield\", r.value], done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n "
+ };
+ function createAsyncGeneratorHelper(context, generatorFunc) {
+ context.requestEmitHelper(asyncGeneratorHelper);
+ // Mark this node as originally an async function
+ (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072 /* AsyncFunctionBody */;
+ return ts.createCall(ts.getHelperName("__asyncGenerator"),
+ /*typeArguments*/ undefined, [
+ ts.createThis(),
+ ts.createIdentifier("arguments"),
+ generatorFunc
+ ]);
+ }
+ var asyncDelegator = {
+ name: "typescript:asyncDelegator",
+ scoped: false,
+ text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) };\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return { value: [\"delegate\", (o[n] || f).call(o, v)], done: false }; }; }\n };\n "
+ };
+ function createAsyncDelegatorHelper(context, expression, location) {
+ context.requestEmitHelper(asyncDelegator);
+ return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
+ /*typeArguments*/ undefined, [expression]), location);
+ }
+ var asyncValues = {
+ name: "typescript:asyncValues",
+ scoped: false,
+ text: "\n var __asyncValues = (this && this.__asyncIterator) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n "
+ };
+ function createAsyncValuesHelper(context, expression, location) {
+ context.requestEmitHelper(asyncValues);
+ return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
+ /*typeArguments*/ undefined, [expression]), location);
+ }
})(ts || (ts = {}));
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
@@ -48129,7 +52393,6 @@ var ts;
(function (ts) {
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
- var currentSourceFile;
return transformSourceFile;
/**
* Transform JSX-specific syntax in a SourceFile.
@@ -48140,10 +52403,8 @@ var ts;
if (ts.isDeclarationFile(node)) {
return node;
}
- currentSourceFile = node;
var visited = ts.visitEachChild(node, visitor, context);
ts.addEmitHelpers(visited, context.readEmitHelpers());
- currentSourceFile = undefined;
return visited;
}
function visitor(node) {
@@ -48156,11 +52417,11 @@ var ts;
}
function visitorWorker(node) {
switch (node.kind) {
- case 246 /* JsxElement */:
+ case 248 /* JsxElement */:
return visitJsxElement(node, /*isChild*/ false);
- case 247 /* JsxSelfClosingElement */:
+ case 249 /* JsxSelfClosingElement */:
return visitJsxSelfClosingElement(node, /*isChild*/ false);
- case 252 /* JsxExpression */:
+ case 255 /* JsxExpression */:
return visitJsxExpression(node);
default:
return ts.visitEachChild(node, visitor, context);
@@ -48170,11 +52431,11 @@ var ts;
switch (node.kind) {
case 10 /* JsxText */:
return visitJsxText(node);
- case 252 /* JsxExpression */:
+ case 255 /* JsxExpression */:
return visitJsxExpression(node);
- case 246 /* JsxElement */:
+ case 248 /* JsxElement */:
return visitJsxElement(node, /*isChild*/ true);
- case 247 /* JsxSelfClosingElement */:
+ case 249 /* JsxSelfClosingElement */:
return visitJsxSelfClosingElement(node, /*isChild*/ true);
default:
ts.Debug.failBadSyntaxKind(node);
@@ -48190,7 +52451,7 @@ var ts;
function visitJsxOpeningLikeElement(node, children, isChild, location) {
var tagName = getTagName(node);
var objectProperties;
- var attrs = node.attributes;
+ var attrs = node.attributes.properties;
if (attrs.length === 0) {
// When there are no attributes, React wants "null"
objectProperties = ts.createNull();
@@ -48229,13 +52490,16 @@ var ts;
}
function transformJsxAttributeInitializer(node) {
if (node === undefined) {
- return ts.createLiteral(true);
+ return ts.createTrue();
}
else if (node.kind === 9 /* StringLiteral */) {
var decoded = tryDecodeEntities(node.text);
- return decoded ? ts.createLiteral(decoded, /*location*/ node) : node;
+ return decoded ? ts.setTextRange(ts.createLiteral(decoded), node) : node;
}
- else if (node.kind === 252 /* JsxExpression */) {
+ else if (node.kind === 255 /* JsxExpression */) {
+ if (node.expression === undefined) {
+ return ts.createTrue();
+ }
return visitJsxExpression(node);
}
else {
@@ -48243,54 +52507,61 @@ var ts;
}
}
function visitJsxText(node) {
- var text = ts.getTextOfNode(node, /*includeTrivia*/ true);
- var parts;
+ var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true));
+ return fixed === undefined ? undefined : ts.createLiteral(fixed);
+ }
+ /**
+ * JSX trims whitespace at the end and beginning of lines, except that the
+ * start/end of a tag is considered a start/end of a line only if that line is
+ * on the same line as the closing tag. See examples in
+ * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
+ * See also https://www.w3.org/TR/html4/struct/text.html#h-9.1 and https://www.w3.org/TR/CSS2/text.html#white-space-model
+ *
+ * An equivalent algorithm would be:
+ * - If there is only one line, return it.
+ * - If there is only whitespace (but multiple lines), return `undefined`.
+ * - Split the text into lines.
+ * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
+ * - Decode entities on each line (individually).
+ * - Remove empty lines and join the rest with " ".
+ */
+ function fixupWhitespaceAndDecodeEntities(text) {
+ var acc;
+ // First non-whitespace character on this line.
var firstNonWhitespace = 0;
+ // Last non-whitespace character on this line.
var lastNonWhitespace = -1;
- // JSX trims whitespace at the end and beginning of lines, except that the
- // start/end of a tag is considered a start/end of a line only if that line is
- // on the same line as the closing tag. See examples in
- // tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
+ // These initial values are special because the first line is:
+ // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
+ // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
for (var i = 0; i < text.length; i++) {
var c = text.charCodeAt(i);
if (ts.isLineBreak(c)) {
- if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) {
- var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1);
- if (!parts) {
- parts = [];
- }
- // We do not escape the string here as that is handled by the printer
- // when it emits the literal. We do, however, need to decode JSX entities.
- parts.push(ts.createLiteral(decodeEntities(part)));
+ // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
+ // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
+ if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
+ acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
}
+ // Reset firstNonWhitespace for the next line.
+ // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
firstNonWhitespace = -1;
}
- else if (!ts.isWhiteSpace(c)) {
+ else if (!ts.isWhiteSpaceSingleLine(c)) {
lastNonWhitespace = i;
if (firstNonWhitespace === -1) {
firstNonWhitespace = i;
}
}
}
- if (firstNonWhitespace !== -1) {
- var part = text.substr(firstNonWhitespace);
- if (!parts) {
- parts = [];
- }
- // We do not escape the string here as that is handled by the printer
- // when it emits the literal. We do, however, need to decode JSX entities.
- parts.push(ts.createLiteral(decodeEntities(part)));
- }
- if (parts) {
- return ts.reduceLeft(parts, aggregateJsxTextParts);
- }
- return undefined;
+ return firstNonWhitespace !== -1
+ ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
+ : acc;
}
- /**
- * Aggregates two expressions by interpolating them with a whitespace literal.
- */
- function aggregateJsxTextParts(left, right) {
- return ts.createAdd(ts.createAdd(left, ts.createLiteral(" ")), right);
+ function addLineOfJsxText(acc, trimmedLine) {
+ // We do not escape the string here as that is handled by the printer
+ // when it emits the literal. We do, however, need to decode JSX entities.
+ var decoded = decodeEntities(trimmedLine);
+ return acc === undefined ? decoded : acc + " " + decoded;
}
/**
* Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
@@ -48305,7 +52576,7 @@ var ts;
return String.fromCharCode(parseInt(hex, 16));
}
else {
- var ch = entities[word];
+ var ch = entities.get(word);
// If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
return ch ? String.fromCharCode(ch) : match;
}
@@ -48317,16 +52588,16 @@ var ts;
return decoded === text ? undefined : decoded;
}
function getTagName(node) {
- if (node.kind === 246 /* JsxElement */) {
+ if (node.kind === 248 /* JsxElement */) {
return getTagName(node.openingElement);
}
else {
- var name_34 = node.tagName;
- if (ts.isIdentifier(name_34) && ts.isIntrinsicJsxName(name_34.text)) {
- return ts.createLiteral(name_34.text);
+ var name = node.tagName;
+ if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.text)) {
+ return ts.createLiteral(name.text);
}
else {
- return ts.createExpressionFromEntityName(name_34);
+ return ts.createExpressionFromEntityName(name);
}
}
}
@@ -48349,7 +52620,7 @@ var ts;
}
}
ts.transformJsx = transformJsx;
- var entities = ts.createMap({
+ var entities = ts.createMapFromTemplate({
"quot": 0x0022,
"amp": 0x0026,
"apos": 0x0027,
@@ -48610,375 +52881,6 @@ var ts;
/*@internal*/
var ts;
(function (ts) {
- var ES2017SubstitutionFlags;
- (function (ES2017SubstitutionFlags) {
- /** Enables substitutions for async methods with `super` calls. */
- ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
- })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
- function transformES2017(context) {
- var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment;
- var resolver = context.getEmitResolver();
- var compilerOptions = context.getCompilerOptions();
- var languageVersion = ts.getEmitScriptTarget(compilerOptions);
- // These variables contain state that changes as we descend into the tree.
- var currentSourceFile;
- /**
- * Keeps track of whether expression substitution has been enabled for specific edge cases.
- * They are persisted between each SourceFile transformation and should not be reset.
- */
- var enabledSubstitutions;
- /**
- * This keeps track of containers where `super` is valid, for use with
- * just-in-time substitution for `super` expressions inside of async methods.
- */
- var currentSuperContainer;
- // Save the previous transformation hooks.
- var previousOnEmitNode = context.onEmitNode;
- var previousOnSubstituteNode = context.onSubstituteNode;
- // Set new transformation hooks.
- context.onEmitNode = onEmitNode;
- context.onSubstituteNode = onSubstituteNode;
- return transformSourceFile;
- function transformSourceFile(node) {
- if (ts.isDeclarationFile(node)) {
- return node;
- }
- currentSourceFile = node;
- var visited = ts.visitEachChild(node, visitor, context);
- ts.addEmitHelpers(visited, context.readEmitHelpers());
- currentSourceFile = undefined;
- return visited;
- }
- function visitor(node) {
- if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) {
- return node;
- }
- switch (node.kind) {
- case 119 /* AsyncKeyword */:
- // ES2017 async modifier should be elided for targets < ES2017
- return undefined;
- case 189 /* AwaitExpression */:
- // ES2017 'await' expressions must be transformed for targets < ES2017.
- return visitAwaitExpression(node);
- case 149 /* MethodDeclaration */:
- // ES2017 method declarations may be 'async'
- return visitMethodDeclaration(node);
- case 225 /* FunctionDeclaration */:
- // ES2017 function declarations may be 'async'
- return visitFunctionDeclaration(node);
- case 184 /* FunctionExpression */:
- // ES2017 function expressions may be 'async'
- return visitFunctionExpression(node);
- case 185 /* ArrowFunction */:
- // ES2017 arrow functions may be 'async'
- return visitArrowFunction(node);
- default:
- return ts.visitEachChild(node, visitor, context);
- }
- }
- /**
- * Visits an AwaitExpression node.
- *
- * This function will be called any time a ES2017 await expression is encountered.
- *
- * @param node The node to visit.
- */
- function visitAwaitExpression(node) {
- return ts.setOriginalNode(ts.createYield(
- /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression),
- /*location*/ node), node);
- }
- /**
- * Visits a MethodDeclaration node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked as async
- *
- * @param node The node to visit.
- */
- function visitMethodDeclaration(node) {
- return ts.updateMethod(node,
- /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name,
- /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, ts.isAsyncFunctionLike(node)
- ? transformAsyncFunctionBody(node)
- : ts.visitFunctionBody(node.body, visitor, context));
- }
- /**
- * Visits a FunctionDeclaration node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked async
- *
- * @param node The node to visit.
- */
- function visitFunctionDeclaration(node) {
- return ts.updateFunctionDeclaration(node,
- /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name,
- /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, ts.isAsyncFunctionLike(node)
- ? transformAsyncFunctionBody(node)
- : ts.visitFunctionBody(node.body, visitor, context));
- }
- /**
- * Visits a FunctionExpression node.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked async
- *
- * @param node The node to visit.
- */
- function visitFunctionExpression(node) {
- if (ts.nodeIsMissing(node.body)) {
- return ts.createOmittedExpression();
- }
- return ts.updateFunctionExpression(node,
- /*modifiers*/ undefined, node.name,
- /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, ts.isAsyncFunctionLike(node)
- ? transformAsyncFunctionBody(node)
- : ts.visitFunctionBody(node.body, visitor, context));
- }
- /**
- * Visits an ArrowFunction.
- *
- * This function will be called when one of the following conditions are met:
- * - The node is marked async
- *
- * @param node The node to visit.
- */
- function visitArrowFunction(node) {
- return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier),
- /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, ts.isAsyncFunctionLike(node)
- ? transformAsyncFunctionBody(node)
- : ts.visitFunctionBody(node.body, visitor, context));
- }
- function transformAsyncFunctionBody(node) {
- resumeLexicalEnvironment();
- var original = ts.getOriginalNode(node, ts.isFunctionLike);
- var nodeType = original.type;
- var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
- var isArrowFunction = node.kind === 185 /* ArrowFunction */;
- var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
- // An async function is emit as an outer function that calls an inner
- // generator function. To preserve lexical bindings, we pass the current
- // `this` and `arguments` objects to `__awaiter`. The generator function
- // passed to `__awaiter` is executed inside of the callback to the
- // promise constructor.
- if (!isArrowFunction) {
- var statements = [];
- var statementOffset = ts.addPrologueDirectives(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
- statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset))));
- ts.addRange(statements, endLexicalEnvironment());
- var block = ts.createBlock(statements, /*location*/ node.body, /*multiLine*/ true);
- // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
- // This step isn't needed if we eventually transform this to ES5.
- if (languageVersion >= 2 /* ES2015 */) {
- if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
- enableSubstitutionForAsyncMethodsWithSuper();
- ts.addEmitHelper(block, advancedAsyncSuperHelper);
- }
- else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
- enableSubstitutionForAsyncMethodsWithSuper();
- ts.addEmitHelper(block, asyncSuperHelper);
- }
- }
- return block;
- }
- else {
- var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body));
- var declarations = endLexicalEnvironment();
- if (ts.some(declarations)) {
- var block = ts.convertToFunctionBody(expression);
- return ts.updateBlock(block, ts.createNodeArray(ts.concatenate(block.statements, declarations), block.statements));
- }
- return expression;
- }
- }
- function transformFunctionBodyWorker(body, start) {
- if (ts.isBlock(body)) {
- return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start));
- }
- else {
- startLexicalEnvironment();
- var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody));
- var declarations = endLexicalEnvironment();
- return ts.updateBlock(visited, ts.createNodeArray(ts.concatenate(visited.statements, declarations), visited.statements));
- }
- }
- function getPromiseConstructor(type) {
- var typeName = type && ts.getEntityNameFromTypeNode(type);
- if (typeName && ts.isEntityName(typeName)) {
- var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
- if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
- || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
- return typeName;
- }
- }
- return undefined;
- }
- function enableSubstitutionForAsyncMethodsWithSuper() {
- if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
- enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
- // We need to enable substitutions for call, property access, and element access
- // if we need to rewrite super calls.
- context.enableSubstitution(179 /* CallExpression */);
- context.enableSubstitution(177 /* PropertyAccessExpression */);
- context.enableSubstitution(178 /* ElementAccessExpression */);
- // We need to be notified when entering and exiting declarations that bind super.
- context.enableEmitNotification(226 /* ClassDeclaration */);
- context.enableEmitNotification(149 /* MethodDeclaration */);
- context.enableEmitNotification(151 /* GetAccessor */);
- context.enableEmitNotification(152 /* SetAccessor */);
- context.enableEmitNotification(150 /* Constructor */);
- }
- }
- function substituteExpression(node) {
- switch (node.kind) {
- case 177 /* PropertyAccessExpression */:
- return substitutePropertyAccessExpression(node);
- case 178 /* ElementAccessExpression */:
- return substituteElementAccessExpression(node);
- case 179 /* CallExpression */:
- if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) {
- return substituteCallExpression(node);
- }
- break;
- }
- return node;
- }
- function substitutePropertyAccessExpression(node) {
- if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && node.expression.kind === 96 /* SuperKeyword */) {
- var flags = getSuperContainerAsyncMethodFlags();
- if (flags) {
- return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node);
- }
- }
- return node;
- }
- function substituteElementAccessExpression(node) {
- if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && node.expression.kind === 96 /* SuperKeyword */) {
- var flags = getSuperContainerAsyncMethodFlags();
- if (flags) {
- return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node);
- }
- }
- return node;
- }
- function substituteCallExpression(node) {
- var expression = node.expression;
- if (ts.isSuperProperty(expression)) {
- var flags = getSuperContainerAsyncMethodFlags();
- if (flags) {
- var argumentExpression = ts.isPropertyAccessExpression(expression)
- ? substitutePropertyAccessExpression(expression)
- : substituteElementAccessExpression(expression);
- return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"),
- /*typeArguments*/ undefined, [
- ts.createThis()
- ].concat(node.arguments));
- }
- }
- return node;
- }
- function isSuperContainer(node) {
- var kind = node.kind;
- return kind === 226 /* ClassDeclaration */
- || kind === 150 /* Constructor */
- || kind === 149 /* MethodDeclaration */
- || kind === 151 /* GetAccessor */
- || kind === 152 /* SetAccessor */;
- }
- /**
- * Hook for node emit.
- *
- * @param node The node to emit.
- * @param emit A callback used to emit the node in the printer.
- */
- function onEmitNode(emitContext, node, emitCallback) {
- // If we need to support substitutions for `super` in an async method,
- // we should track it here.
- if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
- var savedCurrentSuperContainer = currentSuperContainer;
- currentSuperContainer = node;
- previousOnEmitNode(emitContext, node, emitCallback);
- currentSuperContainer = savedCurrentSuperContainer;
- }
- else {
- previousOnEmitNode(emitContext, node, emitCallback);
- }
- }
- /**
- * Hooks node substitutions.
- *
- * @param node The node to substitute.
- * @param isExpression A value indicating whether the node is to be used in an expression
- * position.
- */
- function onSubstituteNode(emitContext, node) {
- node = previousOnSubstituteNode(emitContext, node);
- if (emitContext === 1 /* Expression */) {
- return substituteExpression(node);
- }
- return node;
- }
- function createSuperAccessInAsyncMethod(argumentExpression, flags, location) {
- if (flags & 4096 /* AsyncMethodWithSuperBinding */) {
- return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"),
- /*typeArguments*/ undefined, [argumentExpression]), "value", location);
- }
- else {
- return ts.createCall(ts.createIdentifier("_super"),
- /*typeArguments*/ undefined, [argumentExpression], location);
- }
- }
- function getSuperContainerAsyncMethodFlags() {
- return currentSuperContainer !== undefined
- && resolver.getNodeCheckFlags(currentSuperContainer) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
- }
- }
- ts.transformES2017 = transformES2017;
- function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
- var generatorFunc = ts.createFunctionExpression(
- /*modifiers*/ undefined, ts.createToken(38 /* AsteriskToken */),
- /*name*/ undefined,
- /*typeParameters*/ undefined,
- /*parameters*/ [],
- /*type*/ undefined, body);
- // Mark this node as originally an async function
- (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072 /* AsyncFunctionBody */;
- return ts.createCall(ts.getHelperName("__awaiter"),
- /*typeArguments*/ undefined, [
- ts.createThis(),
- hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
- promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
- generatorFunc
- ]);
- }
- var awaiterHelper = {
- name: "typescript:awaiter",
- scoped: false,
- priority: 5,
- text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n };"
- };
- var asyncSuperHelper = {
- name: "typescript:async-super",
- scoped: true,
- text: "\n const _super = name => super[name];"
- };
- var advancedAsyncSuperHelper = {
- name: "typescript:advanced-async-super",
- scoped: true,
- text: "\n const _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"
- };
-})(ts || (ts = {}));
-/// <reference path="../factory.ts" />
-/// <reference path="../visitor.ts" />
-/*@internal*/
-var ts;
-(function (ts) {
function transformES2016(context) {
var hoistVariableDeclaration = context.hoistVariableDeclaration;
return transformSourceFile;
@@ -48993,7 +52895,7 @@ var ts;
return node;
}
switch (node.kind) {
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return visitBinaryExpression(node);
default:
return ts.visitEachChild(node, visitor, context);
@@ -49018,25 +52920,21 @@ var ts;
// Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
- target = ts.createElementAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), ts.createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression),
- /*location*/ left);
- value = ts.createElementAccess(expressionTemp, argumentExpressionTemp,
- /*location*/ left);
+ target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
+ value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
}
else if (ts.isPropertyAccessExpression(left)) {
// Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
- target = ts.createPropertyAccess(ts.createAssignment(expressionTemp, left.expression, /*location*/ left.expression), left.name,
- /*location*/ left);
- value = ts.createPropertyAccess(expressionTemp, left.name,
- /*location*/ left);
+ target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
+ value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
}
else {
// Transforms `a **= b` into `a = Math.pow(a, b)`
target = left;
value = left;
}
- return ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node), /*location*/ node);
+ return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
}
function visitExponentiationExpression(node) {
// Transforms `a ** b` into `Math.pow(a, b)`
@@ -49049,6 +52947,7 @@ var ts;
})(ts || (ts = {}));
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
+/// <reference path="./destructuring.ts" />
/*@internal*/
var ts;
(function (ts) {
@@ -49094,8 +52993,85 @@ var ts;
*/
SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn";
})(SuperCaptureResult || (SuperCaptureResult = {}));
+ // Facts we track as we traverse the tree
+ var HierarchyFacts;
+ (function (HierarchyFacts) {
+ HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
+ //
+ // Ancestor facts
+ //
+ HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
+ HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
+ HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
+ HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
+ HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
+ HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
+ HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
+ HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
+ HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
+ HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
+ HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement";
+ HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement";
+ HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper";
+ HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName";
+ // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
+ //
+ // Ancestor masks
+ //
+ HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
+ // We are always in *some* kind of block scope, but only specific block-scope containers are
+ // top-level or Blocks.
+ HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
+ HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 4032] = "BlockScopeExcludes";
+ // A source file is a top-level block scope.
+ HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
+ HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes";
+ // Functions, methods, and accessors are both new lexical scopes and new block scopes.
+ HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
+ HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
+ HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
+ HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
+ // Arrow functions are lexically scoped to their container, but are new block scopes.
+ HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
+ HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes";
+ // Constructors are both new lexical scopes and new block scopes. Constructors are also
+ // always considered non-static members of a class.
+ HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
+ HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
+ // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
+ // within an IterationStatement to indicate whether the embedded statement is an
+ // IterationStatementBlock.
+ HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 256] = "DoOrWhileStatementIncludes";
+ HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
+ // 'for' statements are new block scopes and have special handling for 'let' declarations.
+ HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 1280] = "ForStatementIncludes";
+ HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 3008] = "ForStatementExcludes";
+ // 'for-in' and 'for-of' statements are new block scopes and have special handling for
+ // 'let' declarations.
+ HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 2304] = "ForInOrForOfStatementIncludes";
+ HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 1984] = "ForInOrForOfStatementExcludes";
+ // Blocks (other than function bodies) are new block scopes.
+ HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
+ HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes";
+ HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
+ HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes";
+ // Computed property names track subtree flags differently than their containing members.
+ HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes";
+ HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes";
+ //
+ // Subtree facts
+ //
+ HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
+ HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName";
+ //
+ // Subtree masks
+ //
+ HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
+ HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask";
+ })(HierarchyFacts || (HierarchyFacts = {}));
function transformES2015(context) {
var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
+ var compilerOptions = context.getCompilerOptions();
var resolver = context.getEmitResolver();
var previousOnSubstituteNode = context.onSubstituteNode;
var previousOnEmitNode = context.onEmitNode;
@@ -49103,15 +53079,7 @@ var ts;
context.onSubstituteNode = onSubstituteNode;
var currentSourceFile;
var currentText;
- var currentParent;
- var currentNode;
- var enclosingVariableStatement;
- var enclosingBlockScopeContainer;
- var enclosingBlockScopeContainerParent;
- var enclosingFunction;
- var enclosingNonArrowFunction;
- var enclosingNonAsyncFunctionBody;
- var isInConstructorWithCapturedSuper;
+ var hierarchyFacts;
/**
* Used to track if we are emitting body of the converted loop
*/
@@ -49129,257 +53097,221 @@ var ts;
}
currentSourceFile = node;
currentText = node.text;
- var visited = saveStateAndInvoke(node, visitSourceFile);
+ var visited = visitSourceFile(node);
ts.addEmitHelpers(visited, context.readEmitHelpers());
currentSourceFile = undefined;
currentText = undefined;
+ hierarchyFacts = 0 /* None */;
return visited;
}
- function visitor(node) {
- return saveStateAndInvoke(node, dispatcher);
- }
- function dispatcher(node) {
- return convertedLoopState
- ? visitorForConvertedLoopWorker(node)
- : visitorWorker(node);
- }
- function saveStateAndInvoke(node, f) {
- var savedEnclosingFunction = enclosingFunction;
- var savedEnclosingNonArrowFunction = enclosingNonArrowFunction;
- var savedEnclosingNonAsyncFunctionBody = enclosingNonAsyncFunctionBody;
- var savedEnclosingBlockScopeContainer = enclosingBlockScopeContainer;
- var savedEnclosingBlockScopeContainerParent = enclosingBlockScopeContainerParent;
- var savedEnclosingVariableStatement = enclosingVariableStatement;
- var savedCurrentParent = currentParent;
- var savedCurrentNode = currentNode;
- var savedConvertedLoopState = convertedLoopState;
- var savedIsInConstructorWithCapturedSuper = isInConstructorWithCapturedSuper;
- if (ts.nodeStartsNewLexicalEnvironment(node)) {
- // don't treat content of nodes that start new lexical environment as part of converted loop copy or constructor body
- isInConstructorWithCapturedSuper = false;
- convertedLoopState = undefined;
- }
- onBeforeVisitNode(node);
- var visited = f(node);
- isInConstructorWithCapturedSuper = savedIsInConstructorWithCapturedSuper;
- convertedLoopState = savedConvertedLoopState;
- enclosingFunction = savedEnclosingFunction;
- enclosingNonArrowFunction = savedEnclosingNonArrowFunction;
- enclosingNonAsyncFunctionBody = savedEnclosingNonAsyncFunctionBody;
- enclosingBlockScopeContainer = savedEnclosingBlockScopeContainer;
- enclosingBlockScopeContainerParent = savedEnclosingBlockScopeContainerParent;
- enclosingVariableStatement = savedEnclosingVariableStatement;
- currentParent = savedCurrentParent;
- currentNode = savedCurrentNode;
- return visited;
- }
- function onBeforeVisitNode(node) {
- if (currentNode) {
- if (ts.isBlockScope(currentNode, currentParent)) {
- enclosingBlockScopeContainer = currentNode;
- enclosingBlockScopeContainerParent = currentParent;
- }
- if (ts.isFunctionLike(currentNode)) {
- enclosingFunction = currentNode;
- if (currentNode.kind !== 185 /* ArrowFunction */) {
- enclosingNonArrowFunction = currentNode;
- if (!(ts.getEmitFlags(currentNode) & 131072 /* AsyncFunctionBody */)) {
- enclosingNonAsyncFunctionBody = currentNode;
- }
- }
- }
- // keep track of the enclosing variable statement when in the context of
- // variable statements, variable declarations, binding elements, and binding
- // patterns.
- switch (currentNode.kind) {
- case 205 /* VariableStatement */:
- enclosingVariableStatement = currentNode;
- break;
- case 224 /* VariableDeclarationList */:
- case 223 /* VariableDeclaration */:
- case 174 /* BindingElement */:
- case 172 /* ObjectBindingPattern */:
- case 173 /* ArrayBindingPattern */:
- break;
- default:
- enclosingVariableStatement = undefined;
- }
- }
- currentParent = currentNode;
- currentNode = node;
+ /**
+ * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
+ * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
+ * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
+ */
+ function enterSubtree(excludeFacts, includeFacts) {
+ var ancestorFacts = hierarchyFacts;
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
+ return ancestorFacts;
}
- function returnCapturedThis(node) {
- return ts.setOriginalNode(ts.createReturn(ts.createIdentifier("_this")), node);
+ /**
+ * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
+ * subtree, propagating specific facts from the subtree.
+ * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
+ * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
+ * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
+ */
+ function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
+ hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
}
function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
- return isInConstructorWithCapturedSuper && node.kind === 216 /* ReturnStatement */ && !node.expression;
+ return hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */
+ && node.kind === 218 /* ReturnStatement */
+ && !node.expression;
}
- function shouldCheckNode(node) {
- return (node.transformFlags & 64 /* ES2015 */) !== 0 ||
- node.kind === 219 /* LabeledStatement */ ||
- (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node));
+ function shouldVisitNode(node) {
+ return (node.transformFlags & 128 /* ContainsES2015 */) !== 0
+ || convertedLoopState !== undefined
+ || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && ts.isStatement(node))
+ || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node));
}
- function visitorWorker(node) {
- if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
- return returnCapturedThis(node);
- }
- else if (shouldCheckNode(node)) {
+ function visitor(node) {
+ if (shouldVisitNode(node)) {
return visitJavaScript(node);
}
- else if (node.transformFlags & 128 /* ContainsES2015 */ || (isInConstructorWithCapturedSuper && !ts.isExpression(node))) {
- // we want to dive in this branch either if node has children with ES2015 specific syntax
- // or we are inside constructor that captures result of the super call so all returns without expression should be
- // rewritten. Note: we skip expressions since returns should never appear there
- return ts.visitEachChild(node, visitor, context);
- }
else {
return node;
}
}
- function visitorForConvertedLoopWorker(node) {
- var result;
- if (shouldCheckNode(node)) {
- result = visitJavaScript(node);
- }
- else {
- result = visitNodesInConvertedLoop(node);
+ function functionBodyVisitor(node) {
+ if (shouldVisitNode(node)) {
+ return visitBlock(node, /*isFunctionBody*/ true);
}
- return result;
+ return node;
}
- function visitNodesInConvertedLoop(node) {
- switch (node.kind) {
- case 216 /* ReturnStatement */:
- node = isReturnVoidStatementInConstructorWithCapturedSuper(node) ? returnCapturedThis(node) : node;
- return visitReturnStatement(node);
- case 205 /* VariableStatement */:
- return visitVariableStatement(node);
- case 218 /* SwitchStatement */:
- return visitSwitchStatement(node);
- case 215 /* BreakStatement */:
- case 214 /* ContinueStatement */:
- return visitBreakOrContinueStatement(node);
- case 98 /* ThisKeyword */:
- return visitThisKeyword(node);
- case 70 /* Identifier */:
- return visitIdentifier(node);
- default:
- return ts.visitEachChild(node, visitor, context);
+ function callExpressionVisitor(node) {
+ if (node.kind === 96 /* SuperKeyword */) {
+ return visitSuperKeyword(/*isExpressionOfCall*/ true);
}
+ return visitor(node);
}
function visitJavaScript(node) {
switch (node.kind) {
case 114 /* StaticKeyword */:
return undefined; // elide static keyword
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 197 /* ClassExpression */:
+ case 198 /* ClassExpression */:
return visitClassExpression(node);
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
return visitParameter(node);
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return visitFunctionDeclaration(node);
- case 185 /* ArrowFunction */:
+ case 186 /* ArrowFunction */:
return visitArrowFunction(node);
- case 184 /* FunctionExpression */:
+ case 185 /* FunctionExpression */:
return visitFunctionExpression(node);
- case 223 /* VariableDeclaration */:
+ case 225 /* VariableDeclaration */:
return visitVariableDeclaration(node);
case 70 /* Identifier */:
return visitIdentifier(node);
- case 224 /* VariableDeclarationList */:
+ case 226 /* VariableDeclarationList */:
return visitVariableDeclarationList(node);
- case 219 /* LabeledStatement */:
+ case 220 /* SwitchStatement */:
+ return visitSwitchStatement(node);
+ case 234 /* CaseBlock */:
+ return visitCaseBlock(node);
+ case 206 /* Block */:
+ return visitBlock(node, /*isFunctionBody*/ false);
+ case 217 /* BreakStatement */:
+ case 216 /* ContinueStatement */:
+ return visitBreakOrContinueStatement(node);
+ case 221 /* LabeledStatement */:
return visitLabeledStatement(node);
- case 209 /* DoStatement */:
- return visitDoStatement(node);
- case 210 /* WhileStatement */:
- return visitWhileStatement(node);
- case 211 /* ForStatement */:
- return visitForStatement(node);
- case 212 /* ForInStatement */:
- return visitForInStatement(node);
- case 213 /* ForOfStatement */:
- return visitForOfStatement(node);
- case 207 /* ExpressionStatement */:
+ case 211 /* DoStatement */:
+ case 212 /* WhileStatement */:
+ return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
+ case 213 /* ForStatement */:
+ return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
+ case 214 /* ForInStatement */:
+ return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
+ case 215 /* ForOfStatement */:
+ return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
+ case 209 /* ExpressionStatement */:
return visitExpressionStatement(node);
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
return visitObjectLiteralExpression(node);
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return visitCatchClause(node);
- case 258 /* ShorthandPropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
return visitShorthandPropertyAssignment(node);
- case 175 /* ArrayLiteralExpression */:
+ case 143 /* ComputedPropertyName */:
+ return visitComputedPropertyName(node);
+ case 176 /* ArrayLiteralExpression */:
return visitArrayLiteralExpression(node);
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
return visitCallExpression(node);
- case 180 /* NewExpression */:
+ case 181 /* NewExpression */:
return visitNewExpression(node);
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
case 12 /* NoSubstitutionTemplateLiteral */:
case 13 /* TemplateHead */:
case 14 /* TemplateMiddle */:
case 15 /* TemplateTail */:
return visitTemplateLiteral(node);
- case 181 /* TaggedTemplateExpression */:
+ case 9 /* StringLiteral */:
+ return visitStringLiteral(node);
+ case 8 /* NumericLiteral */:
+ return visitNumericLiteral(node);
+ case 182 /* TaggedTemplateExpression */:
return visitTaggedTemplateExpression(node);
- case 194 /* TemplateExpression */:
+ case 195 /* TemplateExpression */:
return visitTemplateExpression(node);
- case 195 /* YieldExpression */:
+ case 196 /* YieldExpression */:
return visitYieldExpression(node);
- case 196 /* SpreadElement */:
+ case 197 /* SpreadElement */:
return visitSpreadElement(node);
case 96 /* SuperKeyword */:
- return visitSuperKeyword();
- case 195 /* YieldExpression */:
- // `yield` will be handled by a generators transform.
- return ts.visitEachChild(node, visitor, context);
- case 149 /* MethodDeclaration */:
+ return visitSuperKeyword(/*isExpressionOfCall*/ false);
+ case 98 /* ThisKeyword */:
+ return visitThisKeyword(node);
+ case 203 /* MetaProperty */:
+ return visitMetaProperty(node);
+ case 150 /* MethodDeclaration */:
return visitMethodDeclaration(node);
- case 205 /* VariableStatement */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ return visitAccessorDeclaration(node);
+ case 207 /* VariableStatement */:
return visitVariableStatement(node);
+ case 218 /* ReturnStatement */:
+ return visitReturnStatement(node);
default:
- ts.Debug.failBadSyntaxKind(node);
return ts.visitEachChild(node, visitor, context);
}
}
function visitSourceFile(node) {
+ var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
var statements = [];
startLexicalEnvironment();
- var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor);
+ var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
addCaptureThisForNodeIfNeeded(statements, node);
+ statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor);
ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
ts.addRange(statements, endLexicalEnvironment());
- return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements));
+ exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
}
function visitSwitchStatement(node) {
- ts.Debug.assert(convertedLoopState !== undefined);
- var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
- // for switch statement allow only non-labeled break
- convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
- var result = ts.visitEachChild(node, visitor, context);
- convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
- return result;
+ if (convertedLoopState !== undefined) {
+ var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
+ // for switch statement allow only non-labeled break
+ convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
+ var result = ts.visitEachChild(node, visitor, context);
+ convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
+ return result;
+ }
+ return ts.visitEachChild(node, visitor, context);
+ }
+ function visitCaseBlock(node) {
+ var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
+ var updated = ts.visitEachChild(node, visitor, context);
+ exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ return updated;
+ }
+ function returnCapturedThis(node) {
+ return ts.setOriginalNode(ts.createReturn(ts.createIdentifier("_this")), node);
}
function visitReturnStatement(node) {
- ts.Debug.assert(convertedLoopState !== undefined);
- convertedLoopState.nonLocalJumps |= 8 /* Return */;
- return ts.createReturn(ts.createObjectLiteral([
- ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
- ? ts.visitNode(node.expression, visitor, ts.isExpression)
- : ts.createVoidZero())
- ]));
+ if (convertedLoopState) {
+ convertedLoopState.nonLocalJumps |= 8 /* Return */;
+ if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
+ node = returnCapturedThis(node);
+ }
+ return ts.createReturn(ts.createObjectLiteral([
+ ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
+ ? ts.visitNode(node.expression, visitor, ts.isExpression)
+ : ts.createVoidZero())
+ ]));
+ }
+ else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
+ return returnCapturedThis(node);
+ }
+ return ts.visitEachChild(node, visitor, context);
}
function visitThisKeyword(node) {
- ts.Debug.assert(convertedLoopState !== undefined);
- if (enclosingFunction && enclosingFunction.kind === 185 /* ArrowFunction */) {
- // if the enclosing function is an ArrowFunction is then we use the captured 'this' keyword.
- convertedLoopState.containsLexicalThis = true;
- return node;
+ if (convertedLoopState) {
+ if (hierarchyFacts & 2 /* ArrowFunction */) {
+ // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
+ convertedLoopState.containsLexicalThis = true;
+ return node;
+ }
+ return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
}
- return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
+ return node;
}
function visitIdentifier(node) {
if (!convertedLoopState) {
@@ -49388,7 +53320,7 @@ var ts;
if (ts.isGeneratedIdentifier(node)) {
return node;
}
- if (node.text !== "arguments" && !resolver.isArgumentsLocalBinding(node)) {
+ if (node.text !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
return node;
}
return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments"));
@@ -49399,13 +53331,13 @@ var ts;
// it is possible if either
// - break/continue is labeled and label is located inside the converted loop
// - break/continue is non-labeled and located in non-converted loop/switch statement
- var jump = node.kind === 215 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
- var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) ||
+ var jump = node.kind === 217 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
+ var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(node.label.text)) ||
(!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
if (!canUseBreakOrContinue) {
var labelMarker = void 0;
if (!node.label) {
- if (node.kind === 215 /* BreakStatement */) {
+ if (node.kind === 217 /* BreakStatement */) {
convertedLoopState.nonLocalJumps |= 2 /* Break */;
labelMarker = "break";
}
@@ -49416,7 +53348,7 @@ var ts;
}
}
else {
- if (node.kind === 215 /* BreakStatement */) {
+ if (node.kind === 217 /* BreakStatement */) {
labelMarker = "break-" + node.label.text;
setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker);
}
@@ -49464,8 +53396,9 @@ var ts;
/*type*/ undefined, transformClassLikeDeclarationToExpression(node));
ts.setOriginalNode(variable, node);
var statements = [];
- var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]), /*location*/ node);
+ var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]));
ts.setOriginalNode(statement, node);
+ ts.setTextRange(statement, node);
ts.startOnNewLine(statement);
statements.push(statement);
// Add an `export default` statement for default exports (for `--target es5 --module es6`)
@@ -49583,7 +53516,7 @@ var ts;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
ts.addRange(statements, endLexicalEnvironment());
- var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true);
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
}
@@ -49596,7 +53529,7 @@ var ts;
*/
function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
if (extendsClauseElement) {
- statements.push(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node)),
+ statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))),
/*location*/ extendsClauseElement));
}
}
@@ -49608,6 +53541,9 @@ var ts;
* @param extendsClauseElement The expression for the class `extends` clause.
*/
function addConstructor(statements, node, extendsClauseElement) {
+ var savedConvertedLoopState = convertedLoopState;
+ convertedLoopState = undefined;
+ var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
var constructor = ts.getFirstConstructorWithBody(node);
var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
var constructorFunction = ts.createFunctionDeclaration(
@@ -49615,12 +53551,14 @@ var ts;
/*modifiers*/ undefined,
/*asteriskToken*/ undefined, ts.getDeclarationName(node),
/*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper),
- /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper),
- /*location*/ constructor || node);
+ /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
+ ts.setTextRange(constructorFunction, constructor || node);
if (extendsClauseElement) {
ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
}
statements.push(constructorFunction);
+ exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ convertedLoopState = savedConvertedLoopState;
}
/**
* Transforms the parameters of the constructor declaration of a class.
@@ -49658,38 +53596,46 @@ var ts;
statementOffset = 0;
}
else if (constructor) {
- // Otherwise, try to emit all potential prologue directives first.
- statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, /*ensureUseStrict*/ false, visitor);
+ statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false);
}
if (constructor) {
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
+ if (!hasSynthesizedSuper) {
+ // If no super call has been synthesized, emit custom prologue directives.
+ statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
+ }
ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
}
- var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset);
+ // determine whether the class is known syntactically to be a derived class (e.g. a
+ // class that extends a value that is not syntactically known to be `null`).
+ var isDerivedClass = extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 94 /* NullKeyword */;
+ var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset);
// The last statement expression was replaced. Skip it.
if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) {
statementOffset++;
}
if (constructor) {
- var body = saveStateAndInvoke(constructor, function (constructor) {
- isInConstructorWithCapturedSuper = superCaptureStatus === 1 /* ReplaceSuperCapture */;
- return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset);
- });
- ts.addRange(statements, body);
+ if (superCaptureStatus === 1 /* ReplaceSuperCapture */) {
+ hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */;
+ }
+ ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
}
// Return `_this` unless we're sure enough that it would be pointless to add a return statement.
// If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return.
- if (extendsClauseElement
+ if (isDerivedClass
&& superCaptureStatus !== 2 /* ReplaceWithReturn */
&& !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
statements.push(ts.createReturn(ts.createIdentifier("_this")));
}
ts.addRange(statements, endLexicalEnvironment());
- var block = ts.createBlock(ts.createNodeArray(statements,
+ if (constructor) {
+ prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
+ }
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements),
/*location*/ constructor ? constructor.body.statements : node.members),
- /*location*/ constructor ? constructor.body : node,
/*multiLine*/ true);
+ ts.setTextRange(block, constructor ? constructor.body : node);
if (!constructor) {
ts.setEmitFlags(block, 1536 /* NoComments */);
}
@@ -49702,17 +53648,17 @@ var ts;
*/
function isSufficientlyCoveredByReturnStatements(statement) {
// A return statement is considered covered.
- if (statement.kind === 216 /* ReturnStatement */) {
+ if (statement.kind === 218 /* ReturnStatement */) {
return true;
}
- else if (statement.kind === 208 /* IfStatement */) {
+ else if (statement.kind === 210 /* IfStatement */) {
var ifStatement = statement;
if (ifStatement.elseStatement) {
return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
}
}
- else if (statement.kind === 204 /* Block */) {
+ else if (statement.kind === 206 /* Block */) {
var lastStatement = ts.lastOrUndefined(statement.statements);
if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
return true;
@@ -49725,9 +53671,9 @@ var ts;
*
* @returns The new statement offset into the `statements` array.
*/
- function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) {
+ function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) {
// If this isn't a derived class, just capture 'this' for arrow functions if necessary.
- if (!hasExtendsClause) {
+ if (!isDerivedClass) {
if (ctor) {
addCaptureThisForNodeIfNeeded(statements, ctor);
}
@@ -49770,16 +53716,18 @@ var ts;
var ctorStatements = ctor.body.statements;
if (statementOffset < ctorStatements.length) {
firstStatement = ctorStatements[statementOffset];
- if (firstStatement.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) {
- var superCall = firstStatement.expression;
- superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall);
+ if (firstStatement.kind === 209 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) {
+ superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
}
}
- // Return the result if we have an immediate super() call on the last statement.
- if (superCallExpression && statementOffset === ctorStatements.length - 1) {
+ // Return the result if we have an immediate super() call on the last statement,
+ // but only if the constructor itself doesn't use 'this' elsewhere.
+ if (superCallExpression
+ && statementOffset === ctorStatements.length - 1
+ && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) {
var returnStatement = ts.createReturn(superCallExpression);
- if (superCallExpression.kind !== 192 /* BinaryExpression */
- || superCallExpression.left.kind !== 179 /* CallExpression */) {
+ if (superCallExpression.kind !== 193 /* BinaryExpression */
+ || superCallExpression.left.kind !== 180 /* CallExpression */) {
ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'.");
}
// Shift comments from the original super call to the return statement.
@@ -49788,18 +53736,18 @@ var ts;
return 2 /* ReplaceWithReturn */;
}
// Perform the capture.
- captureThisForNode(statements, ctor, superCallExpression, firstStatement);
+ captureThisForNode(statements, ctor, superCallExpression || createActualThis(), firstStatement);
// If we're actually replacing the original statement, we need to signal this to the caller.
if (superCallExpression) {
return 1 /* ReplaceSuperCapture */;
}
return 0 /* NoReplacement */;
}
+ function createActualThis() {
+ return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
+ }
function createDefaultSuperCallOrThis() {
- var actualThis = ts.createThis();
- ts.setEmitFlags(actualThis, 4 /* NoSubstitution */);
- var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments"));
- return ts.createLogicalOr(superCall, actualThis);
+ return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createIdentifier("_super"), ts.createNull()), ts.createFunctionApply(ts.createIdentifier("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis());
}
/**
* Visits a parameter declaration.
@@ -49814,25 +53762,25 @@ var ts;
else if (ts.isBindingPattern(node.name)) {
// Binding patterns are converted into a generated name and are
// evaluated inside the function body.
- return ts.setOriginalNode(ts.createParameter(
+ return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node),
/*questionToken*/ undefined,
/*type*/ undefined,
- /*initializer*/ undefined,
+ /*initializer*/ undefined),
/*location*/ node),
/*original*/ node);
}
else if (node.initializer) {
// Initializers are elided
- return ts.setOriginalNode(ts.createParameter(
+ return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined, node.name,
/*questionToken*/ undefined,
/*type*/ undefined,
- /*initializer*/ undefined,
+ /*initializer*/ undefined),
/*location*/ node),
/*original*/ node);
}
@@ -49862,17 +53810,17 @@ var ts;
}
for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
var parameter = _a[_i];
- var name_35 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
+ var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
// A rest parameter cannot have a binding pattern or an initializer,
// so let's just ignore it.
if (dotDotDotToken) {
continue;
}
- if (ts.isBindingPattern(name_35)) {
- addDefaultValueAssignmentForBindingPattern(statements, parameter, name_35, initializer);
+ if (ts.isBindingPattern(name)) {
+ addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer);
}
else if (initializer) {
- addDefaultValueAssignmentForInitializer(statements, parameter, name_35, initializer);
+ addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
}
}
}
@@ -49907,13 +53855,11 @@ var ts;
*/
function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
initializer = ts.visitNode(initializer, visitor, ts.isExpression);
- var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.createBlock([
- ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer)),
- /*location*/ parameter))
- ], /*location*/ parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */),
- /*elseStatement*/ undefined,
- /*location*/ parameter);
+ var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
+ ts.createStatement(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer))), parameter))
+ ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */));
statement.startsOnNewLine = true;
+ ts.setTextRange(statement, parameter);
ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 524288 /* CustomPrologue */);
statements.push(statement);
}
@@ -49950,22 +53896,21 @@ var ts;
var restIndex = node.parameters.length - 1;
var temp = ts.createLoopVariable();
// var param = [];
- statements.push(ts.setEmitFlags(ts.createVariableStatement(
+ statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(declarationName,
/*type*/ undefined, ts.createArrayLiteral([]))
- ]),
+ ])),
/*location*/ parameter), 524288 /* CustomPrologue */));
// for (var _i = restIndex; _i < arguments.length; _i++) {
// param[_i - restIndex] = arguments[_i];
// }
- var forStatement = ts.createFor(ts.createVariableDeclarationList([
+ var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex))
- ], /*location*/ parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"),
- /*location*/ parameter), ts.createPostfixIncrement(temp, /*location*/ parameter), ts.createBlock([
- ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
+ ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([
+ ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
? temp
- : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)),
+ : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))),
/*location*/ parameter))
]));
ts.setEmitFlags(forStatement, 524288 /* CustomPrologue */);
@@ -49979,7 +53924,7 @@ var ts;
* @param node A node.
*/
function addCaptureThisForNodeIfNeeded(statements, node) {
- if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 185 /* ArrowFunction */) {
+ if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 186 /* ArrowFunction */) {
captureThisForNode(statements, node, ts.createThis());
}
}
@@ -49989,11 +53934,52 @@ var ts;
/*modifiers*/ undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration("_this",
/*type*/ undefined, initializer)
- ]), originalStatement);
+ ]));
ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 524288 /* CustomPrologue */);
+ ts.setTextRange(captureThisStatement, originalStatement);
ts.setSourceMapRange(captureThisStatement, node);
statements.push(captureThisStatement);
}
+ function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
+ if (hierarchyFacts & 16384 /* NewTarget */) {
+ var newTarget = void 0;
+ switch (node.kind) {
+ case 186 /* ArrowFunction */:
+ return statements;
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ // Methods and accessors cannot be constructors, so 'new.target' will
+ // always return 'undefined'.
+ newTarget = ts.createVoidZero();
+ break;
+ case 151 /* Constructor */:
+ // Class constructors can only be called with `new`, so `this.constructor`
+ // should be relatively safe to use.
+ newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor");
+ break;
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ // Functions can be called or constructed, and may have a `this` due to
+ // being a member or when calling an imported function via `other_1.f()`.
+ newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 92 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero());
+ break;
+ default:
+ ts.Debug.failBadSyntaxKind(node);
+ break;
+ }
+ var captureNewTargetStatement = ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList([
+ ts.createVariableDeclaration("_newTarget",
+ /*type*/ undefined, newTarget)
+ ]));
+ if (copyOnWrite) {
+ return [captureNewTargetStatement].concat(statements);
+ }
+ statements.unshift(captureNewTargetStatement);
+ }
+ return statements;
+ }
/**
* Adds statements to the class body function for a class to define the members of the
* class.
@@ -50005,20 +53991,20 @@ var ts;
for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
var member = _a[_i];
switch (member.kind) {
- case 203 /* SemicolonClassElement */:
+ case 205 /* SemicolonClassElement */:
statements.push(transformSemicolonClassElementToStatement(member));
break;
- case 149 /* MethodDeclaration */:
- statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member));
+ case 150 /* MethodDeclaration */:
+ statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
break;
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
var accessors = ts.getAllAccessorDeclarations(node.members, member);
if (member === accessors.firstAccessor) {
- statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors));
+ statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
}
break;
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
// Constructors are handled in visitClassExpression/visitClassDeclaration
break;
default:
@@ -50033,7 +54019,7 @@ var ts;
* @param member The SemicolonClassElement node.
*/
function transformSemicolonClassElementToStatement(member) {
- return ts.createEmptyStatement(/*location*/ member);
+ return ts.setTextRange(ts.createEmptyStatement(), member);
}
/**
* Transforms a MethodDeclaration into a statement for a class body function.
@@ -50041,14 +54027,15 @@ var ts;
* @param receiver The receiver for the member.
* @param member The MethodDeclaration node.
*/
- function transformClassMethodDeclarationToStatement(receiver, member) {
+ function transformClassMethodDeclarationToStatement(receiver, member, container) {
+ var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
var commentRange = ts.getCommentRange(member);
var sourceMapRange = ts.getSourceMapRange(member);
var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name);
- var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined);
+ var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
ts.setSourceMapRange(memberFunction, sourceMapRange);
- var statement = ts.createStatement(ts.createAssignment(memberName, memberFunction),
+ var statement = ts.setTextRange(ts.createStatement(ts.createAssignment(memberName, memberFunction)),
/*location*/ member);
ts.setOriginalNode(statement, member);
ts.setCommentRange(statement, commentRange);
@@ -50056,6 +54043,7 @@ var ts;
// No source map should be emitted for this statement to align with the
// old emitter.
ts.setEmitFlags(statement, 48 /* NoSourceMap */);
+ exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return statement;
}
/**
@@ -50064,13 +54052,13 @@ var ts;
* @param receiver The receiver for the member.
* @param accessors The set of related get/set accessors.
*/
- function transformAccessorsToStatement(receiver, accessors) {
- var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false),
- /*location*/ ts.getSourceMapRange(accessors.firstAccessor));
+ function transformAccessorsToStatement(receiver, accessors, container) {
+ var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
// The location for the statement is used to emit source maps only.
// No comments should be emitted for this statement to align with the
// old emitter.
ts.setEmitFlags(statement, 1536 /* NoComments */);
+ ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
return statement;
}
/**
@@ -50079,8 +54067,9 @@ var ts;
*
* @param receiver The receiver for the member.
*/
- function transformAccessorsToExpression(receiver, _a, startsOnNewLine) {
+ function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
+ var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
// To align with source maps in the old emitter, the receiver and property name
// arguments are both mapped contiguously to the accessor name.
var target = ts.getMutableClone(receiver);
@@ -50091,7 +54080,7 @@ var ts;
ts.setSourceMapRange(propertyName, firstAccessor.name);
var properties = [];
if (getAccessor) {
- var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined);
+ var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
var getter = ts.createPropertyAssignment("get", getterFunction);
@@ -50099,23 +54088,24 @@ var ts;
properties.push(getter);
}
if (setAccessor) {
- var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined);
+ var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
var setter = ts.createPropertyAssignment("set", setterFunction);
ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
properties.push(setter);
}
- properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true)));
+ properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue()));
var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
/*typeArguments*/ undefined, [
target,
propertyName,
- ts.createObjectLiteral(properties, /*location*/ undefined, /*multiLine*/ true)
+ ts.createObjectLiteral(properties, /*multiLine*/ true)
]);
if (startsOnNewLine) {
call.startsOnNewLine = true;
}
+ exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return call;
}
/**
@@ -50127,14 +54117,20 @@ var ts;
if (node.transformFlags & 16384 /* ContainsLexicalThis */) {
enableSubstitutionsForCapturedThis();
}
+ var savedConvertedLoopState = convertedLoopState;
+ convertedLoopState = undefined;
+ var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
var func = ts.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, transformFunctionBody(node), node);
+ /*type*/ undefined, transformFunctionBody(node));
+ ts.setTextRange(func, node);
ts.setOriginalNode(func, node);
ts.setEmitFlags(func, 8 /* CapturesThis */);
+ exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ convertedLoopState = savedConvertedLoopState;
return func;
}
/**
@@ -50143,12 +54139,24 @@ var ts;
* @param node a FunctionExpression node.
*/
function visitFunctionExpression(node) {
- return ts.updateFunctionExpression(node,
- /*modifiers*/ undefined, node.name,
- /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, node.transformFlags & 64 /* ES2015 */
+ var ancestorFacts = ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */
+ ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
+ : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var savedConvertedLoopState = convertedLoopState;
+ convertedLoopState = undefined;
+ var parameters = ts.visitParameterList(node.parameters, visitor, context);
+ var body = node.transformFlags & 64 /* ES2015 */
? transformFunctionBody(node)
- : ts.visitFunctionBody(node.body, visitor, context));
+ : visitFunctionBodyDownLevel(node);
+ var name = hierarchyFacts & 16384 /* NewTarget */
+ ? ts.getLocalName(node)
+ : node.name;
+ exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ convertedLoopState = savedConvertedLoopState;
+ return ts.updateFunctionExpression(node,
+ /*modifiers*/ undefined, node.asteriskToken, name,
+ /*typeParameters*/ undefined, parameters,
+ /*type*/ undefined, body);
}
/**
* Visits a FunctionDeclaration node.
@@ -50156,12 +54164,22 @@ var ts;
* @param node a FunctionDeclaration node.
*/
function visitFunctionDeclaration(node) {
- return ts.updateFunctionDeclaration(node,
- /*decorators*/ undefined, node.modifiers, node.name,
- /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, node.transformFlags & 64 /* ES2015 */
+ var savedConvertedLoopState = convertedLoopState;
+ convertedLoopState = undefined;
+ var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var parameters = ts.visitParameterList(node.parameters, visitor, context);
+ var body = node.transformFlags & 64 /* ES2015 */
? transformFunctionBody(node)
- : ts.visitFunctionBody(node.body, visitor, context));
+ : visitFunctionBodyDownLevel(node);
+ var name = hierarchyFacts & 16384 /* NewTarget */
+ ? ts.getLocalName(node)
+ : node.name;
+ exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ convertedLoopState = savedConvertedLoopState;
+ return ts.updateFunctionDeclaration(node,
+ /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name,
+ /*typeParameters*/ undefined, parameters,
+ /*type*/ undefined, body);
}
/**
* Transforms a function-like node into a FunctionExpression.
@@ -50170,18 +54188,24 @@ var ts;
* @param location The source-map location for the new FunctionExpression.
* @param name The name of the new FunctionExpression.
*/
- function transformFunctionLikeToExpression(node, location, name) {
- var savedContainingNonArrowFunction = enclosingNonArrowFunction;
- if (node.kind !== 185 /* ArrowFunction */) {
- enclosingNonArrowFunction = node;
+ function transformFunctionLikeToExpression(node, location, name, container) {
+ var savedConvertedLoopState = convertedLoopState;
+ convertedLoopState = undefined;
+ var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
+ ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
+ : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var parameters = ts.visitParameterList(node.parameters, visitor, context);
+ var body = transformFunctionBody(node);
+ if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 227 /* FunctionDeclaration */ || node.kind === 185 /* FunctionExpression */)) {
+ name = ts.getGeneratedNameForNode(node);
}
- var expression = ts.setOriginalNode(ts.createFunctionExpression(
+ exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ convertedLoopState = savedConvertedLoopState;
+ return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
/*modifiers*/ undefined, node.asteriskToken, name,
- /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, saveStateAndInvoke(node, transformFunctionBody), location),
+ /*typeParameters*/ undefined, parameters,
+ /*type*/ undefined, body), location),
/*original*/ node);
- enclosingNonArrowFunction = savedContainingNonArrowFunction;
- return expression;
}
/**
* Transforms the body of a function-like node.
@@ -50199,8 +54223,8 @@ var ts;
resumeLexicalEnvironment();
if (ts.isBlock(body)) {
// ensureUseStrict is false because no new prologue-directive should be added.
- // addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array
- statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor);
+ // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
+ statementOffset = ts.addStandardPrologue(statements, body.statements, /*ensureUseStrict*/ false);
}
addCaptureThisForNodeIfNeeded(statements, node);
addDefaultValueAssignmentsIfNeeded(statements, node);
@@ -50210,6 +54234,8 @@ var ts;
multiLine = true;
}
if (ts.isBlock(body)) {
+ // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
+ statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
statementsLocation = body.statements;
ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
// If the original body was a multi-line block, this must be a multi-line block.
@@ -50218,7 +54244,7 @@ var ts;
}
}
else {
- ts.Debug.assert(node.kind === 185 /* ArrowFunction */);
+ ts.Debug.assert(node.kind === 186 /* ArrowFunction */);
// To align with the old emitter, we use a synthetic end position on the location
// for the statement list we synthesize when we down-level an arrow function with
// an expression function body. This prevents both comments and source maps from
@@ -50234,7 +54260,8 @@ var ts;
}
}
var expression = ts.visitNode(body, visitor, ts.isExpression);
- var returnStatement = ts.createReturn(expression, /*location*/ body);
+ var returnStatement = ts.createReturn(expression);
+ ts.setTextRange(returnStatement, body);
ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
statements.push(returnStatement);
// To align with the source map emit for the old emitter, we set a custom
@@ -50243,11 +54270,13 @@ var ts;
}
var lexicalEnvironment = context.endLexicalEnvironment();
ts.addRange(statements, lexicalEnvironment);
+ prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
// If we added any final generated statements, this must be a multi-line block
if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) {
multiLine = true;
}
- var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine);
+ var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
+ ts.setTextRange(block, node.body);
if (!multiLine && singleLine) {
ts.setEmitFlags(block, 1 /* SingleLine */);
}
@@ -50257,6 +54286,23 @@ var ts;
ts.setOriginalNode(block, node.body);
return block;
}
+ function visitFunctionBodyDownLevel(node) {
+ var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context);
+ return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)),
+ /*location*/ updated.statements));
+ }
+ function visitBlock(node, isFunctionBody) {
+ if (isFunctionBody) {
+ // A function body is not a block scope.
+ return ts.visitEachChild(node, visitor, context);
+ }
+ var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
+ ? enterSubtree(4032 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
+ : enterSubtree(3904 /* BlockExcludes */, 128 /* BlockIncludes */);
+ var updated = ts.visitEachChild(node, visitor, context);
+ exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ return updated;
+ }
/**
* Visits an ExpressionStatement that contains a destructuring assignment.
*
@@ -50265,9 +54311,9 @@ var ts;
function visitExpressionStatement(node) {
// If we are here it is most likely because our expression is a destructuring assignment.
switch (node.expression.kind) {
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
}
return ts.visitEachChild(node, visitor, context);
@@ -50282,10 +54328,13 @@ var ts;
function visitParenthesizedExpression(node, needsDestructuringValue) {
// If we are here it is most likely because our expression is a destructuring assignment.
if (!needsDestructuringValue) {
+ // By default we always emit the RHS at the end of a flattened destructuring
+ // expression. If we are in a state where we do not need the destructuring value,
+ // we pass that information along to the children that care about it.
switch (node.expression.kind) {
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
}
}
@@ -50303,9 +54352,12 @@ var ts;
if (ts.isDestructuringAssignment(node)) {
return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
}
+ return ts.visitEachChild(node, visitor, context);
}
function visitVariableStatement(node) {
- if (convertedLoopState && (ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) == 0) {
+ var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
+ var updated;
+ if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) {
// we are inside a converted loop - hoist variable declarations
var assignments = void 0;
for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
@@ -50319,18 +54371,22 @@ var ts;
else {
assignment = ts.createBinary(decl.name, 57 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
}
- (assignments || (assignments = [])).push(assignment);
+ assignments = ts.append(assignments, assignment);
}
}
if (assignments) {
- return ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 25 /* CommaToken */, acc); }), node);
+ updated = ts.setTextRange(ts.createStatement(ts.reduceLeft(assignments, function (acc, v) { return ts.createBinary(v, 25 /* CommaToken */, acc); })), node);
}
else {
// none of declarations has initializer - the entire variable statement can be deleted
- return undefined;
+ updated = undefined;
}
}
- return ts.visitEachChild(node, visitor, context);
+ else {
+ updated = ts.visitEachChild(node, visitor, context);
+ }
+ exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ return updated;
}
/**
* Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
@@ -50338,25 +54394,29 @@ var ts;
* @param node A VariableDeclarationList node.
*/
function visitVariableDeclarationList(node) {
- if (node.flags & 3 /* BlockScoped */) {
- enableSubstitutionsForBlockScopedBindings();
- }
- var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 /* Let */
- ? visitVariableDeclarationInLetDeclarationList
- : visitVariableDeclaration));
- var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node);
- ts.setOriginalNode(declarationList, node);
- ts.setCommentRange(declarationList, node);
- if (node.transformFlags & 8388608 /* ContainsBindingPattern */
- && (ts.isBindingPattern(node.declarations[0].name)
- || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) {
- // If the first or last declaration is a binding pattern, we need to modify
- // the source map range for the declaration list.
- var firstDeclaration = ts.firstOrUndefined(declarations);
- var lastDeclaration = ts.lastOrUndefined(declarations);
- ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end));
+ if (node.transformFlags & 64 /* ES2015 */) {
+ if (node.flags & 3 /* BlockScoped */) {
+ enableSubstitutionsForBlockScopedBindings();
+ }
+ var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 /* Let */
+ ? visitVariableDeclarationInLetDeclarationList
+ : visitVariableDeclaration));
+ var declarationList = ts.createVariableDeclarationList(declarations);
+ ts.setOriginalNode(declarationList, node);
+ ts.setTextRange(declarationList, node);
+ ts.setCommentRange(declarationList, node);
+ if (node.transformFlags & 8388608 /* ContainsBindingPattern */
+ && (ts.isBindingPattern(node.declarations[0].name)
+ || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) {
+ // If the first or last declaration is a binding pattern, we need to modify
+ // the source map range for the declaration list.
+ var firstDeclaration = ts.firstOrUndefined(declarations);
+ var lastDeclaration = ts.lastOrUndefined(declarations);
+ ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end));
+ }
+ return declarationList;
}
- return declarationList;
+ return ts.visitEachChild(node, visitor, context);
}
/**
* Gets a value indicating whether we should emit an explicit initializer for a variable
@@ -50407,18 +54467,16 @@ var ts;
var flags = resolver.getNodeCheckFlags(node);
var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */;
var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */;
- var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(enclosingBlockScopeContainer)
+ var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
|| (isCapturedInFunction
&& isDeclaredInLoop
- && ts.isBlock(enclosingBlockScopeContainer)
- && ts.isIterationStatement(enclosingBlockScopeContainerParent, /*lookInLabeledStatements*/ false));
+ && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
var emitExplicitInitializer = !emittedAsTopLevel
- && enclosingBlockScopeContainer.kind !== 212 /* ForInStatement */
- && enclosingBlockScopeContainer.kind !== 213 /* ForOfStatement */
+ && (hierarchyFacts & 2048 /* ForInOrForOfStatement */) === 0
&& (!resolver.isDeclarationWithCollidingName(node)
|| (isDeclaredInLoop
&& !isCapturedInFunction
- && !ts.isIterationStatement(enclosingBlockScopeContainer, /*lookInLabeledStatements*/ false)));
+ && (hierarchyFacts & (1024 /* ForStatement */ | 2048 /* ForInOrForOfStatement */)) === 0));
return emitExplicitInitializer;
}
/**
@@ -50447,101 +54505,77 @@ var ts;
* @param node A VariableDeclaration node.
*/
function visitVariableDeclaration(node) {
- // If we are here it is because the name contains a binding pattern.
+ var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
+ var updated;
if (ts.isBindingPattern(node.name)) {
- var hoistTempVariables = enclosingVariableStatement
- && ts.hasModifier(enclosingVariableStatement, 1 /* Export */);
- return ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */,
- /*value*/ undefined, hoistTempVariables);
- }
- return ts.visitEachChild(node, visitor, context);
- }
- function visitLabeledStatement(node) {
- if (convertedLoopState) {
- if (!convertedLoopState.labels) {
- convertedLoopState.labels = ts.createMap();
- }
- convertedLoopState.labels[node.label.text] = node.label.text;
- }
- var result;
- if (ts.isIterationStatement(node.statement, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node.statement)) {
- result = ts.visitNodes(ts.createNodeArray([node.statement]), visitor, ts.isStatement);
+ updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */,
+ /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
}
else {
- result = ts.visitEachChild(node, visitor, context);
+ updated = ts.visitEachChild(node, visitor, context);
}
- if (convertedLoopState) {
- convertedLoopState.labels[node.label.text] = undefined;
+ exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ return updated;
+ }
+ function recordLabel(node) {
+ convertedLoopState.labels.set(node.label.text, node.label.text);
+ }
+ function resetLabel(node) {
+ convertedLoopState.labels.set(node.label.text, undefined);
+ }
+ function visitLabeledStatement(node) {
+ if (convertedLoopState && !convertedLoopState.labels) {
+ convertedLoopState.labels = ts.createMap();
}
- return result;
+ var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
+ return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
+ ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
+ : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement), node, convertedLoopState && resetLabel);
}
- function visitDoStatement(node) {
- return convertIterationStatementBodyIfNecessary(node);
+ function visitIterationStatement(node, outermostLabeledStatement) {
+ switch (node.kind) {
+ case 211 /* DoStatement */:
+ case 212 /* WhileStatement */:
+ return visitDoOrWhileStatement(node, outermostLabeledStatement);
+ case 213 /* ForStatement */:
+ return visitForStatement(node, outermostLabeledStatement);
+ case 214 /* ForInStatement */:
+ return visitForInStatement(node, outermostLabeledStatement);
+ case 215 /* ForOfStatement */:
+ return visitForOfStatement(node, outermostLabeledStatement);
+ }
+ }
+ function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
+ var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
+ var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert);
+ exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ return updated;
}
- function visitWhileStatement(node) {
- return convertIterationStatementBodyIfNecessary(node);
+ function visitDoOrWhileStatement(node, outermostLabeledStatement) {
+ return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 256 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
}
- function visitForStatement(node) {
- return convertIterationStatementBodyIfNecessary(node);
+ function visitForStatement(node, outermostLabeledStatement) {
+ return visitIterationStatementWithFacts(3008 /* ForStatementExcludes */, 1280 /* ForStatementIncludes */, node, outermostLabeledStatement);
}
- function visitForInStatement(node) {
- return convertIterationStatementBodyIfNecessary(node);
+ function visitForInStatement(node, outermostLabeledStatement) {
+ return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
}
- /**
- * Visits a ForOfStatement and converts it into a compatible ForStatement.
- *
- * @param node A ForOfStatement.
- */
- function visitForOfStatement(node) {
- return convertIterationStatementBodyIfNecessary(node, convertForOfToFor);
+ function visitForOfStatement(node, outermostLabeledStatement) {
+ return visitIterationStatementWithFacts(1984 /* ForInOrForOfStatementExcludes */, 2304 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
}
- function convertForOfToFor(node, convertedLoopBodyStatements) {
- // The following ES6 code:
- //
- // for (let v of expr) { }
- //
- // should be emitted as
- //
- // for (var _i = 0, _a = expr; _i < _a.length; _i++) {
- // var v = _a[_i];
- // }
- //
- // where _a and _i are temps emitted to capture the RHS and the counter,
- // respectively.
- // When the left hand side is an expression instead of a let declaration,
- // the "let v" is not emitted.
- // When the left hand side is a let/const, the v is renamed if there is
- // another v in scope.
- // Note that all assignments to the LHS are emitted in the body, including
- // all destructuring.
- // Note also that because an extra statement is needed to assign to the LHS,
- // for-of bodies are always emitted as blocks.
- var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
- var initializer = node.initializer;
+ function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
var statements = [];
- // In the case where the user wrote an identifier as the RHS, like this:
- //
- // for (let v of arr) { }
- //
- // we don't want to emit a temporary variable for the RHS, just use it directly.
- var counter = ts.createLoopVariable();
- var rhsReference = expression.kind === 70 /* Identifier */
- ? ts.createUniqueName(expression.text)
- : ts.createTempVariable(/*recordTempVariable*/ undefined);
- var elementAccess = ts.createElementAccess(rhsReference, counter);
- // Initialize LHS
- // var v = _a[_i];
- if (ts.isVariableDeclarationList(initializer)) {
- if (initializer.flags & 3 /* BlockScoped */) {
+ if (ts.isVariableDeclarationList(node.initializer)) {
+ if (node.initializer.flags & 3 /* BlockScoped */) {
enableSubstitutionsForBlockScopedBindings();
}
- var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
+ var firstOriginalDeclaration = ts.firstOrUndefined(node.initializer.declarations);
if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
// This works whether the declaration is a var, let, or const.
// It will use rhsIterationValue _a[_i] as the initializer.
- var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, elementAccess);
- var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ initializer);
- ts.setOriginalNode(declarationList, initializer);
+ var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
+ var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer);
+ ts.setOriginalNode(declarationList, node.initializer);
// Adjust the source map range for the first declaration to align with the old
// emitter.
var firstDeclaration = declarations[0];
@@ -50553,27 +54587,24 @@ var ts;
else {
// The following call does not include the initializer, so we have
// to emit it separately.
- statements.push(ts.createVariableStatement(
- /*modifiers*/ undefined, ts.setOriginalNode(ts.createVariableDeclarationList([
+ statements.push(ts.setTextRange(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([
ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined),
- /*type*/ undefined, ts.createElementAccess(rhsReference, counter))
- ], /*location*/ ts.moveRangePos(initializer, -1)), initializer),
- /*location*/ ts.moveRangeEnd(initializer, -1)));
+ /*type*/ undefined, boundValue)
+ ]), ts.moveRangePos(node.initializer, -1)), node.initializer)), ts.moveRangeEnd(node.initializer, -1)));
}
}
else {
// Initializer is an expression. Emit the expression in the body, so that it's
// evaluated on every iteration.
- var assignment = ts.createAssignment(initializer, elementAccess);
+ var assignment = ts.createAssignment(node.initializer, boundValue);
if (ts.isDestructuringAssignment(assignment)) {
- // This is a destructuring pattern, so we flatten the destructuring instead.
- statements.push(ts.createStatement(ts.flattenDestructuringAssignment(assignment, visitor, context, 0 /* All */)));
+ ts.aggregateTransformFlags(assignment);
+ statements.push(ts.createStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
}
else {
- // Currently there is not way to check that assignment is binary expression of destructing assignment
- // so we have to cast never type to binaryExpression
- assignment.end = initializer.end;
- statements.push(ts.createStatement(assignment, /*location*/ ts.moveRangeEnd(initializer, -1)));
+ assignment.end = node.initializer.end;
+ statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1)));
}
}
var bodyLocation;
@@ -50582,7 +54613,7 @@ var ts;
ts.addRange(statements, convertedLoopBodyStatements);
}
else {
- var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
+ var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
if (ts.isBlock(statement)) {
ts.addRange(statements, statement.statements);
bodyLocation = statement;
@@ -50592,22 +54623,92 @@ var ts;
statements.push(statement);
}
}
- // The old emitter does not emit source maps for the expression
- ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
// The old emitter does not emit source maps for the block.
// We add the location to preserve comments.
- var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation),
- /*location*/ bodyLocation);
- ts.setEmitFlags(body, 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
- var forStatement = ts.createFor(ts.setEmitFlags(ts.createVariableDeclarationList([
- ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)),
- ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression)
- ], /*location*/ node.expression), 1048576 /* NoHoisting */), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"),
- /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body,
+ return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation),
+ /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
+ }
+ function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
+ // The following ES6 code:
+ //
+ // for (let v of expr) { }
+ //
+ // should be emitted as
+ //
+ // for (var _i = 0, _a = expr; _i < _a.length; _i++) {
+ // var v = _a[_i];
+ // }
+ //
+ // where _a and _i are temps emitted to capture the RHS and the counter,
+ // respectively.
+ // When the left hand side is an expression instead of a let declaration,
+ // the "let v" is not emitted.
+ // When the left hand side is a let/const, the v is renamed if there is
+ // another v in scope.
+ // Note that all assignments to the LHS are emitted in the body, including
+ // all destructuring.
+ // Note also that because an extra statement is needed to assign to the LHS,
+ // for-of bodies are always emitted as blocks.
+ var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
+ // In the case where the user wrote an identifier as the RHS, like this:
+ //
+ // for (let v of arr) { }
+ //
+ // we don't want to emit a temporary variable for the RHS, just use it directly.
+ var counter = ts.createLoopVariable();
+ var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
+ // The old emitter does not emit source maps for the expression
+ ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
+ var forStatement = ts.setTextRange(ts.createFor(
+ /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
+ ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)),
+ ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression)
+ ]), node.expression), 1048576 /* NoHoisting */),
+ /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression),
+ /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression),
+ /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)),
/*location*/ node);
// Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
- return forStatement;
+ ts.setTextRange(forStatement, node);
+ return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
+ }
+ function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements) {
+ var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
+ var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
+ var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
+ var errorRecord = ts.createUniqueName("e");
+ var catchVariable = ts.getGeneratedNameForNode(errorRecord);
+ var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
+ var values = ts.createValuesHelper(context, expression, node.expression);
+ var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
+ hoistVariableDeclaration(errorRecord);
+ hoistVariableDeclaration(returnMethod);
+ var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
+ /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
+ ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression),
+ ts.createVariableDeclaration(result, /*type*/ undefined, next)
+ ]), node.expression), 1048576 /* NoHoisting */),
+ /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")),
+ /*incrementor*/ ts.createAssignment(result, next),
+ /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)),
+ /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
+ return ts.createTry(ts.createBlock([
+ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
+ ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
+ ts.createStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
+ ts.createPropertyAssignment("error", catchVariable)
+ ])))
+ ]), 1 /* SingleLine */)), ts.createBlock([
+ ts.createTry(
+ /*tryBlock*/ ts.createBlock([
+ ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */),
+ ]),
+ /*catchClause*/ undefined,
+ /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
+ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
+ ]), 1 /* SingleLine */))
+ ]));
}
/**
* Visits an ObjectLiteralExpression with computed propety names.
@@ -50621,31 +54722,39 @@ var ts;
// Find the first computed property.
// Everything until that point can be emitted as part of the initial object literal.
var numInitialProperties = numProperties;
+ var numInitialPropertiesWithoutYield = numProperties;
for (var i = 0; i < numProperties; i++) {
var property = properties[i];
- if (property.transformFlags & 16777216 /* ContainsYield */
- || property.name.kind === 142 /* ComputedPropertyName */) {
+ if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
+ && i < numInitialPropertiesWithoutYield) {
+ numInitialPropertiesWithoutYield = i;
+ }
+ if (property.name.kind === 143 /* ComputedPropertyName */) {
numInitialProperties = i;
break;
}
}
- ts.Debug.assert(numInitialProperties !== numProperties);
- // For computed properties, we need to create a unique handle to the object
- // literal so we can modify it without risking internal assignments tainting the object.
- var temp = ts.createTempVariable(hoistVariableDeclaration);
- // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
- var expressions = [];
- var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties),
- /*location*/ undefined, node.multiLine), 32768 /* Indented */));
- if (node.multiLine) {
- assignment.startsOnNewLine = true;
- }
- expressions.push(assignment);
- addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
- // We need to clone the temporary identifier so that we can write it on a
- // new line
- expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
- return ts.inlineExpressions(expressions);
+ if (numInitialProperties !== numProperties) {
+ if (numInitialPropertiesWithoutYield < numInitialProperties) {
+ numInitialProperties = numInitialPropertiesWithoutYield;
+ }
+ // For computed properties, we need to create a unique handle to the object
+ // literal so we can modify it without risking internal assignments tainting the object.
+ var temp = ts.createTempVariable(hoistVariableDeclaration);
+ // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
+ var expressions = [];
+ var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 32768 /* Indented */));
+ if (node.multiLine) {
+ assignment.startsOnNewLine = true;
+ }
+ expressions.push(assignment);
+ addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
+ // We need to clone the temporary identifier so that we can write it on a
+ // new line
+ expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
+ return ts.inlineExpressions(expressions);
+ }
+ return ts.visitEachChild(node, visitor, context);
}
function shouldConvertIterationStatementBody(node) {
return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
@@ -50672,7 +54781,7 @@ var ts;
}
}
}
- function convertIterationStatementBodyIfNecessary(node, convert) {
+ function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) {
if (!shouldConvertIterationStatementBody(node)) {
var saveAllowedNonLabeledJumps = void 0;
if (convertedLoopState) {
@@ -50681,7 +54790,9 @@ var ts;
saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
}
- var result = convert ? convert(node, /*convertedLoopBodyStatements*/ undefined) : ts.visitEachChild(node, visitor, context);
+ var result = convert
+ ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined)
+ : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
if (convertedLoopState) {
convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
}
@@ -50690,11 +54801,11 @@ var ts;
var functionName = ts.createUniqueName("_loop");
var loopInitializer;
switch (node.kind) {
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
var initializer = node.initializer;
- if (initializer && initializer.kind === 224 /* VariableDeclarationList */) {
+ if (initializer && initializer.kind === 226 /* VariableDeclarationList */) {
loopInitializer = initializer;
}
break;
@@ -50730,19 +54841,26 @@ var ts;
convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables;
}
}
- var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement);
+ startLexicalEnvironment();
+ var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
+ var lexicalEnvironment = endLexicalEnvironment();
var currentState = convertedLoopState;
convertedLoopState = outerConvertedLoopState;
- if (loopOutParameters.length) {
+ if (loopOutParameters.length || lexicalEnvironment) {
var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody];
- copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4);
- loopBody = ts.createBlock(statements_4, /*location*/ undefined, /*multiline*/ true);
+ if (loopOutParameters.length) {
+ copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4);
+ }
+ ts.addRange(statements_4, lexicalEnvironment);
+ loopBody = ts.createBlock(statements_4, /*multiline*/ true);
}
- if (!ts.isBlock(loopBody)) {
- loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true);
+ if (ts.isBlock(loopBody)) {
+ loopBody.multiLine = true;
}
- var isAsyncBlockContainingAwait = enclosingNonArrowFunction
- && (ts.getEmitFlags(enclosingNonArrowFunction) & 131072 /* AsyncFunctionBody */) !== 0
+ else {
+ loopBody = ts.createBlock([loopBody], /*multiline*/ true);
+ }
+ var isAsyncBlockContainingAwait = hierarchyFacts & 4 /* AsyncFunctionBody */
&& (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0;
var loopBodyFlags = 0;
if (currentState.containsLexicalThis) {
@@ -50825,25 +54943,22 @@ var ts;
var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, isAsyncBlockContainingAwait);
var loop;
if (convert) {
- loop = convert(node, convertedLoopBodyStatements);
+ loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements);
}
else {
- loop = ts.getMutableClone(node);
+ var clone_4 = ts.getMutableClone(node);
// clean statement part
- loop.statement = undefined;
+ clone_4.statement = undefined;
// visit childnodes to transform initializer/condition/incrementor parts
- loop = ts.visitEachChild(loop, visitor, context);
+ clone_4 = ts.visitEachChild(clone_4, visitor, context);
// set loop statement
- loop.statement = ts.createBlock(convertedLoopBodyStatements,
- /*location*/ undefined,
- /*multiline*/ true);
+ clone_4.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true);
// reset and re-aggregate the transform flags
- loop.transformFlags = 0;
- ts.aggregateTransformFlags(loop);
+ clone_4.transformFlags = 0;
+ ts.aggregateTransformFlags(clone_4);
+ loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
}
- statements.push(currentParent.kind === 219 /* LabeledStatement */
- ? ts.createLabel(currentParent.label, loop)
- : loop);
+ statements.push(loop);
return statements;
}
function copyOutParameter(outParam, copyDirection) {
@@ -50867,7 +54982,9 @@ var ts;
!state.labeledNonLocalBreaks &&
!state.labeledNonLocalContinues;
var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; }));
- var callResult = isAsyncBlockContainingAwait ? ts.createYield(ts.createToken(38 /* AsteriskToken */), call) : call;
+ var callResult = isAsyncBlockContainingAwait
+ ? ts.createYield(ts.createToken(38 /* AsteriskToken */), ts.setEmitFlags(call, 4194304 /* Iterator */))
+ : call;
if (isSimpleLoop) {
statements.push(ts.createStatement(callResult));
copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements);
@@ -50906,26 +55023,25 @@ var ts;
if (!state.labeledNonLocalBreaks) {
state.labeledNonLocalBreaks = ts.createMap();
}
- state.labeledNonLocalBreaks[labelText] = labelMarker;
+ state.labeledNonLocalBreaks.set(labelText, labelMarker);
}
else {
if (!state.labeledNonLocalContinues) {
state.labeledNonLocalContinues = ts.createMap();
}
- state.labeledNonLocalContinues[labelText] = labelMarker;
+ state.labeledNonLocalContinues.set(labelText, labelMarker);
}
}
function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
if (!table) {
return;
}
- for (var labelText in table) {
- var labelMarker = table[labelText];
+ table.forEach(function (labelMarker, labelText) {
var statements = [];
// if there are no outer converted loop or outer label in question is located inside outer converted loop
// then emit labeled break\continue
// otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
- if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) {
+ if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
var label = ts.createIdentifier(labelText);
statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label));
}
@@ -50934,7 +55050,7 @@ var ts;
statements.push(ts.createReturn(loopResultName));
}
caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements));
- }
+ });
}
function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) {
var name = decl.name;
@@ -50949,7 +55065,7 @@ var ts;
else {
loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) {
- var outParamName = ts.createUniqueName("out_" + name.text);
+ var outParamName = ts.createUniqueName("out_" + ts.unescapeIdentifier(name.text));
loopOutParameters.push({ originalName: name, outParamName: outParamName });
}
}
@@ -50969,22 +55085,22 @@ var ts;
for (var i = start; i < numProperties; i++) {
var property = properties[i];
switch (property.kind) {
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
var accessors = ts.getAllAccessorDeclarations(node.properties, property);
if (property === accessors.firstAccessor) {
- expressions.push(transformAccessorsToExpression(receiver, accessors, node.multiLine));
+ expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine));
}
break;
- case 257 /* PropertyAssignment */:
+ case 150 /* MethodDeclaration */:
+ expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
+ break;
+ case 260 /* PropertyAssignment */:
expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
break;
- case 258 /* ShorthandPropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
break;
- case 149 /* MethodDeclaration */:
- expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node.multiLine));
- break;
default:
ts.Debug.failBadSyntaxKind(node);
break;
@@ -50999,8 +55115,8 @@ var ts;
* @param receiver The receiver for the assignment.
*/
function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
- var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression),
- /*location*/ property);
+ var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
+ ts.setTextRange(expression, property);
if (startsOnNewLine) {
expression.startsOnNewLine = true;
}
@@ -51014,8 +55130,8 @@ var ts;
* @param receiver The receiver for the assignment.
*/
function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
- var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name),
- /*location*/ property);
+ var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name));
+ ts.setTextRange(expression, property);
if (startsOnNewLine) {
expression.startsOnNewLine = true;
}
@@ -51028,22 +55144,34 @@ var ts;
* @param method The MethodDeclaration node.
* @param receiver The receiver for the assignment.
*/
- function transformObjectLiteralMethodDeclarationToExpression(method, receiver, startsOnNewLine) {
- var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined),
- /*location*/ method);
+ function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
+ var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */);
+ var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
+ ts.setTextRange(expression, method);
if (startsOnNewLine) {
expression.startsOnNewLine = true;
}
+ exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */);
return expression;
}
function visitCatchClause(node) {
- ts.Debug.assert(ts.isBindingPattern(node.variableDeclaration.name));
- var temp = ts.createTempVariable(undefined);
- var newVariableDeclaration = ts.createVariableDeclaration(temp, undefined, undefined, node.variableDeclaration);
- var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
- var list = ts.createVariableDeclarationList(vars, /*location*/ node.variableDeclaration, /*flags*/ node.variableDeclaration.flags);
- var destructure = ts.createVariableStatement(undefined, list);
- return ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
+ var ancestorFacts = enterSubtree(4032 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
+ var updated;
+ if (ts.isBindingPattern(node.variableDeclaration.name)) {
+ var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
+ var newVariableDeclaration = ts.createVariableDeclaration(temp);
+ ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
+ var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
+ var list = ts.createVariableDeclarationList(vars);
+ ts.setTextRange(list, node.variableDeclaration);
+ var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list);
+ updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
+ }
+ else {
+ updated = ts.visitEachChild(node, visitor, context);
+ }
+ exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ return updated;
}
function addStatementToStartOfBlock(block, statement) {
var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
@@ -51060,20 +55188,41 @@ var ts;
// Methods on classes are handled in visitClassDeclaration/visitClassExpression.
// Methods with computed property names are handled in visitObjectLiteralExpression.
ts.Debug.assert(!ts.isComputedPropertyName(node.name));
- var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined);
+ var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
- return ts.createPropertyAssignment(node.name, functionExpression,
+ return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression),
/*location*/ node);
}
/**
+ * Visits an AccessorDeclaration of an ObjectLiteralExpression.
+ *
+ * @param node An AccessorDeclaration node.
+ */
+ function visitAccessorDeclaration(node) {
+ ts.Debug.assert(!ts.isComputedPropertyName(node.name));
+ var savedConvertedLoopState = convertedLoopState;
+ convertedLoopState = undefined;
+ var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
+ var updated = ts.visitEachChild(node, visitor, context);
+ exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */);
+ convertedLoopState = savedConvertedLoopState;
+ return updated;
+ }
+ /**
* Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
*
* @param node A ShorthandPropertyAssignment node.
*/
function visitShorthandPropertyAssignment(node) {
- return ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name),
+ return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)),
/*location*/ node);
}
+ function visitComputedPropertyName(node) {
+ var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */);
+ var updated = ts.visitEachChild(node, visitor, context);
+ exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */);
+ return updated;
+ }
/**
* Visits a YieldExpression node.
*
@@ -51089,8 +55238,11 @@ var ts;
* @param node An ArrayLiteralExpression node.
*/
function visitArrayLiteralExpression(node) {
- // We are here because we contain a SpreadElementExpression.
- return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma);
+ if (node.transformFlags & 64 /* ES2015 */) {
+ // We are here because we contain a SpreadElementExpression.
+ return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma);
+ }
+ return ts.visitEachChild(node, visitor, context);
}
/**
* Visits a CallExpression that contains either a spread element or `super`.
@@ -51098,7 +55250,11 @@ var ts;
* @param node a CallExpression.
*/
function visitCallExpression(node) {
- return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
+ if (node.transformFlags & 64 /* ES2015 */) {
+ return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
+ }
+ return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression),
+ /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
}
function visitImmediateSuperCallInBody(node) {
return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
@@ -51125,7 +55281,7 @@ var ts;
// _super.apply(this, a.concat([b]))
// _super.m.apply(this, a.concat([b]))
// _super.prototype.m.apply(this, a.concat([b]))
- resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
+ resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
}
else {
// [source]
@@ -51137,18 +55293,18 @@ var ts;
// _super.call(this, a)
// _super.m.call(this, a)
// _super.prototype.m.call(this, a)
- resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
+ resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression),
/*location*/ node);
}
if (node.expression.kind === 96 /* SuperKeyword */) {
var actualThis = ts.createThis();
ts.setEmitFlags(actualThis, 4 /* NoSubstitution */);
var initializer = ts.createLogicalOr(resultingCall, actualThis);
- return assignToCapturedThis
+ resultingCall = assignToCapturedThis
? ts.createAssignment(ts.createIdentifier("_this"), initializer)
: initializer;
}
- return resultingCall;
+ return ts.setOriginalNode(resultingCall, node);
}
/**
* Visits a NewExpression that contains a spread element.
@@ -51156,16 +55312,18 @@ var ts;
* @param node A NewExpression node.
*/
function visitNewExpression(node) {
- // We are here because we contain a SpreadElementExpression.
- ts.Debug.assert((node.transformFlags & 524288 /* ContainsSpread */) !== 0);
- // [source]
- // new C(...a)
- //
- // [output]
- // new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
- var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
- return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)),
- /*typeArguments*/ undefined, []);
+ if (node.transformFlags & 524288 /* ContainsSpread */) {
+ // We are here because we contain a SpreadElementExpression.
+ // [source]
+ // new C(...a)
+ //
+ // [output]
+ // new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
+ var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
+ return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)),
+ /*typeArguments*/ undefined, []);
+ }
+ return ts.visitEachChild(node, visitor, context);
}
/**
* Transforms an array of Expression nodes that contains a SpreadExpression.
@@ -51186,14 +55344,28 @@ var ts;
var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
}));
- if (segments.length === 1) {
- var firstElement = elements[0];
- return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 175 /* ArrayLiteralExpression */
- ? ts.createArraySlice(segments[0])
- : segments[0];
+ if (compilerOptions.downlevelIteration) {
+ if (segments.length === 1) {
+ var firstSegment = segments[0];
+ if (ts.isCallExpression(firstSegment)
+ && ts.isIdentifier(firstSegment.expression)
+ && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
+ && firstSegment.expression.text === "___spread") {
+ return segments[0];
+ }
+ }
+ return ts.createSpreadHelper(context, segments);
+ }
+ else {
+ if (segments.length === 1) {
+ var firstElement = elements[0];
+ return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 176 /* ArrayLiteralExpression */
+ ? ts.createArraySlice(segments[0])
+ : segments[0];
+ }
+ // Rewrite using the pattern <segment0>.concat(<segment1>, <segment2>, ...)
+ return ts.createArrayConcat(segments.shift(), segments);
}
- // Rewrite using the pattern <segment0>.concat(<segment1>, <segment2>, ...)
- return ts.createArrayConcat(segments.shift(), segments);
}
function partitionSpread(node) {
return ts.isSpreadExpression(node)
@@ -51204,8 +55376,7 @@ var ts;
return ts.map(chunk, visitExpressionOfSpread);
}
function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
- return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, /*location*/ undefined, hasTrailingComma), visitor, ts.isExpression),
- /*location*/ undefined, multiLine);
+ return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
}
function visitSpreadElement(node) {
return ts.visitNode(node.expression, visitor, ts.isExpression);
@@ -51224,7 +55395,29 @@ var ts;
* @param node A template literal.
*/
function visitTemplateLiteral(node) {
- return ts.createLiteral(node.text, /*location*/ node);
+ return ts.setTextRange(ts.createLiteral(node.text), node);
+ }
+ /**
+ * Visits a string literal with an extended unicode escape.
+ *
+ * @param node A string literal.
+ */
+ function visitStringLiteral(node) {
+ if (node.hasExtendedUnicodeEscape) {
+ return ts.setTextRange(ts.createLiteral(node.text), node);
+ }
+ return node;
+ }
+ /**
+ * Visits a binary or octal (ES6) numeric literal.
+ *
+ * @param node A string literal.
+ */
+ function visitNumericLiteral(node) {
+ if (node.numericLiteralFlags & 48 /* BinaryOrOctalSpecifier */) {
+ return ts.setTextRange(ts.createNumericLiteral(node.text), node);
+ }
+ return node;
}
/**
* Visits a TaggedTemplateExpression node.
@@ -51284,7 +55477,7 @@ var ts;
// ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
// <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
text = text.replace(/\r\n?/g, "\n");
- return ts.createLiteral(text, /*location*/ node);
+ return ts.setTextRange(ts.createLiteral(text), node);
}
/**
* Visits a TemplateExpression node.
@@ -51306,7 +55499,8 @@ var ts;
// "abc" + (1 << 2) + ""
var expression = ts.reduceLeft(expressions, ts.createAdd);
if (ts.nodeIsSynthesized(expression)) {
- ts.setTextRange(expression, node);
+ expression.pos = node.pos;
+ expression.end = node.end;
}
return expression;
}
@@ -51368,27 +55562,42 @@ var ts;
/**
* Visits the `super` keyword
*/
- function visitSuperKeyword() {
- return enclosingNonAsyncFunctionBody
- && ts.isClassElement(enclosingNonAsyncFunctionBody)
- && !ts.hasModifier(enclosingNonAsyncFunctionBody, 32 /* Static */)
- && currentParent.kind !== 179 /* CallExpression */
+ function visitSuperKeyword(isExpressionOfCall) {
+ return hierarchyFacts & 8 /* NonStaticClassElement */
+ && !isExpressionOfCall
? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype")
: ts.createIdentifier("_super");
}
+ function visitMetaProperty(node) {
+ if (node.keywordToken === 93 /* NewKeyword */ && node.name.text === "target") {
+ if (hierarchyFacts & 8192 /* ComputedPropertyName */) {
+ hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */;
+ }
+ else {
+ hierarchyFacts |= 16384 /* NewTarget */;
+ }
+ return ts.createIdentifier("_newTarget");
+ }
+ return node;
+ }
/**
* Called by the printer just before a node is printed.
*
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to be printed.
+ * @param emitCallback The callback used to emit the node.
*/
- function onEmitNode(emitContext, node, emitCallback) {
- var savedEnclosingFunction = enclosingFunction;
+ function onEmitNode(hint, node, emitCallback) {
if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
// If we are tracking a captured `this`, keep track of the enclosing function.
- enclosingFunction = node;
+ var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
+ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
+ : 65 /* FunctionIncludes */);
+ previousOnEmitNode(hint, node, emitCallback);
+ exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
+ return;
}
- previousOnEmitNode(emitContext, node, emitCallback);
- enclosingFunction = savedEnclosingFunction;
+ previousOnEmitNode(hint, node, emitCallback);
}
/**
* Enables a more costly code path for substitutions when we determine a source file
@@ -51408,24 +55617,24 @@ var ts;
if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
enabledSubstitutions |= 1 /* CapturedThis */;
context.enableSubstitution(98 /* ThisKeyword */);
- context.enableEmitNotification(150 /* Constructor */);
- context.enableEmitNotification(149 /* MethodDeclaration */);
- context.enableEmitNotification(151 /* GetAccessor */);
- context.enableEmitNotification(152 /* SetAccessor */);
- context.enableEmitNotification(185 /* ArrowFunction */);
- context.enableEmitNotification(184 /* FunctionExpression */);
- context.enableEmitNotification(225 /* FunctionDeclaration */);
+ context.enableEmitNotification(151 /* Constructor */);
+ context.enableEmitNotification(150 /* MethodDeclaration */);
+ context.enableEmitNotification(152 /* GetAccessor */);
+ context.enableEmitNotification(153 /* SetAccessor */);
+ context.enableEmitNotification(186 /* ArrowFunction */);
+ context.enableEmitNotification(185 /* FunctionExpression */);
+ context.enableEmitNotification(227 /* FunctionDeclaration */);
}
}
/**
* Hooks node substitutions.
*
- * @param emitContext The context for the emitter.
+ * @param hint The context for the emitter.
* @param node The node to substitute.
*/
- function onSubstituteNode(emitContext, node) {
- node = previousOnSubstituteNode(emitContext, node);
- if (emitContext === 1 /* Expression */) {
+ function onSubstituteNode(hint, node) {
+ node = previousOnSubstituteNode(hint, node);
+ if (hint === 1 /* Expression */) {
return substituteExpression(node);
}
if (ts.isIdentifier(node)) {
@@ -51442,7 +55651,7 @@ var ts;
if (enabledSubstitutions & 2 /* BlockScopedBindings */) {
var original = ts.getParseTreeNode(node, ts.isIdentifier);
if (original && isNameOfDeclarationWithCollidingName(original)) {
- return ts.getGeneratedNameForNode(original);
+ return ts.setTextRange(ts.getGeneratedNameForNode(original), node);
}
}
return node;
@@ -51456,10 +55665,10 @@ var ts;
function isNameOfDeclarationWithCollidingName(node) {
var parent = node.parent;
switch (parent.kind) {
- case 174 /* BindingElement */:
- case 226 /* ClassDeclaration */:
- case 229 /* EnumDeclaration */:
- case 223 /* VariableDeclaration */:
+ case 175 /* BindingElement */:
+ case 228 /* ClassDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 225 /* VariableDeclaration */:
return parent.name === node
&& resolver.isDeclarationWithCollidingName(parent);
}
@@ -51488,7 +55697,7 @@ var ts;
if (enabledSubstitutions & 2 /* BlockScopedBindings */) {
var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
if (declaration) {
- return ts.getGeneratedNameForNode(declaration.name);
+ return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node);
}
}
return node;
@@ -51500,9 +55709,8 @@ var ts;
*/
function substituteThisKeyword(node) {
if (enabledSubstitutions & 1 /* CapturedThis */
- && enclosingFunction
- && ts.getEmitFlags(enclosingFunction) & 8 /* CapturesThis */) {
- return ts.createIdentifier("_this", /*location*/ node);
+ && hierarchyFacts & 16 /* CapturesThis */) {
+ return ts.setTextRange(ts.createIdentifier("_this"), node);
}
return node;
}
@@ -51518,11 +55726,11 @@ var ts;
return false;
}
var statement = ts.firstOrUndefined(constructor.body.statements);
- if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 207 /* ExpressionStatement */) {
+ if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 209 /* ExpressionStatement */) {
return false;
}
var statementExpression = statement.expression;
- if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 179 /* CallExpression */) {
+ if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 180 /* CallExpression */) {
return false;
}
var callTarget = statementExpression.expression;
@@ -51530,7 +55738,7 @@ var ts;
return false;
}
var callArgument = ts.singleOrUndefined(statementExpression.arguments);
- if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 196 /* SpreadElement */) {
+ if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 197 /* SpreadElement */) {
return false;
}
var expression = callArgument.expression;
@@ -51550,11 +55758,123 @@ var ts;
name: "typescript:extends",
scoped: false,
priority: 0,
- text: "\n var __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };"
+ text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
})(ts || (ts = {}));
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
+/*@internal*/
+var ts;
+(function (ts) {
+ /**
+ * Transforms ES5 syntax into ES3 syntax.
+ *
+ * @param context Context and state information for the transformation.
+ */
+ function transformES5(context) {
+ var compilerOptions = context.getCompilerOptions();
+ // enable emit notification only if using --jsx preserve or react-native
+ var previousOnEmitNode;
+ var noSubstitution;
+ if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
+ previousOnEmitNode = context.onEmitNode;
+ context.onEmitNode = onEmitNode;
+ context.enableEmitNotification(250 /* JsxOpeningElement */);
+ context.enableEmitNotification(251 /* JsxClosingElement */);
+ context.enableEmitNotification(249 /* JsxSelfClosingElement */);
+ noSubstitution = [];
+ }
+ var previousOnSubstituteNode = context.onSubstituteNode;
+ context.onSubstituteNode = onSubstituteNode;
+ context.enableSubstitution(178 /* PropertyAccessExpression */);
+ context.enableSubstitution(260 /* PropertyAssignment */);
+ return transformSourceFile;
+ /**
+ * Transforms an ES5 source file to ES3.
+ *
+ * @param node A SourceFile
+ */
+ function transformSourceFile(node) {
+ return node;
+ }
+ /**
+ * Called by the printer just before a node is printed.
+ *
+ * @param hint A hint as to the intended usage of the node.
+ * @param node The node to emit.
+ * @param emitCallback A callback used to emit the node.
+ */
+ function onEmitNode(hint, node, emitCallback) {
+ switch (node.kind) {
+ case 250 /* JsxOpeningElement */:
+ case 251 /* JsxClosingElement */:
+ case 249 /* JsxSelfClosingElement */:
+ var tagName = node.tagName;
+ noSubstitution[ts.getOriginalNodeId(tagName)] = true;
+ break;
+ }
+ previousOnEmitNode(hint, node, emitCallback);
+ }
+ /**
+ * Hooks node substitutions.
+ *
+ * @param hint A hint as to the intended usage of the node.
+ * @param node The node to substitute.
+ */
+ function onSubstituteNode(hint, node) {
+ if (node.id && noSubstitution && noSubstitution[node.id]) {
+ return previousOnSubstituteNode(hint, node);
+ }
+ node = previousOnSubstituteNode(hint, node);
+ if (ts.isPropertyAccessExpression(node)) {
+ return substitutePropertyAccessExpression(node);
+ }
+ else if (ts.isPropertyAssignment(node)) {
+ return substitutePropertyAssignment(node);
+ }
+ return node;
+ }
+ /**
+ * Substitutes a PropertyAccessExpression whose name is a reserved word.
+ *
+ * @param node A PropertyAccessExpression
+ */
+ function substitutePropertyAccessExpression(node) {
+ var literalName = trySubstituteReservedName(node.name);
+ if (literalName) {
+ return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
+ }
+ return node;
+ }
+ /**
+ * Substitutes a PropertyAssignment whose name is a reserved word.
+ *
+ * @param node A PropertyAssignment
+ */
+ function substitutePropertyAssignment(node) {
+ var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
+ if (literalName) {
+ return ts.updatePropertyAssignment(node, literalName, node.initializer);
+ }
+ return node;
+ }
+ /**
+ * If an identifier name is a reserved word, returns a string literal for the name.
+ *
+ * @param name An Identifier
+ */
+ function trySubstituteReservedName(name) {
+ var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined);
+ if (token >= 71 /* FirstReservedWord */ && token <= 106 /* LastReservedWord */) {
+ return ts.setTextRange(ts.createLiteral(name), name);
+ }
+ return undefined;
+ }
+ }
+ ts.transformES5 = transformES5;
+})(ts || (ts = {}));
+/// <reference path="../factory.ts" />
+/// <reference path="../visitor.ts" />
// Transforms generator functions into a compatible ES5 representation with similar runtime
// semantics. This is accomplished by first transforming the body of each generator
// function into an intermediate representation that is the compiled into a JavaScript
@@ -51725,13 +56045,15 @@ var ts;
Instruction[Instruction["Catch"] = 6] = "Catch";
Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
})(Instruction || (Instruction = {}));
- var instructionNames = ts.createMap((_a = {},
- _a[2 /* Return */] = "return",
- _a[3 /* Break */] = "break",
- _a[4 /* Yield */] = "yield",
- _a[5 /* YieldStar */] = "yield*",
- _a[7 /* Endfinally */] = "endfinally",
- _a));
+ function getInstructionName(instruction) {
+ switch (instruction) {
+ case 2 /* Return */: return "return";
+ case 3 /* Break */: return "break";
+ case 4 /* Yield */: return "yield";
+ case 5 /* YieldStar */: return "yield*";
+ case 7 /* Endfinally */: return "endfinally";
+ }
+ }
function transformGenerators(context) {
var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
var compilerOptions = context.getCompilerOptions();
@@ -51823,13 +56145,13 @@ var ts;
*/
function visitJavaScriptInStatementContainingYield(node) {
switch (node.kind) {
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
return visitDoStatement(node);
- case 210 /* WhileStatement */:
+ case 212 /* WhileStatement */:
return visitWhileStatement(node);
- case 218 /* SwitchStatement */:
+ case 220 /* SwitchStatement */:
return visitSwitchStatement(node);
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
return visitLabeledStatement(node);
default:
return visitJavaScriptInGeneratorFunctionBody(node);
@@ -51842,24 +56164,24 @@ var ts;
*/
function visitJavaScriptInGeneratorFunctionBody(node) {
switch (node.kind) {
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return visitFunctionDeclaration(node);
- case 184 /* FunctionExpression */:
+ case 185 /* FunctionExpression */:
return visitFunctionExpression(node);
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
return visitAccessorDeclaration(node);
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
return visitVariableStatement(node);
- case 211 /* ForStatement */:
+ case 213 /* ForStatement */:
return visitForStatement(node);
- case 212 /* ForInStatement */:
+ case 214 /* ForInStatement */:
return visitForInStatement(node);
- case 215 /* BreakStatement */:
+ case 217 /* BreakStatement */:
return visitBreakStatement(node);
- case 214 /* ContinueStatement */:
+ case 216 /* ContinueStatement */:
return visitContinueStatement(node);
- case 216 /* ReturnStatement */:
+ case 218 /* ReturnStatement */:
return visitReturnStatement(node);
default:
if (node.transformFlags & 16777216 /* ContainsYield */) {
@@ -51880,21 +56202,21 @@ var ts;
*/
function visitJavaScriptContainingYield(node) {
switch (node.kind) {
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return visitBinaryExpression(node);
- case 193 /* ConditionalExpression */:
+ case 194 /* ConditionalExpression */:
return visitConditionalExpression(node);
- case 195 /* YieldExpression */:
+ case 196 /* YieldExpression */:
return visitYieldExpression(node);
- case 175 /* ArrayLiteralExpression */:
+ case 176 /* ArrayLiteralExpression */:
return visitArrayLiteralExpression(node);
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
return visitObjectLiteralExpression(node);
- case 178 /* ElementAccessExpression */:
+ case 179 /* ElementAccessExpression */:
return visitElementAccessExpression(node);
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
return visitCallExpression(node);
- case 180 /* NewExpression */:
+ case 181 /* NewExpression */:
return visitNewExpression(node);
default:
return ts.visitEachChild(node, visitor, context);
@@ -51907,9 +56229,9 @@ var ts;
*/
function visitGenerator(node) {
switch (node.kind) {
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return visitFunctionDeclaration(node);
- case 184 /* FunctionExpression */:
+ case 185 /* FunctionExpression */:
return visitFunctionExpression(node);
default:
ts.Debug.failBadSyntaxKind(node);
@@ -51927,12 +56249,12 @@ var ts;
*/
function visitFunctionDeclaration(node) {
// Currently, we only support generators that were originally async functions.
- if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) {
- node = ts.setOriginalNode(ts.createFunctionDeclaration(
+ if (node.asteriskToken) {
+ node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
/*decorators*/ undefined, node.modifiers,
/*asteriskToken*/ undefined, node.name,
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, transformGeneratorFunctionBody(node.body),
+ /*type*/ undefined, transformGeneratorFunctionBody(node.body)),
/*location*/ node), node);
}
else {
@@ -51965,12 +56287,12 @@ var ts;
*/
function visitFunctionExpression(node) {
// Currently, we only support generators that were originally async functions.
- if (node.asteriskToken && ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */) {
- node = ts.setOriginalNode(ts.createFunctionExpression(
+ if (node.asteriskToken) {
+ node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined, node.name,
/*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context),
- /*type*/ undefined, transformGeneratorFunctionBody(node.body),
+ /*type*/ undefined, transformGeneratorFunctionBody(node.body)),
/*location*/ node), node);
}
else {
@@ -52039,7 +56361,7 @@ var ts;
state = ts.createTempVariable(/*recordTempVariable*/ undefined);
// Build the generator
resumeLexicalEnvironment();
- var statementOffset = ts.addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor);
+ var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
ts.addRange(statements, endLexicalEnvironment());
@@ -52058,7 +56380,7 @@ var ts;
operationArguments = savedOperationArguments;
operationLocations = savedOperationLocations;
state = savedState;
- return ts.createBlock(statements, /*location*/ body, body.multiLine);
+ return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
}
/**
* Visits a variable statement.
@@ -52137,7 +56459,7 @@ var ts;
if (containsYield(right)) {
var target = void 0;
switch (left.kind) {
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
// [source]
// a.b = yield;
//
@@ -52149,7 +56471,7 @@ var ts;
// _a.b = %sent%;
target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
break;
- case 178 /* ElementAccessExpression */:
+ case 179 /* ElementAccessExpression */:
// [source]
// a[b] = yield;
//
@@ -52168,7 +56490,7 @@ var ts;
}
var operator = node.operatorToken.kind;
if (isCompoundAssignment(operator)) {
- return ts.createBinary(target, 57 /* EqualsToken */, ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression), node), node);
+ return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), getOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
}
else {
return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression));
@@ -52192,10 +56514,10 @@ var ts;
// _a = a();
// .yield resumeLabel
// _a + %sent% + c()
- var clone_4 = ts.getMutableClone(node);
- clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
- clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression);
- return clone_4;
+ var clone_5 = ts.getMutableClone(node);
+ clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
+ clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression);
+ return clone_5;
}
return ts.visitEachChild(node, visitor, context);
}
@@ -52330,17 +56652,19 @@ var ts;
// .yield resumeLabel, (a())
// .mark resumeLabel
// x = %sent%;
- // NOTE: we are explicitly not handling YieldStar at this time.
var resumeLabel = defineLabel();
var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
if (node.asteriskToken) {
- emitYieldStar(expression, /*location*/ node);
+ var iterator = (ts.getEmitFlags(node.expression) & 4194304 /* Iterator */) === 0
+ ? ts.createValuesHelper(context, expression, /*location*/ node)
+ : expression;
+ emitYieldStar(iterator, /*location*/ node);
}
else {
emitYield(expression, /*location*/ node);
}
markLabel(resumeLabel);
- return createGeneratorResume();
+ return createGeneratorResume(/*location*/ node);
}
/**
* Visits an ArrayLiteralExpression that contains a YieldExpression.
@@ -52368,26 +56692,27 @@ var ts;
// .mark resumeLabel
// ar = _a.concat([%sent%, 2]);
var numInitialElements = countInitialNodesWithoutYield(elements);
- var temp = declareLocal();
- var hasAssignedTemp = false;
+ var temp;
if (numInitialElements > 0) {
+ temp = declareLocal();
var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
emitAssignment(temp, ts.createArrayLiteral(leadingElement
? [leadingElement].concat(initialElements) : initialElements));
leadingElement = undefined;
- hasAssignedTemp = true;
}
var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
- return hasAssignedTemp
- ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, /*location*/ undefined, multiLine)])
- : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, location, multiLine);
+ return temp
+ ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
+ : ts.setTextRange(ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine), location);
function reduceElement(expressions, element) {
if (containsYield(element) && expressions.length > 0) {
+ var hasAssignedTemp = temp !== undefined;
+ if (!temp) {
+ temp = declareLocal();
+ }
emitAssignment(temp, hasAssignedTemp
- ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, /*location*/ undefined, multiLine)])
- : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions,
- /*location*/ undefined, multiLine));
- hasAssignedTemp = true;
+ ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
+ : ts.createArrayLiteral(leadingElement ? [leadingElement].concat(expressions) : expressions, multiLine));
leadingElement = undefined;
expressions = [];
}
@@ -52417,8 +56742,7 @@ var ts;
var multiLine = node.multiLine;
var numInitialProperties = countInitialNodesWithoutYield(properties);
var temp = declareLocal();
- emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties),
- /*location*/ undefined, multiLine));
+ emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
return ts.inlineExpressions(expressions);
@@ -52454,10 +56778,10 @@ var ts;
// .yield resumeLabel
// .mark resumeLabel
// a = _a[%sent%]
- var clone_5 = ts.getMutableClone(node);
- clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
- clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
- return clone_5;
+ var clone_6 = ts.getMutableClone(node);
+ clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
+ clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
+ return clone_6;
}
return ts.visitEachChild(node, visitor, context);
}
@@ -52492,10 +56816,9 @@ var ts;
// .mark resumeLabel
// new (_b.apply(_a, _c.concat([%sent%, 2])));
var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
- return ts.setOriginalNode(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments,
+ return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments,
/*leadingElement*/ ts.createVoidZero())),
- /*typeArguments*/ undefined, [],
- /*location*/ node), node);
+ /*typeArguments*/ undefined, []), node), node);
}
return ts.visitEachChild(node, visitor, context);
}
@@ -52524,38 +56847,38 @@ var ts;
}
function transformAndEmitStatementWorker(node) {
switch (node.kind) {
- case 204 /* Block */:
+ case 206 /* Block */:
return transformAndEmitBlock(node);
- case 207 /* ExpressionStatement */:
+ case 209 /* ExpressionStatement */:
return transformAndEmitExpressionStatement(node);
- case 208 /* IfStatement */:
+ case 210 /* IfStatement */:
return transformAndEmitIfStatement(node);
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
return transformAndEmitDoStatement(node);
- case 210 /* WhileStatement */:
+ case 212 /* WhileStatement */:
return transformAndEmitWhileStatement(node);
- case 211 /* ForStatement */:
+ case 213 /* ForStatement */:
return transformAndEmitForStatement(node);
- case 212 /* ForInStatement */:
+ case 214 /* ForInStatement */:
return transformAndEmitForInStatement(node);
- case 214 /* ContinueStatement */:
+ case 216 /* ContinueStatement */:
return transformAndEmitContinueStatement(node);
- case 215 /* BreakStatement */:
+ case 217 /* BreakStatement */:
return transformAndEmitBreakStatement(node);
- case 216 /* ReturnStatement */:
+ case 218 /* ReturnStatement */:
return transformAndEmitReturnStatement(node);
- case 217 /* WithStatement */:
+ case 219 /* WithStatement */:
return transformAndEmitWithStatement(node);
- case 218 /* SwitchStatement */:
+ case 220 /* SwitchStatement */:
return transformAndEmitSwitchStatement(node);
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
return transformAndEmitLabeledStatement(node);
- case 220 /* ThrowStatement */:
+ case 222 /* ThrowStatement */:
return transformAndEmitThrowStatement(node);
- case 221 /* TryStatement */:
+ case 223 /* TryStatement */:
return transformAndEmitTryStatement(node);
default:
- return emitStatement(ts.visitNode(node, visitor, ts.isStatement, /*optional*/ true));
+ return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
}
}
function transformAndEmitBlock(node) {
@@ -52572,7 +56895,9 @@ var ts;
function transformAndEmitVariableDeclarationList(node) {
for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
var variable = _a[_i];
- hoistVariableDeclaration(variable.name);
+ var name = ts.getSynthesizedClone(variable.name);
+ ts.setCommentRange(name, variable.name);
+ hoistVariableDeclaration(name);
}
var variables = ts.getInitializedVariables(node);
var numVariables = variables.length;
@@ -52615,7 +56940,7 @@ var ts;
if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
var endLabel = defineLabel();
var elseLabel = node.elseStatement ? defineLabel() : undefined;
- emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
+ emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
transformAndEmitEmbeddedStatement(node.thenStatement);
if (node.elseStatement) {
emitBreak(endLabel);
@@ -52738,8 +57063,7 @@ var ts;
transformAndEmitVariableDeclarationList(initializer);
}
else {
- emitStatement(ts.createStatement(ts.visitNode(initializer, visitor, ts.isExpression),
- /*location*/ initializer));
+ emitStatement(ts.setTextRange(ts.createStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
}
}
markLabel(conditionLabel);
@@ -52749,8 +57073,7 @@ var ts;
transformAndEmitEmbeddedStatement(node.statement);
markLabel(incrementLabel);
if (node.incrementor) {
- emitStatement(ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression),
- /*location*/ node.incrementor));
+ emitStatement(ts.setTextRange(ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
}
emitBreak(conditionLabel);
endLoopBlock();
@@ -52764,7 +57087,7 @@ var ts;
beginScriptLoopBlock();
}
var initializer = node.initializer;
- if (ts.isVariableDeclarationList(initializer)) {
+ if (initializer && ts.isVariableDeclarationList(initializer)) {
for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
var variable = _a[_i];
hoistVariableDeclaration(variable.name);
@@ -52772,7 +57095,7 @@ var ts;
var variables = ts.getInitializedVariables(initializer);
node = ts.updateFor(node, variables.length > 0
? ts.inlineExpressions(ts.map(variables, transformInitializedVariable))
- : undefined, ts.visitNode(node.condition, visitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.incrementor, visitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, ts.liftToBlock));
+ : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
}
else {
node = ts.visitEachChild(node, visitor, context);
@@ -52864,7 +57187,7 @@ var ts;
var variable = _a[_i];
hoistVariableDeclaration(variable.name);
}
- node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, /*optional*/ false, ts.liftToBlock));
+ node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
}
else {
node = ts.visitEachChild(node, visitor, context);
@@ -52903,11 +57226,11 @@ var ts;
return ts.visitEachChild(node, visitor, context);
}
function transformAndEmitReturnStatement(node) {
- emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true),
+ emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression),
/*location*/ node);
}
function visitReturnStatement(node) {
- return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression, /*optional*/ true),
+ return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression),
/*location*/ node);
}
function transformAndEmitWithStatement(node) {
@@ -52972,7 +57295,7 @@ var ts;
for (var i = 0; i < numClauses; i++) {
var clause = caseBlock.clauses[i];
clauseLabels.push(defineLabel());
- if (clause.kind === 254 /* DefaultClause */ && defaultClauseIndex === -1) {
+ if (clause.kind === 257 /* DefaultClause */ && defaultClauseIndex === -1) {
defaultClauseIndex = i;
}
}
@@ -52985,7 +57308,7 @@ var ts;
var defaultClausesSkipped = 0;
for (var i = clausesWritten; i < numClauses; i++) {
var clause = caseBlock.clauses[i];
- if (clause.kind === 253 /* CaseClause */) {
+ if (clause.kind === 256 /* CaseClause */) {
var caseClause = clause;
if (containsYield(caseClause.expression) && pendingClauses.length > 0) {
break;
@@ -53127,9 +57450,9 @@ var ts;
}
return -1;
}
- function onSubstituteNode(emitContext, node) {
- node = previousOnSubstituteNode(emitContext, node);
- if (emitContext === 1 /* Expression */) {
+ function onSubstituteNode(hint, node) {
+ node = previousOnSubstituteNode(hint, node);
+ if (hint === 1 /* Expression */) {
return substituteExpression(node);
}
return node;
@@ -53141,17 +57464,17 @@ var ts;
return node;
}
function substituteExpressionIdentifier(node) {
- if (renamedCatchVariables && ts.hasProperty(renamedCatchVariables, node.text)) {
+ if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(node.text)) {
var original = ts.getOriginalNode(node);
if (ts.isIdentifier(original) && original.parent) {
var declaration = resolver.getReferencedValueDeclaration(original);
if (declaration) {
- var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration)));
- if (name_36) {
- var clone_6 = ts.getMutableClone(name_36);
- ts.setSourceMapRange(clone_6, node);
- ts.setCommentRange(clone_6, node);
- return clone_6;
+ var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
+ if (name) {
+ var clone_7 = ts.getMutableClone(name);
+ ts.setSourceMapRange(clone_7, node);
+ ts.setCommentRange(clone_7, node);
+ return clone_7;
}
}
}
@@ -53160,7 +57483,7 @@ var ts;
}
function cacheExpression(node) {
var temp;
- if (ts.isGeneratedIdentifier(node)) {
+ if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
return node;
}
temp = ts.createTempVariable(hoistVariableDeclaration);
@@ -53288,15 +57611,23 @@ var ts;
*/
function beginCatchBlock(variable) {
ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
- var text = variable.name.text;
- var name = declareLocal(text);
- if (!renamedCatchVariables) {
- renamedCatchVariables = ts.createMap();
- renamedCatchVariableDeclarations = ts.createMap();
- context.enableSubstitution(70 /* Identifier */);
+ // generated identifiers should already be unique within a file
+ var name;
+ if (ts.isGeneratedIdentifier(variable.name)) {
+ name = variable.name;
+ hoistVariableDeclaration(variable.name);
+ }
+ else {
+ var text = variable.name.text;
+ name = declareLocal(text);
+ if (!renamedCatchVariables) {
+ renamedCatchVariables = ts.createMap();
+ renamedCatchVariableDeclarations = [];
+ context.enableSubstitution(70 /* Identifier */);
+ }
+ renamedCatchVariables.set(text, true);
+ renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
}
- renamedCatchVariables[text] = true;
- renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
var exception = peekBlock();
ts.Debug.assert(exception.state < 1 /* Catch */);
var endLabel = exception.endLabel;
@@ -53566,7 +57897,7 @@ var ts;
*/
function createInstruction(instruction) {
var literal = ts.createLiteral(instruction);
- literal.trailingComment = instructionNames[instruction];
+ ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
return literal;
}
/**
@@ -53577,10 +57908,10 @@ var ts;
*/
function createInlineBreak(label, location) {
ts.Debug.assert(label > 0, "Invalid label: " + label);
- return ts.createReturn(ts.createArrayLiteral([
+ return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
createInstruction(3 /* Break */),
createLabel(label)
- ]), location);
+ ])), location);
}
/**
* Creates a statement that can be used indicate a Return operation.
@@ -53589,15 +57920,16 @@ var ts;
* @param location An optional source map location for the statement.
*/
function createInlineReturn(expression, location) {
- return ts.createReturn(ts.createArrayLiteral(expression
+ return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
? [createInstruction(2 /* Return */), expression]
- : [createInstruction(2 /* Return */)]), location);
+ : [createInstruction(2 /* Return */)])), location);
}
/**
* Creates an expression that can be used to resume from a Yield operation.
*/
function createGeneratorResume(location) {
- return ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, [], location);
+ return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"),
+ /*typeArguments*/ undefined, []), location);
}
/**
* Emits an empty instruction.
@@ -53743,7 +58075,6 @@ var ts;
/*name*/ undefined,
/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)],
/*type*/ undefined, ts.createBlock(buildResult,
- /*location*/ undefined,
/*multiLine*/ buildResult.length > 0)), 262144 /* ReuseTempVariableScope */));
}
/**
@@ -54014,7 +58345,7 @@ var ts;
* @param operationLocation The source map location for the operation.
*/
function writeAssign(left, right, operationLocation) {
- writeStatement(ts.createStatement(ts.createAssignment(left, right), operationLocation));
+ writeStatement(ts.setTextRange(ts.createStatement(ts.createAssignment(left, right)), operationLocation));
}
/**
* Writes a Throw operation to the current label's statement list.
@@ -54025,7 +58356,7 @@ var ts;
function writeThrow(expression, operationLocation) {
lastOperationWasAbrupt = true;
lastOperationWasCompletion = true;
- writeStatement(ts.createThrow(expression, operationLocation));
+ writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation));
}
/**
* Writes a Return operation to the current label's statement list.
@@ -54036,9 +58367,9 @@ var ts;
function writeReturn(expression, operationLocation) {
lastOperationWasAbrupt = true;
lastOperationWasCompletion = true;
- writeStatement(ts.createReturn(ts.createArrayLiteral(expression
+ writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
? [createInstruction(2 /* Return */), expression]
- : [createInstruction(2 /* Return */)]), operationLocation));
+ : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
}
/**
* Writes a Break operation to the current label's statement list.
@@ -54048,10 +58379,10 @@ var ts;
*/
function writeBreak(label, operationLocation) {
lastOperationWasAbrupt = true;
- writeStatement(ts.createReturn(ts.createArrayLiteral([
+ writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
createInstruction(3 /* Break */),
createLabel(label)
- ]), operationLocation));
+ ])), operationLocation), 384 /* NoTokenSourceMaps */));
}
/**
* Writes a BreakWhenTrue operation to the current label's statement list.
@@ -54061,10 +58392,10 @@ var ts;
* @param operationLocation The source map location for the operation.
*/
function writeBreakWhenTrue(label, condition, operationLocation) {
- writeStatement(ts.createIf(condition, ts.createReturn(ts.createArrayLiteral([
+ writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
createInstruction(3 /* Break */),
createLabel(label)
- ]), operationLocation)));
+ ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
}
/**
* Writes a BreakWhenFalse operation to the current label's statement list.
@@ -54074,10 +58405,10 @@ var ts;
* @param operationLocation The source map location for the operation.
*/
function writeBreakWhenFalse(label, condition, operationLocation) {
- writeStatement(ts.createIf(ts.createLogicalNot(condition), ts.createReturn(ts.createArrayLiteral([
+ writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
createInstruction(3 /* Break */),
createLabel(label)
- ]), operationLocation)));
+ ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
}
/**
* Writes a Yield operation to the current label's statement list.
@@ -54087,9 +58418,9 @@ var ts;
*/
function writeYield(expression, operationLocation) {
lastOperationWasAbrupt = true;
- writeStatement(ts.createReturn(ts.createArrayLiteral(expression
+ writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
? [createInstruction(4 /* Yield */), expression]
- : [createInstruction(4 /* Yield */)]), operationLocation));
+ : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
}
/**
* Writes a YieldStar instruction to the current label's statement list.
@@ -54099,10 +58430,10 @@ var ts;
*/
function writeYieldStar(expression, operationLocation) {
lastOperationWasAbrupt = true;
- writeStatement(ts.createReturn(ts.createArrayLiteral([
+ writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
createInstruction(5 /* YieldStar */),
expression
- ]), operationLocation));
+ ])), operationLocation), 384 /* NoTokenSourceMaps */));
}
/**
* Writes an Endfinally instruction to the current label's statement list.
@@ -54183,157 +58514,918 @@ var ts;
name: "typescript:generator",
scoped: false,
priority: 6,
- text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };"
+ text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };"
};
- var _a;
})(ts || (ts = {}));
-/// <reference path="../factory.ts" />
-/// <reference path="../visitor.ts" />
+/// <reference path="../../factory.ts" />
+/// <reference path="../../visitor.ts" />
+/// <reference path="../destructuring.ts" />
/*@internal*/
var ts;
(function (ts) {
- /**
- * Transforms ES5 syntax into ES3 syntax.
- *
- * @param context Context and state information for the transformation.
- */
- function transformES5(context) {
+ function transformModule(context) {
+ function getTransformModuleDelegate(moduleKind) {
+ switch (moduleKind) {
+ case ts.ModuleKind.AMD: return transformAMDModule;
+ case ts.ModuleKind.UMD: return transformUMDModule;
+ default: return transformCommonJSModule;
+ }
+ }
+ var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment;
+ var compilerOptions = context.getCompilerOptions();
+ var resolver = context.getEmitResolver();
+ var host = context.getEmitHost();
+ var languageVersion = ts.getEmitScriptTarget(compilerOptions);
+ var moduleKind = ts.getEmitModuleKind(compilerOptions);
var previousOnSubstituteNode = context.onSubstituteNode;
+ var previousOnEmitNode = context.onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableSubstitution(177 /* PropertyAccessExpression */);
- context.enableSubstitution(257 /* PropertyAssignment */);
+ context.onEmitNode = onEmitNode;
+ context.enableSubstitution(70 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
+ context.enableSubstitution(193 /* BinaryExpression */); // Substitutes assignments to exported symbols.
+ context.enableSubstitution(191 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
+ context.enableSubstitution(192 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
+ context.enableSubstitution(261 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
+ context.enableEmitNotification(264 /* SourceFile */); // Restore state when substituting nodes in a file.
+ var moduleInfoMap = []; // The ExternalModuleInfo for each file.
+ var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
+ var currentSourceFile; // The current file.
+ var currentModuleInfo; // The ExternalModuleInfo for the current file.
+ var noSubstitution; // Set of nodes for which substitution rules should be ignored.
return transformSourceFile;
/**
- * Transforms an ES5 source file to ES3.
+ * Transforms the module aspects of a SourceFile.
*
- * @param node A SourceFile
+ * @param node The SourceFile node.
*/
function transformSourceFile(node) {
- return node;
+ if (ts.isDeclarationFile(node) || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) {
+ return node;
+ }
+ currentSourceFile = node;
+ currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
+ moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
+ // Perform the transformation.
+ var transformModule = getTransformModuleDelegate(moduleKind);
+ var updated = transformModule(node);
+ currentSourceFile = undefined;
+ currentModuleInfo = undefined;
+ return ts.aggregateTransformFlags(updated);
+ }
+ function shouldEmitUnderscoreUnderscoreESModule() {
+ if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
+ return true;
+ }
+ return false;
}
/**
- * Hooks node substitutions.
+ * Transforms a SourceFile into a CommonJS module.
*
- * @param emitContext The context for the emitter.
- * @param node The node to substitute.
+ * @param node The SourceFile node.
*/
- function onSubstituteNode(emitContext, node) {
- node = previousOnSubstituteNode(emitContext, node);
- if (ts.isPropertyAccessExpression(node)) {
- return substitutePropertyAccessExpression(node);
+ function transformCommonJSModule(node) {
+ startLexicalEnvironment();
+ var statements = [];
+ var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
+ var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
+ if (shouldEmitUnderscoreUnderscoreESModule()) {
+ ts.append(statements, createUnderscoreUnderscoreESModule());
}
- else if (ts.isPropertyAssignment(node)) {
- return substitutePropertyAssignment(node);
+ ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
+ ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
+ addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
+ ts.addRange(statements, endLexicalEnvironment());
+ var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
+ if (currentModuleInfo.hasExportStarsToExportValues) {
+ // If we have any `export * from ...` declarations
+ // we need to inform the emitter to add the __export helper.
+ ts.addEmitHelper(updated, exportStarHelper);
}
- return node;
+ return updated;
}
/**
- * Substitutes a PropertyAccessExpression whose name is a reserved word.
+ * Transforms a SourceFile into an AMD module.
*
- * @param node A PropertyAccessExpression
+ * @param node The SourceFile node.
*/
- function substitutePropertyAccessExpression(node) {
- var literalName = trySubstituteReservedName(node.name);
- if (literalName) {
- return ts.createElementAccess(node.expression, literalName, /*location*/ node);
+ function transformAMDModule(node) {
+ var define = ts.createIdentifier("define");
+ var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
+ // An AMD define function has the following shape:
+ //
+ // define(id?, dependencies?, factory);
+ //
+ // This has the shape of the following:
+ //
+ // define(name, ["module1", "module2"], function (module1Alias) { ... }
+ //
+ // The location of the alias in the parameter list in the factory function needs to
+ // match the position of the module name in the dependency list.
+ //
+ // To ensure this is true in cases of modules with no aliases, e.g.:
+ //
+ // import "module"
+ //
+ // or
+ //
+ // /// <amd-dependency path= "a.css" />
+ //
+ // we need to add modules without alias names to the end of the dependencies list
+ var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
+ // Create an updated SourceFile:
+ //
+ // define(moduleName?, ["module1", "module2"], function ...
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
+ ts.createStatement(ts.createCall(define,
+ /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([
+ // Add the dependency array argument:
+ //
+ // ["require", "exports", module1", "module2", ...]
+ ts.createArrayLiteral([
+ ts.createLiteral("require"),
+ ts.createLiteral("exports")
+ ].concat(aliasedModuleNames, unaliasedModuleNames)),
+ // Add the module body function argument:
+ //
+ // function (require, exports, module1, module2) ...
+ ts.createFunctionExpression(
+ /*modifiers*/ undefined,
+ /*asteriskToken*/ undefined,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, [
+ ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
+ ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
+ ].concat(importAliasNames),
+ /*type*/ undefined, transformAsynchronousModuleBody(node))
+ ])))
+ ]),
+ /*location*/ node.statements));
+ }
+ /**
+ * Transforms a SourceFile into a UMD module.
+ *
+ * @param node The SourceFile node.
+ */
+ function transformUMDModule(node) {
+ var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
+ var umdHeader = ts.createFunctionExpression(
+ /*modifiers*/ undefined,
+ /*asteriskToken*/ undefined,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")],
+ /*type*/ undefined, ts.setTextRange(ts.createBlock([
+ ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([
+ ts.createVariableStatement(
+ /*modifiers*/ undefined, [
+ ts.createVariableDeclaration("v",
+ /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"),
+ /*typeArguments*/ undefined, [
+ ts.createIdentifier("require"),
+ ts.createIdentifier("exports")
+ ]))
+ ]),
+ ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */)
+ ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([
+ ts.createStatement(ts.createCall(ts.createIdentifier("define"),
+ /*typeArguments*/ undefined, [
+ ts.createArrayLiteral([
+ ts.createLiteral("require"),
+ ts.createLiteral("exports")
+ ].concat(aliasedModuleNames, unaliasedModuleNames)),
+ ts.createIdentifier("factory")
+ ]))
+ ])))
+ ],
+ /*multiLine*/ true),
+ /*location*/ undefined));
+ // Create an updated SourceFile:
+ //
+ // (function (factory) {
+ // if (typeof module === "object" && typeof module.exports === "object") {
+ // var v = factory(require, exports);
+ // if (v !== undefined) module.exports = v;
+ // }
+ // else if (typeof define === 'function' && define.amd) {
+ // define(["require", "exports"], factory);
+ // }
+ // })(function ...)
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
+ ts.createStatement(ts.createCall(umdHeader,
+ /*typeArguments*/ undefined, [
+ // Add the module body function argument:
+ //
+ // function (require, exports) ...
+ ts.createFunctionExpression(
+ /*modifiers*/ undefined,
+ /*asteriskToken*/ undefined,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, [
+ ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
+ ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
+ ].concat(importAliasNames),
+ /*type*/ undefined, transformAsynchronousModuleBody(node))
+ ]))
+ ]),
+ /*location*/ node.statements));
+ }
+ /**
+ * Collect the additional asynchronous dependencies for the module.
+ *
+ * @param node The source file.
+ * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
+ */
+ function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
+ // names of modules with corresponding parameter in the factory function
+ var aliasedModuleNames = [];
+ // names of modules with no corresponding parameters in factory function
+ var unaliasedModuleNames = [];
+ // names of the parameters in the factory function; these
+ // parameters need to match the indexes of the corresponding
+ // module names in aliasedModuleNames.
+ var importAliasNames = [];
+ // Fill in amd-dependency tags
+ for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
+ var amdDependency = _a[_i];
+ if (amdDependency.name) {
+ aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
+ importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
+ }
+ else {
+ unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
+ }
}
- return node;
+ for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
+ var importNode = _c[_b];
+ // Find the name of the external module
+ var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
+ // Find the name of the module alias, if there is one
+ var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
+ // It is possible that externalModuleName is undefined if it is not string literal.
+ // This can happen in the invalid import syntax.
+ // E.g : "import * from alias from 'someLib';"
+ if (externalModuleName) {
+ if (includeNonAmdDependencies && importAliasName) {
+ // Set emitFlags on the name of the classDeclaration
+ // This is so that when printer will not substitute the identifier
+ ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
+ aliasedModuleNames.push(externalModuleName);
+ importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
+ }
+ else {
+ unaliasedModuleNames.push(externalModuleName);
+ }
+ }
+ }
+ return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
}
/**
- * Substitutes a PropertyAssignment whose name is a reserved word.
+ * Transforms a SourceFile into an AMD or UMD module body.
*
- * @param node A PropertyAssignment
+ * @param node The SourceFile node.
*/
- function substitutePropertyAssignment(node) {
- var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
- if (literalName) {
- return ts.updatePropertyAssignment(node, literalName, node.initializer);
+ function transformAsynchronousModuleBody(node) {
+ startLexicalEnvironment();
+ var statements = [];
+ var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
+ if (shouldEmitUnderscoreUnderscoreESModule()) {
+ ts.append(statements, createUnderscoreUnderscoreESModule());
}
- return node;
+ // Visit each statement of the module body.
+ ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
+ ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
+ // Append the 'export =' statement if provided.
+ addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
+ // End the lexical environment for the module body
+ // and merge any new lexical declarations.
+ ts.addRange(statements, endLexicalEnvironment());
+ var body = ts.createBlock(statements, /*multiLine*/ true);
+ if (currentModuleInfo.hasExportStarsToExportValues) {
+ // If we have any `export * from ...` declarations
+ // we need to inform the emitter to add the __export helper.
+ ts.addEmitHelper(body, exportStarHelper);
+ }
+ return body;
}
/**
- * If an identifier name is a reserved word, returns a string literal for the name.
+ * Adds the down-level representation of `export=` to the statement list if one exists
+ * in the source file.
*
- * @param name An Identifier
+ * @param statements The Statement list to modify.
+ * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
+ * return statement.
*/
- function trySubstituteReservedName(name) {
- var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined);
- if (token >= 71 /* FirstReservedWord */ && token <= 106 /* LastReservedWord */) {
- return ts.createLiteral(name, /*location*/ name);
+ function addExportEqualsIfNeeded(statements, emitAsReturn) {
+ if (currentModuleInfo.exportEquals) {
+ if (emitAsReturn) {
+ var statement = ts.createReturn(currentModuleInfo.exportEquals.expression);
+ ts.setTextRange(statement, currentModuleInfo.exportEquals);
+ ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
+ statements.push(statement);
+ }
+ else {
+ var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression));
+ ts.setTextRange(statement, currentModuleInfo.exportEquals);
+ ts.setEmitFlags(statement, 1536 /* NoComments */);
+ statements.push(statement);
+ }
}
- return undefined;
}
- }
- ts.transformES5 = transformES5;
-})(ts || (ts = {}));
-/// <reference path="../../factory.ts" />
-/// <reference path="../../visitor.ts" />
-/*@internal*/
-var ts;
-(function (ts) {
- function transformES2015Module(context) {
- var compilerOptions = context.getCompilerOptions();
- var previousOnEmitNode = context.onEmitNode;
- var previousOnSubstituteNode = context.onSubstituteNode;
- context.onEmitNode = onEmitNode;
- context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(261 /* SourceFile */);
- context.enableSubstitution(70 /* Identifier */);
- var currentSourceFile;
- return transformSourceFile;
- function transformSourceFile(node) {
- if (ts.isDeclarationFile(node)) {
- return node;
+ //
+ // Top-Level Source Element Visitors
+ //
+ /**
+ * Visits a node at the top level of the source file.
+ *
+ * @param node The node to visit.
+ */
+ function sourceElementVisitor(node) {
+ switch (node.kind) {
+ case 237 /* ImportDeclaration */:
+ return visitImportDeclaration(node);
+ case 236 /* ImportEqualsDeclaration */:
+ return visitImportEqualsDeclaration(node);
+ case 243 /* ExportDeclaration */:
+ return visitExportDeclaration(node);
+ case 242 /* ExportAssignment */:
+ return visitExportAssignment(node);
+ case 207 /* VariableStatement */:
+ return visitVariableStatement(node);
+ case 227 /* FunctionDeclaration */:
+ return visitFunctionDeclaration(node);
+ case 228 /* ClassDeclaration */:
+ return visitClassDeclaration(node);
+ case 296 /* MergeDeclarationMarker */:
+ return visitMergeDeclarationMarker(node);
+ case 297 /* EndOfDeclarationMarker */:
+ return visitEndOfDeclarationMarker(node);
+ default:
+ // This visitor does not descend into the tree, as export/import statements
+ // are only transformed at the top level of a file.
+ return node;
}
- if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
- var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions);
- if (externalHelpersModuleName) {
- var statements = [];
- var statementOffset = ts.addPrologueDirectives(statements, node.statements);
- ts.append(statements, ts.createImportDeclaration(
- /*decorators*/ undefined,
- /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)));
- ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
- return ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements));
+ }
+ /**
+ * Visits an ImportDeclaration node.
+ *
+ * @param node The node to visit.
+ */
+ function visitImportDeclaration(node) {
+ var statements;
+ var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
+ if (moduleKind !== ts.ModuleKind.AMD) {
+ if (!node.importClause) {
+ // import "mod";
+ return ts.setTextRange(ts.createStatement(createRequireCall(node)), node);
}
else {
- return ts.visitEachChild(node, visitor, context);
+ var variables = [];
+ if (namespaceDeclaration && !ts.isDefaultImport(node)) {
+ // import * as n from "mod";
+ variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
+ /*type*/ undefined, createRequireCall(node)));
+ }
+ else {
+ // import d from "mod";
+ // import { x, y } from "mod";
+ // import d, { x, y } from "mod";
+ // import d, * as n from "mod";
+ variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node),
+ /*type*/ undefined, createRequireCall(node)));
+ if (namespaceDeclaration && ts.isDefaultImport(node)) {
+ variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
+ /*type*/ undefined, ts.getGeneratedNameForNode(node)));
+ }
+ }
+ statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)),
+ /*location*/ node));
}
}
+ else if (namespaceDeclaration && ts.isDefaultImport(node)) {
+ // import d, * as n from "mod";
+ statements = ts.append(statements, ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList([
+ ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
+ /*type*/ undefined, ts.getGeneratedNameForNode(node)),
+ /*location*/ node)
+ ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
+ }
+ if (hasAssociatedEndOfDeclarationMarker(node)) {
+ // Defer exports until we encounter an EndOfDeclarationMarker node
+ var id = ts.getOriginalNodeId(node);
+ deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
+ }
+ else {
+ statements = appendExportsOfImportDeclaration(statements, node);
+ }
+ return ts.singleOrMany(statements);
+ }
+ /**
+ * Creates a `require()` call to import an external module.
+ *
+ * @param importNode The declararation to import.
+ */
+ function createRequireCall(importNode) {
+ var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
+ var args = [];
+ if (moduleName) {
+ args.push(moduleName);
+ }
+ return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
+ }
+ /**
+ * Visits an ImportEqualsDeclaration node.
+ *
+ * @param node The node to visit.
+ */
+ function visitImportEqualsDeclaration(node) {
+ ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
+ var statements;
+ if (moduleKind !== ts.ModuleKind.AMD) {
+ if (ts.hasModifier(node, 1 /* Export */)) {
+ statements = ts.append(statements, ts.setTextRange(ts.createStatement(createExportExpression(node.name, createRequireCall(node))), node));
+ }
+ else {
+ statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList([
+ ts.createVariableDeclaration(ts.getSynthesizedClone(node.name),
+ /*type*/ undefined, createRequireCall(node))
+ ],
+ /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node));
+ }
+ }
+ else {
+ if (ts.hasModifier(node, 1 /* Export */)) {
+ statements = ts.append(statements, ts.setTextRange(ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node));
+ }
+ }
+ if (hasAssociatedEndOfDeclarationMarker(node)) {
+ // Defer exports until we encounter an EndOfDeclarationMarker node
+ var id = ts.getOriginalNodeId(node);
+ deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
+ }
+ else {
+ statements = appendExportsOfImportEqualsDeclaration(statements, node);
+ }
+ return ts.singleOrMany(statements);
+ }
+ /**
+ * Visits an ExportDeclaration node.
+ *
+ * @param The node to visit.
+ */
+ function visitExportDeclaration(node) {
+ if (!node.moduleSpecifier) {
+ // Elide export declarations with no module specifier as they are handled
+ // elsewhere.
+ return undefined;
+ }
+ var generatedName = ts.getGeneratedNameForNode(node);
+ if (node.exportClause) {
+ var statements = [];
+ // export { x, y } from "mod";
+ if (moduleKind !== ts.ModuleKind.AMD) {
+ statements.push(ts.setTextRange(ts.createVariableStatement(
+ /*modifiers*/ undefined, ts.createVariableDeclarationList([
+ ts.createVariableDeclaration(generatedName,
+ /*type*/ undefined, createRequireCall(node))
+ ])),
+ /*location*/ node));
+ }
+ for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
+ var specifier = _a[_i];
+ var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
+ statements.push(ts.setTextRange(ts.createStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier));
+ }
+ return ts.singleOrMany(statements);
+ }
+ else {
+ // export * from "mod";
+ return ts.setTextRange(ts.createStatement(ts.createCall(ts.createIdentifier("__export"),
+ /*typeArguments*/ undefined, [
+ moduleKind !== ts.ModuleKind.AMD
+ ? createRequireCall(node)
+ : generatedName
+ ])), node);
+ }
+ }
+ /**
+ * Visits an ExportAssignment node.
+ *
+ * @param node The node to visit.
+ */
+ function visitExportAssignment(node) {
+ if (node.isExportEquals) {
+ return undefined;
+ }
+ var statements;
+ var original = node.original;
+ if (original && hasAssociatedEndOfDeclarationMarker(original)) {
+ // Defer exports until we encounter an EndOfDeclarationMarker node
+ var id = ts.getOriginalNodeId(node);
+ deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true);
+ }
+ else {
+ statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true);
+ }
+ return ts.singleOrMany(statements);
+ }
+ /**
+ * Visits a FunctionDeclaration node.
+ *
+ * @param node The node to visit.
+ */
+ function visitFunctionDeclaration(node) {
+ var statements;
+ if (ts.hasModifier(node, 1 /* Export */)) {
+ statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
+ /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
+ /*typeParameters*/ undefined, node.parameters,
+ /*type*/ undefined, node.body),
+ /*location*/ node),
+ /*original*/ node));
+ }
+ else {
+ statements = ts.append(statements, node);
+ }
+ if (hasAssociatedEndOfDeclarationMarker(node)) {
+ // Defer exports until we encounter an EndOfDeclarationMarker node
+ var id = ts.getOriginalNodeId(node);
+ deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
+ }
+ else {
+ statements = appendExportsOfHoistedDeclaration(statements, node);
+ }
+ return ts.singleOrMany(statements);
+ }
+ /**
+ * Visits a ClassDeclaration node.
+ *
+ * @param node The node to visit.
+ */
+ function visitClassDeclaration(node) {
+ var statements;
+ if (ts.hasModifier(node, 1 /* Export */)) {
+ statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
+ /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
+ /*typeParameters*/ undefined, node.heritageClauses, node.members), node), node));
+ }
+ else {
+ statements = ts.append(statements, node);
+ }
+ if (hasAssociatedEndOfDeclarationMarker(node)) {
+ // Defer exports until we encounter an EndOfDeclarationMarker node
+ var id = ts.getOriginalNodeId(node);
+ deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
+ }
+ else {
+ statements = appendExportsOfHoistedDeclaration(statements, node);
+ }
+ return ts.singleOrMany(statements);
+ }
+ /**
+ * Visits a VariableStatement node.
+ *
+ * @param node The node to visit.
+ */
+ function visitVariableStatement(node) {
+ var statements;
+ var variables;
+ var expressions;
+ if (ts.hasModifier(node, 1 /* Export */)) {
+ var modifiers = void 0;
+ // If we're exporting these variables, then these just become assignments to 'exports.x'.
+ // We only want to emit assignments for variables with initializers.
+ for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
+ var variable = _a[_i];
+ if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
+ if (!modifiers) {
+ modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
+ }
+ variables = ts.append(variables, variable);
+ }
+ else if (variable.initializer) {
+ expressions = ts.append(expressions, transformInitializedVariable(variable));
+ }
+ }
+ if (variables) {
+ statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
+ }
+ if (expressions) {
+ statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.inlineExpressions(expressions)), node));
+ }
+ }
+ else {
+ statements = ts.append(statements, node);
+ }
+ if (hasAssociatedEndOfDeclarationMarker(node)) {
+ // Defer exports until we encounter an EndOfDeclarationMarker node
+ var id = ts.getOriginalNodeId(node);
+ deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
+ }
+ else {
+ statements = appendExportsOfVariableStatement(statements, node);
+ }
+ return ts.singleOrMany(statements);
+ }
+ /**
+ * Transforms an exported variable with an initializer into an expression.
+ *
+ * @param node The node to transform.
+ */
+ function transformInitializedVariable(node) {
+ if (ts.isBindingPattern(node.name)) {
+ return ts.flattenDestructuringAssignment(node,
+ /*visitor*/ undefined, context, 0 /* All */,
+ /*needsValue*/ false, createExportExpression);
+ }
+ else {
+ return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name),
+ /*location*/ node.name), node.initializer);
+ }
+ }
+ /**
+ * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
+ * and transformed declaration.
+ *
+ * @param node The node to visit.
+ */
+ function visitMergeDeclarationMarker(node) {
+ // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
+ // declaration we do not emit a leading variable declaration. To preserve the
+ // begin/end semantics of the declararation and to properly handle exports
+ // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
+ //
+ // To balance the declaration, add the exports of the elided variable
+ // statement.
+ if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 207 /* VariableStatement */) {
+ var id = ts.getOriginalNodeId(node);
+ deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
+ }
return node;
}
- function visitor(node) {
+ /**
+ * Determines whether a node has an associated EndOfDeclarationMarker.
+ *
+ * @param node The node to test.
+ */
+ function hasAssociatedEndOfDeclarationMarker(node) {
+ return (ts.getEmitFlags(node) & 2097152 /* HasEndOfDeclarationMarker */) !== 0;
+ }
+ /**
+ * Visits a DeclarationMarker used as a placeholder for the end of a transformed
+ * declaration.
+ *
+ * @param node The node to visit.
+ */
+ function visitEndOfDeclarationMarker(node) {
+ // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
+ // end of the transformed declaration. We use this marker to emit any deferred exports
+ // of the declaration.
+ var id = ts.getOriginalNodeId(node);
+ var statements = deferredExports[id];
+ if (statements) {
+ delete deferredExports[id];
+ return ts.append(statements, node);
+ }
+ return node;
+ }
+ /**
+ * Appends the exports of an ImportDeclaration to a statement list, returning the
+ * statement list.
+ *
+ * @param statements A statement list to which the down-level export statements are to be
+ * appended. If `statements` is `undefined`, a new array is allocated if statements are
+ * appended.
+ * @param decl The declaration whose exports are to be recorded.
+ */
+ function appendExportsOfImportDeclaration(statements, decl) {
+ if (currentModuleInfo.exportEquals) {
+ return statements;
+ }
+ var importClause = decl.importClause;
+ if (!importClause) {
+ return statements;
+ }
+ if (importClause.name) {
+ statements = appendExportsOfDeclaration(statements, importClause);
+ }
+ var namedBindings = importClause.namedBindings;
+ if (namedBindings) {
+ switch (namedBindings.kind) {
+ case 239 /* NamespaceImport */:
+ statements = appendExportsOfDeclaration(statements, namedBindings);
+ break;
+ case 240 /* NamedImports */:
+ for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
+ var importBinding = _a[_i];
+ statements = appendExportsOfDeclaration(statements, importBinding);
+ }
+ break;
+ }
+ }
+ return statements;
+ }
+ /**
+ * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
+ * statement list.
+ *
+ * @param statements A statement list to which the down-level export statements are to be
+ * appended. If `statements` is `undefined`, a new array is allocated if statements are
+ * appended.
+ * @param decl The declaration whose exports are to be recorded.
+ */
+ function appendExportsOfImportEqualsDeclaration(statements, decl) {
+ if (currentModuleInfo.exportEquals) {
+ return statements;
+ }
+ return appendExportsOfDeclaration(statements, decl);
+ }
+ /**
+ * Appends the exports of a VariableStatement to a statement list, returning the statement
+ * list.
+ *
+ * @param statements A statement list to which the down-level export statements are to be
+ * appended. If `statements` is `undefined`, a new array is allocated if statements are
+ * appended.
+ * @param node The VariableStatement whose exports are to be recorded.
+ */
+ function appendExportsOfVariableStatement(statements, node) {
+ if (currentModuleInfo.exportEquals) {
+ return statements;
+ }
+ for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ statements = appendExportsOfBindingElement(statements, decl);
+ }
+ return statements;
+ }
+ /**
+ * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
+ * returning the statement list.
+ *
+ * @param statements A statement list to which the down-level export statements are to be
+ * appended. If `statements` is `undefined`, a new array is allocated if statements are
+ * appended.
+ * @param decl The declaration whose exports are to be recorded.
+ */
+ function appendExportsOfBindingElement(statements, decl) {
+ if (currentModuleInfo.exportEquals) {
+ return statements;
+ }
+ if (ts.isBindingPattern(decl.name)) {
+ for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
+ var element = _a[_i];
+ if (!ts.isOmittedExpression(element)) {
+ statements = appendExportsOfBindingElement(statements, element);
+ }
+ }
+ }
+ else if (!ts.isGeneratedIdentifier(decl.name)) {
+ statements = appendExportsOfDeclaration(statements, decl);
+ }
+ return statements;
+ }
+ /**
+ * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
+ * returning the statement list.
+ *
+ * @param statements A statement list to which the down-level export statements are to be
+ * appended. If `statements` is `undefined`, a new array is allocated if statements are
+ * appended.
+ * @param decl The declaration whose exports are to be recorded.
+ */
+ function appendExportsOfHoistedDeclaration(statements, decl) {
+ if (currentModuleInfo.exportEquals) {
+ return statements;
+ }
+ if (ts.hasModifier(decl, 1 /* Export */)) {
+ var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : decl.name;
+ statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
+ }
+ if (decl.name) {
+ statements = appendExportsOfDeclaration(statements, decl);
+ }
+ return statements;
+ }
+ /**
+ * Appends the exports of a declaration to a statement list, returning the statement list.
+ *
+ * @param statements A statement list to which the down-level export statements are to be
+ * appended. If `statements` is `undefined`, a new array is allocated if statements are
+ * appended.
+ * @param decl The declaration to export.
+ */
+ function appendExportsOfDeclaration(statements, decl) {
+ var name = ts.getDeclarationName(decl);
+ var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name.text);
+ if (exportSpecifiers) {
+ for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
+ var exportSpecifier = exportSpecifiers_1[_i];
+ statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name);
+ }
+ }
+ return statements;
+ }
+ /**
+ * Appends the down-level representation of an export to a statement list, returning the
+ * statement list.
+ *
+ * @param statements A statement list to which the down-level export statements are to be
+ * appended. If `statements` is `undefined`, a new array is allocated if statements are
+ * appended.
+ * @param exportName The name of the export.
+ * @param expression The expression to export.
+ * @param location The location to use for source maps and comments for the export.
+ * @param allowComments Whether to allow comments on the export.
+ */
+ function appendExportStatement(statements, exportName, expression, location, allowComments) {
+ statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments));
+ return statements;
+ }
+ function createUnderscoreUnderscoreESModule() {
+ var statement;
+ if (languageVersion === 0 /* ES3 */) {
+ statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true)));
+ }
+ else {
+ statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
+ /*typeArguments*/ undefined, [
+ ts.createIdentifier("exports"),
+ ts.createLiteral("__esModule"),
+ ts.createObjectLiteral([
+ ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true))
+ ])
+ ]));
+ }
+ ts.setEmitFlags(statement, 524288 /* CustomPrologue */);
+ return statement;
+ }
+ /**
+ * Creates a call to the current file's export function to export a value.
+ *
+ * @param name The bound name of the export.
+ * @param value The exported value.
+ * @param location The location to use for source maps and comments for the export.
+ * @param allowComments An optional value indicating whether to emit comments for the statement.
+ */
+ function createExportStatement(name, value, location, allowComments) {
+ var statement = ts.setTextRange(ts.createStatement(createExportExpression(name, value)), location);
+ ts.startOnNewLine(statement);
+ if (!allowComments) {
+ ts.setEmitFlags(statement, 1536 /* NoComments */);
+ }
+ return statement;
+ }
+ /**
+ * Creates a call to the current file's export function to export a value.
+ *
+ * @param name The bound name of the export.
+ * @param value The exported value.
+ * @param location The location to use for source maps and comments for the export.
+ */
+ function createExportExpression(name, value, location) {
+ return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location);
+ }
+ //
+ // Modifier Visitors
+ //
+ /**
+ * Visit nodes to elide module-specific modifiers.
+ *
+ * @param node The node to visit.
+ */
+ function modifierVisitor(node) {
+ // Elide module-specific modifiers.
switch (node.kind) {
- case 234 /* ImportEqualsDeclaration */:
- // Elide `import=` as it is not legal with --module ES6
+ case 83 /* ExportKeyword */:
+ case 78 /* DefaultKeyword */:
return undefined;
- case 240 /* ExportAssignment */:
- return visitExportAssignment(node);
}
return node;
}
- function visitExportAssignment(node) {
- // Elide `export=` as it is not legal with --module ES6
- return node.isExportEquals ? undefined : node;
- }
//
// Emit Notification
//
/**
- * Hook for node emit.
+ * Hook for node emit notifications.
*
- * @param emitContext A context hint for the emitter.
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emit A callback used to emit the node in the printer.
*/
- function onEmitNode(emitContext, node, emitCallback) {
- if (ts.isSourceFile(node)) {
+ function onEmitNode(hint, node, emitCallback) {
+ if (node.kind === 264 /* SourceFile */) {
currentSourceFile = node;
- previousOnEmitNode(emitContext, node, emitCallback);
+ currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
+ noSubstitution = [];
+ previousOnEmitNode(hint, node, emitCallback);
currentSourceFile = undefined;
+ currentModuleInfo = undefined;
+ noSubstitution = undefined;
}
else {
- previousOnEmitNode(emitContext, node, emitCallback);
+ previousOnEmitNode(hint, node, emitCallback);
}
}
//
@@ -54342,30 +59434,192 @@ var ts;
/**
* Hooks node substitutions.
*
- * @param emitContext A context hint for the emitter.
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
- function onSubstituteNode(emitContext, node) {
- node = previousOnSubstituteNode(emitContext, node);
- if (ts.isIdentifier(node) && emitContext === 1 /* Expression */) {
- return substituteExpressionIdentifier(node);
+ function onSubstituteNode(hint, node) {
+ node = previousOnSubstituteNode(hint, node);
+ if (node.id && noSubstitution[node.id]) {
+ return node;
+ }
+ if (hint === 1 /* Expression */) {
+ return substituteExpression(node);
+ }
+ else if (ts.isShorthandPropertyAssignment(node)) {
+ return substituteShorthandPropertyAssignment(node);
+ }
+ return node;
+ }
+ /**
+ * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
+ * or exported symbol.
+ *
+ * @param node The node to substitute.
+ */
+ function substituteShorthandPropertyAssignment(node) {
+ var name = node.name;
+ var exportedOrImportedName = substituteExpressionIdentifier(name);
+ if (exportedOrImportedName !== name) {
+ // A shorthand property with an assignment initializer is probably part of a
+ // destructuring assignment
+ if (node.objectAssignmentInitializer) {
+ var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
+ return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
+ }
+ return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node);
+ }
+ return node;
+ }
+ /**
+ * Substitution for an Expression that may contain an imported or exported symbol.
+ *
+ * @param node The node to substitute.
+ */
+ function substituteExpression(node) {
+ switch (node.kind) {
+ case 70 /* Identifier */:
+ return substituteExpressionIdentifier(node);
+ case 193 /* BinaryExpression */:
+ return substituteBinaryExpression(node);
+ case 192 /* PostfixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
+ return substituteUnaryExpression(node);
}
return node;
}
+ /**
+ * Substitution for an Identifier expression that may contain an imported or exported
+ * symbol.
+ *
+ * @param node The node to substitute.
+ */
function substituteExpressionIdentifier(node) {
if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
if (externalHelpersModuleName) {
return ts.createPropertyAccess(externalHelpersModuleName, node);
}
+ return node;
+ }
+ if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
+ var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
+ if (exportContainer && exportContainer.kind === 264 /* SourceFile */) {
+ return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
+ /*location*/ node);
+ }
+ var importDeclaration = resolver.getReferencedImportDeclaration(node);
+ if (importDeclaration) {
+ if (ts.isImportClause(importDeclaration)) {
+ return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")),
+ /*location*/ node);
+ }
+ else if (ts.isImportSpecifier(importDeclaration)) {
+ var name = importDeclaration.propertyName || importDeclaration.name;
+ return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)),
+ /*location*/ node);
+ }
+ }
}
return node;
}
+ /**
+ * Substitution for a BinaryExpression that may contain an imported or exported symbol.
+ *
+ * @param node The node to substitute.
+ */
+ function substituteBinaryExpression(node) {
+ // When we see an assignment expression whose left-hand side is an exported symbol,
+ // we should ensure all exports of that symbol are updated with the correct value.
+ //
+ // - We do not substitute generated identifiers for any reason.
+ // - We do not substitute identifiers tagged with the LocalName flag.
+ // - We do not substitute identifiers that were originally the name of an enum or
+ // namespace due to how they are transformed in TypeScript.
+ // - We only substitute identifiers that are exported at the top level.
+ if (ts.isAssignmentOperator(node.operatorToken.kind)
+ && ts.isIdentifier(node.left)
+ && !ts.isGeneratedIdentifier(node.left)
+ && !ts.isLocalName(node.left)
+ && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
+ var exportedNames = getExports(node.left);
+ if (exportedNames) {
+ // For each additional export of the declaration, apply an export assignment.
+ var expression = node;
+ for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
+ var exportName = exportedNames_1[_i];
+ // Mark the node to prevent triggering this rule again.
+ noSubstitution[ts.getNodeId(expression)] = true;
+ expression = createExportExpression(exportName, expression, /*location*/ node);
+ }
+ return expression;
+ }
+ }
+ return node;
+ }
+ /**
+ * Substitution for a UnaryExpression that may contain an imported or exported symbol.
+ *
+ * @param node The node to substitute.
+ */
+ function substituteUnaryExpression(node) {
+ // When we see a prefix or postfix increment expression whose operand is an exported
+ // symbol, we should ensure all exports of that symbol are updated with the correct
+ // value.
+ //
+ // - We do not substitute generated identifiers for any reason.
+ // - We do not substitute identifiers tagged with the LocalName flag.
+ // - We do not substitute identifiers that were originally the name of an enum or
+ // namespace due to how they are transformed in TypeScript.
+ // - We only substitute identifiers that are exported at the top level.
+ if ((node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */)
+ && ts.isIdentifier(node.operand)
+ && !ts.isGeneratedIdentifier(node.operand)
+ && !ts.isLocalName(node.operand)
+ && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
+ var exportedNames = getExports(node.operand);
+ if (exportedNames) {
+ var expression = node.kind === 192 /* PostfixUnaryExpression */
+ ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 42 /* PlusPlusToken */ ? 58 /* PlusEqualsToken */ : 59 /* MinusEqualsToken */), ts.createLiteral(1)),
+ /*location*/ node)
+ : node;
+ for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
+ var exportName = exportedNames_2[_i];
+ // Mark the node to prevent triggering this rule again.
+ noSubstitution[ts.getNodeId(expression)] = true;
+ expression = createExportExpression(exportName, expression);
+ }
+ return expression;
+ }
+ }
+ return node;
+ }
+ /**
+ * Gets the additional exports of a name.
+ *
+ * @param name The name.
+ */
+ function getExports(name) {
+ if (!ts.isGeneratedIdentifier(name)) {
+ var valueDeclaration = resolver.getReferencedImportDeclaration(name)
+ || resolver.getReferencedValueDeclaration(name);
+ if (valueDeclaration) {
+ return currentModuleInfo
+ && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
+ }
+ }
+ }
}
- ts.transformES2015Module = transformES2015Module;
+ ts.transformModule = transformModule;
+ // emit output for the __export helper function
+ var exportStarHelper = {
+ name: "typescript:export-star",
+ scoped: true,
+ text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }"
+ };
})(ts || (ts = {}));
/// <reference path="../../factory.ts" />
/// <reference path="../../visitor.ts" />
+/// <reference path="../destructuring.ts" />
/*@internal*/
var ts;
(function (ts) {
@@ -54379,14 +59633,14 @@ var ts;
context.onSubstituteNode = onSubstituteNode;
context.onEmitNode = onEmitNode;
context.enableSubstitution(70 /* Identifier */); // Substitutes expression identifiers for imported symbols.
- context.enableSubstitution(192 /* BinaryExpression */); // Substitutes assignments to exported symbols.
- context.enableSubstitution(190 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableSubstitution(191 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(261 /* SourceFile */); // Restore state when substituting nodes in a file.
- var moduleInfoMap = ts.createMap(); // The ExternalModuleInfo for each file.
- var deferredExports = ts.createMap(); // Exports to defer until an EndOfDeclarationMarker is found.
- var exportFunctionsMap = ts.createMap(); // The export function associated with a source file.
- var noSubstitutionMap = ts.createMap(); // Set of nodes for which substitution rules should be ignored for each file.
+ context.enableSubstitution(193 /* BinaryExpression */); // Substitutes assignments to exported symbols.
+ context.enableSubstitution(191 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
+ context.enableSubstitution(192 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
+ context.enableEmitNotification(264 /* SourceFile */); // Restore state when substituting nodes in a file.
+ var moduleInfoMap = []; // The ExternalModuleInfo for each file.
+ var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
+ var exportFunctionsMap = []; // The export function associated with a source file.
+ var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
var currentSourceFile; // The current file.
var moduleInfo; // ExternalModuleInfo for the current file.
var exportFunction; // The export function for the current file.
@@ -54425,7 +59679,8 @@ var ts;
moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
// Make sure that the name of the 'exports' function does not conflict with
// existing identifiers.
- exportFunction = exportFunctionsMap[id] = ts.createUniqueName("exports");
+ exportFunction = ts.createUniqueName("exports");
+ exportFunctionsMap[id] = exportFunction;
contextObject = ts.createUniqueName("context");
// Add the body of the module.
var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
@@ -54444,12 +59699,12 @@ var ts;
// So the helper will be emit at the correct position instead of at the top of the source-file
var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
- var updated = ts.updateSourceFileNode(node, ts.createNodeArray([
+ var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"),
/*typeArguments*/ undefined, moduleName
? [moduleName, dependencies, moduleBodyFunction]
: [dependencies, moduleBodyFunction]))
- ], node.statements));
+ ]), node.statements)), 1024 /* NoTrailingComments */);
if (!(compilerOptions.outFile || compilerOptions.out)) {
ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
}
@@ -54476,18 +59731,20 @@ var ts;
for (var i = 0; i < externalImports.length; i++) {
var externalImport = externalImports[i];
var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
- var text = externalModuleName.text;
- if (ts.hasProperty(groupIndices, text)) {
- // deduplicate/group entries in dependency list by the dependency name
- var groupIndex = groupIndices[text];
- dependencyGroups[groupIndex].externalImports.push(externalImport);
- }
- else {
- groupIndices[text] = dependencyGroups.length;
- dependencyGroups.push({
- name: externalModuleName,
- externalImports: [externalImport]
- });
+ if (externalModuleName) {
+ var text = externalModuleName.text;
+ var groupIndex = groupIndices.get(text);
+ if (groupIndex !== undefined) {
+ // deduplicate/group entries in dependency list by the dependency name
+ dependencyGroups[groupIndex].externalImports.push(externalImport);
+ }
+ else {
+ groupIndices.set(text, dependencyGroups.length);
+ dependencyGroups.push({
+ name: externalModuleName,
+ externalImports: [externalImport]
+ });
+ }
}
}
return dependencyGroups;
@@ -54545,7 +59802,8 @@ var ts;
// only in the outer module body and not in the inner one.
startLexicalEnvironment();
// Add any prologue directives.
- var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
+ var ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
+ var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
// var __moduleName = context_1 && context_1.id;
statements.push(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
@@ -54553,7 +59811,7 @@ var ts;
/*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id")))
])));
// Visit the synthetic external helpers import declaration if present
- ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true);
+ ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
// Visit the statements of the source file, emitting any transformations into
// the `executeStatements` array. We do this *before* we fill the `setters` array
// as we both emit transformations as well as aggregate some data used when creating
@@ -54567,7 +59825,7 @@ var ts;
// - Temporary variables will appear at the top rather than at the bottom of the file
ts.addRange(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements);
- statements.push(ts.createReturn(ts.setMultiLine(ts.createObjectLiteral([
+ var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
ts.createPropertyAssignment("execute", ts.createFunctionExpression(
/*modifiers*/ undefined,
@@ -54575,12 +59833,11 @@ var ts;
/*name*/ undefined,
/*typeParameters*/ undefined,
/*parameters*/ [],
- /*type*/ undefined, ts.createBlock(executeStatements,
- /*location*/ undefined,
- /*multiLine*/ true)))
- ]),
- /*multiLine*/ true)));
- return ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true);
+ /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true)))
+ ]);
+ moduleObject.multiLine = true;
+ statements.push(ts.createReturn(moduleObject));
+ return ts.createBlock(statements, /*multiLine*/ true);
}
/**
* Adds an exportStar function to a statement list if it is needed for the file.
@@ -54596,13 +59853,13 @@ var ts;
// to support this we store names of local/indirect exported entries in a set.
// this set is used to filter names brought by star expors.
// local names set should only be added if we have anything exported
- if (!moduleInfo.exportedNames && ts.isEmpty(moduleInfo.exportSpecifiers)) {
+ if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
// no exported declarations (export var ...) or export specifiers (export {x})
// check if we have any non star export declarations.
var hasExportDeclarationWithExportClause = false;
for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
var externalImport = _a[_i];
- if (externalImport.kind === 241 /* ExportDeclaration */ && externalImport.exportClause) {
+ if (externalImport.kind === 243 /* ExportDeclaration */ && externalImport.exportClause) {
hasExportDeclarationWithExportClause = true;
break;
}
@@ -54622,12 +59879,12 @@ var ts;
continue;
}
// write name of exported declaration, i.e 'export var x...'
- exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createLiteral(true)));
+ exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue()));
}
}
for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) {
var externalImport = _e[_d];
- if (externalImport.kind !== 241 /* ExportDeclaration */) {
+ if (externalImport.kind !== 243 /* ExportDeclaration */) {
continue;
}
var exportDecl = externalImport;
@@ -54638,14 +59895,14 @@ var ts;
for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) {
var element = _g[_f];
// write name of indirectly exported entry, i.e. 'export {x} from ...'
- exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createLiteral(true)));
+ exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createTrue()));
}
}
var exportedNamesStorageRef = ts.createUniqueName("exportedNames");
statements.push(ts.createVariableStatement(
/*modifiers*/ undefined, ts.createVariableDeclarationList([
ts.createVariableDeclaration(exportedNamesStorageRef,
- /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*location*/ undefined, /*multiline*/ true))
+ /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true))
])));
var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
statements.push(exportStarFunction);
@@ -54686,9 +59943,7 @@ var ts;
])),
ts.createStatement(ts.createCall(exportFunction,
/*typeArguments*/ undefined, [exports]))
- ],
- /*location*/ undefined,
- /*multiline*/ true));
+ ], /*multiline*/ true));
}
/**
* Creates an array setter callbacks for each dependency group.
@@ -54708,19 +59963,19 @@ var ts;
var entry = _b[_a];
var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile);
switch (entry.kind) {
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
if (!entry.importClause) {
// 'import "..."' case
// module is imported only for side-effects, no emit required
break;
}
- // fall-through
- case 234 /* ImportEqualsDeclaration */:
+ // falls through
+ case 236 /* ImportEqualsDeclaration */:
ts.Debug.assert(importVariableName !== undefined);
// save import into the local
statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName)));
break;
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
ts.Debug.assert(importVariableName !== undefined);
if (entry.exportClause) {
// export {a, b as c} from 'foo'
@@ -54737,7 +59992,7 @@ var ts;
properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text))));
}
statements.push(ts.createStatement(ts.createCall(exportFunction,
- /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*location*/ undefined, /*multiline*/ true)])));
+ /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)])));
}
else {
// export * from 'foo'
@@ -54756,9 +60011,9 @@ var ts;
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
- /*type*/ undefined, ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true)));
+ /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true)));
}
- return ts.createArrayLiteral(setters, /*location*/ undefined, /*multiLine*/ true);
+ return ts.createArrayLiteral(setters, /*multiLine*/ true);
}
//
// Top-level Source Element Visitors
@@ -54770,15 +60025,15 @@ var ts;
*/
function sourceElementVisitor(node) {
switch (node.kind) {
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
return visitImportDeclaration(node);
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
return visitImportEqualsDeclaration(node);
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
// ExportDeclarations are elided as they are handled via
// `appendExportsOfDeclaration`.
return undefined;
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
return visitExportAssignment(node);
default:
return nestedElementVisitor(node);
@@ -54851,7 +60106,7 @@ var ts;
*/
function visitFunctionDeclaration(node) {
if (ts.hasModifier(node, 1 /* Export */)) {
- hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
+ hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
/*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration),
/*type*/ undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock)));
}
@@ -54879,11 +60134,9 @@ var ts;
var name = ts.getLocalName(node);
hoistVariableDeclaration(name);
// Rewrite the class declaration into an assignment of a class expression.
- statements = ts.append(statements, ts.createStatement(ts.createAssignment(name, ts.createClassExpression(
+ statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(
/*modifiers*/ undefined, node.name,
- /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement),
- /*location*/ node)),
- /*location*/ node));
+ /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement)), node))), node));
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
var id = ts.getOriginalNodeId(node);
@@ -54918,7 +60171,7 @@ var ts;
}
var statements;
if (expressions) {
- statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), /*location*/ node));
+ statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.inlineExpressions(expressions)), node));
}
if (isMarkedDeclaration) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -54956,7 +60209,7 @@ var ts;
function shouldHoistVariableDeclarationList(node) {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
return (ts.getEmitFlags(node) & 1048576 /* NoHoisting */) === 0
- && (enclosingBlockScopedContainer.kind === 261 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 264 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -55003,8 +60256,8 @@ var ts;
function createVariableAssignment(name, value, location, isExportedDeclaration) {
hoistVariableDeclaration(ts.getSynthesizedClone(name));
return isExportedDeclaration
- ? createExportExpression(name, preventSubstitution(ts.createAssignment(name, value, location)))
- : preventSubstitution(ts.createAssignment(name, value, location));
+ ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)))
+ : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location));
}
/**
* Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
@@ -55020,7 +60273,7 @@ var ts;
//
// To balance the declaration, we defer the exports of the elided variable
// statement until we visit this declaration's `EndOfDeclarationMarker`.
- if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205 /* VariableStatement */) {
+ if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 207 /* VariableStatement */) {
var id = ts.getOriginalNodeId(node);
var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
@@ -55076,10 +60329,10 @@ var ts;
var namedBindings = importClause.namedBindings;
if (namedBindings) {
switch (namedBindings.kind) {
- case 237 /* NamespaceImport */:
+ case 239 /* NamespaceImport */:
statements = appendExportsOfDeclaration(statements, namedBindings);
break;
- case 238 /* NamedImports */:
+ case 240 /* NamedImports */:
for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
var importBinding = _a[_i];
statements = appendExportsOfDeclaration(statements, importBinding);
@@ -55197,10 +60450,10 @@ var ts;
return statements;
}
var name = ts.getDeclarationName(decl);
- var exportSpecifiers = moduleInfo.exportSpecifiers[name.text];
+ var exportSpecifiers = moduleInfo.exportSpecifiers.get(name.text);
if (exportSpecifiers) {
- for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
- var exportSpecifier = exportSpecifiers_1[_i];
+ for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
+ var exportSpecifier = exportSpecifiers_2[_i];
if (exportSpecifier.name.text !== excludeName) {
statements = appendExportStatement(statements, exportSpecifier.name, name);
}
@@ -55258,43 +60511,43 @@ var ts;
*/
function nestedElementVisitor(node) {
switch (node.kind) {
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
return visitVariableStatement(node);
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return visitFunctionDeclaration(node);
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 211 /* ForStatement */:
+ case 213 /* ForStatement */:
return visitForStatement(node);
- case 212 /* ForInStatement */:
+ case 214 /* ForInStatement */:
return visitForInStatement(node);
- case 213 /* ForOfStatement */:
+ case 215 /* ForOfStatement */:
return visitForOfStatement(node);
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
return visitDoStatement(node);
- case 210 /* WhileStatement */:
+ case 212 /* WhileStatement */:
return visitWhileStatement(node);
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
return visitLabeledStatement(node);
- case 217 /* WithStatement */:
+ case 219 /* WithStatement */:
return visitWithStatement(node);
- case 218 /* SwitchStatement */:
+ case 220 /* SwitchStatement */:
return visitSwitchStatement(node);
- case 232 /* CaseBlock */:
+ case 234 /* CaseBlock */:
return visitCaseBlock(node);
- case 253 /* CaseClause */:
+ case 256 /* CaseClause */:
return visitCaseClause(node);
- case 254 /* DefaultClause */:
+ case 257 /* DefaultClause */:
return visitDefaultClause(node);
- case 221 /* TryStatement */:
+ case 223 /* TryStatement */:
return visitTryStatement(node);
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return visitCatchClause(node);
- case 204 /* Block */:
+ case 206 /* Block */:
return visitBlock(node);
- case 295 /* MergeDeclarationMarker */:
+ case 296 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 296 /* EndOfDeclarationMarker */:
+ case 297 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringVisitor(node);
@@ -55308,7 +60561,7 @@ var ts;
function visitForStatement(node) {
var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
- node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression, /*optional*/ true), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement));
+ node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement));
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
@@ -55320,7 +60573,7 @@ var ts;
function visitForInStatement(node) {
var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
- node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock));
+ node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
@@ -55332,7 +60585,7 @@ var ts;
function visitForOfStatement(node) {
var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
- node = ts.updateForOf(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock));
+ node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
@@ -55352,6 +60605,9 @@ var ts;
* @param node The node to visit.
*/
function visitForInitializer(node) {
+ if (!node) {
+ return node;
+ }
if (shouldHoistForInitializer(node)) {
var expressions = void 0;
for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
@@ -55370,7 +60626,7 @@ var ts;
* @param node The node to visit.
*/
function visitDoStatement(node) {
- return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression));
+ return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression));
}
/**
* Visits the body of a WhileStatement to hoist declarations.
@@ -55378,7 +60634,7 @@ var ts;
* @param node The node to visit.
*/
function visitWhileStatement(node) {
- return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock));
+ return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
}
/**
* Visits the body of a LabeledStatement to hoist declarations.
@@ -55386,7 +60642,7 @@ var ts;
* @param node The node to visit.
*/
function visitLabeledStatement(node) {
- return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock));
+ return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
}
/**
* Visits the body of a WithStatement to hoist declarations.
@@ -55394,7 +60650,7 @@ var ts;
* @param node The node to visit.
*/
function visitWithStatement(node) {
- return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/ false, ts.liftToBlock));
+ return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
}
/**
* Visits the body of a SwitchStatement to hoist declarations.
@@ -55474,7 +60730,7 @@ var ts;
*/
function destructuringVisitor(node) {
if (node.transformFlags & 1024 /* DestructuringAssignment */
- && node.kind === 192 /* BinaryExpression */) {
+ && node.kind === 193 /* BinaryExpression */) {
return visitDestructuringAssignment(node);
}
else if (node.transformFlags & 2048 /* ContainsDestructuringAssignment */) {
@@ -55502,7 +60758,7 @@ var ts;
* @param node The destructuring target.
*/
function hasExportedReferenceInDestructuringTarget(node) {
- if (ts.isAssignmentExpression(node)) {
+ if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
return hasExportedReferenceInDestructuringTarget(node.left);
}
else if (ts.isSpreadExpression(node)) {
@@ -55522,7 +60778,7 @@ var ts;
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 261 /* SourceFile */;
+ return container !== undefined && container.kind === 264 /* SourceFile */;
}
else {
return false;
@@ -55550,12 +60806,12 @@ var ts;
/**
* Hook for node emit notifications.
*
- * @param emitContext A context hint for the emitter.
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
- * @param emit A callback used to emit the node in the printer.
+ * @param emitCallback A callback used to emit the node in the printer.
*/
- function onEmitNode(emitContext, node, emitCallback) {
- if (node.kind === 261 /* SourceFile */) {
+ function onEmitNode(hint, node, emitCallback) {
+ if (node.kind === 264 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -55564,14 +60820,14 @@ var ts;
if (noSubstitution) {
delete noSubstitutionMap[id];
}
- previousOnEmitNode(emitContext, node, emitCallback);
+ previousOnEmitNode(hint, node, emitCallback);
currentSourceFile = undefined;
moduleInfo = undefined;
exportFunction = undefined;
noSubstitution = undefined;
}
else {
- previousOnEmitNode(emitContext, node, emitCallback);
+ previousOnEmitNode(hint, node, emitCallback);
}
}
//
@@ -55580,15 +60836,15 @@ var ts;
/**
* Hooks node substitutions.
*
- * @param emitContext A context hint for the emitter.
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
- function onSubstituteNode(emitContext, node) {
- node = previousOnSubstituteNode(emitContext, node);
+ function onSubstituteNode(hint, node) {
+ node = previousOnSubstituteNode(hint, node);
if (isSubstitutionPrevented(node)) {
return node;
}
- if (emitContext === 1 /* Expression */) {
+ if (hint === 1 /* Expression */) {
return substituteExpression(node);
}
return node;
@@ -55602,10 +60858,10 @@ var ts;
switch (node.kind) {
case 70 /* Identifier */:
return substituteExpressionIdentifier(node);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return substituteBinaryExpression(node);
- case 190 /* PrefixUnaryExpression */:
- case 191 /* PostfixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
return substituteUnaryExpression(node);
}
return node;
@@ -55633,11 +60889,11 @@ var ts;
var importDeclaration = resolver.getReferencedImportDeclaration(node);
if (importDeclaration) {
if (ts.isImportClause(importDeclaration)) {
- return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"),
+ return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")),
/*location*/ node);
}
else if (ts.isImportSpecifier(importDeclaration)) {
- return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name),
+ return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)),
/*location*/ node);
}
}
@@ -55667,8 +60923,8 @@ var ts;
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
var expression = node;
- for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
- var exportName = exportedNames_1[_i];
+ for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
+ var exportName = exportedNames_3[_i];
expression = createExportExpression(exportName, preventSubstitution(expression));
}
return expression;
@@ -55698,15 +60954,14 @@ var ts;
&& !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
var exportedNames = getExports(node.operand);
if (exportedNames) {
- var expression = node.kind === 191 /* PostfixUnaryExpression */
- ? ts.createPrefix(node.operator, node.operand,
- /*location*/ node)
+ var expression = node.kind === 192 /* PostfixUnaryExpression */
+ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
: node;
- for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
- var exportName = exportedNames_2[_i];
+ for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
+ var exportName = exportedNames_4[_i];
expression = createExportExpression(exportName, preventSubstitution(expression));
}
- if (node.kind === 191 /* PostfixUnaryExpression */) {
+ if (node.kind === 192 /* PostfixUnaryExpression */) {
expression = node.operator === 42 /* PlusPlusToken */
? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1))
: ts.createAdd(preventSubstitution(expression), ts.createLiteral(1));
@@ -55728,7 +60983,7 @@ var ts;
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 261 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 264 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -55743,7 +60998,7 @@ var ts;
*/
function preventSubstitution(node) {
if (noSubstitution === undefined)
- noSubstitution = ts.createMap();
+ noSubstitution = [];
noSubstitution[ts.getNodeId(node)] = true;
return node;
}
@@ -55763,852 +61018,69 @@ var ts;
/*@internal*/
var ts;
(function (ts) {
- function transformModule(context) {
- var transformModuleDelegates = ts.createMap((_a = {},
- _a[ts.ModuleKind.None] = transformCommonJSModule,
- _a[ts.ModuleKind.CommonJS] = transformCommonJSModule,
- _a[ts.ModuleKind.AMD] = transformAMDModule,
- _a[ts.ModuleKind.UMD] = transformUMDModule,
- _a));
- var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment;
+ function transformES2015Module(context) {
var compilerOptions = context.getCompilerOptions();
- var resolver = context.getEmitResolver();
- var host = context.getEmitHost();
- var languageVersion = ts.getEmitScriptTarget(compilerOptions);
- var moduleKind = ts.getEmitModuleKind(compilerOptions);
- var previousOnSubstituteNode = context.onSubstituteNode;
var previousOnEmitNode = context.onEmitNode;
- context.onSubstituteNode = onSubstituteNode;
+ var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
- context.enableSubstitution(70 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
- context.enableSubstitution(192 /* BinaryExpression */); // Substitutes assignments to exported symbols.
- context.enableSubstitution(190 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableSubstitution(191 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableSubstitution(258 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(261 /* SourceFile */); // Restore state when substituting nodes in a file.
- var moduleInfoMap = ts.createMap(); // The ExternalModuleInfo for each file.
- var deferredExports = ts.createMap(); // Exports to defer until an EndOfDeclarationMarker is found.
- var currentSourceFile; // The current file.
- var currentModuleInfo; // The ExternalModuleInfo for the current file.
- var noSubstitution; // Set of nodes for which substitution rules should be ignored.
+ context.onSubstituteNode = onSubstituteNode;
+ context.enableEmitNotification(264 /* SourceFile */);
+ context.enableSubstitution(70 /* Identifier */);
+ var currentSourceFile;
return transformSourceFile;
- /**
- * Transforms the module aspects of a SourceFile.
- *
- * @param node The SourceFile node.
- */
function transformSourceFile(node) {
- if (ts.isDeclarationFile(node)
- || !(ts.isExternalModule(node)
- || compilerOptions.isolatedModules)) {
+ if (ts.isDeclarationFile(node)) {
return node;
}
- currentSourceFile = node;
- currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(node)] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
- // Perform the transformation.
- var transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ts.ModuleKind.None];
- var updated = transformModule(node);
- currentSourceFile = undefined;
- currentModuleInfo = undefined;
- return ts.aggregateTransformFlags(updated);
- }
- /**
- * Transforms a SourceFile into a CommonJS module.
- *
- * @param node The SourceFile node.
- */
- function transformCommonJSModule(node) {
- startLexicalEnvironment();
- var statements = [];
- var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
- ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true));
- ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
- ts.addRange(statements, endLexicalEnvironment());
- addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
- var updated = ts.updateSourceFileNode(node, ts.createNodeArray(statements, node.statements));
- if (currentModuleInfo.hasExportStarsToExportValues) {
- ts.addEmitHelper(updated, exportStarHelper);
- }
- return updated;
- }
- /**
- * Transforms a SourceFile into an AMD module.
- *
- * @param node The SourceFile node.
- */
- function transformAMDModule(node) {
- var define = ts.createIdentifier("define");
- var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
- return transformAsynchronousModule(node, define, moduleName, /*includeNonAmdDependencies*/ true);
- }
- /**
- * Transforms a SourceFile into a UMD module.
- *
- * @param node The SourceFile node.
- */
- function transformUMDModule(node) {
- var define = ts.createRawExpression(umdHelper);
- return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false);
- }
- /**
- * Transforms a SourceFile into an AMD or UMD module.
- *
- * @param node The SourceFile node.
- * @param define The expression used to define the module.
- * @param moduleName An expression for the module name, if available.
- * @param includeNonAmdDependencies A value indicating whether to incldue any non-AMD dependencies.
- */
- function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) {
- // An AMD define function has the following shape:
- //
- // define(id?, dependencies?, factory);
- //
- // This has the shape of the following:
- //
- // define(name, ["module1", "module2"], function (module1Alias) { ... }
- //
- // The location of the alias in the parameter list in the factory function needs to
- // match the position of the module name in the dependency list.
- //
- // To ensure this is true in cases of modules with no aliases, e.g.:
- //
- // import "module"
- //
- // or
- //
- // /// <amd-dependency path= "a.css" />
- //
- // we need to add modules without alias names to the end of the dependencies list
- var _a = collectAsynchronousDependencies(node, includeNonAmdDependencies), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
- // Create an updated SourceFile:
- //
- // define(moduleName?, ["module1", "module2"], function ...
- return ts.updateSourceFileNode(node, ts.createNodeArray([
- ts.createStatement(ts.createCall(define,
- /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([
- // Add the dependency array argument:
- //
- // ["require", "exports", module1", "module2", ...]
- ts.createArrayLiteral([
- ts.createLiteral("require"),
- ts.createLiteral("exports")
- ].concat(aliasedModuleNames, unaliasedModuleNames)),
- // Add the module body function argument:
- //
- // function (require, exports, module1, module2) ...
- ts.createFunctionExpression(
- /*modifiers*/ undefined,
- /*asteriskToken*/ undefined,
- /*name*/ undefined,
- /*typeParameters*/ undefined, [
- ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
- ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
- ].concat(importAliasNames),
- /*type*/ undefined, transformAsynchronousModuleBody(node))
- ])))
- ],
- /*location*/ node.statements));
- }
- /**
- * Collect the additional asynchronous dependencies for the module.
- *
- * @param node The source file.
- * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
- */
- function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
- // names of modules with corresponding parameter in the factory function
- var aliasedModuleNames = [];
- // names of modules with no corresponding parameters in factory function
- var unaliasedModuleNames = [];
- // names of the parameters in the factory function; these
- // parameters need to match the indexes of the corresponding
- // module names in aliasedModuleNames.
- var importAliasNames = [];
- // Fill in amd-dependency tags
- for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
- var amdDependency = _a[_i];
- if (amdDependency.name) {
- aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
- importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
- }
- else {
- unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
- }
- }
- for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
- var importNode = _c[_b];
- // Find the name of the external module
- var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
- // Find the name of the module alias, if there is one
- var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
- if (includeNonAmdDependencies && importAliasName) {
- // Set emitFlags on the name of the classDeclaration
- // This is so that when printer will not substitute the identifier
- ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
- aliasedModuleNames.push(externalModuleName);
- importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
- }
- else {
- unaliasedModuleNames.push(externalModuleName);
- }
- }
- return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
- }
- /**
- * Transforms a SourceFile into an AMD or UMD module body.
- *
- * @param node The SourceFile node.
- */
- function transformAsynchronousModuleBody(node) {
- startLexicalEnvironment();
- var statements = [];
- var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
- // Visit each statement of the module body.
- ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true));
- ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
- // End the lexical environment for the module body
- // and merge any new lexical declarations.
- ts.addRange(statements, endLexicalEnvironment());
- // Append the 'export =' statement if provided.
- addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
- var body = ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true);
- if (currentModuleInfo.hasExportStarsToExportValues) {
- // If we have any `export * from ...` declarations
- // we need to inform the emitter to add the __export helper.
- ts.addEmitHelper(body, exportStarHelper);
- }
- return body;
- }
- /**
- * Adds the down-level representation of `export=` to the statement list if one exists
- * in the source file.
- *
- * @param statements The Statement list to modify.
- * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
- * return statement.
- */
- function addExportEqualsIfNeeded(statements, emitAsReturn) {
- if (currentModuleInfo.exportEquals) {
- if (emitAsReturn) {
- var statement = ts.createReturn(currentModuleInfo.exportEquals.expression,
- /*location*/ currentModuleInfo.exportEquals);
- ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
- statements.push(statement);
- }
- else {
- var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), currentModuleInfo.exportEquals.expression),
- /*location*/ currentModuleInfo.exportEquals);
- ts.setEmitFlags(statement, 1536 /* NoComments */);
- statements.push(statement);
- }
- }
- }
- //
- // Top-Level Source Element Visitors
- //
- /**
- * Visits a node at the top level of the source file.
- *
- * @param node The node to visit.
- */
- function sourceElementVisitor(node) {
- switch (node.kind) {
- case 235 /* ImportDeclaration */:
- return visitImportDeclaration(node);
- case 234 /* ImportEqualsDeclaration */:
- return visitImportEqualsDeclaration(node);
- case 241 /* ExportDeclaration */:
- return visitExportDeclaration(node);
- case 240 /* ExportAssignment */:
- return visitExportAssignment(node);
- case 205 /* VariableStatement */:
- return visitVariableStatement(node);
- case 225 /* FunctionDeclaration */:
- return visitFunctionDeclaration(node);
- case 226 /* ClassDeclaration */:
- return visitClassDeclaration(node);
- case 295 /* MergeDeclarationMarker */:
- return visitMergeDeclarationMarker(node);
- case 296 /* EndOfDeclarationMarker */:
- return visitEndOfDeclarationMarker(node);
- default:
- // This visitor does not descend into the tree, as export/import statements
- // are only transformed at the top level of a file.
- return node;
- }
- }
- /**
- * Visits an ImportDeclaration node.
- *
- * @param node The node to visit.
- */
- function visitImportDeclaration(node) {
- var statements;
- var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
- if (moduleKind !== ts.ModuleKind.AMD) {
- if (!node.importClause) {
- // import "mod";
- return ts.createStatement(createRequireCall(node), /*location*/ node);
- }
- else {
- var variables = [];
- if (namespaceDeclaration && !ts.isDefaultImport(node)) {
- // import * as n from "mod";
- variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
- /*type*/ undefined, createRequireCall(node)));
- }
- else {
- // import d from "mod";
- // import { x, y } from "mod";
- // import d, { x, y } from "mod";
- // import d, * as n from "mod";
- variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node),
- /*type*/ undefined, createRequireCall(node)));
- if (namespaceDeclaration && ts.isDefaultImport(node)) {
- variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
- /*type*/ undefined, ts.getGeneratedNameForNode(node)));
- }
- }
- statements = ts.append(statements, ts.createVariableStatement(
- /*modifiers*/ undefined, ts.createVariableDeclarationList(variables,
- /*location*/ undefined, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */),
- /*location*/ node));
- }
- }
- else if (namespaceDeclaration && ts.isDefaultImport(node)) {
- // import d, * as n from "mod";
- statements = ts.append(statements, ts.createVariableStatement(
- /*modifiers*/ undefined, ts.createVariableDeclarationList([
- ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name),
- /*type*/ undefined, ts.getGeneratedNameForNode(node),
- /*location*/ node)
- ],
- /*location*/ undefined, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
- }
- if (hasAssociatedEndOfDeclarationMarker(node)) {
- // Defer exports until we encounter an EndOfDeclarationMarker node
- var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
- }
- else {
- statements = appendExportsOfImportDeclaration(statements, node);
- }
- return ts.singleOrMany(statements);
- }
- /**
- * Creates a `require()` call to import an external module.
- *
- * @param importNode The declararation to import.
- */
- function createRequireCall(importNode) {
- var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
- var args = [];
- if (moduleName) {
- args.push(moduleName);
- }
- return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
- }
- /**
- * Visits an ImportEqualsDeclaration node.
- *
- * @param node The node to visit.
- */
- function visitImportEqualsDeclaration(node) {
- ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
- var statements;
- if (moduleKind !== ts.ModuleKind.AMD) {
- if (ts.hasModifier(node, 1 /* Export */)) {
- statements = ts.append(statements, ts.createStatement(createExportExpression(node.name, createRequireCall(node)),
- /*location*/ node));
+ if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
+ var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions);
+ if (externalHelpersModuleName) {
+ var statements = [];
+ var statementOffset = ts.addPrologue(statements, node.statements);
+ ts.append(statements, ts.createImportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)));
+ ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
+ return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
}
else {
- statements = ts.append(statements, ts.createVariableStatement(
- /*modifiers*/ undefined, ts.createVariableDeclarationList([
- ts.createVariableDeclaration(ts.getSynthesizedClone(node.name),
- /*type*/ undefined, createRequireCall(node))
- ],
- /*location*/ undefined,
- /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */),
- /*location*/ node));
- }
- }
- else {
- if (ts.hasModifier(node, 1 /* Export */)) {
- statements = ts.append(statements, ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node)),
- /*location*/ node));
- }
- }
- if (hasAssociatedEndOfDeclarationMarker(node)) {
- // Defer exports until we encounter an EndOfDeclarationMarker node
- var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
- }
- else {
- statements = appendExportsOfImportEqualsDeclaration(statements, node);
- }
- return ts.singleOrMany(statements);
- }
- /**
- * Visits an ExportDeclaration node.
- *
- * @param The node to visit.
- */
- function visitExportDeclaration(node) {
- if (!node.moduleSpecifier) {
- // Elide export declarations with no module specifier as they are handled
- // elsewhere.
- return undefined;
- }
- var generatedName = ts.getGeneratedNameForNode(node);
- if (node.exportClause) {
- var statements = [];
- // export { x, y } from "mod";
- if (moduleKind !== ts.ModuleKind.AMD) {
- statements.push(ts.createVariableStatement(
- /*modifiers*/ undefined, ts.createVariableDeclarationList([
- ts.createVariableDeclaration(generatedName,
- /*type*/ undefined, createRequireCall(node))
- ]),
- /*location*/ node));
- }
- for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
- var specifier = _a[_i];
- var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
- statements.push(ts.createStatement(createExportExpression(ts.getExportName(specifier), exportedValue),
- /*location*/ specifier));
- }
- return ts.singleOrMany(statements);
- }
- else {
- // export * from "mod";
- return ts.createStatement(ts.createCall(ts.createIdentifier("__export"),
- /*typeArguments*/ undefined, [
- moduleKind !== ts.ModuleKind.AMD
- ? createRequireCall(node)
- : generatedName
- ]),
- /*location*/ node);
- }
- }
- /**
- * Visits an ExportAssignment node.
- *
- * @param node The node to visit.
- */
- function visitExportAssignment(node) {
- if (node.isExportEquals) {
- return undefined;
- }
- var statements;
- var original = node.original;
- if (original && hasAssociatedEndOfDeclarationMarker(original)) {
- // Defer exports until we encounter an EndOfDeclarationMarker node
- var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true);
- }
- else {
- statements = appendExportStatement(statements, ts.createIdentifier("default"), node.expression, /*location*/ node, /*allowComments*/ true);
- }
- return ts.singleOrMany(statements);
- }
- /**
- * Visits a FunctionDeclaration node.
- *
- * @param node The node to visit.
- */
- function visitFunctionDeclaration(node) {
- var statements;
- if (ts.hasModifier(node, 1 /* Export */)) {
- statements = ts.append(statements, ts.setOriginalNode(ts.createFunctionDeclaration(
- /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
- /*typeParameters*/ undefined, node.parameters,
- /*type*/ undefined, node.body,
- /*location*/ node),
- /*original*/ node));
- }
- else {
- statements = ts.append(statements, node);
- }
- if (hasAssociatedEndOfDeclarationMarker(node)) {
- // Defer exports until we encounter an EndOfDeclarationMarker node
- var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
- }
- else {
- statements = appendExportsOfHoistedDeclaration(statements, node);
- }
- return ts.singleOrMany(statements);
- }
- /**
- * Visits a ClassDeclaration node.
- *
- * @param node The node to visit.
- */
- function visitClassDeclaration(node) {
- var statements;
- if (ts.hasModifier(node, 1 /* Export */)) {
- statements = ts.append(statements, ts.setOriginalNode(ts.createClassDeclaration(
- /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
- /*typeParameters*/ undefined, node.heritageClauses, node.members,
- /*location*/ node),
- /*original*/ node));
- }
- else {
- statements = ts.append(statements, node);
- }
- if (hasAssociatedEndOfDeclarationMarker(node)) {
- // Defer exports until we encounter an EndOfDeclarationMarker node
- var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
- }
- else {
- statements = appendExportsOfHoistedDeclaration(statements, node);
- }
- return ts.singleOrMany(statements);
- }
- /**
- * Visits a VariableStatement node.
- *
- * @param node The node to visit.
- */
- function visitVariableStatement(node) {
- var statements;
- var variables;
- var expressions;
- if (ts.hasModifier(node, 1 /* Export */)) {
- var modifiers = void 0;
- // If we're exporting these variables, then these just become assignments to 'exports.x'.
- // We only want to emit assignments for variables with initializers.
- for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
- var variable = _a[_i];
- if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
- if (!modifiers) {
- modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
- }
- variables = ts.append(variables, variable);
- }
- else if (variable.initializer) {
- expressions = ts.append(expressions, transformInitializedVariable(variable));
- }
- }
- if (variables) {
- statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
- }
- if (expressions) {
- statements = ts.append(statements, ts.createStatement(ts.inlineExpressions(expressions), /*location*/ node));
+ return ts.visitEachChild(node, visitor, context);
}
}
- else {
- statements = ts.append(statements, node);
- }
- if (hasAssociatedEndOfDeclarationMarker(node)) {
- // Defer exports until we encounter an EndOfDeclarationMarker node
- var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
- }
- else {
- statements = appendExportsOfVariableStatement(statements, node);
- }
- return ts.singleOrMany(statements);
- }
- /**
- * Transforms an exported variable with an initializer into an expression.
- *
- * @param node The node to transform.
- */
- function transformInitializedVariable(node) {
- if (ts.isBindingPattern(node.name)) {
- return ts.flattenDestructuringAssignment(node,
- /*visitor*/ undefined, context, 0 /* All */,
- /*needsValue*/ false, createExportExpression);
- }
- else {
- return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name,
- /*location*/ node.name), node.initializer);
- }
- }
- /**
- * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
- * and transformed declaration.
- *
- * @param node The node to visit.
- */
- function visitMergeDeclarationMarker(node) {
- // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
- // declaration we do not emit a leading variable declaration. To preserve the
- // begin/end semantics of the declararation and to properly handle exports
- // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
- //
- // To balance the declaration, add the exports of the elided variable
- // statement.
- if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 205 /* VariableStatement */) {
- var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
- }
return node;
}
- /**
- * Determines whether a node has an associated EndOfDeclarationMarker.
- *
- * @param node The node to test.
- */
- function hasAssociatedEndOfDeclarationMarker(node) {
- return (ts.getEmitFlags(node) & 2097152 /* HasEndOfDeclarationMarker */) !== 0;
- }
- /**
- * Visits a DeclarationMarker used as a placeholder for the end of a transformed
- * declaration.
- *
- * @param node The node to visit.
- */
- function visitEndOfDeclarationMarker(node) {
- // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
- // end of the transformed declaration. We use this marker to emit any deferred exports
- // of the declaration.
- var id = ts.getOriginalNodeId(node);
- var statements = deferredExports[id];
- if (statements) {
- delete deferredExports[id];
- return ts.append(statements, node);
- }
- return node;
- }
- /**
- * Appends the exports of an ImportDeclaration to a statement list, returning the
- * statement list.
- *
- * @param statements A statement list to which the down-level export statements are to be
- * appended. If `statements` is `undefined`, a new array is allocated if statements are
- * appended.
- * @param decl The declaration whose exports are to be recorded.
- */
- function appendExportsOfImportDeclaration(statements, decl) {
- if (currentModuleInfo.exportEquals) {
- return statements;
- }
- var importClause = decl.importClause;
- if (!importClause) {
- return statements;
- }
- if (importClause.name) {
- statements = appendExportsOfDeclaration(statements, importClause);
- }
- var namedBindings = importClause.namedBindings;
- if (namedBindings) {
- switch (namedBindings.kind) {
- case 237 /* NamespaceImport */:
- statements = appendExportsOfDeclaration(statements, namedBindings);
- break;
- case 238 /* NamedImports */:
- for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
- var importBinding = _a[_i];
- statements = appendExportsOfDeclaration(statements, importBinding);
- }
- break;
- }
- }
- return statements;
- }
- /**
- * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
- * statement list.
- *
- * @param statements A statement list to which the down-level export statements are to be
- * appended. If `statements` is `undefined`, a new array is allocated if statements are
- * appended.
- * @param decl The declaration whose exports are to be recorded.
- */
- function appendExportsOfImportEqualsDeclaration(statements, decl) {
- if (currentModuleInfo.exportEquals) {
- return statements;
- }
- return appendExportsOfDeclaration(statements, decl);
- }
- /**
- * Appends the exports of a VariableStatement to a statement list, returning the statement
- * list.
- *
- * @param statements A statement list to which the down-level export statements are to be
- * appended. If `statements` is `undefined`, a new array is allocated if statements are
- * appended.
- * @param node The VariableStatement whose exports are to be recorded.
- */
- function appendExportsOfVariableStatement(statements, node) {
- if (currentModuleInfo.exportEquals) {
- return statements;
- }
- for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
- var decl = _a[_i];
- statements = appendExportsOfBindingElement(statements, decl);
- }
- return statements;
- }
- /**
- * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
- * returning the statement list.
- *
- * @param statements A statement list to which the down-level export statements are to be
- * appended. If `statements` is `undefined`, a new array is allocated if statements are
- * appended.
- * @param decl The declaration whose exports are to be recorded.
- */
- function appendExportsOfBindingElement(statements, decl) {
- if (currentModuleInfo.exportEquals) {
- return statements;
- }
- if (ts.isBindingPattern(decl.name)) {
- for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
- var element = _a[_i];
- if (!ts.isOmittedExpression(element)) {
- statements = appendExportsOfBindingElement(statements, element);
- }
- }
- }
- else if (!ts.isGeneratedIdentifier(decl.name)) {
- statements = appendExportsOfDeclaration(statements, decl);
- }
- return statements;
- }
- /**
- * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
- * returning the statement list.
- *
- * @param statements A statement list to which the down-level export statements are to be
- * appended. If `statements` is `undefined`, a new array is allocated if statements are
- * appended.
- * @param decl The declaration whose exports are to be recorded.
- */
- function appendExportsOfHoistedDeclaration(statements, decl) {
- if (currentModuleInfo.exportEquals) {
- return statements;
- }
- if (ts.hasModifier(decl, 1 /* Export */)) {
- var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : decl.name;
- statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
- }
- if (decl.name) {
- statements = appendExportsOfDeclaration(statements, decl);
- }
- return statements;
- }
- /**
- * Appends the exports of a declaration to a statement list, returning the statement list.
- *
- * @param statements A statement list to which the down-level export statements are to be
- * appended. If `statements` is `undefined`, a new array is allocated if statements are
- * appended.
- * @param decl The declaration to export.
- */
- function appendExportsOfDeclaration(statements, decl) {
- var name = ts.getDeclarationName(decl);
- var exportSpecifiers = currentModuleInfo.exportSpecifiers[name.text];
- if (exportSpecifiers) {
- for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
- var exportSpecifier = exportSpecifiers_2[_i];
- statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name);
- }
- }
- return statements;
- }
- /**
- * Appends the down-level representation of an export to a statement list, returning the
- * statement list.
- *
- * @param statements A statement list to which the down-level export statements are to be
- * appended. If `statements` is `undefined`, a new array is allocated if statements are
- * appended.
- * @param exportName The name of the export.
- * @param expression The expression to export.
- * @param location The location to use for source maps and comments for the export.
- * @param allowComments Whether to allow comments on the export.
- */
- function appendExportStatement(statements, exportName, expression, location, allowComments) {
- if (exportName.text === "default") {
- var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile);
- if (sourceFile && !sourceFile.symbol.exports["___esModule"]) {
- if (languageVersion === 0 /* ES3 */) {
- statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true))));
- }
- else {
- statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"),
- /*typeArguments*/ undefined, [
- ts.createIdentifier("exports"),
- ts.createLiteral("__esModule"),
- ts.createObjectLiteral([
- ts.createPropertyAssignment("value", ts.createLiteral(true))
- ])
- ])));
- }
- }
- }
- statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments));
- return statements;
- }
- /**
- * Creates a call to the current file's export function to export a value.
- *
- * @param name The bound name of the export.
- * @param value The exported value.
- * @param location The location to use for source maps and comments for the export.
- * @param allowComments An optional value indicating whether to emit comments for the statement.
- */
- function createExportStatement(name, value, location, allowComments) {
- var statement = ts.createStatement(createExportExpression(name, value), location);
- ts.startOnNewLine(statement);
- if (!allowComments) {
- ts.setEmitFlags(statement, 1536 /* NoComments */);
- }
- return statement;
- }
- /**
- * Creates a call to the current file's export function to export a value.
- *
- * @param name The bound name of the export.
- * @param value The exported value.
- * @param location The location to use for source maps and comments for the export.
- */
- function createExportExpression(name, value, location) {
- return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value, location);
- }
- //
- // Modifier Visitors
- //
- /**
- * Visit nodes to elide module-specific modifiers.
- *
- * @param node The node to visit.
- */
- function modifierVisitor(node) {
- // Elide module-specific modifiers.
+ function visitor(node) {
switch (node.kind) {
- case 83 /* ExportKeyword */:
- case 78 /* DefaultKeyword */:
+ case 236 /* ImportEqualsDeclaration */:
+ // Elide `import=` as it is not legal with --module ES6
return undefined;
+ case 242 /* ExportAssignment */:
+ return visitExportAssignment(node);
}
return node;
}
+ function visitExportAssignment(node) {
+ // Elide `export=` as it is not legal with --module ES6
+ return node.isExportEquals ? undefined : node;
+ }
//
// Emit Notification
//
/**
- * Hook for node emit notifications.
+ * Hook for node emit.
*
- * @param emitContext A context hint for the emitter.
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emit A callback used to emit the node in the printer.
*/
- function onEmitNode(emitContext, node, emitCallback) {
- if (node.kind === 261 /* SourceFile */) {
+ function onEmitNode(hint, node, emitCallback) {
+ if (ts.isSourceFile(node)) {
currentSourceFile = node;
- currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
- noSubstitution = ts.createMap();
- previousOnEmitNode(emitContext, node, emitCallback);
+ previousOnEmitNode(hint, node, emitCallback);
currentSourceFile = undefined;
- currentModuleInfo = undefined;
- noSubstitution = undefined;
}
else {
- previousOnEmitNode(emitContext, node, emitCallback);
+ previousOnEmitNode(hint, node, emitCallback);
}
}
//
@@ -56617,191 +61089,27 @@ var ts;
/**
* Hooks node substitutions.
*
- * @param emitContext A context hint for the emitter.
- * @param node The node to substitute.
- */
- function onSubstituteNode(emitContext, node) {
- node = previousOnSubstituteNode(emitContext, node);
- if (node.id && noSubstitution[node.id]) {
- return node;
- }
- if (emitContext === 1 /* Expression */) {
- return substituteExpression(node);
- }
- else if (ts.isShorthandPropertyAssignment(node)) {
- return substituteShorthandPropertyAssignment(node);
- }
- return node;
- }
- /**
- * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
- * or exported symbol.
- *
- * @param node The node to substitute.
- */
- function substituteShorthandPropertyAssignment(node) {
- var name = node.name;
- var exportedOrImportedName = substituteExpressionIdentifier(name);
- if (exportedOrImportedName !== name) {
- // A shorthand property with an assignment initializer is probably part of a
- // destructuring assignment
- if (node.objectAssignmentInitializer) {
- var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
- return ts.createPropertyAssignment(name, initializer, /*location*/ node);
- }
- return ts.createPropertyAssignment(name, exportedOrImportedName, /*location*/ node);
- }
- return node;
- }
- /**
- * Substitution for an Expression that may contain an imported or exported symbol.
- *
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
- function substituteExpression(node) {
- switch (node.kind) {
- case 70 /* Identifier */:
- return substituteExpressionIdentifier(node);
- case 192 /* BinaryExpression */:
- return substituteBinaryExpression(node);
- case 191 /* PostfixUnaryExpression */:
- case 190 /* PrefixUnaryExpression */:
- return substituteUnaryExpression(node);
+ function onSubstituteNode(hint, node) {
+ node = previousOnSubstituteNode(hint, node);
+ if (ts.isIdentifier(node) && hint === 1 /* Expression */) {
+ return substituteExpressionIdentifier(node);
}
return node;
}
- /**
- * Substitution for an Identifier expression that may contain an imported or exported
- * symbol.
- *
- * @param node The node to substitute.
- */
function substituteExpressionIdentifier(node) {
if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
if (externalHelpersModuleName) {
return ts.createPropertyAccess(externalHelpersModuleName, node);
}
- return node;
- }
- if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
- var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 261 /* SourceFile */) {
- return ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node),
- /*location*/ node);
- }
- var importDeclaration = resolver.getReferencedImportDeclaration(node);
- if (importDeclaration) {
- if (ts.isImportClause(importDeclaration)) {
- return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"),
- /*location*/ node);
- }
- else if (ts.isImportSpecifier(importDeclaration)) {
- var name_37 = importDeclaration.propertyName || importDeclaration.name;
- return ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name_37),
- /*location*/ node);
- }
- }
- }
- return node;
- }
- /**
- * Substitution for a BinaryExpression that may contain an imported or exported symbol.
- *
- * @param node The node to substitute.
- */
- function substituteBinaryExpression(node) {
- // When we see an assignment expression whose left-hand side is an exported symbol,
- // we should ensure all exports of that symbol are updated with the correct value.
- //
- // - We do not substitute generated identifiers for any reason.
- // - We do not substitute identifiers tagged with the LocalName flag.
- // - We do not substitute identifiers that were originally the name of an enum or
- // namespace due to how they are transformed in TypeScript.
- // - We only substitute identifiers that are exported at the top level.
- if (ts.isAssignmentOperator(node.operatorToken.kind)
- && ts.isIdentifier(node.left)
- && !ts.isGeneratedIdentifier(node.left)
- && !ts.isLocalName(node.left)
- && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
- var exportedNames = getExports(node.left);
- if (exportedNames) {
- // For each additional export of the declaration, apply an export assignment.
- var expression = node;
- for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
- var exportName = exportedNames_3[_i];
- // Mark the node to prevent triggering this rule again.
- noSubstitution[ts.getNodeId(expression)] = true;
- expression = createExportExpression(exportName, expression, /*location*/ node);
- }
- return expression;
- }
- }
- return node;
- }
- /**
- * Substitution for a UnaryExpression that may contain an imported or exported symbol.
- *
- * @param node The node to substitute.
- */
- function substituteUnaryExpression(node) {
- // When we see a prefix or postfix increment expression whose operand is an exported
- // symbol, we should ensure all exports of that symbol are updated with the correct
- // value.
- //
- // - We do not substitute generated identifiers for any reason.
- // - We do not substitute identifiers tagged with the LocalName flag.
- // - We do not substitute identifiers that were originally the name of an enum or
- // namespace due to how they are transformed in TypeScript.
- // - We only substitute identifiers that are exported at the top level.
- if ((node.operator === 42 /* PlusPlusToken */ || node.operator === 43 /* MinusMinusToken */)
- && ts.isIdentifier(node.operand)
- && !ts.isGeneratedIdentifier(node.operand)
- && !ts.isLocalName(node.operand)
- && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
- var exportedNames = getExports(node.operand);
- if (exportedNames) {
- var expression = node.kind === 191 /* PostfixUnaryExpression */
- ? ts.createBinary(node.operand, ts.createToken(node.operator === 42 /* PlusPlusToken */ ? 58 /* PlusEqualsToken */ : 59 /* MinusEqualsToken */), ts.createLiteral(1),
- /*location*/ node)
- : node;
- for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
- var exportName = exportedNames_4[_i];
- // Mark the node to prevent triggering this rule again.
- noSubstitution[ts.getNodeId(expression)] = true;
- expression = createExportExpression(exportName, expression);
- }
- return expression;
- }
}
return node;
}
- /**
- * Gets the additional exports of a name.
- *
- * @param name The name.
- */
- function getExports(name) {
- if (!ts.isGeneratedIdentifier(name)) {
- var valueDeclaration = resolver.getReferencedImportDeclaration(name)
- || resolver.getReferencedValueDeclaration(name);
- if (valueDeclaration) {
- return currentModuleInfo
- && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
- }
- }
- }
- var _a;
}
- ts.transformModule = transformModule;
- // emit output for the __export helper function
- var exportStarHelper = {
- name: "typescript:export-star",
- scoped: true,
- text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }"
- };
- // emit output for the UMD helper function.
- var umdHelper = "\n (function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n })";
+ ts.transformES2015Module = transformES2015Module;
})(ts || (ts = {}));
/// <reference path="visitor.ts" />
/// <reference path="transformers/ts.ts" />
@@ -56818,24 +61126,34 @@ var ts;
/* @internal */
var ts;
(function (ts) {
- var moduleTransformerMap = ts.createMap((_a = {},
- _a[ts.ModuleKind.ES2015] = ts.transformES2015Module,
- _a[ts.ModuleKind.System] = ts.transformSystemModule,
- _a[ts.ModuleKind.AMD] = ts.transformModule,
- _a[ts.ModuleKind.CommonJS] = ts.transformModule,
- _a[ts.ModuleKind.UMD] = ts.transformModule,
- _a[ts.ModuleKind.None] = ts.transformModule,
- _a));
+ function getModuleTransformer(moduleKind) {
+ switch (moduleKind) {
+ case ts.ModuleKind.ES2015:
+ return ts.transformES2015Module;
+ case ts.ModuleKind.System:
+ return ts.transformSystemModule;
+ default:
+ return ts.transformModule;
+ }
+ }
+ var TransformationState;
+ (function (TransformationState) {
+ TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
+ TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
+ TransformationState[TransformationState["Completed"] = 2] = "Completed";
+ TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
+ })(TransformationState || (TransformationState = {}));
var SyntaxKindFeatureFlags;
(function (SyntaxKindFeatureFlags) {
SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
})(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
- function getTransformers(compilerOptions) {
+ function getTransformers(compilerOptions, customTransformers) {
var jsx = compilerOptions.jsx;
var languageVersion = ts.getEmitScriptTarget(compilerOptions);
var moduleKind = ts.getEmitModuleKind(compilerOptions);
var transformers = [];
+ ts.addRange(transformers, customTransformers && customTransformers.before);
transformers.push(ts.transformTypeScript);
if (jsx === 2 /* React */) {
transformers.push(ts.transformJsx);
@@ -56853,12 +61171,13 @@ var ts;
transformers.push(ts.transformES2015);
transformers.push(ts.transformGenerators);
}
- transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ts.ModuleKind.None]);
+ transformers.push(getModuleTransformer(moduleKind));
// The ES5 transformer is last so that it can substitute expressions like `exports.default`
// for ES3.
if (languageVersion < 1 /* ES5 */) {
transformers.push(ts.transformES5);
}
+ ts.addRange(transformers, customTransformers && customTransformers.after);
return transformers;
}
ts.getTransformers = getTransformers;
@@ -56866,13 +61185,14 @@ var ts;
* Transforms an array of SourceFiles by passing them through each transformer.
*
* @param resolver The emit resolver provided by the checker.
- * @param host The emit host.
- * @param sourceFiles An array of source files
- * @param transforms An array of Transformers.
+ * @param host The emit host object used to interact with the file system.
+ * @param options Compiler options to surface in the `TransformationContext`.
+ * @param nodes An array of nodes to transform.
+ * @param transforms An array of `TransformerFactory` callbacks.
+ * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
*/
- function transformFiles(resolver, host, sourceFiles, transformers) {
+ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
var enabledSyntaxKindFeatures = new Array(298 /* Count */);
- var lexicalEnvironmentDisabled = false;
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -56880,10 +61200,13 @@ var ts;
var lexicalEnvironmentStackOffset = 0;
var lexicalEnvironmentSuspended = false;
var emitHelpers;
+ var onSubstituteNode = function (_, node) { return node; };
+ var onEmitNode = function (hint, node, callback) { return callback(hint, node); };
+ var state = 0 /* Uninitialized */;
// The transformation context is provided to each transformer as part of transformer
// initialization.
var context = {
- getCompilerOptions: function () { return host.getCompilerOptions(); },
+ getCompilerOptions: function () { return options; },
getEmitResolver: function () { return resolver; },
getEmitHost: function () { return host; },
startLexicalEnvironment: startLexicalEnvironment,
@@ -56894,39 +61217,53 @@ var ts;
hoistFunctionDeclaration: hoistFunctionDeclaration,
requestEmitHelper: requestEmitHelper,
readEmitHelpers: readEmitHelpers,
- onSubstituteNode: function (_emitContext, node) { return node; },
enableSubstitution: enableSubstitution,
- isSubstitutionEnabled: isSubstitutionEnabled,
- onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); },
enableEmitNotification: enableEmitNotification,
- isEmitNotificationEnabled: isEmitNotificationEnabled
+ isSubstitutionEnabled: isSubstitutionEnabled,
+ isEmitNotificationEnabled: isEmitNotificationEnabled,
+ get onSubstituteNode() { return onSubstituteNode; },
+ set onSubstituteNode(value) {
+ ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
+ ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
+ onSubstituteNode = value;
+ },
+ get onEmitNode() { return onEmitNode; },
+ set onEmitNode(value) {
+ ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
+ ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
+ onEmitNode = value;
+ }
};
+ // Ensure the parse tree is clean before applying transformations
+ for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
+ var node = nodes_4[_i];
+ ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
+ }
+ ts.performance.mark("beforeTransform");
// Chain together and initialize each transformer.
var transformation = ts.chain.apply(void 0, transformers)(context);
- // Transform each source file.
- var transformed = ts.map(sourceFiles, transformSourceFile);
- // Disable modification of the lexical environment.
- lexicalEnvironmentDisabled = true;
+ // prevent modification of transformation hooks.
+ state = 1 /* Initialized */;
+ // Transform each node.
+ var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
+ // prevent modification of the lexical environment.
+ state = 2 /* Completed */;
+ ts.performance.mark("afterTransform");
+ ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
return {
transformed: transformed,
- emitNodeWithSubstitution: emitNodeWithSubstitution,
- emitNodeWithNotification: emitNodeWithNotification
+ substituteNode: substituteNode,
+ emitNodeWithNotification: emitNodeWithNotification,
+ dispose: dispose
};
- /**
- * Transforms a source file.
- *
- * @param sourceFile The source file to transform.
- */
- function transformSourceFile(sourceFile) {
- if (ts.isDeclarationFile(sourceFile)) {
- return sourceFile;
- }
- return transformation(sourceFile);
+ function transformRoot(node) {
+ return node && (!ts.isSourceFile(node) || !ts.isDeclarationFile(node)) ? transformation(node) : node;
}
/**
* Enables expression substitutions in the pretty printer for the provided SyntaxKind.
*/
function enableSubstitution(kind) {
+ ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
}
/**
@@ -56939,26 +61276,19 @@ var ts;
/**
* Emits a node with possible substitution.
*
- * @param emitContext The current emit context.
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emitCallback The callback used to emit the node or its substitute.
*/
- function emitNodeWithSubstitution(emitContext, node, emitCallback) {
- if (node) {
- if (isSubstitutionEnabled(node)) {
- var substitute = context.onSubstituteNode(emitContext, node);
- if (substitute && substitute !== node) {
- emitCallback(emitContext, substitute);
- return;
- }
- }
- emitCallback(emitContext, node);
- }
+ function substituteNode(hint, node) {
+ ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
+ return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
}
/**
* Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
*/
function enableEmitNotification(kind) {
+ ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
}
/**
@@ -56972,17 +61302,18 @@ var ts;
/**
* Emits a node with possible emit notification.
*
- * @param emitContext The current emit context.
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emitCallback The callback used to emit the node.
*/
- function emitNodeWithNotification(emitContext, node, emitCallback) {
+ function emitNodeWithNotification(hint, node, emitCallback) {
+ ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
if (node) {
if (isEmitNotificationEnabled(node)) {
- context.onEmitNode(emitContext, node, emitCallback);
+ onEmitNode(hint, node, emitCallback);
}
else {
- emitCallback(emitContext, node);
+ emitCallback(hint, node);
}
}
}
@@ -56990,7 +61321,8 @@ var ts;
* Records a hoisted variable declaration for the provided name within a lexical environment.
*/
function hoistVariableDeclaration(name) {
- ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
+ ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
+ ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
var decl = ts.createVariableDeclaration(name);
if (!lexicalEnvironmentVariableDeclarations) {
lexicalEnvironmentVariableDeclarations = [decl];
@@ -57003,7 +61335,8 @@ var ts;
* Records a hoisted function declaration within a lexical environment.
*/
function hoistFunctionDeclaration(func) {
- ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
+ ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
+ ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
if (!lexicalEnvironmentFunctionDeclarations) {
lexicalEnvironmentFunctionDeclarations = [func];
}
@@ -57016,7 +61349,8 @@ var ts;
* are pushed onto a stack, and the related storage variables are reset.
*/
function startLexicalEnvironment() {
- ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase.");
+ ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
+ ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
// Save the current lexical environment. Rather than resizing the array we adjust the
// stack size variable. This allows us to reuse existing array slots we've
@@ -57030,13 +61364,15 @@ var ts;
}
/** Suspends the current lexical environment, usually after visiting a parameter list. */
function suspendLexicalEnvironment() {
- ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot suspend a lexical environment during the print phase.");
+ ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
+ ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
lexicalEnvironmentSuspended = true;
}
/** Resumes a suspended lexical environment, usually before visiting a function body. */
function resumeLexicalEnvironment() {
- ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot resume a lexical environment during the print phase.");
+ ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
+ ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
lexicalEnvironmentSuspended = false;
}
@@ -57045,7 +61381,8 @@ var ts;
* any hoisted declarations added in this environment are returned.
*/
function endLexicalEnvironment() {
- ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase.");
+ ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
+ ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
var statements;
if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) {
@@ -57074,19 +61411,39 @@ var ts;
return statements;
}
function requestEmitHelper(helper) {
- ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
+ ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
+ ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
emitHelpers = ts.append(emitHelpers, helper);
}
function readEmitHelpers() {
- ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
+ ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
+ ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
var helpers = emitHelpers;
emitHelpers = undefined;
return helpers;
}
- }
- ts.transformFiles = transformFiles;
- var _a;
+ function dispose() {
+ if (state < 3 /* Disposed */) {
+ // Clean up emit nodes on parse tree
+ for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
+ var node = nodes_5[_i];
+ ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
+ }
+ // Release references to external entries for GC purposes.
+ lexicalEnvironmentVariableDeclarations = undefined;
+ lexicalEnvironmentVariableDeclarationsStack = undefined;
+ lexicalEnvironmentFunctionDeclarations = undefined;
+ lexicalEnvironmentFunctionDeclarationsStack = undefined;
+ onSubstituteNode = undefined;
+ onEmitNode = undefined;
+ emitHelpers = undefined;
+ // Prevent further use of the transformation result.
+ state = 3 /* Disposed */;
+ }
+ }
+ }
+ ts.transformNodes = transformNodes;
})(ts || (ts = {}));
/// <reference path="checker.ts"/>
/* @internal */
@@ -57131,10 +61488,9 @@ var ts;
*
* @param filePath The path to the generated output file.
* @param sourceMapFilePath The path to the output source map file.
- * @param sourceFiles The input source files for the program.
- * @param isBundledEmit A value indicating whether the generated output file is a bundle.
+ * @param sourceFileOrBundle The input source file or bundle for the program.
*/
- function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) {
+ function initialize(filePath, sourceMapFilePath, sourceFileOrBundle) {
if (disabled) {
return;
}
@@ -57170,11 +61526,10 @@ var ts;
}
if (compilerOptions.mapRoot) {
sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot);
- if (!isBundledEmit) {
- ts.Debug.assert(sourceFiles.length === 1);
+ if (sourceFileOrBundle.kind === 264 /* SourceFile */) {
// For modules or multiple emit files the mapRoot will have directory structure like the sources
// So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
- sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir));
+ sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir));
}
if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) {
// The relative paths are relative to the common directory
@@ -57297,31 +61652,32 @@ var ts;
/**
* Emits a node with possible leading and trailing source maps.
*
+ * @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emitCallback The callback used to emit the node.
*/
- function emitNodeWithSourceMap(emitContext, node, emitCallback) {
+ function emitNodeWithSourceMap(hint, node, emitCallback) {
if (disabled) {
- return emitCallback(emitContext, node);
+ return emitCallback(hint, node);
}
if (node) {
var emitNode = node.emitNode;
var emitFlags = emitNode && emitNode.flags;
var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end;
- if (node.kind !== 293 /* NotEmittedStatement */
+ if (node.kind !== 294 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitPos(ts.skipTrivia(currentSourceText, pos));
}
if (emitFlags & 64 /* NoNestedSourceMaps */) {
disabled = true;
- emitCallback(emitContext, node);
+ emitCallback(hint, node);
disabled = false;
}
else {
- emitCallback(emitContext, node);
+ emitCallback(hint, node);
}
- if (node.kind !== 293 /* NotEmittedStatement */
+ if (node.kind !== 294 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitPos(end);
@@ -57391,7 +61747,7 @@ var ts;
return;
}
encodeLastRecordedSourceMapSpan();
- return ts.stringify({
+ return JSON.stringify({
version: 3,
file: sourceMapData.sourceMapFile,
sourceRoot: sourceMapData.sourceMapSourceRoot,
@@ -57456,11 +61812,10 @@ var ts;
/* @internal */
var ts;
(function (ts) {
- function createCommentWriter(host, writer, sourceMap) {
- var compilerOptions = host.getCompilerOptions();
- var extendedDiagnostics = compilerOptions.extendedDiagnostics;
- var newLine = host.getNewLine();
- var emitPos = sourceMap.emitPos;
+ function createCommentWriter(printerOptions, emitPos) {
+ var extendedDiagnostics = printerOptions.extendedDiagnostics;
+ var newLine = ts.getNewLineCharacter(printerOptions);
+ var writer;
var containerPos = -1;
var containerEnd = -1;
var declarationListContainerEnd = -1;
@@ -57469,38 +61824,35 @@ var ts;
var currentLineMap;
var detachedCommentsInfo;
var hasWrittenComment = false;
- var disabled = compilerOptions.removeComments;
+ var disabled = printerOptions.removeComments;
return {
reset: reset,
+ setWriter: setWriter,
setSourceFile: setSourceFile,
emitNodeWithComments: emitNodeWithComments,
emitBodyWithDetachedComments: emitBodyWithDetachedComments,
emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition,
+ emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition,
};
- function emitNodeWithComments(emitContext, node, emitCallback) {
+ function emitNodeWithComments(hint, node, emitCallback) {
if (disabled) {
- emitCallback(emitContext, node);
+ emitCallback(hint, node);
return;
}
if (node) {
- var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var emitFlags = ts.getEmitFlags(node);
+ hasWrittenComment = false;
+ var emitNode = node.emitNode;
+ var emitFlags = emitNode && emitNode.flags;
+ var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end;
if ((pos < 0 && end < 0) || (pos === end)) {
// Both pos and end are synthesized, so just emit the node without comments.
- if (emitFlags & 2048 /* NoNestedComments */) {
- disabled = true;
- emitCallback(emitContext, node);
- disabled = false;
- }
- else {
- emitCallback(emitContext, node);
- }
+ emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback);
}
else {
if (extendedDiagnostics) {
ts.performance.mark("preEmitNodeWithComment");
}
- var isEmittedNode = node.kind !== 293 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 294 /* NotEmittedStatement */;
var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
// Emit leading comments if the position is not synthesized and the node
@@ -57519,23 +61871,16 @@ var ts;
containerEnd = end;
// To avoid invalid comment emit in a down-level binding pattern, we
// keep track of the last declaration list container's end
- if (node.kind === 224 /* VariableDeclarationList */) {
+ if (node.kind === 226 /* VariableDeclarationList */) {
declarationListContainerEnd = end;
}
}
if (extendedDiagnostics) {
ts.performance.measure("commentTime", "preEmitNodeWithComment");
}
- if (emitFlags & 2048 /* NoNestedComments */) {
- disabled = true;
- emitCallback(emitContext, node);
- disabled = false;
- }
- else {
- emitCallback(emitContext, node);
- }
+ emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback);
if (extendedDiagnostics) {
- ts.performance.mark("beginEmitNodeWithComment");
+ ts.performance.mark("postEmitNodeWithComment");
}
// Restore previous container state.
containerPos = savedContainerPos;
@@ -57547,11 +61892,75 @@ var ts;
emitTrailingComments(end);
}
if (extendedDiagnostics) {
- ts.performance.measure("commentTime", "beginEmitNodeWithComment");
+ ts.performance.measure("commentTime", "postEmitNodeWithComment");
}
}
}
}
+ function emitNodeWithSynthesizedComments(hint, node, emitNode, emitFlags, emitCallback) {
+ var leadingComments = emitNode && emitNode.leadingComments;
+ if (ts.some(leadingComments)) {
+ if (extendedDiagnostics) {
+ ts.performance.mark("preEmitNodeWithSynthesizedComments");
+ }
+ ts.forEach(leadingComments, emitLeadingSynthesizedComment);
+ if (extendedDiagnostics) {
+ ts.performance.measure("commentTime", "preEmitNodeWithSynthesizedComments");
+ }
+ }
+ emitNodeWithNestedComments(hint, node, emitFlags, emitCallback);
+ var trailingComments = emitNode && emitNode.trailingComments;
+ if (ts.some(trailingComments)) {
+ if (extendedDiagnostics) {
+ ts.performance.mark("postEmitNodeWithSynthesizedComments");
+ }
+ ts.forEach(trailingComments, emitTrailingSynthesizedComment);
+ if (extendedDiagnostics) {
+ ts.performance.measure("commentTime", "postEmitNodeWithSynthesizedComments");
+ }
+ }
+ }
+ function emitLeadingSynthesizedComment(comment) {
+ if (comment.kind === 2 /* SingleLineCommentTrivia */) {
+ writer.writeLine();
+ }
+ writeSynthesizedComment(comment);
+ if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
+ writer.writeLine();
+ }
+ else {
+ writer.write(" ");
+ }
+ }
+ function emitTrailingSynthesizedComment(comment) {
+ if (!writer.isAtStartOfLine()) {
+ writer.write(" ");
+ }
+ writeSynthesizedComment(comment);
+ if (comment.hasTrailingNewLine) {
+ writer.writeLine();
+ }
+ }
+ function writeSynthesizedComment(comment) {
+ var text = formatSynthesizedComment(comment);
+ var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
+ ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
+ }
+ function formatSynthesizedComment(comment) {
+ return comment.kind === 3 /* MultiLineCommentTrivia */
+ ? "/*" + comment.text + "*/"
+ : "//" + comment.text;
+ }
+ function emitNodeWithNestedComments(hint, node, emitFlags, emitCallback) {
+ if (emitFlags & 2048 /* NoNestedComments */) {
+ disabled = true;
+ emitCallback(hint, node);
+ disabled = false;
+ }
+ else {
+ emitCallback(hint, node);
+ }
+ }
function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
if (extendedDiagnostics) {
ts.performance.mark("preEmitBodyWithDetachedComments");
@@ -57579,6 +61988,9 @@ var ts;
}
if (!skipTrailingComments) {
emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
+ if (hasWrittenComment && !writer.isAtStartOfLine()) {
+ writer.writeLine();
+ }
}
if (extendedDiagnostics) {
ts.performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns");
@@ -57612,9 +62024,11 @@ var ts;
hasWrittenComment = true;
}
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
- emitPos(commentPos);
+ if (emitPos)
+ emitPos(commentPos);
ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
- emitPos(commentEnd);
+ if (emitPos)
+ emitPos(commentEnd);
if (hasTrailingNewLine) {
writer.writeLine();
}
@@ -57622,6 +62036,12 @@ var ts;
writer.write(" ");
}
}
+ function emitLeadingCommentsOfPosition(pos) {
+ if (disabled || pos === -1) {
+ return;
+ }
+ emitLeadingComments(pos, /*isEmittedNode*/ true);
+ }
function emitTrailingComments(pos) {
forEachTrailingCommentToEmit(pos, emitTrailingComment);
}
@@ -57630,9 +62050,11 @@ var ts;
if (!writer.isAtStartOfLine()) {
writer.write(" ");
}
- emitPos(commentPos);
+ if (emitPos)
+ emitPos(commentPos);
ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
- emitPos(commentEnd);
+ if (emitPos)
+ emitPos(commentEnd);
if (hasTrailingNewLine) {
writer.writeLine();
}
@@ -57651,9 +62073,11 @@ var ts;
}
function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
// trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
- emitPos(commentPos);
+ if (emitPos)
+ emitPos(commentPos);
ts.writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
- emitPos(commentEnd);
+ if (emitPos)
+ emitPos(commentEnd);
if (hasTrailingNewLine) {
writer.writeLine();
}
@@ -57684,6 +62108,9 @@ var ts;
currentLineMap = undefined;
detachedCommentsInfo = undefined;
}
+ function setWriter(output) {
+ writer = output;
+ }
function setSourceFile(sourceFile) {
currentSourceFile = sourceFile;
currentText = currentSourceFile.text;
@@ -57716,15 +62143,17 @@ var ts;
}
}
function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
- emitPos(commentPos);
+ if (emitPos)
+ emitPos(commentPos);
ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
- emitPos(commentEnd);
+ if (emitPos)
+ emitPos(commentEnd);
}
/**
* Determine if the given comment is a triple-slash
*
* @return true if the comment is a triple-slash comment else false
- **/
+ */
function isTripleSlashComment(commentPos, commentEnd) {
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
@@ -57747,15 +62176,17 @@ var ts;
(function (ts) {
function getDeclarationDiagnostics(host, resolver, targetSourceFile) {
var declarationDiagnostics = ts.createDiagnosticCollection();
- ts.forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);
+ ts.forEachEmittedFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);
return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);
- function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) {
+ function getDeclarationDiagnosticsFromFile(_a, sourceFileOrBundle) {
var declarationFilePath = _a.declarationFilePath;
- emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false);
+ emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, /*emitOnlyDtsFiles*/ false);
}
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
- function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) {
+ function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) {
+ var sourceFiles = sourceFileOrBundle.kind === 265 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle];
+ var isBundledEmit = sourceFileOrBundle.kind === 265 /* Bundle */;
var newLine = host.getNewLine();
var compilerOptions = host.getCompilerOptions();
var write;
@@ -57829,7 +62260,7 @@ var ts;
var oldWriter = writer;
ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) {
if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) {
- ts.Debug.assert(aliasEmitInfo.node.kind === 235 /* ImportDeclaration */);
+ ts.Debug.assert(aliasEmitInfo.node.kind === 237 /* ImportDeclaration */);
createAndSetNewTextWriterWithSymbolWriter();
ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit));
for (var i = 0; i < aliasEmitInfo.indent; i++) {
@@ -57855,9 +62286,9 @@ var ts;
}
});
if (usedTypeDirectiveReferences) {
- for (var directive in usedTypeDirectiveReferences) {
+ ts.forEachKey(usedTypeDirectiveReferences, function (directive) {
referencesOutput += "/// <reference types=\"" + directive + "\" />" + newLine;
- }
+ });
}
return {
reportedDeclarationError: reportedDeclarationError,
@@ -57882,12 +62313,14 @@ var ts;
var writer = ts.createTextWriter(newLine);
writer.trackSymbol = trackSymbol;
writer.reportInaccessibleThisError = reportInaccessibleThisError;
+ writer.reportIllegalExtends = reportIllegalExtends;
writer.writeKeyword = writer.write;
writer.writeOperator = writer.write;
writer.writePunctuation = writer.write;
writer.writeSpace = writer.write;
writer.writeStringLiteral = writer.writeLiteral;
writer.writeParameter = writer.write;
+ writer.writeProperty = writer.write;
writer.writeSymbol = writer.write;
setWriter(writer);
}
@@ -57903,10 +62336,10 @@ var ts;
var oldWriter = writer;
ts.forEach(nodes, function (declaration) {
var nodeToCheck;
- if (declaration.kind === 223 /* VariableDeclaration */) {
+ if (declaration.kind === 225 /* VariableDeclaration */) {
nodeToCheck = declaration.parent.parent;
}
- else if (declaration.kind === 238 /* NamedImports */ || declaration.kind === 239 /* ImportSpecifier */ || declaration.kind === 236 /* ImportClause */) {
+ else if (declaration.kind === 240 /* NamedImports */ || declaration.kind === 241 /* ImportSpecifier */ || declaration.kind === 238 /* ImportClause */) {
ts.Debug.fail("We should be getting ImportDeclaration instead to write");
}
else {
@@ -57924,7 +62357,7 @@ var ts;
// Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing,
// we would write alias foo declaration when we visit it since it would now be marked as visible
if (moduleElementEmitInfo) {
- if (moduleElementEmitInfo.node.kind === 235 /* ImportDeclaration */) {
+ if (moduleElementEmitInfo.node.kind === 237 /* ImportDeclaration */) {
// we have to create asynchronous output only after we have collected complete information
// because it is possible to enable multiple bindings as asynchronously visible
moduleElementEmitInfo.isVisible = true;
@@ -57934,12 +62367,12 @@ var ts;
for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) {
increaseIndent();
}
- if (nodeToCheck.kind === 230 /* ModuleDeclaration */) {
+ if (nodeToCheck.kind === 232 /* ModuleDeclaration */) {
ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined);
asynchronousSubModuleDeclarationEmitInfo = [];
}
writeModuleElement(nodeToCheck);
- if (nodeToCheck.kind === 230 /* ModuleDeclaration */) {
+ if (nodeToCheck.kind === 232 /* ModuleDeclaration */) {
moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo;
asynchronousSubModuleDeclarationEmitInfo = undefined;
}
@@ -57958,8 +62391,8 @@ var ts;
}
for (var _i = 0, typeReferenceDirectives_1 = typeReferenceDirectives; _i < typeReferenceDirectives_1.length; _i++) {
var directive = typeReferenceDirectives_1[_i];
- if (!(directive in usedTypeDirectiveReferences)) {
- usedTypeDirectiveReferences[directive] = directive;
+ if (!usedTypeDirectiveReferences.has(directive)) {
+ usedTypeDirectiveReferences.set(directive, directive);
}
}
}
@@ -57988,6 +62421,12 @@ var ts;
handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
+ function reportIllegalExtends() {
+ if (errorNameNode) {
+ reportedDeclarationError = true;
+ emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced, ts.declarationNameToString(errorNameNode)));
+ }
+ }
function reportInaccessibleThisError() {
if (errorNameNode) {
reportedDeclarationError = true;
@@ -57997,13 +62436,19 @@ var ts;
function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) {
writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic;
write(": ");
- if (type) {
+ // use the checker's type, not the declared type,
+ // for non-optional initialized parameters that aren't a parameter property
+ var shouldUseResolverType = declaration.kind === 145 /* Parameter */ &&
+ resolver.isRequiredInitializedParameter(declaration);
+ if (type && !shouldUseResolverType) {
// Write the type
emitType(type);
}
else {
errorNameNode = declaration.name;
- resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer);
+ var format = 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */ |
+ (shouldUseResolverType ? 4096 /* AddUndefined */ : 0);
+ resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer);
errorNameNode = undefined;
}
}
@@ -58021,15 +62466,15 @@ var ts;
}
}
function emitLines(nodes) {
- for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
- var node = nodes_4[_i];
+ for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) {
+ var node = nodes_6[_i];
emit(node);
}
}
function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) {
var currentWriterPos = writer.getTextPos();
- for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
- var node = nodes_5[_i];
+ for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
+ var node = nodes_7[_i];
if (!canEmitFn || canEmitFn(node)) {
if (currentWriterPos !== writer.getTextPos()) {
write(separator);
@@ -58057,49 +62502,50 @@ var ts;
function emitType(type) {
switch (type.kind) {
case 118 /* AnyKeyword */:
- case 134 /* StringKeyword */:
+ case 135 /* StringKeyword */:
case 132 /* NumberKeyword */:
case 121 /* BooleanKeyword */:
- case 135 /* SymbolKeyword */:
+ case 133 /* ObjectKeyword */:
+ case 136 /* SymbolKeyword */:
case 104 /* VoidKeyword */:
- case 137 /* UndefinedKeyword */:
+ case 138 /* UndefinedKeyword */:
case 94 /* NullKeyword */:
case 129 /* NeverKeyword */:
- case 167 /* ThisType */:
- case 171 /* LiteralType */:
+ case 168 /* ThisType */:
+ case 172 /* LiteralType */:
return writeTextOfNode(currentText, type);
- case 199 /* ExpressionWithTypeArguments */:
+ case 200 /* ExpressionWithTypeArguments */:
return emitExpressionWithTypeArguments(type);
- case 157 /* TypeReference */:
+ case 158 /* TypeReference */:
return emitTypeReference(type);
- case 160 /* TypeQuery */:
+ case 161 /* TypeQuery */:
return emitTypeQuery(type);
- case 162 /* ArrayType */:
+ case 163 /* ArrayType */:
return emitArrayType(type);
- case 163 /* TupleType */:
+ case 164 /* TupleType */:
return emitTupleType(type);
- case 164 /* UnionType */:
+ case 165 /* UnionType */:
return emitUnionType(type);
- case 165 /* IntersectionType */:
+ case 166 /* IntersectionType */:
return emitIntersectionType(type);
- case 166 /* ParenthesizedType */:
+ case 167 /* ParenthesizedType */:
return emitParenType(type);
- case 168 /* TypeOperator */:
+ case 169 /* TypeOperator */:
return emitTypeOperator(type);
- case 169 /* IndexedAccessType */:
+ case 170 /* IndexedAccessType */:
return emitIndexedAccessType(type);
- case 170 /* MappedType */:
+ case 171 /* MappedType */:
return emitMappedType(type);
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
return emitSignatureDeclarationWithJsDocComments(type);
- case 161 /* TypeLiteral */:
+ case 162 /* TypeLiteral */:
return emitTypeLiteral(type);
case 70 /* Identifier */:
return emitEntityName(type);
- case 141 /* QualifiedName */:
+ case 142 /* QualifiedName */:
return emitEntityName(type);
- case 156 /* TypePredicate */:
+ case 157 /* TypePredicate */:
return emitTypePredicate(type);
}
function writeEntityName(entityName) {
@@ -58107,8 +62553,8 @@ var ts;
writeTextOfNode(currentText, entityName);
}
else {
- var left = entityName.kind === 141 /* QualifiedName */ ? entityName.left : entityName.expression;
- var right = entityName.kind === 141 /* QualifiedName */ ? entityName.right : entityName.name;
+ var left = entityName.kind === 142 /* QualifiedName */ ? entityName.left : entityName.expression;
+ var right = entityName.kind === 142 /* QualifiedName */ ? entityName.right : entityName.name;
writeEntityName(left);
write(".");
writeTextOfNode(currentText, right);
@@ -58117,14 +62563,14 @@ var ts;
function emitEntityName(entityName) {
var visibilityResult = resolver.isEntityNameVisible(entityName,
// Aliases can be written asynchronously so use correct enclosing declaration
- entityName.parent.kind === 234 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration);
+ entityName.parent.kind === 236 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration);
handleSymbolAccessibilityError(visibilityResult);
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
writeEntityName(entityName);
}
function emitExpressionWithTypeArguments(node) {
if (ts.isEntityNameExpression(node.expression)) {
- ts.Debug.assert(node.expression.kind === 70 /* Identifier */ || node.expression.kind === 177 /* PropertyAccessExpression */);
+ ts.Debug.assert(node.expression.kind === 70 /* Identifier */ || node.expression.kind === 178 /* PropertyAccessExpression */);
emitEntityName(node.expression);
if (node.typeArguments) {
write("<");
@@ -58224,7 +62670,7 @@ var ts;
currentIdentifiers = node.identifiers;
isCurrentFileExternalModule = ts.isExternalModule(node);
enclosingDeclaration = node;
- ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true /* remove comments */);
+ ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true);
emitLines(node.statements);
}
// Return a temp variable name to be used in `export default` statements.
@@ -58233,15 +62679,15 @@ var ts;
// do not need to keep track of created temp names.
function getExportDefaultTempVariableName() {
var baseName = "_default";
- if (!(baseName in currentIdentifiers)) {
+ if (!currentIdentifiers.has(baseName)) {
return baseName;
}
var count = 0;
while (true) {
count++;
- var name_38 = baseName + "_" + count;
- if (!(name_38 in currentIdentifiers)) {
- return name_38;
+ var name = baseName + "_" + count;
+ if (!currentIdentifiers.has(name)) {
+ return name;
}
}
}
@@ -58288,10 +62734,10 @@ var ts;
if (isModuleElementVisible) {
writeModuleElement(node);
}
- else if (node.kind === 234 /* ImportEqualsDeclaration */ ||
- (node.parent.kind === 261 /* SourceFile */ && isCurrentFileExternalModule)) {
+ else if (node.kind === 236 /* ImportEqualsDeclaration */ ||
+ (node.parent.kind === 264 /* SourceFile */ && isCurrentFileExternalModule)) {
var isVisible = void 0;
- if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 261 /* SourceFile */) {
+ if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 264 /* SourceFile */) {
// Import declaration of another module that is visited async so lets put it in right spot
asynchronousSubModuleDeclarationEmitInfo.push({
node: node,
@@ -58301,7 +62747,7 @@ var ts;
});
}
else {
- if (node.kind === 235 /* ImportDeclaration */) {
+ if (node.kind === 237 /* ImportDeclaration */) {
var importDeclaration = node;
if (importDeclaration.importClause) {
isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) ||
@@ -58319,23 +62765,23 @@ var ts;
}
function writeModuleElement(node) {
switch (node.kind) {
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return writeFunctionDeclaration(node);
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
return writeVariableStatement(node);
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
return writeInterfaceDeclaration(node);
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
return writeClassDeclaration(node);
- case 228 /* TypeAliasDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
return writeTypeAliasDeclaration(node);
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
return writeEnumDeclaration(node);
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return writeModuleDeclaration(node);
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
return writeImportEqualsDeclaration(node);
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
return writeImportDeclaration(node);
default:
ts.Debug.fail("Unknown symbol kind");
@@ -58343,7 +62789,7 @@ var ts;
}
function emitModuleElementDeclarationFlags(node) {
// If the node is parented in the current source file we need to emit export declare or just export
- if (node.parent.kind === 261 /* SourceFile */) {
+ if (node.parent.kind === 264 /* SourceFile */) {
var modifiers = ts.getModifierFlags(node);
// If the node is exported
if (modifiers & 1 /* Export */) {
@@ -58352,7 +62798,7 @@ var ts;
if (modifiers & 512 /* Default */) {
write("default ");
}
- else if (node.kind !== 227 /* InterfaceDeclaration */ && !noDeclare) {
+ else if (node.kind !== 229 /* InterfaceDeclaration */ && !noDeclare) {
write("declare ");
}
}
@@ -58404,7 +62850,7 @@ var ts;
}
function isVisibleNamedBinding(namedBindings) {
if (namedBindings) {
- if (namedBindings.kind === 237 /* NamespaceImport */) {
+ if (namedBindings.kind === 239 /* NamespaceImport */) {
return resolver.isDeclarationVisible(namedBindings);
}
else {
@@ -58428,7 +62874,7 @@ var ts;
// If the default binding was emitted, write the separated
write(", ");
}
- if (node.importClause.namedBindings.kind === 237 /* NamespaceImport */) {
+ if (node.importClause.namedBindings.kind === 239 /* NamespaceImport */) {
write("* as ");
writeTextOfNode(currentText, node.importClause.namedBindings.name);
}
@@ -58449,13 +62895,13 @@ var ts;
// the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered
// external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}'
// so compiler will treat them as external modules.
- resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 230 /* ModuleDeclaration */;
+ resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 232 /* ModuleDeclaration */;
var moduleSpecifier;
- if (parent.kind === 234 /* ImportEqualsDeclaration */) {
+ if (parent.kind === 236 /* ImportEqualsDeclaration */) {
var node = parent;
moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node);
}
- else if (parent.kind === 230 /* ModuleDeclaration */) {
+ else if (parent.kind === 232 /* ModuleDeclaration */) {
moduleSpecifier = parent.name;
}
else {
@@ -58525,7 +62971,7 @@ var ts;
writeTextOfNode(currentText, node.name);
}
}
- while (node.body && node.body.kind !== 231 /* ModuleBlock */) {
+ while (node.body && node.body.kind !== 233 /* ModuleBlock */) {
node = node.body;
write(".");
writeTextOfNode(currentText, node.name);
@@ -58595,7 +63041,7 @@ var ts;
writeLine();
}
function isPrivateMethodTypeParameter(node) {
- return node.parent.kind === 149 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
+ return node.parent.kind === 150 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
}
function emitTypeParameters(typeParameters) {
function emitTypeParameter(node) {
@@ -58606,53 +63052,70 @@ var ts;
// If there is constraint present and this is not a type parameter of the private method emit the constraint
if (node.constraint && !isPrivateMethodTypeParameter(node)) {
write(" extends ");
- if (node.parent.kind === 158 /* FunctionType */ ||
- node.parent.kind === 159 /* ConstructorType */ ||
- (node.parent.parent && node.parent.parent.kind === 161 /* TypeLiteral */)) {
- ts.Debug.assert(node.parent.kind === 149 /* MethodDeclaration */ ||
- node.parent.kind === 148 /* MethodSignature */ ||
- node.parent.kind === 158 /* FunctionType */ ||
- node.parent.kind === 159 /* ConstructorType */ ||
- node.parent.kind === 153 /* CallSignature */ ||
- node.parent.kind === 154 /* ConstructSignature */);
+ if (node.parent.kind === 159 /* FunctionType */ ||
+ node.parent.kind === 160 /* ConstructorType */ ||
+ (node.parent.parent && node.parent.parent.kind === 162 /* TypeLiteral */)) {
+ ts.Debug.assert(node.parent.kind === 150 /* MethodDeclaration */ ||
+ node.parent.kind === 149 /* MethodSignature */ ||
+ node.parent.kind === 159 /* FunctionType */ ||
+ node.parent.kind === 160 /* ConstructorType */ ||
+ node.parent.kind === 154 /* CallSignature */ ||
+ node.parent.kind === 155 /* ConstructSignature */);
emitType(node.constraint);
}
else {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError);
}
}
+ if (node.default && !isPrivateMethodTypeParameter(node)) {
+ write(" = ");
+ if (node.parent.kind === 159 /* FunctionType */ ||
+ node.parent.kind === 160 /* ConstructorType */ ||
+ (node.parent.parent && node.parent.parent.kind === 162 /* TypeLiteral */)) {
+ ts.Debug.assert(node.parent.kind === 150 /* MethodDeclaration */ ||
+ node.parent.kind === 149 /* MethodSignature */ ||
+ node.parent.kind === 159 /* FunctionType */ ||
+ node.parent.kind === 160 /* ConstructorType */ ||
+ node.parent.kind === 154 /* CallSignature */ ||
+ node.parent.kind === 155 /* ConstructSignature */);
+ emitType(node.default);
+ }
+ else {
+ emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.default, getTypeParameterConstraintVisibilityError);
+ }
+ }
function getTypeParameterConstraintVisibilityError() {
// Type parameter constraints are named by user so we should always be able to name it
var diagnosticMessage;
switch (node.parent.kind) {
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
break;
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
- case 154 /* ConstructSignature */:
+ case 155 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
break;
- case 153 /* CallSignature */:
+ case 154 /* CallSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
break;
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
if (ts.hasModifier(node.parent, 32 /* Static */)) {
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
}
- else if (node.parent.parent.kind === 226 /* ClassDeclaration */) {
+ else if (node.parent.parent.kind === 228 /* ClassDeclaration */) {
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
}
else {
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
}
break;
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
break;
- case 228 /* TypeAliasDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
break;
default:
@@ -58671,7 +63134,7 @@ var ts;
write(">");
}
}
- function emitHeritageClause(typeReferences, isImplementsList) {
+ function emitHeritageClause(className, typeReferences, isImplementsList) {
if (typeReferences) {
write(isImplementsList ? " implements " : " extends ");
emitCommaList(typeReferences, emitTypeOfTypeReference);
@@ -58685,20 +63148,22 @@ var ts;
}
else {
writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError;
+ errorNameNode = className;
resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer);
+ errorNameNode = undefined;
}
function getHeritageClauseVisibilityError() {
var diagnosticMessage;
// Heritage clause is written by user so it can always be named
- if (node.parent.parent.kind === 226 /* ClassDeclaration */) {
+ if (node.parent.parent.kind === 228 /* ClassDeclaration */) {
// Class or Interface implemented/extended is inaccessible
diagnosticMessage = isImplementsList ?
ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
- ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
+ ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
}
else {
// interface is inaccessible
- diagnosticMessage = ts.Diagnostics.Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
+ diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
}
return {
diagnosticMessage: diagnosticMessage,
@@ -58730,9 +63195,10 @@ var ts;
emitTypeParameters(node.typeParameters);
var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node);
if (baseTypeNode) {
- emitHeritageClause([baseTypeNode], /*isImplementsList*/ false);
+ node.name;
+ emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false);
}
- emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true);
+ emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true);
write(" {");
writeLine();
increaseIndent();
@@ -58753,7 +63219,7 @@ var ts;
emitTypeParameters(node.typeParameters);
var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); });
if (interfaceExtendsTypes && interfaceExtendsTypes.length) {
- emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false);
+ emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false);
}
write(" {");
writeLine();
@@ -58777,7 +63243,7 @@ var ts;
function emitVariableDeclaration(node) {
// If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted
// so there is no check needed to see if declaration is visible
- if (node.kind !== 223 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) {
+ if (node.kind !== 225 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) {
if (ts.isBindingPattern(node.name)) {
emitBindingPattern(node.name);
}
@@ -58788,11 +63254,11 @@ var ts;
writeTextOfNode(currentText, node.name);
// If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor
// we don't want to emit property declaration with "?"
- if ((node.kind === 147 /* PropertyDeclaration */ || node.kind === 146 /* PropertySignature */ ||
- (node.kind === 144 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) {
+ if ((node.kind === 148 /* PropertyDeclaration */ || node.kind === 147 /* PropertySignature */ ||
+ (node.kind === 145 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) {
write("?");
}
- if ((node.kind === 147 /* PropertyDeclaration */ || node.kind === 146 /* PropertySignature */) && node.parent.kind === 161 /* TypeLiteral */) {
+ if ((node.kind === 148 /* PropertyDeclaration */ || node.kind === 147 /* PropertySignature */) && node.parent.kind === 162 /* TypeLiteral */) {
emitTypeOfVariableDeclarationFromTypeLiteral(node);
}
else if (resolver.isLiteralConstDeclaration(node)) {
@@ -58805,14 +63271,14 @@ var ts;
}
}
function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
- if (node.kind === 223 /* VariableDeclaration */) {
+ if (node.kind === 225 /* VariableDeclaration */) {
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
}
- else if (node.kind === 147 /* PropertyDeclaration */ || node.kind === 146 /* PropertySignature */) {
+ else if (node.kind === 148 /* PropertyDeclaration */ || node.kind === 147 /* PropertySignature */) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (ts.hasModifier(node, 32 /* Static */)) {
return symbolAccessibilityResult.errorModuleName ?
@@ -58821,7 +63287,7 @@ var ts;
ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
}
- else if (node.parent.kind === 226 /* ClassDeclaration */) {
+ else if (node.parent.kind === 228 /* ClassDeclaration */) {
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
@@ -58853,7 +63319,7 @@ var ts;
var elements = [];
for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) {
var element = _a[_i];
- if (element.kind !== 198 /* OmittedExpression */) {
+ if (element.kind !== 199 /* OmittedExpression */) {
elements.push(element);
}
}
@@ -58923,7 +63389,7 @@ var ts;
var type = getTypeAnnotationFromAccessor(node);
if (!type) {
// couldn't get type for the first accessor, try the another one
- var anotherAccessor = node.kind === 151 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor;
+ var anotherAccessor = node.kind === 152 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor;
type = getTypeAnnotationFromAccessor(anotherAccessor);
if (type) {
accessorWithTypeAnnotation = anotherAccessor;
@@ -58936,7 +63402,7 @@ var ts;
}
function getTypeAnnotationFromAccessor(accessor) {
if (accessor) {
- return accessor.kind === 151 /* GetAccessor */
+ return accessor.kind === 152 /* GetAccessor */
? accessor.type // Getter - return type
: accessor.parameters.length > 0
? accessor.parameters[0].type // Setter parameter type
@@ -58945,7 +63411,7 @@ var ts;
}
function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
var diagnosticMessage;
- if (accessorWithTypeAnnotation.kind === 152 /* SetAccessor */) {
+ if (accessorWithTypeAnnotation.kind === 153 /* SetAccessor */) {
// Setters have to have type named and cannot infer it so, the type should always be named
if (ts.hasModifier(accessorWithTypeAnnotation.parent, 32 /* Static */)) {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
@@ -58995,17 +63461,17 @@ var ts;
// so no need to verify if the declaration is visible
if (!resolver.isImplementationOfOverload(node)) {
emitJsDocComments(node);
- if (node.kind === 225 /* FunctionDeclaration */) {
+ if (node.kind === 227 /* FunctionDeclaration */) {
emitModuleElementDeclarationFlags(node);
}
- else if (node.kind === 149 /* MethodDeclaration */ || node.kind === 150 /* Constructor */) {
+ else if (node.kind === 150 /* MethodDeclaration */ || node.kind === 151 /* Constructor */) {
emitClassMemberDeclarationFlags(ts.getModifierFlags(node));
}
- if (node.kind === 225 /* FunctionDeclaration */) {
+ if (node.kind === 227 /* FunctionDeclaration */) {
write("function ");
writeTextOfNode(currentText, node.name);
}
- else if (node.kind === 150 /* Constructor */) {
+ else if (node.kind === 151 /* Constructor */) {
write("constructor");
}
else {
@@ -59025,17 +63491,17 @@ var ts;
var prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
var closeParenthesizedFunctionType = false;
- if (node.kind === 155 /* IndexSignature */) {
+ if (node.kind === 156 /* IndexSignature */) {
// Index signature can have readonly modifier
emitClassMemberDeclarationFlags(ts.getModifierFlags(node));
write("[");
}
else {
// Construct signature or constructor type write new Signature
- if (node.kind === 154 /* ConstructSignature */ || node.kind === 159 /* ConstructorType */) {
+ if (node.kind === 155 /* ConstructSignature */ || node.kind === 160 /* ConstructorType */) {
write("new ");
}
- else if (node.kind === 158 /* FunctionType */) {
+ else if (node.kind === 159 /* FunctionType */) {
var currentOutput = writer.getText();
// Do not generate incorrect type when function type with type parameters is type argument
// This could happen if user used space between two '<' making it error free
@@ -59050,22 +63516,22 @@ var ts;
}
// Parameters
emitCommaList(node.parameters, emitParameterDeclaration);
- if (node.kind === 155 /* IndexSignature */) {
+ if (node.kind === 156 /* IndexSignature */) {
write("]");
}
else {
write(")");
}
// If this is not a constructor and is not private, emit the return type
- var isFunctionTypeOrConstructorType = node.kind === 158 /* FunctionType */ || node.kind === 159 /* ConstructorType */;
- if (isFunctionTypeOrConstructorType || node.parent.kind === 161 /* TypeLiteral */) {
+ var isFunctionTypeOrConstructorType = node.kind === 159 /* FunctionType */ || node.kind === 160 /* ConstructorType */;
+ if (isFunctionTypeOrConstructorType || node.parent.kind === 162 /* TypeLiteral */) {
// Emit type literal signature return type only if specified
if (node.type) {
write(isFunctionTypeOrConstructorType ? " => " : ": ");
emitType(node.type);
}
}
- else if (node.kind !== 150 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) {
+ else if (node.kind !== 151 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) {
writeReturnTypeAtSignature(node, getReturnTypeVisibilityError);
}
enclosingDeclaration = prevEnclosingDeclaration;
@@ -59079,26 +63545,26 @@ var ts;
function getReturnTypeVisibilityError(symbolAccessibilityResult) {
var diagnosticMessage;
switch (node.kind) {
- case 154 /* ConstructSignature */:
+ case 155 /* ConstructSignature */:
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
break;
- case 153 /* CallSignature */:
+ case 154 /* CallSignature */:
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
break;
- case 155 /* IndexSignature */:
+ case 156 /* IndexSignature */:
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
break;
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
if (ts.hasModifier(node, 32 /* Static */)) {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
@@ -59106,7 +63572,7 @@ var ts;
ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
}
- else if (node.parent.kind === 226 /* ClassDeclaration */) {
+ else if (node.parent.kind === 228 /* ClassDeclaration */) {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
@@ -59120,7 +63586,7 @@ var ts;
ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
}
break;
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
@@ -59155,9 +63621,9 @@ var ts;
write("?");
}
decreaseIndent();
- if (node.parent.kind === 158 /* FunctionType */ ||
- node.parent.kind === 159 /* ConstructorType */ ||
- node.parent.parent.kind === 161 /* TypeLiteral */) {
+ if (node.parent.kind === 159 /* FunctionType */ ||
+ node.parent.kind === 160 /* ConstructorType */ ||
+ node.parent.parent.kind === 162 /* TypeLiteral */) {
emitTypeOfVariableDeclarationFromTypeLiteral(node);
}
else if (!ts.hasModifier(node.parent, 8 /* Private */)) {
@@ -59173,24 +63639,29 @@ var ts;
}
function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
switch (node.parent.kind) {
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
- case 154 /* ConstructSignature */:
+ case 155 /* ConstructSignature */:
// Interfaces cannot have parameter types that cannot be named
return symbolAccessibilityResult.errorModuleName ?
ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
- case 153 /* CallSignature */:
+ case 154 /* CallSignature */:
// Interfaces cannot have parameter types that cannot be named
return symbolAccessibilityResult.errorModuleName ?
ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 156 /* IndexSignature */:
+ // Interfaces cannot have parameter types that cannot be named
+ return symbolAccessibilityResult.errorModuleName ?
+ ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
+ ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
if (ts.hasModifier(node.parent, 32 /* Static */)) {
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
@@ -59198,7 +63669,7 @@ var ts;
ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
}
- else if (node.parent.parent.kind === 226 /* ClassDeclaration */) {
+ else if (node.parent.parent.kind === 228 /* ClassDeclaration */) {
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
@@ -59211,7 +63682,7 @@ var ts;
ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
}
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
@@ -59223,12 +63694,12 @@ var ts;
}
function emitBindingPattern(bindingPattern) {
// We have to explicitly emit square bracket and bracket because these tokens are not store inside the node.
- if (bindingPattern.kind === 172 /* ObjectBindingPattern */) {
+ if (bindingPattern.kind === 173 /* ObjectBindingPattern */) {
write("{");
emitCommaList(bindingPattern.elements, emitBindingElement);
write("}");
}
- else if (bindingPattern.kind === 173 /* ArrayBindingPattern */) {
+ else if (bindingPattern.kind === 174 /* ArrayBindingPattern */) {
write("[");
var elements = bindingPattern.elements;
emitCommaList(elements, emitBindingElement);
@@ -59239,7 +63710,7 @@ var ts;
}
}
function emitBindingElement(bindingElement) {
- if (bindingElement.kind === 198 /* OmittedExpression */) {
+ if (bindingElement.kind === 199 /* OmittedExpression */) {
// If bindingElement is an omittedExpression (i.e. containing elision),
// we will emit blank space (although this may differ from users' original code,
// it allows emitSeparatedList to write separator appropriately)
@@ -59248,7 +63719,7 @@ var ts;
// emit : function foo([ , x, , ]) {}
write(" ");
}
- else if (bindingElement.kind === 174 /* BindingElement */) {
+ else if (bindingElement.kind === 175 /* BindingElement */) {
if (bindingElement.propertyName) {
// bindingElement has propertyName property in the following case:
// { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y"
@@ -59287,40 +63758,40 @@ var ts;
}
function emitNode(node) {
switch (node.kind) {
- case 225 /* FunctionDeclaration */:
- case 230 /* ModuleDeclaration */:
- case 234 /* ImportEqualsDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 226 /* ClassDeclaration */:
- case 228 /* TypeAliasDeclaration */:
- case 229 /* EnumDeclaration */:
+ case 227 /* FunctionDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
+ case 231 /* EnumDeclaration */:
return emitModuleElement(node, isModuleElementVisible(node));
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
return emitModuleElement(node, isVariableStatementVisible(node));
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
// Import declaration without import clause is visible, otherwise it is not visible
return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause);
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
return emitExportDeclaration(node);
- case 150 /* Constructor */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
return writeFunctionDeclaration(node);
- case 154 /* ConstructSignature */:
- case 153 /* CallSignature */:
- case 155 /* IndexSignature */:
+ case 155 /* ConstructSignature */:
+ case 154 /* CallSignature */:
+ case 156 /* IndexSignature */:
return emitSignatureDeclarationWithJsDocComments(node);
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
return emitAccessorDeclaration(node);
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
return emitPropertyDeclaration(node);
- case 260 /* EnumMember */:
+ case 263 /* EnumMember */:
return emitEnumMemberDeclaration(node);
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
return emitExportAssignment(node);
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
return emitSourceFile(node);
}
}
@@ -59338,7 +63809,7 @@ var ts;
}
else {
// Get the declaration file path
- ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles);
+ ts.forEachEmittedFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles);
}
if (declFileName) {
declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName,
@@ -59346,8 +63817,9 @@ var ts;
referencesOutput += "/// <reference path=\"" + declFileName + "\" />" + newLine;
}
return addedBundledEmitReference;
- function getDeclFileName(emitFileNames, _sourceFiles, isBundledEmit) {
+ function getDeclFileName(emitFileNames, sourceFileOrBundle) {
// Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path
+ var isBundledEmit = sourceFileOrBundle.kind === 265 /* Bundle */;
if (isBundledEmit && !addBundledFileReference) {
return;
}
@@ -59358,10 +63830,11 @@ var ts;
}
}
/* @internal */
- function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) {
- var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles);
+ function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) {
+ var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles);
var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
if (!emitSkipped) {
+ var sourceFiles = sourceFileOrBundle.kind === 265 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle];
var declarationOutput = emitDeclarationResult.referencesOutput
+ getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo);
ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles);
@@ -59384,83 +63857,73 @@ var ts;
}
ts.writeDeclarationFile = writeDeclarationFile;
})(ts || (ts = {}));
-/// <reference path="checker.ts"/>
+/// <reference path="checker.ts" />
/// <reference path="transformer.ts" />
-/// <reference path="declarationEmitter.ts"/>
-/// <reference path="sourcemap.ts"/>
+/// <reference path="declarationEmitter.ts" />
+/// <reference path="sourcemap.ts" />
/// <reference path="comments.ts" />
-/* @internal */
var ts;
(function (ts) {
- // Flags enum to track count of temp variables and a few dedicated names
- var TempFlags;
- (function (TempFlags) {
- TempFlags[TempFlags["Auto"] = 0] = "Auto";
- TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
- TempFlags[TempFlags["_i"] = 268435456] = "_i";
- })(TempFlags || (TempFlags = {}));
- var id = function (s) { return s; };
- var nullTransformers = [function (_) { return id; }];
+ var delimiters = createDelimiterMap();
+ var brackets = createBracketsMap();
+ /*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) {
- var delimiters = createDelimiterMap();
- var brackets = createBracketsMap();
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) {
var compilerOptions = host.getCompilerOptions();
- var languageVersion = ts.getEmitScriptTarget(compilerOptions);
var moduleKind = ts.getEmitModuleKind(compilerOptions);
var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
var emitterDiagnostics = ts.createDiagnosticCollection();
var newLine = host.getNewLine();
- var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions);
var writer = ts.createTextWriter(newLine);
- var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent;
var sourceMap = ts.createSourceMapWriter(host, writer);
- var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap;
- var comments = ts.createCommentWriter(host, writer, sourceMap);
- var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition;
- var nodeIdToGeneratedName;
- var autoGeneratedIdToGeneratedName;
- var generatedNameSet;
- var tempFlags;
var currentSourceFile;
- var currentText;
- var currentFileIdentifiers;
var bundledHelpers;
var isOwnFileEmit;
var emitSkipped = false;
var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile);
// Transform the source files
- ts.performance.mark("beforeTransform");
- var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification;
- ts.performance.measure("transformTime", "beforeTransform");
+ var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false);
+ // Create a printer to print the nodes
+ var printer = createPrinter(compilerOptions, {
+ // resolver hooks
+ hasGlobalName: resolver.hasGlobalName,
+ // transform hooks
+ onEmitNode: transform.emitNodeWithNotification,
+ substituteNode: transform.substituteNode,
+ // sourcemap hooks
+ onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap,
+ onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap,
+ onEmitSourceMapOfPosition: sourceMap.emitPos,
+ // emitter hooks
+ onEmitHelpers: emitHelpers,
+ onSetSourceFile: setSourceFile,
+ });
// Emit each output file
ts.performance.mark("beforePrint");
- ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles);
+ ts.forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles);
ts.performance.measure("printTime", "beforePrint");
// Clean up emit nodes on parse tree
- for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) {
- var sourceFile = sourceFiles_4[_b];
- ts.disposeEmitNodes(sourceFile);
- }
+ transform.dispose();
return {
emitSkipped: emitSkipped,
diagnostics: emitterDiagnostics.getDiagnostics(),
emittedFiles: emittedFilesList,
sourceMaps: sourceMapDataList
};
- function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) {
+ function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath;
// Make sure not to write js file and source map file if any of them cannot be written
if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) {
if (!emitOnlyDtsFiles) {
- printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle);
}
}
else {
emitSkipped = true;
}
if (declarationFilePath) {
- emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped;
+ emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped;
}
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
@@ -59474,26 +63937,24 @@ var ts;
}
}
}
- function printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) {
- sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit);
- nodeIdToGeneratedName = [];
- autoGeneratedIdToGeneratedName = [];
- generatedNameSet = ts.createMap();
- bundledHelpers = isBundledEmit ? ts.createMap() : undefined;
- isOwnFileEmit = !isBundledEmit;
- // Emit helpers from all the files
- if (isBundledEmit && moduleKind) {
- for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) {
- var sourceFile = sourceFiles_5[_a];
- emitHelpers(sourceFile, /*isBundle*/ true);
- }
- }
- // Print each transformed source file.
- ts.forEach(sourceFiles, printSourceFile);
- writeLine();
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) {
+ var bundle = sourceFileOrBundle.kind === 265 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 264 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
+ sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle);
+ if (bundle) {
+ bundledHelpers = ts.createMap();
+ isOwnFileEmit = false;
+ printer.writeBundle(bundle, writer);
+ }
+ else {
+ isOwnFileEmit = true;
+ printer.writeFile(sourceFile, writer);
+ }
+ writer.writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
- write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
+ writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
}
// Write the source map
if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) {
@@ -59507,138 +63968,232 @@ var ts;
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles);
// Reset state
sourceMap.reset();
- comments.reset();
writer.reset();
- tempFlags = 0 /* Auto */;
currentSourceFile = undefined;
- currentText = undefined;
+ bundledHelpers = undefined;
isOwnFileEmit = false;
}
- function printSourceFile(node) {
+ function setSourceFile(node) {
currentSourceFile = node;
- currentText = node.text;
- currentFileIdentifiers = node.identifiers;
sourceMap.setSourceFile(node);
- comments.setSourceFile(node);
- pipelineEmitWithNotification(0 /* SourceFile */, node);
}
- /**
- * Emits a node.
- */
+ function emitHelpers(node, writeLines) {
+ var helpersEmitted = false;
+ var bundle = node.kind === 265 /* Bundle */ ? node : undefined;
+ if (bundle && moduleKind === ts.ModuleKind.None) {
+ return;
+ }
+ var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ for (var i = 0; i < numNodes; i++) {
+ var currentNode = bundle ? bundle.sourceFiles[i] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
+ var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
+ var helpers = ts.getEmitHelpers(currentNode);
+ if (helpers) {
+ for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
+ var helper = _b[_a];
+ if (!helper.scoped) {
+ // Skip the helper if it can be skipped and the noEmitHelpers compiler
+ // option is set, or if it can be imported and the importHelpers compiler
+ // option is set.
+ if (shouldSkip)
+ continue;
+ // Skip the helper if it can be bundled but hasn't already been emitted and we
+ // are emitting a bundled module.
+ if (shouldBundle) {
+ if (bundledHelpers.get(helper.name)) {
+ continue;
+ }
+ bundledHelpers.set(helper.name, true);
+ }
+ }
+ else if (bundle) {
+ // Skip the helper if it is scoped and we are emitting bundled helpers
+ continue;
+ }
+ writeLines(helper.text);
+ helpersEmitted = true;
+ }
+ }
+ }
+ return helpersEmitted;
+ }
+ }
+ ts.emitFiles = emitFiles;
+ function createPrinter(printerOptions, handlers) {
+ if (printerOptions === void 0) { printerOptions = {}; }
+ if (handlers === void 0) { handlers = {}; }
+ var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray;
+ var newLine = ts.getNewLineCharacter(printerOptions);
+ var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition);
+ var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition;
+ var currentSourceFile;
+ var nodeIdToGeneratedName; // Map of generated names for specific nodes.
+ var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
+ var generatedNames; // Set of names generated by the NameGenerator.
+ var tempFlagsStack; // Stack of enclosing name generation scopes.
+ var tempFlags; // TempFlags for the current name generation scope.
+ var writer;
+ var ownWriter;
+ reset();
+ return {
+ // public API
+ printNode: printNode,
+ printFile: printFile,
+ printBundle: printBundle,
+ // internal API
+ writeNode: writeNode,
+ writeFile: writeFile,
+ writeBundle: writeBundle
+ };
+ function printNode(hint, node, sourceFile) {
+ switch (hint) {
+ case 0 /* SourceFile */:
+ ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
+ break;
+ case 2 /* IdentifierName */:
+ ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
+ break;
+ case 1 /* Expression */:
+ ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
+ break;
+ }
+ switch (node.kind) {
+ case 264 /* SourceFile */: return printFile(node);
+ case 265 /* Bundle */: return printBundle(node);
+ }
+ writeNode(hint, node, sourceFile, beginPrint());
+ return endPrint();
+ }
+ function printBundle(bundle) {
+ writeBundle(bundle, beginPrint());
+ return endPrint();
+ }
+ function printFile(sourceFile) {
+ writeFile(sourceFile, beginPrint());
+ return endPrint();
+ }
+ function writeNode(hint, node, sourceFile, output) {
+ var previousWriter = writer;
+ setWriter(output);
+ print(hint, node, sourceFile);
+ reset();
+ writer = previousWriter;
+ }
+ function writeBundle(bundle, output) {
+ var previousWriter = writer;
+ setWriter(output);
+ emitShebangIfNeeded(bundle);
+ emitPrologueDirectivesIfNeeded(bundle);
+ emitHelpersIndirect(bundle);
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ print(0 /* SourceFile */, sourceFile, sourceFile);
+ }
+ reset();
+ writer = previousWriter;
+ }
+ function writeFile(sourceFile, output) {
+ var previousWriter = writer;
+ setWriter(output);
+ emitShebangIfNeeded(sourceFile);
+ emitPrologueDirectivesIfNeeded(sourceFile);
+ print(0 /* SourceFile */, sourceFile, sourceFile);
+ reset();
+ writer = previousWriter;
+ }
+ function beginPrint() {
+ return ownWriter || (ownWriter = ts.createTextWriter(newLine));
+ }
+ function endPrint() {
+ var text = ownWriter.getText();
+ ownWriter.reset();
+ return text;
+ }
+ function print(hint, node, sourceFile) {
+ setSourceFile(sourceFile);
+ pipelineEmitWithNotification(hint, node);
+ }
+ function setSourceFile(sourceFile) {
+ currentSourceFile = sourceFile;
+ comments.setSourceFile(sourceFile);
+ if (onSetSourceFile) {
+ onSetSourceFile(sourceFile);
+ }
+ }
+ function setWriter(output) {
+ writer = output;
+ comments.setWriter(output);
+ }
+ function reset() {
+ nodeIdToGeneratedName = [];
+ autoGeneratedIdToGeneratedName = [];
+ generatedNames = ts.createMap();
+ tempFlagsStack = [];
+ tempFlags = 0 /* Auto */;
+ comments.reset();
+ setWriter(/*output*/ undefined);
+ }
function emit(node) {
pipelineEmitWithNotification(3 /* Unspecified */, node);
}
- /**
- * Emits an IdentifierName.
- */
function emitIdentifierName(node) {
pipelineEmitWithNotification(2 /* IdentifierName */, node);
}
- /**
- * Emits an expression node.
- */
function emitExpression(node) {
pipelineEmitWithNotification(1 /* Expression */, node);
}
- /**
- * Emits a node with possible notification.
- *
- * NOTE: Do not call this method directly. It is part of the emit pipeline
- * and should only be called from printSourceFile, emit, emitExpression, or
- * emitIdentifierName.
- */
- function pipelineEmitWithNotification(emitContext, node) {
- emitNodeWithNotification(emitContext, node, pipelineEmitWithComments);
- }
- /**
- * Emits a node with comments.
- *
- * NOTE: Do not call this method directly. It is part of the emit pipeline
- * and should only be called indirectly from pipelineEmitWithNotification.
- */
- function pipelineEmitWithComments(emitContext, node) {
- // Do not emit comments for SourceFile
- if (emitContext === 0 /* SourceFile */) {
- pipelineEmitWithSourceMap(emitContext, node);
- return;
+ function pipelineEmitWithNotification(hint, node) {
+ if (onEmitNode) {
+ onEmitNode(hint, node, pipelineEmitWithComments);
}
- emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap);
- }
- /**
- * Emits a node with source maps.
- *
- * NOTE: Do not call this method directly. It is part of the emit pipeline
- * and should only be called indirectly from pipelineEmitWithComments.
- */
- function pipelineEmitWithSourceMap(emitContext, node) {
- // Do not emit source mappings for SourceFile or IdentifierName
- if (emitContext === 0 /* SourceFile */
- || emitContext === 2 /* IdentifierName */) {
- pipelineEmitWithSubstitution(emitContext, node);
- return;
+ else {
+ pipelineEmitWithComments(hint, node);
}
- emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution);
- }
- /**
- * Emits a node with possible substitution.
- *
- * NOTE: Do not call this method directly. It is part of the emit pipeline
- * and should only be called indirectly from pipelineEmitWithSourceMap or
- * pipelineEmitInUnspecifiedContext (when picking a more specific context).
- */
- function pipelineEmitWithSubstitution(emitContext, node) {
- emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext);
}
- /**
- * Emits a node.
- *
- * NOTE: Do not call this method directly. It is part of the emit pipeline
- * and should only be called indirectly from pipelineEmitWithSubstitution.
- */
- function pipelineEmitForContext(emitContext, node) {
- switch (emitContext) {
- case 0 /* SourceFile */: return pipelineEmitInSourceFileContext(node);
- case 2 /* IdentifierName */: return pipelineEmitInIdentifierNameContext(node);
- case 3 /* Unspecified */: return pipelineEmitInUnspecifiedContext(node);
- case 1 /* Expression */: return pipelineEmitInExpressionContext(node);
+ function pipelineEmitWithComments(hint, node) {
+ node = trySubstituteNode(hint, node);
+ if (emitNodeWithComments && hint !== 0 /* SourceFile */) {
+ emitNodeWithComments(hint, node, pipelineEmitWithSourceMap);
+ }
+ else {
+ pipelineEmitWithSourceMap(hint, node);
}
}
- /**
- * Emits a node in the SourceFile EmitContext.
- *
- * NOTE: Do not call this method directly. It is part of the emit pipeline
- * and should only be called indirectly from pipelineEmitForContext.
- */
- function pipelineEmitInSourceFileContext(node) {
- var kind = node.kind;
- switch (kind) {
- // Top-level nodes
- case 261 /* SourceFile */:
- return emitSourceFile(node);
+ function pipelineEmitWithSourceMap(hint, node) {
+ if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) {
+ onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
+ }
+ else {
+ pipelineEmitWithHint(hint, node);
}
}
- /**
- * Emits a node in the IdentifierName EmitContext.
- *
- * NOTE: Do not call this method directly. It is part of the emit pipeline
- * and should only be called indirectly from pipelineEmitForContext.
- */
- function pipelineEmitInIdentifierNameContext(node) {
- var kind = node.kind;
- switch (kind) {
- // Identifiers
- case 70 /* Identifier */:
- return emitIdentifier(node);
+ function pipelineEmitWithHint(hint, node) {
+ switch (hint) {
+ case 0 /* SourceFile */: return pipelineEmitSourceFile(node);
+ case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node);
+ case 1 /* Expression */: return pipelineEmitExpression(node);
+ case 3 /* Unspecified */: return pipelineEmitUnspecified(node);
}
}
- /**
- * Emits a node in the Unspecified EmitContext.
- *
- * NOTE: Do not call this method directly. It is part of the emit pipeline
- * and should only be called indirectly from pipelineEmitForContext.
- */
- function pipelineEmitInUnspecifiedContext(node) {
+ function pipelineEmitSourceFile(node) {
+ ts.Debug.assertNode(node, ts.isSourceFile);
+ emitSourceFile(node);
+ }
+ function pipelineEmitIdentifierName(node) {
+ ts.Debug.assertNode(node, ts.isIdentifier);
+ emitIdentifier(node);
+ }
+ function pipelineEmitUnspecified(node) {
var kind = node.kind;
+ // Reserved words
+ // Strict mode reserved words
+ // Contextual keywords
+ if (ts.isKeyword(kind)) {
+ writeTokenText(kind);
+ return;
+ }
switch (kind) {
// Pseudo-literals
case 13 /* TemplateHead */:
@@ -59648,254 +64203,217 @@ var ts;
// Identifiers
case 70 /* Identifier */:
return emitIdentifier(node);
- // Reserved words
- case 75 /* ConstKeyword */:
- case 78 /* DefaultKeyword */:
- case 83 /* ExportKeyword */:
- case 104 /* VoidKeyword */:
- // Strict mode reserved words
- case 111 /* PrivateKeyword */:
- case 112 /* ProtectedKeyword */:
- case 113 /* PublicKeyword */:
- case 114 /* StaticKeyword */:
- // Contextual keywords
- case 116 /* AbstractKeyword */:
- case 117 /* AsKeyword */:
- case 118 /* AnyKeyword */:
- case 119 /* AsyncKeyword */:
- case 120 /* AwaitKeyword */:
- case 121 /* BooleanKeyword */:
- case 122 /* ConstructorKeyword */:
- case 123 /* DeclareKeyword */:
- case 124 /* GetKeyword */:
- case 125 /* IsKeyword */:
- case 127 /* ModuleKeyword */:
- case 128 /* NamespaceKeyword */:
- case 129 /* NeverKeyword */:
- case 130 /* ReadonlyKeyword */:
- case 131 /* RequireKeyword */:
- case 132 /* NumberKeyword */:
- case 133 /* SetKeyword */:
- case 134 /* StringKeyword */:
- case 135 /* SymbolKeyword */:
- case 136 /* TypeKeyword */:
- case 137 /* UndefinedKeyword */:
- case 138 /* FromKeyword */:
- case 139 /* GlobalKeyword */:
- case 140 /* OfKeyword */:
- writeTokenText(kind);
- return;
// Parse tree nodes
// Names
- case 141 /* QualifiedName */:
+ case 142 /* QualifiedName */:
return emitQualifiedName(node);
- case 142 /* ComputedPropertyName */:
+ case 143 /* ComputedPropertyName */:
return emitComputedPropertyName(node);
// Signature elements
- case 143 /* TypeParameter */:
+ case 144 /* TypeParameter */:
return emitTypeParameter(node);
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
return emitParameter(node);
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
return emitDecorator(node);
// Type members
- case 146 /* PropertySignature */:
+ case 147 /* PropertySignature */:
return emitPropertySignature(node);
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
return emitPropertyDeclaration(node);
- case 148 /* MethodSignature */:
+ case 149 /* MethodSignature */:
return emitMethodSignature(node);
- case 149 /* MethodDeclaration */:
+ case 150 /* MethodDeclaration */:
return emitMethodDeclaration(node);
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
return emitConstructor(node);
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
return emitAccessorDeclaration(node);
- case 153 /* CallSignature */:
+ case 154 /* CallSignature */:
return emitCallSignature(node);
- case 154 /* ConstructSignature */:
+ case 155 /* ConstructSignature */:
return emitConstructSignature(node);
- case 155 /* IndexSignature */:
+ case 156 /* IndexSignature */:
return emitIndexSignature(node);
// Types
- case 156 /* TypePredicate */:
+ case 157 /* TypePredicate */:
return emitTypePredicate(node);
- case 157 /* TypeReference */:
+ case 158 /* TypeReference */:
return emitTypeReference(node);
- case 158 /* FunctionType */:
+ case 159 /* FunctionType */:
return emitFunctionType(node);
- case 159 /* ConstructorType */:
+ case 160 /* ConstructorType */:
return emitConstructorType(node);
- case 160 /* TypeQuery */:
+ case 161 /* TypeQuery */:
return emitTypeQuery(node);
- case 161 /* TypeLiteral */:
+ case 162 /* TypeLiteral */:
return emitTypeLiteral(node);
- case 162 /* ArrayType */:
+ case 163 /* ArrayType */:
return emitArrayType(node);
- case 163 /* TupleType */:
+ case 164 /* TupleType */:
return emitTupleType(node);
- case 164 /* UnionType */:
+ case 165 /* UnionType */:
return emitUnionType(node);
- case 165 /* IntersectionType */:
+ case 166 /* IntersectionType */:
return emitIntersectionType(node);
- case 166 /* ParenthesizedType */:
+ case 167 /* ParenthesizedType */:
return emitParenthesizedType(node);
- case 199 /* ExpressionWithTypeArguments */:
+ case 200 /* ExpressionWithTypeArguments */:
return emitExpressionWithTypeArguments(node);
- case 167 /* ThisType */:
+ case 168 /* ThisType */:
return emitThisType();
- case 168 /* TypeOperator */:
+ case 169 /* TypeOperator */:
return emitTypeOperator(node);
- case 169 /* IndexedAccessType */:
+ case 170 /* IndexedAccessType */:
return emitIndexedAccessType(node);
- case 170 /* MappedType */:
+ case 171 /* MappedType */:
return emitMappedType(node);
- case 171 /* LiteralType */:
+ case 172 /* LiteralType */:
return emitLiteralType(node);
// Binding patterns
- case 172 /* ObjectBindingPattern */:
+ case 173 /* ObjectBindingPattern */:
return emitObjectBindingPattern(node);
- case 173 /* ArrayBindingPattern */:
+ case 174 /* ArrayBindingPattern */:
return emitArrayBindingPattern(node);
- case 174 /* BindingElement */:
+ case 175 /* BindingElement */:
return emitBindingElement(node);
// Misc
- case 202 /* TemplateSpan */:
+ case 204 /* TemplateSpan */:
return emitTemplateSpan(node);
- case 203 /* SemicolonClassElement */:
+ case 205 /* SemicolonClassElement */:
return emitSemicolonClassElement();
// Statements
- case 204 /* Block */:
+ case 206 /* Block */:
return emitBlock(node);
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
return emitVariableStatement(node);
- case 206 /* EmptyStatement */:
+ case 208 /* EmptyStatement */:
return emitEmptyStatement();
- case 207 /* ExpressionStatement */:
+ case 209 /* ExpressionStatement */:
return emitExpressionStatement(node);
- case 208 /* IfStatement */:
+ case 210 /* IfStatement */:
return emitIfStatement(node);
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
return emitDoStatement(node);
- case 210 /* WhileStatement */:
+ case 212 /* WhileStatement */:
return emitWhileStatement(node);
- case 211 /* ForStatement */:
+ case 213 /* ForStatement */:
return emitForStatement(node);
- case 212 /* ForInStatement */:
+ case 214 /* ForInStatement */:
return emitForInStatement(node);
- case 213 /* ForOfStatement */:
+ case 215 /* ForOfStatement */:
return emitForOfStatement(node);
- case 214 /* ContinueStatement */:
+ case 216 /* ContinueStatement */:
return emitContinueStatement(node);
- case 215 /* BreakStatement */:
+ case 217 /* BreakStatement */:
return emitBreakStatement(node);
- case 216 /* ReturnStatement */:
+ case 218 /* ReturnStatement */:
return emitReturnStatement(node);
- case 217 /* WithStatement */:
+ case 219 /* WithStatement */:
return emitWithStatement(node);
- case 218 /* SwitchStatement */:
+ case 220 /* SwitchStatement */:
return emitSwitchStatement(node);
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
return emitLabeledStatement(node);
- case 220 /* ThrowStatement */:
+ case 222 /* ThrowStatement */:
return emitThrowStatement(node);
- case 221 /* TryStatement */:
+ case 223 /* TryStatement */:
return emitTryStatement(node);
- case 222 /* DebuggerStatement */:
+ case 224 /* DebuggerStatement */:
return emitDebuggerStatement(node);
// Declarations
- case 223 /* VariableDeclaration */:
+ case 225 /* VariableDeclaration */:
return emitVariableDeclaration(node);
- case 224 /* VariableDeclarationList */:
+ case 226 /* VariableDeclarationList */:
return emitVariableDeclarationList(node);
- case 225 /* FunctionDeclaration */:
+ case 227 /* FunctionDeclaration */:
return emitFunctionDeclaration(node);
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
return emitClassDeclaration(node);
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
return emitInterfaceDeclaration(node);
- case 228 /* TypeAliasDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
return emitTypeAliasDeclaration(node);
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
return emitEnumDeclaration(node);
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return emitModuleDeclaration(node);
- case 231 /* ModuleBlock */:
+ case 233 /* ModuleBlock */:
return emitModuleBlock(node);
- case 232 /* CaseBlock */:
+ case 234 /* CaseBlock */:
return emitCaseBlock(node);
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
return emitImportEqualsDeclaration(node);
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
return emitImportDeclaration(node);
- case 236 /* ImportClause */:
+ case 238 /* ImportClause */:
return emitImportClause(node);
- case 237 /* NamespaceImport */:
+ case 239 /* NamespaceImport */:
return emitNamespaceImport(node);
- case 238 /* NamedImports */:
+ case 240 /* NamedImports */:
return emitNamedImports(node);
- case 239 /* ImportSpecifier */:
+ case 241 /* ImportSpecifier */:
return emitImportSpecifier(node);
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
return emitExportAssignment(node);
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
return emitExportDeclaration(node);
- case 242 /* NamedExports */:
+ case 244 /* NamedExports */:
return emitNamedExports(node);
- case 243 /* ExportSpecifier */:
+ case 245 /* ExportSpecifier */:
return emitExportSpecifier(node);
- case 244 /* MissingDeclaration */:
+ case 246 /* MissingDeclaration */:
return;
// Module references
- case 245 /* ExternalModuleReference */:
+ case 247 /* ExternalModuleReference */:
return emitExternalModuleReference(node);
// JSX (non-expression)
case 10 /* JsxText */:
return emitJsxText(node);
- case 248 /* JsxOpeningElement */:
+ case 250 /* JsxOpeningElement */:
return emitJsxOpeningElement(node);
- case 249 /* JsxClosingElement */:
+ case 251 /* JsxClosingElement */:
return emitJsxClosingElement(node);
- case 250 /* JsxAttribute */:
+ case 252 /* JsxAttribute */:
return emitJsxAttribute(node);
- case 251 /* JsxSpreadAttribute */:
+ case 253 /* JsxAttributes */:
+ return emitJsxAttributes(node);
+ case 254 /* JsxSpreadAttribute */:
return emitJsxSpreadAttribute(node);
- case 252 /* JsxExpression */:
+ case 255 /* JsxExpression */:
return emitJsxExpression(node);
// Clauses
- case 253 /* CaseClause */:
+ case 256 /* CaseClause */:
return emitCaseClause(node);
- case 254 /* DefaultClause */:
+ case 257 /* DefaultClause */:
return emitDefaultClause(node);
- case 255 /* HeritageClause */:
+ case 258 /* HeritageClause */:
return emitHeritageClause(node);
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return emitCatchClause(node);
// Property assignments
- case 257 /* PropertyAssignment */:
+ case 260 /* PropertyAssignment */:
return emitPropertyAssignment(node);
- case 258 /* ShorthandPropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
return emitShorthandPropertyAssignment(node);
- case 259 /* SpreadAssignment */:
+ case 262 /* SpreadAssignment */:
return emitSpreadAssignment(node);
// Enum
- case 260 /* EnumMember */:
+ case 263 /* EnumMember */:
return emitEnumMember(node);
}
// If the node is an expression, try to emit it as an expression with
// substitution.
if (ts.isExpression(node)) {
- return pipelineEmitWithSubstitution(1 /* Expression */, node);
+ return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node));
+ }
+ if (ts.isToken(node)) {
+ writeTokenText(kind);
+ return;
}
}
- /**
- * Emits a node in the Expression EmitContext.
- *
- * NOTE: Do not call this method directly. It is part of the emit pipeline
- * and should only be called indirectly from pipelineEmitForContext.
- */
- function pipelineEmitInExpressionContext(node) {
+ function pipelineEmitExpression(node) {
var kind = node.kind;
switch (kind) {
// Literals
@@ -59917,68 +64435,76 @@ var ts;
writeTokenText(kind);
return;
// Expressions
- case 175 /* ArrayLiteralExpression */:
+ case 176 /* ArrayLiteralExpression */:
return emitArrayLiteralExpression(node);
- case 176 /* ObjectLiteralExpression */:
+ case 177 /* ObjectLiteralExpression */:
return emitObjectLiteralExpression(node);
- case 177 /* PropertyAccessExpression */:
+ case 178 /* PropertyAccessExpression */:
return emitPropertyAccessExpression(node);
- case 178 /* ElementAccessExpression */:
+ case 179 /* ElementAccessExpression */:
return emitElementAccessExpression(node);
- case 179 /* CallExpression */:
+ case 180 /* CallExpression */:
return emitCallExpression(node);
- case 180 /* NewExpression */:
+ case 181 /* NewExpression */:
return emitNewExpression(node);
- case 181 /* TaggedTemplateExpression */:
+ case 182 /* TaggedTemplateExpression */:
return emitTaggedTemplateExpression(node);
- case 182 /* TypeAssertionExpression */:
+ case 183 /* TypeAssertionExpression */:
return emitTypeAssertionExpression(node);
- case 183 /* ParenthesizedExpression */:
+ case 184 /* ParenthesizedExpression */:
return emitParenthesizedExpression(node);
- case 184 /* FunctionExpression */:
+ case 185 /* FunctionExpression */:
return emitFunctionExpression(node);
- case 185 /* ArrowFunction */:
+ case 186 /* ArrowFunction */:
return emitArrowFunction(node);
- case 186 /* DeleteExpression */:
+ case 187 /* DeleteExpression */:
return emitDeleteExpression(node);
- case 187 /* TypeOfExpression */:
+ case 188 /* TypeOfExpression */:
return emitTypeOfExpression(node);
- case 188 /* VoidExpression */:
+ case 189 /* VoidExpression */:
return emitVoidExpression(node);
- case 189 /* AwaitExpression */:
+ case 190 /* AwaitExpression */:
return emitAwaitExpression(node);
- case 190 /* PrefixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
return emitPrefixUnaryExpression(node);
- case 191 /* PostfixUnaryExpression */:
+ case 192 /* PostfixUnaryExpression */:
return emitPostfixUnaryExpression(node);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return emitBinaryExpression(node);
- case 193 /* ConditionalExpression */:
+ case 194 /* ConditionalExpression */:
return emitConditionalExpression(node);
- case 194 /* TemplateExpression */:
+ case 195 /* TemplateExpression */:
return emitTemplateExpression(node);
- case 195 /* YieldExpression */:
+ case 196 /* YieldExpression */:
return emitYieldExpression(node);
- case 196 /* SpreadElement */:
+ case 197 /* SpreadElement */:
return emitSpreadExpression(node);
- case 197 /* ClassExpression */:
+ case 198 /* ClassExpression */:
return emitClassExpression(node);
- case 198 /* OmittedExpression */:
+ case 199 /* OmittedExpression */:
return;
- case 200 /* AsExpression */:
+ case 201 /* AsExpression */:
return emitAsExpression(node);
- case 201 /* NonNullExpression */:
+ case 202 /* NonNullExpression */:
return emitNonNullExpression(node);
+ case 203 /* MetaProperty */:
+ return emitMetaProperty(node);
// JSX
- case 246 /* JsxElement */:
+ case 248 /* JsxElement */:
return emitJsxElement(node);
- case 247 /* JsxSelfClosingElement */:
+ case 249 /* JsxSelfClosingElement */:
return emitJsxSelfClosingElement(node);
// Transformation nodes
- case 294 /* PartiallyEmittedExpression */:
+ case 295 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 297 /* RawExpression */:
- return writeLines(node.text);
+ }
+ }
+ function trySubstituteNode(hint, node) {
+ return node && substituteNode && substituteNode(hint, node) || node;
+ }
+ function emitHelpersIndirect(node) {
+ if (onEmitHelpers) {
+ onEmitHelpers(node, writeLines);
}
}
//
@@ -59987,9 +64513,6 @@ var ts;
// SyntaxKind.NumericLiteral
function emitNumericLiteral(node) {
emitLiteral(node);
- if (node.trailingComment) {
- write(" /*" + node.trailingComment + "*/");
- }
}
// SyntaxKind.StringLiteral
// SyntaxKind.RegularExpressionLiteral
@@ -59999,7 +64522,7 @@ var ts;
// SyntaxKind.TemplateTail
function emitLiteral(node) {
var text = getLiteralTextOfNode(node);
- if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap)
+ if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
&& (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
writer.writeLiteral(text);
}
@@ -60047,8 +64570,8 @@ var ts;
writeIfPresent(node.dotDotDotToken, "...");
emit(node.name);
writeIfPresent(node.questionToken, "?");
- emitExpressionWithPrefix(" = ", node.initializer);
emitWithPrefix(": ", node.type);
+ emitExpressionWithPrefix(" = ", node.initializer);
}
function emitDecorator(decorator) {
write("@");
@@ -60098,7 +64621,7 @@ var ts;
function emitAccessorDeclaration(node) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
- write(node.kind === 151 /* GetAccessor */ ? "get " : "set ");
+ write(node.kind === 152 /* GetAccessor */ ? "get " : "set ");
emit(node.name);
emitSignatureAndBody(node, emitSignatureHead);
}
@@ -60201,17 +64724,13 @@ var ts;
write("{");
writeLine();
increaseIndent();
- if (node.readonlyToken) {
- write("readonly ");
- }
+ writeIfPresent(node.readonlyToken, "readonly ");
write("[");
emit(node.typeParameter.name);
write(" in ");
emit(node.typeParameter.constraint);
write("]");
- if (node.questionToken) {
- write("?");
- }
+ writeIfPresent(node.questionToken, "?");
write(": ");
emit(node.type);
write(";");
@@ -60277,7 +64796,7 @@ var ts;
increaseIndent();
}
var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */;
- var allowTrailingComma = languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */;
+ var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */;
emitList(node, properties, 978 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
if (indentedFlag) {
decreaseIndent();
@@ -60289,7 +64808,7 @@ var ts;
var indentAfterDot = false;
if (!(ts.getEmitFlags(node) & 65536 /* NoIndentation */)) {
var dotRangeStart = node.expression.end;
- var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1;
+ var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1;
var dotToken = { kind: 22 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd };
indentBeforeDot = needsIndentation(node, node.expression, dotToken);
indentAfterDot = needsIndentation(node, dotToken, node.name);
@@ -60305,10 +64824,12 @@ var ts;
// 1..toString is a valid property access, emit a dot after the literal
// Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
function needsDotDotForPropertyAccess(expression) {
- if (expression.kind === 8 /* NumericLiteral */) {
- // check if numeric literal was originally written with a dot
+ expression = ts.skipPartiallyEmittedExpressions(expression);
+ if (ts.isNumericLiteral(expression)) {
+ // check if numeric literal is a decimal literal that was originally written with a dot
var text = getLiteralTextOfNode(expression);
- return text.indexOf(ts.tokenToString(22 /* DotToken */)) < 0;
+ return !expression.numericLiteralFlags
+ && text.indexOf(ts.tokenToString(22 /* DotToken */)) < 0;
}
else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) {
// check if constant enum value is integer
@@ -60316,7 +64837,7 @@ var ts;
// isFinite handles cases when constantValue is undefined
return isFinite(constantValue)
&& Math.floor(constantValue) === constantValue
- && compilerOptions.removeComments;
+ && printerOptions.removeComments;
}
}
function emitElementAccessExpression(node) {
@@ -60342,11 +64863,9 @@ var ts;
emitExpression(node.template);
}
function emitTypeAssertionExpression(node) {
- if (node.type) {
- write("<");
- emit(node.type);
- write(">");
- }
+ write("<");
+ emit(node.type);
+ write(">");
emitExpression(node.expression);
}
function emitParenthesizedExpression(node) {
@@ -60405,7 +64924,7 @@ var ts;
// expression a prefix increment whose operand is a plus expression - (++(+x))
// The same is true of minus of course.
var operand = node.operand;
- return operand.kind === 190 /* PrefixUnaryExpression */
+ return operand.kind === 191 /* PrefixUnaryExpression */
&& ((node.operator === 36 /* PlusToken */ && (operand.operator === 36 /* PlusToken */ || operand.operator === 42 /* PlusPlusToken */))
|| (node.operator === 37 /* MinusToken */ && (operand.operator === 37 /* MinusToken */ || operand.operator === 43 /* MinusMinusToken */)));
}
@@ -60471,6 +64990,11 @@ var ts;
emitExpression(node.expression);
write("!");
}
+ function emitMetaProperty(node) {
+ writeToken(node.keywordToken, node.pos);
+ write(".");
+ emit(node.name);
+ }
//
// Misc
//
@@ -60490,6 +65014,10 @@ var ts;
else {
writeToken(16 /* OpenBraceToken */, node.pos, /*contextNode*/ node);
emitBlockStatements(node);
+ // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted
+ increaseIndent();
+ emitLeadingCommentsOfPosition(node.statements.end);
+ decreaseIndent();
writeToken(17 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node);
}
}
@@ -60519,27 +65047,27 @@ var ts;
writeToken(18 /* OpenParenToken */, openParenPos, node);
emitExpression(node.expression);
writeToken(19 /* CloseParenToken */, node.expression.end, node);
- emitEmbeddedStatement(node.thenStatement);
+ emitEmbeddedStatement(node, node.thenStatement);
if (node.elseStatement) {
- writeLine();
+ writeLineOrSpace(node);
writeToken(81 /* ElseKeyword */, node.thenStatement.end, node);
- if (node.elseStatement.kind === 208 /* IfStatement */) {
+ if (node.elseStatement.kind === 210 /* IfStatement */) {
write(" ");
emit(node.elseStatement);
}
else {
- emitEmbeddedStatement(node.elseStatement);
+ emitEmbeddedStatement(node, node.elseStatement);
}
}
}
function emitDoStatement(node) {
write("do");
- emitEmbeddedStatement(node.statement);
+ emitEmbeddedStatement(node, node.statement);
if (ts.isBlock(node.statement)) {
write(" ");
}
else {
- writeLine();
+ writeLineOrSpace(node);
}
write("while (");
emitExpression(node.expression);
@@ -60549,7 +65077,7 @@ var ts;
write("while (");
emitExpression(node.expression);
write(")");
- emitEmbeddedStatement(node.statement);
+ emitEmbeddedStatement(node, node.statement);
}
function emitForStatement(node) {
var openParenPos = writeToken(87 /* ForKeyword */, node.pos);
@@ -60561,7 +65089,7 @@ var ts;
write(";");
emitExpressionWithPrefix(" ", node.incrementor);
write(")");
- emitEmbeddedStatement(node.statement);
+ emitEmbeddedStatement(node, node.statement);
}
function emitForInStatement(node) {
var openParenPos = writeToken(87 /* ForKeyword */, node.pos);
@@ -60571,21 +65099,22 @@ var ts;
write(" in ");
emitExpression(node.expression);
writeToken(19 /* CloseParenToken */, node.expression.end);
- emitEmbeddedStatement(node.statement);
+ emitEmbeddedStatement(node, node.statement);
}
function emitForOfStatement(node) {
var openParenPos = writeToken(87 /* ForKeyword */, node.pos);
write(" ");
+ emitWithSuffix(node.awaitModifier, " ");
writeToken(18 /* OpenParenToken */, openParenPos);
emitForBinding(node.initializer);
write(" of ");
emitExpression(node.expression);
writeToken(19 /* CloseParenToken */, node.expression.end);
- emitEmbeddedStatement(node.statement);
+ emitEmbeddedStatement(node, node.statement);
}
function emitForBinding(node) {
if (node !== undefined) {
- if (node.kind === 224 /* VariableDeclarationList */) {
+ if (node.kind === 226 /* VariableDeclarationList */) {
emit(node);
}
else {
@@ -60612,7 +65141,7 @@ var ts;
write("with (");
emitExpression(node.expression);
write(")");
- emitEmbeddedStatement(node.statement);
+ emitEmbeddedStatement(node, node.statement);
}
function emitSwitchStatement(node) {
var openParenPos = writeToken(97 /* SwitchKeyword */, node.pos);
@@ -60636,9 +65165,12 @@ var ts;
function emitTryStatement(node) {
write("try ");
emit(node.tryBlock);
- emit(node.catchClause);
+ if (node.catchClause) {
+ writeLineOrSpace(node);
+ emit(node.catchClause);
+ }
if (node.finallyBlock) {
- writeLine();
+ writeLineOrSpace(node);
write("finally ");
emit(node.finallyBlock);
}
@@ -60669,6 +65201,9 @@ var ts;
emitIdentifierName(node.name);
emitSignatureAndBody(node, emitSignatureHead);
}
+ function emitBlockCallback(_hint, body) {
+ emitBlockFunctionBody(body);
+ }
function emitSignatureAndBody(node, emitSignatureHead) {
var body = node.body;
if (body) {
@@ -60679,14 +65214,23 @@ var ts;
}
if (ts.getEmitFlags(node) & 262144 /* ReuseTempVariableScope */) {
emitSignatureHead(node);
- emitBlockFunctionBody(body);
+ if (onEmitNode) {
+ onEmitNode(3 /* Unspecified */, body, emitBlockCallback);
+ }
+ else {
+ emitBlockFunctionBody(body);
+ }
}
else {
- var savedTempFlags = tempFlags;
- tempFlags = 0;
+ pushNameGenerationScope();
emitSignatureHead(node);
- emitBlockFunctionBody(body);
- tempFlags = savedTempFlags;
+ if (onEmitNode) {
+ onEmitNode(3 /* Unspecified */, body, emitBlockCallback);
+ }
+ else {
+ emitBlockFunctionBody(body);
+ }
+ popNameGenerationScope();
}
if (indentedFlag) {
decreaseIndent();
@@ -60741,9 +65285,15 @@ var ts;
function emitBlockFunctionBody(body) {
write(" {");
increaseIndent();
- emitBodyWithDetachedComments(body, body.statements, shouldEmitBlockFunctionBodyOnSingleLine(body)
+ var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
? emitBlockFunctionBodyOnSingleLine
- : emitBlockFunctionBodyWorker);
+ : emitBlockFunctionBodyWorker;
+ if (emitBodyWithDetachedComments) {
+ emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
+ }
+ else {
+ emitBlockFunctionBody(body);
+ }
decreaseIndent();
writeToken(17 /* CloseBraceToken */, body.statements.end, body);
}
@@ -60753,8 +65303,9 @@ var ts;
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
- var helpersEmitted = emitHelpers(body);
- if (statementOffset === 0 && !helpersEmitted && emitBlockFunctionBodyOnSingleLine) {
+ var pos = writer.getTextPos();
+ emitHelpersIndirect(body);
+ if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
decreaseIndent();
emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */);
increaseIndent();
@@ -60777,15 +65328,14 @@ var ts;
}
emitTypeParameters(node, node.typeParameters);
emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */);
- var savedTempFlags = tempFlags;
- tempFlags = 0;
+ pushNameGenerationScope();
write(" {");
emitList(node, node.members, 65 /* ClassMembers */);
write("}");
+ popNameGenerationScope();
if (indentedFlag) {
decreaseIndent();
}
- tempFlags = savedTempFlags;
}
function emitInterfaceDeclaration(node) {
emitDecorators(node, node.decorators);
@@ -60812,19 +65362,18 @@ var ts;
emitModifiers(node, node.modifiers);
write("enum ");
emit(node.name);
- var savedTempFlags = tempFlags;
- tempFlags = 0;
+ pushNameGenerationScope();
write(" {");
emitList(node, node.members, 81 /* EnumMembers */);
write("}");
- tempFlags = savedTempFlags;
+ popNameGenerationScope();
}
function emitModuleDeclaration(node) {
emitModifiers(node, node.modifiers);
write(node.flags & 16 /* Namespace */ ? "namespace " : "module ");
emit(node.name);
var body = node.body;
- while (body.kind === 230 /* ModuleDeclaration */) {
+ while (body.kind === 232 /* ModuleDeclaration */) {
write(".");
emit(body.name);
body = body.body;
@@ -60837,13 +65386,11 @@ var ts;
write("{ }");
}
else {
- var savedTempFlags = tempFlags;
- tempFlags = 0;
+ pushNameGenerationScope();
write("{");
- increaseIndent();
emitBlockStatements(node);
write("}");
- tempFlags = savedTempFlags;
+ popNameGenerationScope();
}
}
function emitCaseBlock(node) {
@@ -60951,14 +65498,20 @@ var ts;
write("<");
emitJsxTagName(node.tagName);
write(" ");
- emitList(node, node.attributes, 131328 /* JsxElementAttributes */);
+ // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap
+ if (node.attributes.properties && node.attributes.properties.length > 0) {
+ emit(node.attributes);
+ }
write("/>");
}
function emitJsxOpeningElement(node) {
write("<");
emitJsxTagName(node.tagName);
- writeIfAny(node.attributes, " ");
- emitList(node, node.attributes, 131328 /* JsxElementAttributes */);
+ writeIfAny(node.attributes.properties, " ");
+ // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap
+ if (node.attributes.properties && node.attributes.properties.length > 0) {
+ emit(node.attributes);
+ }
write(">");
}
function emitJsxText(node) {
@@ -60969,6 +65522,9 @@ var ts;
emitJsxTagName(node.tagName);
write(">");
}
+ function emitJsxAttributes(node) {
+ emitList(node, node.properties, 131328 /* JsxElementAttributes */);
+ }
function emitJsxAttribute(node) {
emit(node.name);
emitWithPrefix("=", node.initializer);
@@ -60981,6 +65537,9 @@ var ts;
function emitJsxExpression(node) {
if (node.expression) {
write("{");
+ if (node.dotDotDotToken) {
+ write("...");
+ }
emitExpression(node.expression);
write("}");
}
@@ -61028,7 +65587,6 @@ var ts;
emitList(node, node.types, 272 /* HeritageClauseTypes */);
}
function emitCatchClause(node) {
- writeLine();
var openParenPos = writeToken(73 /* CatchKeyword */, node.pos);
write(" ");
writeToken(18 /* OpenParenToken */, openParenPos);
@@ -61051,7 +65609,7 @@ var ts;
// "comment1" is not considered to be leading comment for node.initializer
// but rather a trailing comment on the previous node.
var initializer = node.initializer;
- if ((ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
+ if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
var commentRange = ts.getCommentRange(initializer);
emitTrailingCommentsOfPosition(commentRange.pos);
}
@@ -61082,17 +65640,27 @@ var ts;
//
function emitSourceFile(node) {
writeLine();
- emitShebang();
- emitBodyWithDetachedComments(node, node.statements, emitSourceFileWorker);
+ var statements = node.statements;
+ if (emitBodyWithDetachedComments) {
+ // Emit detached comment if there are no prologue directives or if the first node is synthesized.
+ // The synthesized node will have no leading comment so some comments may be missed.
+ var shouldEmitDetachedComment = statements.length === 0 ||
+ !ts.isPrologueDirective(statements[0]) ||
+ ts.nodeIsSynthesized(statements[0]);
+ if (shouldEmitDetachedComment) {
+ emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
+ return;
+ }
+ }
+ emitSourceFileWorker(node);
}
function emitSourceFileWorker(node) {
var statements = node.statements;
- var statementOffset = emitPrologueDirectives(statements);
- var savedTempFlags = tempFlags;
- tempFlags = 0;
- emitHelpers(node);
- emitList(node, statements, 1 /* MultiLine */, statementOffset);
- tempFlags = savedTempFlags;
+ pushNameGenerationScope();
+ emitHelpersIndirect(node);
+ var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
+ emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
+ popNameGenerationScope();
}
// Transformation nodes
function emitPartiallyEmittedExpression(node) {
@@ -61102,13 +65670,20 @@ var ts;
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine) {
+ function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
for (var i = 0; i < statements.length; i++) {
- if (ts.isPrologueDirective(statements[i])) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ var statement = statements[i];
+ if (ts.isPrologueDirective(statement)) {
+ var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
+ if (shouldEmitPrologueDirective) {
+ if (startWithNewLine || i > 0) {
+ writeLine();
+ }
+ emit(statement);
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(statement.expression.text, statement.expression.text);
+ }
}
- emit(statements[i]);
}
else {
// return index of the first non prologue directive
@@ -61117,81 +65692,42 @@ var ts;
}
return statements.length;
}
- function emitHelpers(node, isBundle) {
- var sourceFile = ts.isSourceFile(node) ? node : currentSourceFile;
- var shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
- var shouldBundle = ts.isSourceFile(node) && !isOwnFileEmit;
- var helpersEmitted = false;
- var helpers = ts.getEmitHelpers(node);
- if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
- if (!helper.scoped) {
- // Skip the helper if it can be skipped and the noEmitHelpers compiler
- // option is set, or if it can be imported and the importHelpers compiler
- // option is set.
- if (shouldSkip)
- continue;
- // Skip the helper if it can be bundled but hasn't already been emitted and we
- // are emitting a bundled module.
- if (shouldBundle) {
- if (bundledHelpers[helper.name]) {
- continue;
- }
- bundledHelpers[helper.name] = true;
- }
- }
- else if (isBundle) {
- // Skip the helper if it is scoped and we are emitting bundled helpers
- continue;
- }
- writeLines(helper.text);
- helpersEmitted = true;
- }
+ function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
+ if (ts.isSourceFile(sourceFileOrBundle)) {
+ setSourceFile(sourceFileOrBundle);
+ emitPrologueDirectives(sourceFileOrBundle.statements);
}
- if (helpersEmitted) {
- writeLine();
+ else {
+ var seenPrologueDirectives = ts.createMap();
+ for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ setSourceFile(sourceFile);
+ emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ }
}
- return helpersEmitted;
}
- function writeLines(text) {
- var lines = text.split(/\r\n?|\n/g);
- var indentation = guessIndentation(lines);
- for (var i = 0; i < lines.length; i++) {
- var line = indentation ? lines[i].slice(indentation) : lines[i];
- if (line.length) {
- if (i > 0) {
- writeLine();
- }
- write(line);
+ function emitShebangIfNeeded(sourceFileOrBundle) {
+ if (ts.isSourceFile(sourceFileOrBundle)) {
+ var shebang = ts.getShebang(sourceFileOrBundle.text);
+ if (shebang) {
+ write(shebang);
+ writeLine();
+ return true;
}
}
- }
- function guessIndentation(lines) {
- var indentation;
- for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) {
- var line = lines_1[_a];
- for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) {
- if (!ts.isWhiteSpace(line.charCodeAt(i))) {
- if (indentation === undefined || i < indentation) {
- indentation = i;
- break;
- }
+ else {
+ for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ // Emit only the first encountered shebang
+ if (emitShebangIfNeeded(sourceFile)) {
+ break;
}
}
}
- return indentation;
}
//
// Helpers
//
- function emitShebang() {
- var shebang = ts.getShebang(currentText);
- if (shebang) {
- write(shebang);
- writeLine();
- }
- }
function emitModifiers(node, modifiers) {
if (modifiers && modifiers.length) {
emitList(node, modifiers, 256 /* Modifiers */);
@@ -61216,8 +65752,8 @@ var ts;
write(suffix);
}
}
- function emitEmbeddedStatement(node) {
- if (ts.isBlock(node)) {
+ function emitEmbeddedStatement(parent, node) {
+ if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
write(" ");
emit(node);
}
@@ -61274,6 +65810,9 @@ var ts;
if (format & 7680 /* BracketsMask */) {
write(getOpeningBracket(format));
}
+ if (onBeforeEmitNodeArray) {
+ onBeforeEmitNodeArray(children);
+ }
if (isEmpty) {
// Write a line terminator if the parent node was multi-line
if (format & 1 /* MultiLine */) {
@@ -61306,6 +65845,15 @@ var ts;
var child = children[start + i];
// Write the delimiter if this is not the first node.
if (previousSibling) {
+ // i.e
+ // function commentedParameters(
+ // /* Parameter a */
+ // a
+ // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
+ // ,
+ if (delimiter && previousSibling.end !== parentNode.end) {
+ emitLeadingCommentsOfPosition(previousSibling.end);
+ }
write(delimiter);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
@@ -61322,14 +65870,16 @@ var ts;
write(" ");
}
}
+ // Emit this child.
if (shouldEmitInterveningComments) {
- var commentRange = ts.getCommentRange(child);
- emitTrailingCommentsOfPosition(commentRange.pos);
+ if (emitTrailingCommentsOfPosition) {
+ var commentRange = ts.getCommentRange(child);
+ emitTrailingCommentsOfPosition(commentRange.pos);
+ }
}
else {
shouldEmitInterveningComments = mayEmitInterveningComments;
}
- // Emit this child.
emit(child);
if (shouldDecreaseIndentAfterEmit) {
decreaseIndent();
@@ -61342,6 +65892,15 @@ var ts;
if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
write(",");
}
+ // Emit any trailing comment of the last element in the list
+ // i.e
+ // var array = [...
+ // 2
+ // /* end of element 2 */
+ // ];
+ if (previousSibling && delimiter && previousSibling.end !== parentNode.end) {
+ emitLeadingCommentsOfPosition(previousSibling.end);
+ }
// Decrease the indent, if requested.
if (format & 64 /* Indented */) {
decreaseIndent();
@@ -61354,28 +65913,80 @@ var ts;
write(" ");
}
}
+ if (onAfterEmitNodeArray) {
+ onAfterEmitNodeArray(children);
+ }
if (format & 7680 /* BracketsMask */) {
write(getClosingBracket(format));
}
}
+ function write(s) {
+ writer.write(s);
+ }
+ function writeLine() {
+ writer.writeLine();
+ }
+ function increaseIndent() {
+ writer.increaseIndent();
+ }
+ function decreaseIndent() {
+ writer.decreaseIndent();
+ }
function writeIfAny(nodes, text) {
- if (nodes && nodes.length > 0) {
+ if (ts.some(nodes)) {
write(text);
}
}
function writeIfPresent(node, text) {
- if (node !== undefined) {
+ if (node) {
write(text);
}
}
function writeToken(token, pos, contextNode) {
- return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText);
+ return onEmitSourceMapOfToken
+ ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText)
+ : writeTokenText(token, pos);
}
function writeTokenText(token, pos) {
var tokenString = ts.tokenToString(token);
write(tokenString);
return pos < 0 ? pos : pos + tokenString.length;
}
+ function writeLineOrSpace(node) {
+ if (ts.getEmitFlags(node) & 1 /* SingleLine */) {
+ write(" ");
+ }
+ else {
+ writeLine();
+ }
+ }
+ function writeLines(text) {
+ var lines = text.split(/\r\n?|\n/g);
+ var indentation = guessIndentation(lines);
+ for (var i = 0; i < lines.length; i++) {
+ var line = indentation ? lines[i].slice(indentation) : lines[i];
+ if (line.length) {
+ writeLine();
+ write(line);
+ writeLine();
+ }
+ }
+ }
+ function guessIndentation(lines) {
+ var indentation;
+ for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) {
+ var line = lines_1[_a];
+ for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) {
+ if (!ts.isWhiteSpace(line.charCodeAt(i))) {
+ if (indentation === undefined || i < indentation) {
+ indentation = i;
+ break;
+ }
+ }
+ }
+ }
+ return indentation;
+ }
function increaseIndentIf(value, valueToWriteWhenNotIndenting) {
if (value) {
increaseIndent();
@@ -61485,15 +66096,23 @@ var ts;
&& !ts.nodeIsSynthesized(node2)
&& !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile);
}
+ function isSingleLineEmptyBlock(block) {
+ return !block.multiLine
+ && isEmptyBlock(block);
+ }
+ function isEmptyBlock(block) {
+ return block.statements.length === 0
+ && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
+ }
function skipSynthesizedParentheses(node) {
- while (node.kind === 183 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
+ while (node.kind === 184 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
node = node.expression;
}
return node;
}
function getTextOfNode(node, includeTrivia) {
if (ts.isGeneratedIdentifier(node)) {
- return getGeneratedIdentifier(node);
+ return generateName(node);
}
else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
return ts.unescapeIdentifier(node.text);
@@ -61516,26 +66135,60 @@ var ts;
return getLiteralTextOfNode(textSourceNode);
}
}
- return ts.getLiteralText(node, currentSourceFile, languageVersion);
+ return ts.getLiteralText(node, currentSourceFile);
}
- function isSingleLineEmptyBlock(block) {
- return !block.multiLine
- && isEmptyBlock(block);
+ /**
+ * Push a new name generation scope.
+ */
+ function pushNameGenerationScope() {
+ tempFlagsStack.push(tempFlags);
+ tempFlags = 0;
}
- function isEmptyBlock(block) {
- return block.statements.length === 0
- && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
+ /**
+ * Pop the current name generation scope.
+ */
+ function popNameGenerationScope() {
+ tempFlags = tempFlagsStack.pop();
+ }
+ /**
+ * Generate the text for a generated identifier.
+ */
+ function generateName(name) {
+ if (name.autoGenerateKind === 4 /* Node */) {
+ // Node names generate unique names based on their original node
+ // and are cached based on that node's id.
+ var node = getNodeForGeneratedName(name);
+ return generateNameCached(node);
+ }
+ else {
+ // Auto, Loop, and Unique names are cached based on their unique
+ // autoGenerateId.
+ var autoGenerateId = name.autoGenerateId;
+ return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(makeName(name)));
+ }
}
+ function generateNameCached(node) {
+ var nodeId = ts.getNodeId(node);
+ return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node)));
+ }
+ /**
+ * Returns a value indicating whether a name is unique globally, within the current file,
+ * or within the NameGenerator.
+ */
function isUniqueName(name) {
- return !resolver.hasGlobalName(name) &&
- !ts.hasProperty(currentFileIdentifiers, name) &&
- !ts.hasProperty(generatedNameSet, name);
+ return !(hasGlobalName && hasGlobalName(name))
+ && !currentSourceFile.identifiers.has(name)
+ && !generatedNames.has(name);
}
+ /**
+ * Returns a value indicating whether a name is unique within a container.
+ */
function isUniqueLocalName(name, container) {
for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
- if (node.locals && ts.hasProperty(node.locals, name)) {
+ if (node.locals) {
+ var local = node.locals.get(name);
// We conservatively include alias symbols to cover cases where they're emitted as locals
- if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) {
+ if (local && local.flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) {
return false;
}
}
@@ -61543,16 +66196,16 @@ var ts;
return true;
}
/**
- * Return the next available name in the pattern _a ... _z, _0, _1, ...
- * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
- * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
- */
+ * Return the next available name in the pattern _a ... _z, _0, _1, ...
+ * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
+ * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
+ */
function makeTempVariableName(flags) {
if (flags && !(tempFlags & flags)) {
- var name_39 = flags === 268435456 /* _i */ ? "_i" : "_n";
- if (isUniqueName(name_39)) {
+ var name = flags === 268435456 /* _i */ ? "_i" : "_n";
+ if (isUniqueName(name)) {
tempFlags |= flags;
- return name_39;
+ return name;
}
}
while (true) {
@@ -61560,19 +66213,21 @@ var ts;
tempFlags++;
// Skip over 'i' and 'n'
if (count !== 8 && count !== 13) {
- var name_40 = count < 26
+ var name = count < 26
? "_" + String.fromCharCode(97 /* a */ + count)
: "_" + (count - 26);
- if (isUniqueName(name_40)) {
- return name_40;
+ if (isUniqueName(name)) {
+ return name;
}
}
}
}
- // Generate a name that is unique within the current file and doesn't conflict with any names
- // in global scope. The name is formed by adding an '_n' suffix to the specified base name,
- // where n is a positive integer. Note that names generated by makeTempVariableName and
- // makeUniqueName are guaranteed to never conflict.
+ /**
+ * Generate a name that is unique within the current file and doesn't conflict with any names
+ * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
+ * where n is a positive integer. Note that names generated by makeTempVariableName and
+ * makeUniqueName are guaranteed to never conflict.
+ */
function makeUniqueName(baseName) {
// Find the first unique 'name_n', where n is a positive number
if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
@@ -61582,73 +66237,90 @@ var ts;
while (true) {
var generatedName = baseName + i;
if (isUniqueName(generatedName)) {
- return generatedNameSet[generatedName] = generatedName;
+ generatedNames.set(generatedName, generatedName);
+ return generatedName;
}
i++;
}
}
+ /**
+ * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
+ */
function generateNameForModuleOrEnum(node) {
var name = getTextOfNode(node.name);
// Use module/enum name itself if it is unique, otherwise make a unique variation
return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
}
+ /**
+ * Generates a unique name for an ImportDeclaration or ExportDeclaration.
+ */
function generateNameForImportOrExportDeclaration(node) {
var expr = ts.getExternalModuleName(node);
var baseName = expr.kind === 9 /* StringLiteral */ ?
ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module";
return makeUniqueName(baseName);
}
+ /**
+ * Generates a unique name for a default export.
+ */
function generateNameForExportDefault() {
return makeUniqueName("default");
}
+ /**
+ * Generates a unique name for a class expression.
+ */
function generateNameForClassExpression() {
return makeUniqueName("class");
}
+ function generateNameForMethodOrAccessor(node) {
+ if (ts.isIdentifier(node.name)) {
+ return generateNameCached(node.name);
+ }
+ return makeTempVariableName(0 /* Auto */);
+ }
/**
* Generates a unique name from a node.
- *
- * @param node A node.
*/
function generateNameForNode(node) {
switch (node.kind) {
case 70 /* Identifier */:
return makeUniqueName(getTextOfNode(node));
- case 230 /* ModuleDeclaration */:
- case 229 /* EnumDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ case 231 /* EnumDeclaration */:
return generateNameForModuleOrEnum(node);
- case 235 /* ImportDeclaration */:
- case 241 /* ExportDeclaration */:
+ case 237 /* ImportDeclaration */:
+ case 243 /* ExportDeclaration */:
return generateNameForImportOrExportDeclaration(node);
- case 225 /* FunctionDeclaration */:
- case 226 /* ClassDeclaration */:
- case 240 /* ExportAssignment */:
+ case 227 /* FunctionDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 242 /* ExportAssignment */:
return generateNameForExportDefault();
- case 197 /* ClassExpression */:
+ case 198 /* ClassExpression */:
return generateNameForClassExpression();
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ return generateNameForMethodOrAccessor(node);
default:
return makeTempVariableName(0 /* Auto */);
}
}
/**
* Generates a unique identifier for a node.
- *
- * @param name A generated name.
*/
- function generateName(name) {
+ function makeName(name) {
switch (name.autoGenerateKind) {
case 1 /* Auto */:
return makeTempVariableName(0 /* Auto */);
case 2 /* Loop */:
return makeTempVariableName(268435456 /* _i */);
case 3 /* Unique */:
- return makeUniqueName(name.text);
+ return makeUniqueName(ts.unescapeIdentifier(name.text));
}
ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
}
/**
* Gets the node from which a name should be generated.
- *
- * @param name A generated name wrapper.
*/
function getNodeForGeneratedName(name) {
var autoGenerateId = name.autoGenerateId;
@@ -61668,53 +66340,40 @@ var ts;
// otherwise, return the original node for the source;
return node;
}
- /**
- * Gets the generated identifier text from a generated identifier.
- *
- * @param name The generated identifier.
- */
- function getGeneratedIdentifier(name) {
- if (name.autoGenerateKind === 4 /* Node */) {
- // Generated names generate unique names based on their original node
- // and are cached based on that node's id
- var node = getNodeForGeneratedName(name);
- var nodeId = ts.getNodeId(node);
- return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node)));
- }
- else {
- // Auto, Loop, and Unique names are cached based on their unique
- // autoGenerateId.
- var autoGenerateId = name.autoGenerateId;
- return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(generateName(name)));
- }
- }
- function createDelimiterMap() {
- var delimiters = [];
- delimiters[0 /* None */] = "";
- delimiters[16 /* CommaDelimited */] = ",";
- delimiters[4 /* BarDelimited */] = " |";
- delimiters[8 /* AmpersandDelimited */] = " &";
- return delimiters;
- }
- function getDelimiter(format) {
- return delimiters[format & 28 /* DelimitersMask */];
- }
- function createBracketsMap() {
- var brackets = [];
- brackets[512 /* Braces */] = ["{", "}"];
- brackets[1024 /* Parenthesis */] = ["(", ")"];
- brackets[2048 /* AngleBrackets */] = ["<", ">"];
- brackets[4096 /* SquareBrackets */] = ["[", "]"];
- return brackets;
- }
- function getOpeningBracket(format) {
- return brackets[format & 7680 /* BracketsMask */][0];
- }
- function getClosingBracket(format) {
- return brackets[format & 7680 /* BracketsMask */][1];
- }
}
- ts.emitFiles = emitFiles;
+ ts.createPrinter = createPrinter;
+ function createDelimiterMap() {
+ var delimiters = [];
+ delimiters[0 /* None */] = "";
+ delimiters[16 /* CommaDelimited */] = ",";
+ delimiters[4 /* BarDelimited */] = " |";
+ delimiters[8 /* AmpersandDelimited */] = " &";
+ return delimiters;
+ }
+ function getDelimiter(format) {
+ return delimiters[format & 28 /* DelimitersMask */];
+ }
+ function createBracketsMap() {
+ var brackets = [];
+ brackets[512 /* Braces */] = ["{", "}"];
+ brackets[1024 /* Parenthesis */] = ["(", ")"];
+ brackets[2048 /* AngleBrackets */] = ["<", ">"];
+ brackets[4096 /* SquareBrackets */] = ["[", "]"];
+ return brackets;
+ }
+ function getOpeningBracket(format) {
+ return brackets[format & 7680 /* BracketsMask */][0];
+ }
+ function getClosingBracket(format) {
+ return brackets[format & 7680 /* BracketsMask */][1];
+ }
+ // Flags enum to track count of temp variables and a few dedicated names
+ var TempFlags;
+ (function (TempFlags) {
+ TempFlags[TempFlags["Auto"] = 0] = "Auto";
+ TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
+ TempFlags[TempFlags["_i"] = 268435456] = "_i";
+ })(TempFlags || (TempFlags = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -61790,6 +66449,7 @@ var ts;
var ts;
(function (ts) {
var emptyArray = [];
+ var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/;
function findConfigFile(searchPath, fileExists, configName) {
if (configName === void 0) { configName = "tsconfig.json"; }
while (true) {
@@ -61824,7 +66484,8 @@ var ts;
commonPathComponents = sourcePathComponents;
return;
}
- for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) {
+ var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
+ for (var i = 0; i < n; i++) {
if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
if (i === 0) {
// Failed to find any common path component
@@ -61857,8 +66518,6 @@ var ts;
// otherwise use toLowerCase as a canonical form.
return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
- // returned by CScript sys environment
- var unsupportedFileEncodingErrorCode = -2147024809;
function getSourceFile(fileName, languageVersion, onError) {
var text;
try {
@@ -61869,20 +66528,18 @@ var ts;
}
catch (e) {
if (onError) {
- onError(e.number === unsupportedFileEncodingErrorCode
- ? ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText
- : e.message);
+ onError(e.message);
}
text = "";
}
return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
}
function directoryExists(directoryPath) {
- if (directoryPath in existingDirectories) {
+ if (existingDirectories.has(directoryPath)) {
return true;
}
if (ts.sys.directoryExists(directoryPath)) {
- existingDirectories[directoryPath] = true;
+ existingDirectories.set(directoryPath, true);
return true;
}
return false;
@@ -61901,10 +66558,11 @@ var ts;
}
var hash = ts.sys.createHash(data);
var mtimeBefore = ts.sys.getModifiedTime(fileName);
- if (mtimeBefore && fileName in outputFingerprints) {
- var fingerprint = outputFingerprints[fileName];
+ if (mtimeBefore) {
+ var fingerprint = outputFingerprints.get(fileName);
// If output has not been changed, and the file has no external modification
- if (fingerprint.byteOrderMark === writeByteOrderMark &&
+ if (fingerprint &&
+ fingerprint.byteOrderMark === writeByteOrderMark &&
fingerprint.hash === hash &&
fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
return;
@@ -61912,11 +66570,11 @@ var ts;
}
ts.sys.writeFile(fileName, data, writeByteOrderMark);
var mtimeAfter = ts.sys.getModifiedTime(fileName);
- outputFingerprints[fileName] = {
+ outputFingerprints.set(fileName, {
hash: hash,
byteOrderMark: writeByteOrderMark,
mtime: mtimeAfter
- };
+ });
}
function writeFile(fileName, data, writeByteOrderMark, onError) {
try {
@@ -62015,10 +66673,14 @@ var ts;
var resolutions = [];
var cache = ts.createMap();
for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
- var name_41 = names_1[_i];
- var result = name_41 in cache
- ? cache[name_41]
- : cache[name_41] = loader(name_41, containingFile);
+ var name = names_1[_i];
+ var result = void 0;
+ if (cache.has(name)) {
+ result = cache.get(name);
+ }
+ else {
+ cache.set(name, result = loader(name, containingFile));
+ }
resolutions.push(result);
}
return resolutions;
@@ -62030,6 +66692,8 @@ var ts;
var diagnosticsProducingTypeChecker;
var noDiagnosticsTypeChecker;
var classifiableNames;
+ var cachedSemanticDiagnosticsForFile = {};
+ var cachedDeclarationDiagnosticsForFile = {};
var resolvedTypeReferenceDirectives = ts.createMap();
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
// The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
@@ -62054,6 +66718,7 @@ var ts;
var supportedExtensions = ts.getSupportedExtensions(options);
// Map storing if there is emit blocking diagnostics for given input
var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName);
+ var moduleResolutionCache;
var resolveModuleNamesWorker;
if (host.resolveModuleNames) {
resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) {
@@ -62067,7 +66732,8 @@ var ts;
}); };
}
else {
- var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; };
+ moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); });
+ var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; };
resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); };
}
var resolveTypeReferenceDirectiveNamesWorker;
@@ -62113,6 +66779,8 @@ var ts;
}
}
}
+ // unconditionally set moduleResolutionCache to undefined to avoid unnecessary leaks
+ moduleResolutionCache = undefined;
// unconditionally set oldProgram to undefined to prevent it from being captured in closure
oldProgram = undefined;
program = {
@@ -62147,7 +66815,7 @@ var ts;
return program;
function getCommonSourceDirectory() {
if (commonSourceDirectory === undefined) {
- var emittedFiles = ts.filterSourceFilesInDirectory(files, isSourceFileFromExternalLibrary);
+ var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
@@ -62171,7 +66839,7 @@ var ts;
classifiableNames = ts.createMap();
for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
var sourceFile = files_2[_i];
- ts.copyProperties(sourceFile.classifiableNames, classifiableNames);
+ ts.copyEntries(sourceFile.classifiableNames, classifiableNames);
}
}
return classifiableNames;
@@ -62245,7 +66913,7 @@ var ts;
// combine results of resolutions and predicted results
var j = 0;
for (var i = 0; i < result.length; i++) {
- if (result[i] == predictedToResolveToAmbientModuleMarker) {
+ if (result[i] === predictedToResolveToAmbientModuleMarker) {
result[i] = undefined;
}
else {
@@ -62378,7 +67046,7 @@ var ts;
newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
}
// update fileName -> file mapping
- for (var i = 0, len = newSourceFiles.length; i < len; i++) {
+ for (var i = 0; i < newSourceFiles.length; i++) {
filesByName.set(filePaths[i], newSourceFiles[i]);
}
files = newSourceFiles;
@@ -62407,7 +67075,7 @@ var ts;
};
}
function isSourceFileFromExternalLibrary(file) {
- return sourceFilesFoundSearchingNodeModules[file.path];
+ return sourceFilesFoundSearchingNodeModules.get(file.path);
}
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
@@ -62418,13 +67086,13 @@ var ts;
function getTypeChecker() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
- function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
- return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); });
+ function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) {
+ return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
}
- function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) {
+ function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) {
var declarationDiagnostics = [];
if (options.noEmit) {
return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
@@ -62456,7 +67124,8 @@ var ts;
// checked is to not pass the file to getEmitResolver.
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
ts.performance.mark("beforeEmit");
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles);
+ var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -62529,19 +67198,48 @@ var ts;
}
}
function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
+ return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache);
+ }
+ function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
return runWithCancellationToken(function () {
var typeChecker = getDiagnosticsProducingTypeChecker();
ts.Debug.assert(!!sourceFile.bindDiagnostics);
var bindDiagnostics = sourceFile.bindDiagnostics;
- // For JavaScript files, we don't want to report semantic errors.
- // Instead, we'll report errors for using TypeScript-only constructs from within a
- // JavaScript file when we get syntactic diagnostics for the file.
- var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? [] : typeChecker.getDiagnostics(sourceFile, cancellationToken);
+ // For JavaScript files, we don't want to report semantic errors unless explicitly requested.
+ var includeCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options);
+ var checkDiagnostics = includeCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : [];
var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
- return bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
+ var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
+ return ts.isSourceFileJavaScript(sourceFile)
+ ? ts.filter(diagnostics, shouldReportDiagnostic)
+ : diagnostics;
});
}
+ /**
+ * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines
+ */
+ function shouldReportDiagnostic(diagnostic) {
+ var file = diagnostic.file, start = diagnostic.start;
+ if (file) {
+ var lineStarts = ts.getLineStarts(file);
+ var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line;
+ while (line > 0) {
+ var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]);
+ var result = ignoreDiagnosticCommentRegEx.exec(previousLineText);
+ if (!result) {
+ // non-empty line
+ return true;
+ }
+ if (result[3]) {
+ // @ts-ignore
+ return false;
+ }
+ line--;
+ }
+ }
+ return true;
+ }
function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) {
return runWithCancellationToken(function () {
var diagnostics = [];
@@ -62552,23 +67250,23 @@ var ts;
// Return directly from the case if the given node doesnt want to visit each child
// Otherwise break to visit each child
switch (parent.kind) {
- case 144 /* Parameter */:
- case 147 /* PropertyDeclaration */:
+ case 145 /* Parameter */:
+ case 148 /* PropertyDeclaration */:
if (parent.questionToken === node) {
diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
return;
}
- // Pass through
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 184 /* FunctionExpression */:
- case 225 /* FunctionDeclaration */:
- case 185 /* ArrowFunction */:
- case 225 /* FunctionDeclaration */:
- case 223 /* VariableDeclaration */:
+ // falls through
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 185 /* FunctionExpression */:
+ case 227 /* FunctionDeclaration */:
+ case 186 /* ArrowFunction */:
+ case 227 /* FunctionDeclaration */:
+ case 225 /* VariableDeclaration */:
// type annotation
if (parent.type === node) {
diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file));
@@ -62576,35 +67274,35 @@ var ts;
}
}
switch (node.kind) {
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file));
return;
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
if (node.isExportEquals) {
diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file));
return;
}
break;
- case 255 /* HeritageClause */:
+ case 258 /* HeritageClause */:
var heritageClause = node;
if (heritageClause.token === 107 /* ImplementsKeyword */) {
diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file));
return;
}
break;
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file));
return;
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file));
return;
- case 228 /* TypeAliasDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file));
return;
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file));
return;
- case 182 /* TypeAssertionExpression */:
+ case 183 /* TypeAssertionExpression */:
var typeAssertionExpression = node;
diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file));
return;
@@ -62619,29 +67317,29 @@ var ts;
diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning));
}
switch (parent.kind) {
- case 226 /* ClassDeclaration */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 184 /* FunctionExpression */:
- case 225 /* FunctionDeclaration */:
- case 185 /* ArrowFunction */:
- case 225 /* FunctionDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 185 /* FunctionExpression */:
+ case 227 /* FunctionDeclaration */:
+ case 186 /* ArrowFunction */:
+ case 227 /* FunctionDeclaration */:
// Check type parameters
if (nodes === parent.typeParameters) {
diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file));
return;
}
- // pass through
- case 205 /* VariableStatement */:
+ // falls through
+ case 207 /* VariableStatement */:
// Check modifiers
if (nodes === parent.modifiers) {
- return checkModifiers(nodes, parent.kind === 205 /* VariableStatement */);
+ return checkModifiers(nodes, parent.kind === 207 /* VariableStatement */);
}
break;
- case 147 /* PropertyDeclaration */:
+ case 148 /* PropertyDeclaration */:
// Check modifiers of property declaration
if (nodes === parent.modifiers) {
for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
@@ -62653,16 +67351,16 @@ var ts;
return;
}
break;
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
// Check modifiers of parameter declaration
if (nodes === parent.modifiers) {
diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file));
return;
}
break;
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
- case 199 /* ExpressionWithTypeArguments */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
+ case 200 /* ExpressionWithTypeArguments */:
// Check type arguments
if (nodes === parent.typeArguments) {
diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file));
@@ -62670,8 +67368,8 @@ var ts;
}
break;
}
- for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) {
- var node = nodes_6[_b];
+ for (var _b = 0, nodes_8 = nodes; _b < nodes_8.length; _b++) {
+ var node = nodes_8[_b];
walk(node);
}
}
@@ -62683,7 +67381,8 @@ var ts;
if (isConstValid) {
continue;
}
- // Fallthrough to report error
+ // to report error,
+ // falls through
case 113 /* PublicKeyword */:
case 111 /* PrivateKeyword */:
case 112 /* ProtectedKeyword */:
@@ -62711,12 +67410,34 @@ var ts;
});
}
function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
+ return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
+ }
+ function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
return runWithCancellationToken(function () {
var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile);
});
}
+ function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
+ var cachedResult = sourceFile
+ ? cache.perFile && cache.perFile.get(sourceFile.path)
+ : cache.allDiagnostics;
+ if (cachedResult) {
+ return cachedResult;
+ }
+ var result = getDiagnostics(sourceFile, cancellationToken) || emptyArray;
+ if (sourceFile) {
+ if (!cache.perFile) {
+ cache.perFile = ts.createFileMap();
+ }
+ cache.perFile.set(sourceFile.path, result);
+ }
+ else {
+ cache.allDiagnostics = result;
+ }
+ return result;
+ }
function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
}
@@ -62759,11 +67480,10 @@ var ts;
&& (options.isolatedModules || isExternalModuleFile)
&& !file.isDeclarationFile) {
// synthesize 'import "tslib"' declaration
- var externalHelpersModuleReference = ts.createSynthesizedNode(9 /* StringLiteral */);
- externalHelpersModuleReference.text = ts.externalHelpersModuleNameText;
- var importDecl = ts.createSynthesizedNode(235 /* ImportDeclaration */);
- importDecl.parent = file;
+ var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText);
+ var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined);
externalHelpersModuleReference.parent = importDecl;
+ importDecl.parent = file;
imports = [externalHelpersModuleReference];
}
for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
@@ -62779,9 +67499,9 @@ var ts;
return;
function collectModuleReferences(node, inAmbientModule) {
switch (node.kind) {
- case 235 /* ImportDeclaration */:
- case 234 /* ImportEqualsDeclaration */:
- case 241 /* ExportDeclaration */:
+ case 237 /* ImportDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 243 /* ExportDeclaration */:
var moduleNameExpr = ts.getExternalModuleName(node);
if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) {
break;
@@ -62796,7 +67516,7 @@ var ts;
(imports || (imports = [])).push(moduleNameExpr);
}
break;
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || ts.isDeclarationFile(file))) {
var moduleName = node.name;
// Ambient module declarations can be interpreted as augmentations for some existing external modules.
@@ -62896,18 +67616,18 @@ var ts;
}
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
- if (file_1 && sourceFilesFoundSearchingNodeModules[file_1.path] && currentNodeModulesDepth == 0) {
- sourceFilesFoundSearchingNodeModules[file_1.path] = false;
+ if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) {
+ sourceFilesFoundSearchingNodeModules.set(file_1.path, false);
if (!options.noResolve) {
processReferencedFiles(file_1, isDefaultLib);
processTypeReferenceDirectives(file_1);
}
- modulesWithElidedImports[file_1.path] = false;
+ modulesWithElidedImports.set(file_1.path, false);
processImportedModules(file_1);
}
- else if (file_1 && modulesWithElidedImports[file_1.path]) {
+ else if (file_1 && modulesWithElidedImports.get(file_1.path)) {
if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
- modulesWithElidedImports[file_1.path] = false;
+ modulesWithElidedImports.set(file_1.path, false);
processImportedModules(file_1);
}
}
@@ -62924,7 +67644,7 @@ var ts;
});
filesByName.set(path, file);
if (file) {
- sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
+ sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
@@ -62973,7 +67693,7 @@ var ts;
}
function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) {
// If we already found this library as a primary reference - nothing to do
- var previousResolution = resolvedTypeReferenceDirectives[typeReferenceDirective];
+ var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
if (previousResolution && previousResolution.primary) {
return;
}
@@ -63007,7 +67727,7 @@ var ts;
fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
}
if (saveResolution) {
- resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective;
+ resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
}
}
function createDiagnostic(refFile, refPos, refEnd, message) {
@@ -63056,7 +67776,7 @@ var ts;
// This may still end up being an untyped module -- the file won't be included but imports will be allowed.
var shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
- modulesWithElidedImports[file.path] = true;
+ modulesWithElidedImports.set(file.path, true);
}
else if (shouldAddFile) {
var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName);
@@ -63075,8 +67795,8 @@ var ts;
}
function computeCommonSourceDirectory(sourceFiles) {
var fileNames = [];
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var file = sourceFiles_6[_i];
+ for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
+ var file = sourceFiles_2[_i];
if (!file.isDeclarationFile) {
fileNames.push(file.fileName);
}
@@ -63087,8 +67807,8 @@ var ts;
var allFilesBelongToPath = true;
if (sourceFiles) {
var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
- for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
- var sourceFile = sourceFiles_7[_i];
+ for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
+ var sourceFile = sourceFiles_3[_i];
if (!ts.isDeclarationFile(sourceFile)) {
var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
@@ -63182,7 +67902,7 @@ var ts;
if (options.lib && options.noLib) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"));
}
- if (options.noImplicitUseStrict && options.alwaysStrict) {
+ if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"));
}
var languageVersion = options.target || 0 /* ES3 */;
@@ -63228,6 +67948,9 @@ var ts;
if (!options.noEmit && options.allowJs && options.declaration) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"));
}
+ if (options.checkJs && !options.allowJs) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
+ }
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
@@ -63247,7 +67970,7 @@ var ts;
if (!options.noEmit && !options.suppressOutputPathCheck) {
var emitHost = getEmitHost();
var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined);
- ts.forEachExpectedEmitFile(emitHost, function (emitFileNames) {
+ ts.forEachEmittedFile(emitHost, function (emitFileNames) {
verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
});
@@ -63323,40 +68046,13 @@ var ts;
ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
/* @internal */
ts.optionDeclarations = [
- {
- name: "charset",
- type: "string",
- },
- ts.compileOnSaveCommandLineOption,
- {
- name: "declaration",
- shortName: "d",
- type: "boolean",
- description: ts.Diagnostics.Generates_corresponding_d_ts_file,
- },
- {
- name: "declarationDir",
- type: "string",
- isFilePath: true,
- paramType: ts.Diagnostics.DIRECTORY,
- },
- {
- name: "diagnostics",
- type: "boolean",
- },
- {
- name: "extendedDiagnostics",
- type: "boolean",
- experimental: true
- },
- {
- name: "emitBOM",
- type: "boolean"
- },
+ // CommandLine only options
{
name: "help",
shortName: "h",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
description: ts.Diagnostics.Print_this_message,
},
{
@@ -63365,56 +68061,74 @@ var ts;
type: "boolean"
},
{
- name: "init",
+ name: "all",
type: "boolean",
- description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Show_all_compiler_options,
},
{
- name: "inlineSourceMap",
+ name: "version",
+ shortName: "v",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Print_the_compiler_s_version,
},
{
- name: "inlineSources",
+ name: "init",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
},
{
- name: "jsx",
- type: ts.createMap({
- "preserve": 1 /* Preserve */,
- "react": 2 /* React */
- }),
- paramType: ts.Diagnostics.KIND,
- description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react,
- },
- {
- name: "reactNamespace",
- type: "string",
- description: ts.Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit
- },
- {
- name: "jsxFactory",
+ name: "project",
+ shortName: "p",
type: "string",
- description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
+ isFilePath: true,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
+ description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
},
{
- name: "listFiles",
+ name: "pretty",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
},
{
- name: "locale",
- type: "string",
+ name: "watch",
+ shortName: "w",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Command_line_Options,
+ description: ts.Diagnostics.Watch_input_files,
},
+ // Basic
{
- name: "mapRoot",
- type: "string",
- isFilePath: true,
- description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
- paramType: ts.Diagnostics.LOCATION,
+ name: "target",
+ shortName: "t",
+ type: ts.createMapFromTemplate({
+ "es3": 0 /* ES3 */,
+ "es5": 1 /* ES5 */,
+ "es6": 2 /* ES2015 */,
+ "es2015": 2 /* ES2015 */,
+ "es2016": 3 /* ES2016 */,
+ "es2017": 4 /* ES2017 */,
+ "esnext": 5 /* ESNext */,
+ }),
+ paramType: ts.Diagnostics.VERSION,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT,
},
{
name: "module",
shortName: "m",
- type: ts.createMap({
+ type: ts.createMapFromTemplate({
"none": ts.ModuleKind.None,
"commonjs": ts.ModuleKind.CommonJS,
"amd": ts.ModuleKind.AMD,
@@ -63423,233 +68137,230 @@ var ts;
"es6": ts.ModuleKind.ES2015,
"es2015": ts.ModuleKind.ES2015,
}),
- description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
paramType: ts.Diagnostics.KIND,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
},
{
- name: "newLine",
- type: ts.createMap({
- "crlf": 0 /* CarriageReturnLineFeed */,
- "lf": 1 /* LineFeed */
- }),
- description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
- paramType: ts.Diagnostics.NEWLINE,
- },
- {
- name: "noEmit",
- type: "boolean",
- description: ts.Diagnostics.Do_not_emit_outputs,
- },
- {
- name: "noEmitHelpers",
- type: "boolean"
- },
- {
- name: "noEmitOnError",
- type: "boolean",
- description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
- },
- {
- name: "noErrorTruncation",
- type: "boolean"
- },
- {
- name: "noImplicitAny",
- type: "boolean",
- description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type,
- },
- {
- name: "noImplicitThis",
- type: "boolean",
- description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
- },
- {
- name: "noUnusedLocals",
- type: "boolean",
- description: ts.Diagnostics.Report_errors_on_unused_locals,
+ name: "lib",
+ type: "list",
+ element: {
+ name: "lib",
+ type: ts.createMapFromTemplate({
+ // JavaScript only
+ "es5": "lib.es5.d.ts",
+ "es6": "lib.es2015.d.ts",
+ "es2015": "lib.es2015.d.ts",
+ "es7": "lib.es2016.d.ts",
+ "es2016": "lib.es2016.d.ts",
+ "es2017": "lib.es2017.d.ts",
+ "esnext": "lib.esnext.d.ts",
+ // Host only
+ "dom": "lib.dom.d.ts",
+ "dom.iterable": "lib.dom.iterable.d.ts",
+ "webworker": "lib.webworker.d.ts",
+ "scripthost": "lib.scripthost.d.ts",
+ // ES2015 Or ESNext By-feature options
+ "es2015.core": "lib.es2015.core.d.ts",
+ "es2015.collection": "lib.es2015.collection.d.ts",
+ "es2015.generator": "lib.es2015.generator.d.ts",
+ "es2015.iterable": "lib.es2015.iterable.d.ts",
+ "es2015.promise": "lib.es2015.promise.d.ts",
+ "es2015.proxy": "lib.es2015.proxy.d.ts",
+ "es2015.reflect": "lib.es2015.reflect.d.ts",
+ "es2015.symbol": "lib.es2015.symbol.d.ts",
+ "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts",
+ "es2016.array.include": "lib.es2016.array.include.d.ts",
+ "es2017.object": "lib.es2017.object.d.ts",
+ "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts",
+ "es2017.string": "lib.es2017.string.d.ts",
+ "esnext.asynciterable": "lib.esnext.asynciterable.d.ts",
+ }),
+ },
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon
},
{
- name: "noUnusedParameters",
+ name: "allowJs",
type: "boolean",
- description: ts.Diagnostics.Report_errors_on_unused_parameters,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
},
{
- name: "noLib",
+ name: "checkJs",
type: "boolean",
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Report_errors_in_js_files
},
{
- name: "noResolve",
- type: "boolean",
+ name: "jsx",
+ type: ts.createMapFromTemplate({
+ "preserve": 1 /* Preserve */,
+ "react-native": 3 /* ReactNative */,
+ "react": 2 /* React */
+ }),
+ paramType: ts.Diagnostics.KIND,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
},
{
- name: "skipDefaultLibCheck",
+ name: "declaration",
+ shortName: "d",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Generates_corresponding_d_ts_file,
},
{
- name: "skipLibCheck",
+ name: "sourceMap",
type: "boolean",
- description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
- },
- {
- name: "out",
- type: "string",
- isFilePath: false,
- // for correct behaviour, please use outFile
- paramType: ts.Diagnostics.FILE,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Generates_corresponding_map_file,
},
{
name: "outFile",
type: "string",
isFilePath: true,
- description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
paramType: ts.Diagnostics.FILE,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
},
{
name: "outDir",
type: "string",
isFilePath: true,
- description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
paramType: ts.Diagnostics.DIRECTORY,
- },
- {
- name: "preserveConstEnums",
- type: "boolean",
- description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
- },
- {
- name: "pretty",
- description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental,
- type: "boolean"
- },
- {
- name: "project",
- shortName: "p",
- type: "string",
- isFilePath: true,
- description: ts.Diagnostics.Compile_the_project_in_the_given_directory,
- paramType: ts.Diagnostics.DIRECTORY
- },
- {
- name: "removeComments",
- type: "boolean",
- description: ts.Diagnostics.Do_not_emit_comments_to_output,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
},
{
name: "rootDir",
type: "string",
isFilePath: true,
paramType: ts.Diagnostics.LOCATION,
+ category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
},
{
- name: "isolatedModules",
+ name: "removeComments",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Do_not_emit_comments_to_output,
},
{
- name: "sourceMap",
+ name: "noEmit",
type: "boolean",
- description: ts.Diagnostics.Generates_corresponding_map_file,
- },
- {
- name: "sourceRoot",
- type: "string",
- isFilePath: true,
- description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
- paramType: ts.Diagnostics.LOCATION,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Do_not_emit_outputs,
},
{
- name: "suppressExcessPropertyErrors",
+ name: "importHelpers",
type: "boolean",
- description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
- experimental: true
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Import_emit_helpers_from_tslib
},
{
- name: "suppressImplicitAnyIndexErrors",
+ name: "downlevelIteration",
type: "boolean",
- description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
},
{
- name: "stripInternal",
+ name: "isolatedModules",
type: "boolean",
- description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
- experimental: true
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule
},
+ // Strict Type Checks
{
- name: "target",
- shortName: "t",
- type: ts.createMap({
- "es3": 0 /* ES3 */,
- "es5": 1 /* ES5 */,
- "es6": 2 /* ES2015 */,
- "es2015": 2 /* ES2015 */,
- "es2016": 3 /* ES2016 */,
- "es2017": 4 /* ES2017 */,
- "esnext": 5 /* ESNext */,
- }),
- description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015,
- paramType: ts.Diagnostics.VERSION,
+ name: "strict",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Strict_Type_Checking_Options,
+ description: ts.Diagnostics.Enable_all_strict_type_checking_options
},
{
- name: "version",
- shortName: "v",
+ name: "noImplicitAny",
type: "boolean",
- description: ts.Diagnostics.Print_the_compiler_s_version,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Strict_Type_Checking_Options,
+ description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type,
},
{
- name: "watch",
- shortName: "w",
+ name: "strictNullChecks",
type: "boolean",
- description: ts.Diagnostics.Watch_input_files,
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Strict_Type_Checking_Options,
+ description: ts.Diagnostics.Enable_strict_null_checks
},
{
- name: "experimentalDecorators",
+ name: "noImplicitThis",
type: "boolean",
- description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Strict_Type_Checking_Options,
+ description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
},
{
- name: "emitDecoratorMetadata",
+ name: "alwaysStrict",
type: "boolean",
- experimental: true,
- description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Strict_Type_Checking_Options,
+ description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
},
+ // Additional Checks
{
- name: "moduleResolution",
- type: ts.createMap({
- "node": ts.ModuleResolutionKind.NodeJs,
- "classic": ts.ModuleResolutionKind.Classic,
- }),
- description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
- paramType: ts.Diagnostics.STRATEGY,
+ name: "noUnusedLocals",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Additional_Checks,
+ description: ts.Diagnostics.Report_errors_on_unused_locals,
},
{
- name: "allowUnusedLabels",
+ name: "noUnusedParameters",
type: "boolean",
- description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Additional_Checks,
+ description: ts.Diagnostics.Report_errors_on_unused_parameters,
},
{
name: "noImplicitReturns",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Additional_Checks,
description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
},
{
name: "noFallthroughCasesInSwitch",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Additional_Checks,
description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
},
+ // Module Resolution
{
- name: "allowUnreachableCode",
- type: "boolean",
- description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
- },
- {
- name: "forceConsistentCasingInFileNames",
- type: "boolean",
- description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
+ name: "moduleResolution",
+ type: ts.createMapFromTemplate({
+ "node": ts.ModuleResolutionKind.NodeJs,
+ "classic": ts.ModuleResolutionKind.Classic,
+ }),
+ paramType: ts.Diagnostics.STRATEGY,
+ category: ts.Diagnostics.Module_Resolution_Options,
+ description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
},
{
name: "baseUrl",
type: "string",
isFilePath: true,
+ category: ts.Diagnostics.Module_Resolution_Options,
description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
},
{
@@ -63657,7 +68368,9 @@ var ts;
// use type = object to copy the value as-is
name: "paths",
type: "object",
- isTSConfigOnly: true
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Module_Resolution_Options,
+ description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl
},
{
// this option can only be specified in tsconfig.json
@@ -63669,7 +68382,9 @@ var ts;
name: "rootDirs",
type: "string",
isFilePath: true
- }
+ },
+ category: ts.Diagnostics.Module_Resolution_Options,
+ description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime
},
{
name: "typeRoots",
@@ -63678,7 +68393,9 @@ var ts;
name: "typeRoots",
type: "string",
isFilePath: true
- }
+ },
+ category: ts.Diagnostics.Module_Resolution_Options,
+ description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
},
{
name: "types",
@@ -63687,91 +68404,258 @@ var ts;
name: "types",
type: "string"
},
+ showInSimplifiedHelpView: true,
+ category: ts.Diagnostics.Module_Resolution_Options,
description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation
},
{
+ name: "allowSyntheticDefaultImports",
+ type: "boolean",
+ category: ts.Diagnostics.Module_Resolution_Options,
+ description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
+ },
+ // Source Maps
+ {
+ name: "sourceRoot",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.LOCATION,
+ category: ts.Diagnostics.Source_Map_Options,
+ description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
+ },
+ {
+ name: "mapRoot",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.LOCATION,
+ category: ts.Diagnostics.Source_Map_Options,
+ description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
+ },
+ {
+ name: "inlineSourceMap",
+ type: "boolean",
+ category: ts.Diagnostics.Source_Map_Options,
+ description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
+ },
+ {
+ name: "inlineSources",
+ type: "boolean",
+ category: ts.Diagnostics.Source_Map_Options,
+ description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
+ },
+ // Experimental
+ {
+ name: "experimentalDecorators",
+ type: "boolean",
+ category: ts.Diagnostics.Experimental_Options,
+ description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
+ },
+ {
+ name: "emitDecoratorMetadata",
+ type: "boolean",
+ category: ts.Diagnostics.Experimental_Options,
+ description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
+ },
+ // Advanced
+ {
+ name: "jsxFactory",
+ type: "string",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
+ },
+ {
+ name: "diagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_diagnostic_information
+ },
+ {
+ name: "extendedDiagnostics",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Show_verbose_diagnostic_information
+ },
+ {
name: "traceResolution",
type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
{
- name: "allowJs",
+ name: "listFiles",
type: "boolean",
- description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
},
{
- name: "allowSyntheticDefaultImports",
+ name: "listEmittedFiles",
type: "boolean",
- description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
+ },
+ {
+ name: "out",
+ type: "string",
+ isFilePath: false,
+ // for correct behaviour, please use outFile
+ category: ts.Diagnostics.Advanced_Options,
+ paramType: ts.Diagnostics.FILE,
+ description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
+ },
+ {
+ name: "reactNamespace",
+ type: "string",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
+ },
+ {
+ name: "skipDefaultLibCheck",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
+ },
+ {
+ name: "charset",
+ type: "string",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.The_character_set_of_the_input_files
+ },
+ {
+ name: "emitBOM",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
+ },
+ {
+ name: "locale",
+ type: "string",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
+ },
+ {
+ name: "newLine",
+ type: ts.createMapFromTemplate({
+ "crlf": 0 /* CarriageReturnLineFeed */,
+ "lf": 1 /* LineFeed */
+ }),
+ paramType: ts.Diagnostics.NEWLINE,
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
+ },
+ {
+ name: "noErrorTruncation",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Do_not_truncate_error_messages
+ },
+ {
+ name: "noLib",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts
+ },
+ {
+ name: "noResolve",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files
+ },
+ {
+ name: "stripInternal",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
+ },
+ {
+ name: "disableSizeLimit",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
},
{
name: "noImplicitUseStrict",
type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
},
{
- name: "maxNodeModuleJsDepth",
- type: "number",
- description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
+ name: "noEmitHelpers",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
},
{
- name: "listEmittedFiles",
- type: "boolean"
+ name: "noEmitOnError",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
},
{
- name: "lib",
- type: "list",
- element: {
- name: "lib",
- type: ts.createMap({
- // JavaScript only
- "es5": "lib.es5.d.ts",
- "es6": "lib.es2015.d.ts",
- "es2015": "lib.es2015.d.ts",
- "es7": "lib.es2016.d.ts",
- "es2016": "lib.es2016.d.ts",
- "es2017": "lib.es2017.d.ts",
- // Host only
- "dom": "lib.dom.d.ts",
- "dom.iterable": "lib.dom.iterable.d.ts",
- "webworker": "lib.webworker.d.ts",
- "scripthost": "lib.scripthost.d.ts",
- // ES2015 Or ESNext By-feature options
- "es2015.core": "lib.es2015.core.d.ts",
- "es2015.collection": "lib.es2015.collection.d.ts",
- "es2015.generator": "lib.es2015.generator.d.ts",
- "es2015.iterable": "lib.es2015.iterable.d.ts",
- "es2015.promise": "lib.es2015.promise.d.ts",
- "es2015.proxy": "lib.es2015.proxy.d.ts",
- "es2015.reflect": "lib.es2015.reflect.d.ts",
- "es2015.symbol": "lib.es2015.symbol.d.ts",
- "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts",
- "es2016.array.include": "lib.es2016.array.include.d.ts",
- "es2017.object": "lib.es2017.object.d.ts",
- "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts",
- "es2017.string": "lib.es2017.string.d.ts",
- }),
- },
- description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon
+ name: "preserveConstEnums",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
},
{
- name: "disableSizeLimit",
- type: "boolean"
+ name: "declarationDir",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.DIRECTORY,
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Output_directory_for_generated_declaration_files
},
{
- name: "strictNullChecks",
+ name: "skipLibCheck",
type: "boolean",
- description: ts.Diagnostics.Enable_strict_null_checks
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
},
{
- name: "importHelpers",
+ name: "allowUnusedLabels",
type: "boolean",
- description: ts.Diagnostics.Import_emit_helpers_from_tslib
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
},
{
- name: "alwaysStrict",
+ name: "allowUnreachableCode",
type: "boolean",
- description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
+ },
+ {
+ name: "suppressExcessPropertyErrors",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
+ },
+ {
+ name: "suppressImplicitAnyIndexErrors",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
+ },
+ {
+ name: "forceConsistentCasingInFileNames",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
+ },
+ {
+ name: "maxNodeModuleJsDepth",
+ type: "number",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
+ },
+ {
+ // A list of plugins to load in the language service
+ name: "plugins",
+ type: "list",
+ isTSConfigOnly: true,
+ element: {
+ name: "plugin",
+ type: "object"
+ },
+ description: ts.Diagnostics.List_of_language_service_plugins
}
];
/* @internal */
@@ -63808,8 +68692,7 @@ var ts;
ts.defaultInitCompilerOptions = {
module: ts.ModuleKind.CommonJS,
target: 1 /* ES5 */,
- noImplicitAny: false,
- sourceMap: false,
+ strict: true
};
var optionNameMapCache;
/* @internal */
@@ -63834,9 +68717,9 @@ var ts;
var optionNameMap = ts.createMap();
var shortOptionNames = ts.createMap();
ts.forEach(ts.optionDeclarations, function (option) {
- optionNameMap[option.name.toLowerCase()] = option;
+ optionNameMap.set(option.name.toLowerCase(), option);
if (option.shortName) {
- shortOptionNames[option.shortName] = option.name;
+ shortOptionNames.set(option.shortName, option.name);
}
});
optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames };
@@ -63845,20 +68728,13 @@ var ts;
ts.getOptionNameMap = getOptionNameMap;
/* @internal */
function createCompilerDiagnosticForInvalidCustomType(opt) {
- var namesOfType = Object.keys(opt.type).map(function (key) { return "'" + key + "'"; }).join(", ");
+ var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
}
ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
/* @internal */
function parseCustomTypeOption(opt, value, errors) {
- var key = trimString((value || "")).toLowerCase();
- var map = opt.type;
- if (key in map) {
- return map[key];
- }
- else {
- errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
- }
+ return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
}
ts.parseCustomTypeOption = parseCustomTypeOption;
/* @internal */
@@ -63882,7 +68758,6 @@ var ts;
}
}
ts.parseListTypeOption = parseListTypeOption;
- /* @internal */
function parseCommandLine(commandLine, readFile) {
var options = {};
var fileNames = [];
@@ -63905,11 +68780,12 @@ var ts;
else if (s.charCodeAt(0) === 45 /* minus */) {
s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase();
// Try to translate short option names to their full equivalents.
- if (s in shortOptionNames) {
- s = shortOptionNames[s];
+ var short = shortOptionNames.get(s);
+ if (short !== undefined) {
+ s = short;
}
- if (s in optionNameMap) {
- var opt = optionNameMap[s];
+ var opt = optionNameMap.get(s);
+ if (opt) {
if (opt.isTSConfigOnly) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name));
}
@@ -63997,9 +68873,9 @@ var ts;
}
ts.parseCommandLine = parseCommandLine;
/**
- * Read tsconfig.json file
- * @param fileName The path to the config file
- */
+ * Read tsconfig.json file
+ * @param fileName The path to the config file
+ */
function readConfigFile(fileName, readFile) {
var text = "";
try {
@@ -64012,10 +68888,10 @@ var ts;
}
ts.readConfigFile = readConfigFile;
/**
- * Parse the text of the tsconfig.json file
- * @param fileName The path to the config file
- * @param jsonText The text of the config file
- */
+ * Parse the text of the tsconfig.json file
+ * @param fileName The path to the config file
+ * @param jsonText The text of the config file
+ */
function parseConfigFileTextToJson(fileName, jsonText, stripComments) {
if (stripComments === void 0) { stripComments = true; }
try {
@@ -64033,7 +68909,7 @@ var ts;
* @param fileNames array of filenames to be generated into tsconfig.json
*/
/* @internal */
- function generateTSConfig(options, fileNames) {
+ function generateTSConfig(options, fileNames, newLine) {
var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
var configurations = {
compilerOptions: serializeCompilerOptions(compilerOptions)
@@ -64042,7 +68918,7 @@ var ts;
// only set the files property if we have at least one file
configurations.files = fileNames;
}
- return configurations;
+ return writeConfigurations();
function getCustomTypeMapOfCommandLineOption(optionDefinition) {
if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") {
// this is of a type CommandLineOptionOfPrimitiveType
@@ -64057,58 +68933,130 @@ var ts;
}
function getNameOfCompilerOptionValue(value, customTypeMap) {
// There is a typeMap associated with this command-line option so use it to map value back to its name
- for (var key in customTypeMap) {
- if (customTypeMap[key] === value) {
+ return ts.forEachEntry(customTypeMap, function (mapValue, key) {
+ if (mapValue === value) {
return key;
}
- }
- return undefined;
+ });
}
function serializeCompilerOptions(options) {
- var result = ts.createMap();
+ var result = {};
var optionsNameMap = getOptionNameMap().optionNameMap;
- for (var name_42 in options) {
- if (ts.hasProperty(options, name_42)) {
+ for (var name in options) {
+ if (ts.hasProperty(options, name)) {
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
- switch (name_42) {
- case "init":
- case "watch":
- case "version":
- case "help":
- case "project":
- break;
- default:
- var value = options[name_42];
- var optionDefinition = optionsNameMap[name_42.toLowerCase()];
- if (optionDefinition) {
- var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
- if (!customTypeMap) {
- // There is no map associated with this compiler option then use the value as-is
- // This is the case if the value is expect to be string, number, boolean or list of string
- result[name_42] = value;
- }
- else {
- if (optionDefinition.type === "list") {
- var convertedValue = [];
- for (var _i = 0, _a = value; _i < _a.length; _i++) {
- var element = _a[_i];
- convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap));
- }
- result[name_42] = convertedValue;
- }
- else {
- // There is a typeMap associated with this command-line option so use it to map value back to its name
- result[name_42] = getNameOfCompilerOptionValue(value, customTypeMap);
- }
+ if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
+ continue;
+ }
+ var value = options[name];
+ var optionDefinition = optionsNameMap.get(name.toLowerCase());
+ if (optionDefinition) {
+ var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
+ if (!customTypeMap) {
+ // There is no map associated with this compiler option then use the value as-is
+ // This is the case if the value is expect to be string, number, boolean or list of string
+ result[name] = value;
+ }
+ else {
+ if (optionDefinition.type === "list") {
+ var convertedValue = [];
+ for (var _i = 0, _a = value; _i < _a.length; _i++) {
+ var element = _a[_i];
+ convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap));
}
+ result[name] = convertedValue;
}
- break;
+ else {
+ // There is a typeMap associated with this command-line option so use it to map value back to its name
+ result[name] = getNameOfCompilerOptionValue(value, customTypeMap);
+ }
+ }
}
}
}
return result;
}
+ function getDefaultValueForOption(option) {
+ switch (option.type) {
+ case "number":
+ return 1;
+ case "boolean":
+ return true;
+ case "string":
+ return option.isFilePath ? "./" : "";
+ case "list":
+ return [];
+ case "object":
+ return {};
+ default:
+ return ts.arrayFrom(option.type.keys())[0];
+ }
+ }
+ function makePadding(paddingLength) {
+ return Array(paddingLength + 1).join(" ");
+ }
+ function writeConfigurations() {
+ // Filter applicable options to place in the file
+ var categorizedOptions = ts.reduceLeft(ts.filter(ts.optionDeclarations, function (o) { return o.category !== ts.Diagnostics.Command_line_Options && o.category !== ts.Diagnostics.Advanced_Options; }), function (memo, value) {
+ if (value.category) {
+ var name = ts.getLocaleSpecificMessage(value.category);
+ (memo[name] || (memo[name] = [])).push(value);
+ }
+ return memo;
+ }, {});
+ // Serialize all options and thier descriptions
+ var marginLength = 0;
+ var seenKnownKeys = 0;
+ var nameColumn = [];
+ var descriptionColumn = [];
+ var knownKeysCount = ts.getOwnKeys(configurations.compilerOptions).length;
+ for (var category in categorizedOptions) {
+ if (nameColumn.length !== 0) {
+ nameColumn.push("");
+ descriptionColumn.push("");
+ }
+ nameColumn.push("/* " + category + " */");
+ descriptionColumn.push("");
+ for (var _i = 0, _a = categorizedOptions[category]; _i < _a.length; _i++) {
+ var option = _a[_i];
+ var optionName = void 0;
+ if (ts.hasProperty(configurations.compilerOptions, option.name)) {
+ optionName = "\"" + option.name + "\": " + JSON.stringify(configurations.compilerOptions[option.name]) + ((seenKnownKeys += 1) === knownKeysCount ? "" : ",");
+ }
+ else {
+ optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
+ }
+ nameColumn.push(optionName);
+ descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */");
+ marginLength = Math.max(optionName.length, marginLength);
+ }
+ }
+ // Write the output
+ var tab = makePadding(2);
+ var result = [];
+ result.push("{");
+ result.push(tab + "\"compilerOptions\": {");
+ // Print out each row, aligning all the descriptions on the same column.
+ for (var i = 0; i < nameColumn.length; i++) {
+ var optionName = nameColumn[i];
+ var description = descriptionColumn[i];
+ result.push(tab + tab + optionName + makePadding(marginLength - optionName.length + 2) + description);
+ }
+ if (configurations.files && configurations.files.length) {
+ result.push(tab + "},");
+ result.push(tab + "\"files\": [");
+ for (var i = 0; i < configurations.files.length; i++) {
+ result.push("" + tab + tab + JSON.stringify(configurations.files[i]) + (i === configurations.files.length - 1 ? "" : ","));
+ }
+ result.push(tab + "]");
+ }
+ else {
+ result.push(tab + "}");
+ }
+ result.push("}");
+ return result.join(newLine);
+ }
}
ts.generateTSConfig = generateTSConfig;
/**
@@ -64136,16 +69084,18 @@ var ts;
return output;
}
/**
- * Parse the contents of a config file (tsconfig.json).
- * @param json The contents of the config file to parse
- * @param host Instance of ParseConfigHost used to enumerate files in folder.
- * @param basePath A root directory to resolve relative path entries in the config
- * file to. e.g. outDir
- */
- function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack) {
+ * Parse the contents of a config file (tsconfig.json).
+ * @param json The contents of the config file to parse
+ * @param host Instance of ParseConfigHost used to enumerate files in folder.
+ * @param basePath A root directory to resolve relative path entries in the config
+ * file to. e.g. outDir
+ */
+ function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) {
if (existingOptions === void 0) { existingOptions = {}; }
if (resolutionStack === void 0) { resolutionStack = []; }
+ if (extraFileExtensions === void 0) { extraFileExtensions = []; }
var errors = [];
+ basePath = ts.normalizeSlashes(basePath);
var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
var resolvedPath = ts.toPath(configFileName || "", basePath, getCanonicalFileName);
if (resolutionStack.indexOf(resolvedPath) >= 0) {
@@ -64272,7 +69222,7 @@ var ts;
if (fileNames === undefined && includeSpecs === undefined) {
includeSpecs = ["**/*"];
}
- var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
+ var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions);
if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])));
}
@@ -64323,8 +69273,8 @@ var ts;
}
var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; });
for (var id in jsonOptions) {
- if (id in optionNameMap) {
- var opt = optionNameMap[id];
+ var opt = optionNameMap.get(id);
+ if (opt) {
defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
}
else {
@@ -64358,8 +69308,9 @@ var ts;
}
function convertJsonOptionOfCustomType(opt, value, errors) {
var key = value.toLowerCase();
- if (key in opt.type) {
- return opt.type[key];
+ var val = opt.type.get(key);
+ if (val !== undefined) {
+ return val;
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
@@ -64449,7 +69400,7 @@ var ts;
* @param host The host used to resolve files and directories.
* @param errors An array for diagnostic reporting.
*/
- function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) {
+ function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) {
basePath = ts.normalizePath(basePath);
// The exclude spec list is converted into a regular expression, which allows us to quickly
// test whether a file or directory should be excluded before recursively traversing the
@@ -64476,14 +69427,14 @@ var ts;
var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames);
// Rather than requery this for each file and filespec, we query the supported extensions
// once and store it on the expansion context.
- var supportedExtensions = ts.getSupportedExtensions(options);
+ var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
// Literal files are always included verbatim. An "include" or "exclude" specification cannot
// remove a literal file.
if (fileNames) {
for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
var fileName = fileNames_1[_i];
var file = ts.combinePaths(basePath, fileName);
- literalFileMap[keyMapper(file)] = file;
+ literalFileMap.set(keyMapper(file), file);
}
}
if (include && include.length > 0) {
@@ -64504,14 +69455,13 @@ var ts;
// same directory, we should remove it.
removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
var key = keyMapper(file);
- if (!(key in literalFileMap) && !(key in wildcardFileMap)) {
- wildcardFileMap[key] = file;
+ if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
+ wildcardFileMap.set(key, file);
}
}
}
- var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []);
- var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []);
- wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive);
+ var literalFiles = ts.arrayFrom(literalFileMap.values());
+ var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
return {
fileNames: literalFiles.concat(wildcardFiles),
wildcardDirectories: wildcardDirectories
@@ -64519,8 +69469,8 @@ var ts;
}
function validateSpecs(specs, errors, allowTrailingRecursion) {
var validSpecs = [];
- for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) {
- var spec = specs_2[_i];
+ for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) {
+ var spec = specs_1[_i];
if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec));
}
@@ -64554,7 +69504,7 @@ var ts;
// /a/b/a?z - Watch /a/b directly to catch any new file matching a?z
var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
- var wildcardDirectories = ts.createMap();
+ var wildcardDirectories = {};
if (include !== undefined) {
var recursiveKeys = [];
for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
@@ -64576,14 +69526,15 @@ var ts;
}
}
// Remove any subpaths under an existing recursively watched directory.
- for (var key in wildcardDirectories) {
- for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
- var recursiveKey = recursiveKeys_1[_a];
- if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
- delete wildcardDirectories[key];
+ for (var key in wildcardDirectories)
+ if (ts.hasProperty(wildcardDirectories, key)) {
+ for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
+ var recursiveKey = recursiveKeys_1[_a];
+ if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
+ delete wildcardDirectories[key];
+ }
}
}
- }
}
return wildcardDirectories;
}
@@ -64610,11 +69561,11 @@ var ts;
*/
function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
var extensionPriority = ts.getExtensionPriority(file, extensions);
- var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority);
+ var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
var higherPriorityExtension = extensions[i];
var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
- if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) {
+ if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
return true;
}
}
@@ -64630,24 +69581,14 @@ var ts;
*/
function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
var extensionPriority = ts.getExtensionPriority(file, extensions);
- var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority);
+ var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
for (var i = nextExtensionPriority; i < extensions.length; i++) {
var lowerPriorityExtension = extensions[i];
var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
- delete wildcardFiles[lowerPriorityPath];
+ wildcardFiles.delete(lowerPriorityPath);
}
}
/**
- * Adds a file to an array of files.
- *
- * @param output The output array.
- * @param file The file path.
- */
- function addFileToOutput(output, file) {
- output.push(file);
- return output;
- }
- /**
* Gets a case sensitive key.
*
* @param key The original key.
@@ -64673,7 +69614,9 @@ var ts;
this.text = text;
}
StringScriptSnapshot.prototype.getText = function (start, end) {
- return this.text.substring(start, end);
+ return start === 0 && end === this.text.length
+ ? this.text
+ : this.text.substring(start, end);
};
StringScriptSnapshot.prototype.getLength = function () {
return this.text.length;
@@ -64783,8 +69726,7 @@ var ts;
ScriptElementKind.typeElement = "type";
/** enum E */
ScriptElementKind.enumElement = "enum";
- // TODO: GH#9983
- ScriptElementKind.enumMemberElement = "const";
+ ScriptElementKind.enumMemberElement = "enum member";
/**
* Inside module and script only
* const v = ..
@@ -64827,6 +69769,10 @@ var ts;
ScriptElementKind.letElement = "let";
ScriptElementKind.directory = "directory";
ScriptElementKind.externalModuleName = "external module name";
+ /**
+ * <JsxTagName attribute1 attribute2={0} />
+ */
+ ScriptElementKind.jsxAttribute = "JSX attribute";
})(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {}));
var ScriptElementKindModifier;
(function (ScriptElementKindModifier) {
@@ -64912,33 +69858,34 @@ var ts;
})(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {}));
function getMeaningFromDeclaration(node) {
switch (node.kind) {
- case 144 /* Parameter */:
- case 223 /* VariableDeclaration */:
- case 174 /* BindingElement */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 257 /* PropertyAssignment */:
- case 258 /* ShorthandPropertyAssignment */:
- case 260 /* EnumMember */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 256 /* CatchClause */:
+ case 145 /* Parameter */:
+ case 225 /* VariableDeclaration */:
+ case 175 /* BindingElement */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 260 /* PropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
+ case 263 /* EnumMember */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 259 /* CatchClause */:
+ case 252 /* JsxAttribute */:
return 1 /* Value */;
- case 143 /* TypeParameter */:
- case 227 /* InterfaceDeclaration */:
- case 228 /* TypeAliasDeclaration */:
- case 161 /* TypeLiteral */:
+ case 144 /* TypeParameter */:
+ case 229 /* InterfaceDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
+ case 162 /* TypeLiteral */:
return 2 /* Type */;
- case 226 /* ClassDeclaration */:
- case 229 /* EnumDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 231 /* EnumDeclaration */:
return 1 /* Value */ | 2 /* Type */;
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
if (ts.isAmbientModule(node)) {
return 4 /* Namespace */ | 1 /* Value */;
}
@@ -64948,22 +69895,25 @@ var ts;
else {
return 4 /* Namespace */;
}
- case 238 /* NamedImports */:
- case 239 /* ImportSpecifier */:
- case 234 /* ImportEqualsDeclaration */:
- case 235 /* ImportDeclaration */:
- case 240 /* ExportAssignment */:
- case 241 /* ExportDeclaration */:
+ case 240 /* NamedImports */:
+ case 241 /* ImportSpecifier */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 237 /* ImportDeclaration */:
+ case 242 /* ExportAssignment */:
+ case 243 /* ExportDeclaration */:
return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */;
// An external module can be a Value
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */;
}
ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
function getMeaningFromLocation(node) {
- if (node.parent.kind === 240 /* ExportAssignment */) {
+ if (node.kind === 264 /* SourceFile */) {
+ return 1 /* Value */;
+ }
+ else if (node.parent.kind === 242 /* ExportAssignment */) {
return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */;
}
else if (isInRightSideOfImport(node)) {
@@ -64988,15 +69938,15 @@ var ts;
// import a = |b|; // Namespace
// import a = |b.c|; // Value, type, namespace
// import a = |b.c|.d; // Namespace
- if (node.parent.kind === 141 /* QualifiedName */ &&
+ if (node.parent.kind === 142 /* QualifiedName */ &&
node.parent.right === node &&
- node.parent.parent.kind === 234 /* ImportEqualsDeclaration */) {
+ node.parent.parent.kind === 236 /* ImportEqualsDeclaration */) {
return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */;
}
return 4 /* Namespace */;
}
function isInRightSideOfImport(node) {
- while (node.parent.kind === 141 /* QualifiedName */) {
+ while (node.parent.kind === 142 /* QualifiedName */) {
node = node.parent;
}
return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node;
@@ -65007,27 +69957,27 @@ var ts;
function isQualifiedNameNamespaceReference(node) {
var root = node;
var isLastClause = true;
- if (root.parent.kind === 141 /* QualifiedName */) {
- while (root.parent && root.parent.kind === 141 /* QualifiedName */) {
+ if (root.parent.kind === 142 /* QualifiedName */) {
+ while (root.parent && root.parent.kind === 142 /* QualifiedName */) {
root = root.parent;
}
isLastClause = root.right === node;
}
- return root.parent.kind === 157 /* TypeReference */ && !isLastClause;
+ return root.parent.kind === 158 /* TypeReference */ && !isLastClause;
}
function isPropertyAccessNamespaceReference(node) {
var root = node;
var isLastClause = true;
- if (root.parent.kind === 177 /* PropertyAccessExpression */) {
- while (root.parent && root.parent.kind === 177 /* PropertyAccessExpression */) {
+ if (root.parent.kind === 178 /* PropertyAccessExpression */) {
+ while (root.parent && root.parent.kind === 178 /* PropertyAccessExpression */) {
root = root.parent;
}
isLastClause = root.name === node;
}
- if (!isLastClause && root.parent.kind === 199 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 255 /* HeritageClause */) {
+ if (!isLastClause && root.parent.kind === 200 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 258 /* HeritageClause */) {
var decl = root.parent.parent.parent;
- return (decl.kind === 226 /* ClassDeclaration */ && root.parent.parent.token === 107 /* ImplementsKeyword */) ||
- (decl.kind === 227 /* InterfaceDeclaration */ && root.parent.parent.token === 84 /* ExtendsKeyword */);
+ return (decl.kind === 228 /* ClassDeclaration */ && root.parent.parent.token === 107 /* ImplementsKeyword */) ||
+ (decl.kind === 229 /* InterfaceDeclaration */ && root.parent.parent.token === 84 /* ExtendsKeyword */);
}
return false;
}
@@ -65035,17 +69985,17 @@ var ts;
if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) {
node = node.parent;
}
- return node.parent.kind === 157 /* TypeReference */ ||
- (node.parent.kind === 199 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) ||
+ return node.parent.kind === 158 /* TypeReference */ ||
+ (node.parent.kind === 200 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) ||
(node.kind === 98 /* ThisKeyword */ && !ts.isPartOfExpression(node)) ||
- node.kind === 167 /* ThisType */;
+ node.kind === 168 /* ThisType */;
}
function isCallExpressionTarget(node) {
- return isCallOrNewExpressionTarget(node, 179 /* CallExpression */);
+ return isCallOrNewExpressionTarget(node, 180 /* CallExpression */);
}
ts.isCallExpressionTarget = isCallExpressionTarget;
function isNewExpressionTarget(node) {
- return isCallOrNewExpressionTarget(node, 180 /* NewExpression */);
+ return isCallOrNewExpressionTarget(node, 181 /* NewExpression */);
}
ts.isNewExpressionTarget = isNewExpressionTarget;
function isCallOrNewExpressionTarget(node, kind) {
@@ -65058,7 +70008,7 @@ var ts;
ts.climbPastPropertyAccess = climbPastPropertyAccess;
function getTargetLabel(referenceNode, labelName) {
while (referenceNode) {
- if (referenceNode.kind === 219 /* LabeledStatement */ && referenceNode.label.text === labelName) {
+ if (referenceNode.kind === 221 /* LabeledStatement */ && referenceNode.label.text === labelName) {
return referenceNode.label;
}
referenceNode = referenceNode.parent;
@@ -65068,13 +70018,13 @@ var ts;
ts.getTargetLabel = getTargetLabel;
function isJumpStatementTarget(node) {
return node.kind === 70 /* Identifier */ &&
- (node.parent.kind === 215 /* BreakStatement */ || node.parent.kind === 214 /* ContinueStatement */) &&
+ (node.parent.kind === 217 /* BreakStatement */ || node.parent.kind === 216 /* ContinueStatement */) &&
node.parent.label === node;
}
ts.isJumpStatementTarget = isJumpStatementTarget;
function isLabelOfLabeledStatement(node) {
return node.kind === 70 /* Identifier */ &&
- node.parent.kind === 219 /* LabeledStatement */ &&
+ node.parent.kind === 221 /* LabeledStatement */ &&
node.parent.label === node;
}
function isLabelName(node) {
@@ -65082,15 +70032,15 @@ var ts;
}
ts.isLabelName = isLabelName;
function isRightSideOfQualifiedName(node) {
- return node.parent.kind === 141 /* QualifiedName */ && node.parent.right === node;
+ return node.parent.kind === 142 /* QualifiedName */ && node.parent.right === node;
}
ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName;
function isRightSideOfPropertyAccess(node) {
- return node && node.parent && node.parent.kind === 177 /* PropertyAccessExpression */ && node.parent.name === node;
+ return node && node.parent && node.parent.kind === 178 /* PropertyAccessExpression */ && node.parent.name === node;
}
ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess;
function isNameOfModuleDeclaration(node) {
- return node.parent.kind === 230 /* ModuleDeclaration */ && node.parent.name === node;
+ return node.parent.kind === 232 /* ModuleDeclaration */ && node.parent.name === node;
}
ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration;
function isNameOfFunctionDeclaration(node) {
@@ -65101,19 +70051,19 @@ var ts;
function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) {
if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) {
switch (node.parent.kind) {
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 257 /* PropertyAssignment */:
- case 260 /* EnumMember */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 230 /* ModuleDeclaration */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 260 /* PropertyAssignment */:
+ case 263 /* EnumMember */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 232 /* ModuleDeclaration */:
return node.parent.name === node;
- case 178 /* ElementAccessExpression */:
+ case 179 /* ElementAccessExpression */:
return node.parent.argumentExpression === node;
- case 142 /* ComputedPropertyName */:
+ case 143 /* ComputedPropertyName */:
return true;
}
}
@@ -65162,17 +70112,17 @@ var ts;
return undefined;
}
switch (node.kind) {
- case 261 /* SourceFile */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 229 /* EnumDeclaration */:
- case 230 /* ModuleDeclaration */:
+ case 264 /* SourceFile */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 232 /* ModuleDeclaration */:
return node;
}
}
@@ -65180,46 +70130,46 @@ var ts;
ts.getContainerNode = getContainerNode;
function getNodeKind(node) {
switch (node.kind) {
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement;
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return ts.ScriptElementKind.moduleElement;
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
return ts.ScriptElementKind.classElement;
- case 227 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement;
- case 228 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement;
- case 229 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement;
- case 223 /* VariableDeclaration */:
+ case 229 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement;
+ case 230 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement;
+ case 231 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement;
+ case 225 /* VariableDeclaration */:
return getKindOfVariableDeclaration(node);
- case 174 /* BindingElement */:
+ case 175 /* BindingElement */:
return getKindOfVariableDeclaration(ts.getRootDeclaration(node));
- case 185 /* ArrowFunction */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
return ts.ScriptElementKind.functionElement;
- case 151 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement;
- case 152 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement;
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 152 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement;
+ case 153 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement;
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
return ts.ScriptElementKind.memberFunctionElement;
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
return ts.ScriptElementKind.memberVariableElement;
- case 155 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement;
- case 154 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement;
- case 153 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement;
- case 150 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement;
- case 143 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement;
- case 260 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement;
- case 144 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement;
- case 234 /* ImportEqualsDeclaration */:
- case 239 /* ImportSpecifier */:
- case 236 /* ImportClause */:
- case 243 /* ExportSpecifier */:
- case 237 /* NamespaceImport */:
+ case 156 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement;
+ case 155 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement;
+ case 154 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement;
+ case 151 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement;
+ case 144 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement;
+ case 263 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement;
+ case 145 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement;
+ case 236 /* ImportEqualsDeclaration */:
+ case 241 /* ImportSpecifier */:
+ case 238 /* ImportClause */:
+ case 245 /* ExportSpecifier */:
+ case 239 /* NamespaceImport */:
return ts.ScriptElementKind.alias;
- case 285 /* JSDocTypedefTag */:
+ case 289 /* JSDocTypedefTag */:
return ts.ScriptElementKind.typeElement;
default:
return ts.ScriptElementKind.unknown;
@@ -65233,15 +70183,6 @@ var ts;
}
}
ts.getNodeKind = getNodeKind;
- function getStringLiteralTypeForNode(node, typeChecker) {
- var searchNode = node.parent.kind === 171 /* LiteralType */ ? node.parent : node;
- var type = typeChecker.getTypeAtLocation(searchNode);
- if (type && type.flags & 32 /* StringLiteral */) {
- return type;
- }
- return undefined;
- }
- ts.getStringLiteralTypeForNode = getStringLiteralTypeForNode;
function isThis(node) {
switch (node.kind) {
case 98 /* ThisKeyword */:
@@ -65249,7 +70190,7 @@ var ts;
return true;
case 70 /* Identifier */:
// 'this' as a parameter
- return ts.identifierIsThisKeyword(node) && node.parent.kind === 144 /* Parameter */;
+ return ts.identifierIsThisKeyword(node) && node.parent.kind === 145 /* Parameter */;
default:
return false;
}
@@ -65258,7 +70199,7 @@ var ts;
// Matches the beginning of a triple slash directive
var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*</;
function getLineStartPositionForPosition(position, sourceFile) {
- var lineStarts = sourceFile.getLineStarts();
+ var lineStarts = ts.getLineStarts(sourceFile);
var line = sourceFile.getLineAndCharacterOfPosition(position).line;
return lineStarts[line];
}
@@ -65294,42 +70235,42 @@ var ts;
return false;
}
switch (n.kind) {
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 229 /* EnumDeclaration */:
- case 176 /* ObjectLiteralExpression */:
- case 172 /* ObjectBindingPattern */:
- case 161 /* TypeLiteral */:
- case 204 /* Block */:
- case 231 /* ModuleBlock */:
- case 232 /* CaseBlock */:
- case 238 /* NamedImports */:
- case 242 /* NamedExports */:
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 177 /* ObjectLiteralExpression */:
+ case 173 /* ObjectBindingPattern */:
+ case 162 /* TypeLiteral */:
+ case 206 /* Block */:
+ case 233 /* ModuleBlock */:
+ case 234 /* CaseBlock */:
+ case 240 /* NamedImports */:
+ case 244 /* NamedExports */:
return nodeEndsWith(n, 17 /* CloseBraceToken */, sourceFile);
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return isCompletedNode(n.block, sourceFile);
- case 180 /* NewExpression */:
+ case 181 /* NewExpression */:
if (!n.arguments) {
return true;
}
- // fall through
- case 179 /* CallExpression */:
- case 183 /* ParenthesizedExpression */:
- case 166 /* ParenthesizedType */:
+ // falls through
+ case 180 /* CallExpression */:
+ case 184 /* ParenthesizedExpression */:
+ case 167 /* ParenthesizedType */:
return nodeEndsWith(n, 19 /* CloseParenToken */, sourceFile);
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
return isCompletedNode(n.type, sourceFile);
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 154 /* ConstructSignature */:
- case 153 /* CallSignature */:
- case 185 /* ArrowFunction */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 155 /* ConstructSignature */:
+ case 154 /* CallSignature */:
+ case 186 /* ArrowFunction */:
if (n.body) {
return isCompletedNode(n.body, sourceFile);
}
@@ -65339,67 +70280,67 @@ var ts;
// Even though type parameters can be unclosed, we can get away with
// having at least a closing paren.
return hasChildOfKind(n, 19 /* CloseParenToken */, sourceFile);
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
return n.body && isCompletedNode(n.body, sourceFile);
- case 208 /* IfStatement */:
+ case 210 /* IfStatement */:
if (n.elseStatement) {
return isCompletedNode(n.elseStatement, sourceFile);
}
return isCompletedNode(n.thenStatement, sourceFile);
- case 207 /* ExpressionStatement */:
+ case 209 /* ExpressionStatement */:
return isCompletedNode(n.expression, sourceFile) ||
hasChildOfKind(n, 24 /* SemicolonToken */);
- case 175 /* ArrayLiteralExpression */:
- case 173 /* ArrayBindingPattern */:
- case 178 /* ElementAccessExpression */:
- case 142 /* ComputedPropertyName */:
- case 163 /* TupleType */:
+ case 176 /* ArrayLiteralExpression */:
+ case 174 /* ArrayBindingPattern */:
+ case 179 /* ElementAccessExpression */:
+ case 143 /* ComputedPropertyName */:
+ case 164 /* TupleType */:
return nodeEndsWith(n, 21 /* CloseBracketToken */, sourceFile);
- case 155 /* IndexSignature */:
+ case 156 /* IndexSignature */:
if (n.type) {
return isCompletedNode(n.type, sourceFile);
}
return hasChildOfKind(n, 21 /* CloseBracketToken */, sourceFile);
- case 253 /* CaseClause */:
- case 254 /* DefaultClause */:
+ case 256 /* CaseClause */:
+ case 257 /* DefaultClause */:
// there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed
return false;
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- case 210 /* WhileStatement */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ case 212 /* WhileStatement */:
return isCompletedNode(n.statement, sourceFile);
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
// rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
var hasWhileKeyword = findChildOfKind(n, 105 /* WhileKeyword */, sourceFile);
if (hasWhileKeyword) {
return nodeEndsWith(n, 19 /* CloseParenToken */, sourceFile);
}
return isCompletedNode(n.statement, sourceFile);
- case 160 /* TypeQuery */:
+ case 161 /* TypeQuery */:
return isCompletedNode(n.exprName, sourceFile);
- case 187 /* TypeOfExpression */:
- case 186 /* DeleteExpression */:
- case 188 /* VoidExpression */:
- case 195 /* YieldExpression */:
- case 196 /* SpreadElement */:
+ case 188 /* TypeOfExpression */:
+ case 187 /* DeleteExpression */:
+ case 189 /* VoidExpression */:
+ case 196 /* YieldExpression */:
+ case 197 /* SpreadElement */:
var unaryWordExpression = n;
return isCompletedNode(unaryWordExpression.expression, sourceFile);
- case 181 /* TaggedTemplateExpression */:
+ case 182 /* TaggedTemplateExpression */:
return isCompletedNode(n.template, sourceFile);
- case 194 /* TemplateExpression */:
+ case 195 /* TemplateExpression */:
var lastSpan = ts.lastOrUndefined(n.templateSpans);
return isCompletedNode(lastSpan, sourceFile);
- case 202 /* TemplateSpan */:
+ case 204 /* TemplateSpan */:
return ts.nodeIsPresent(n.literal);
- case 241 /* ExportDeclaration */:
- case 235 /* ImportDeclaration */:
+ case 243 /* ExportDeclaration */:
+ case 237 /* ImportDeclaration */:
return ts.nodeIsPresent(n.moduleSpecifier);
- case 190 /* PrefixUnaryExpression */:
+ case 191 /* PrefixUnaryExpression */:
return isCompletedNode(n.operand, sourceFile);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
return isCompletedNode(n.right, sourceFile);
- case 193 /* ConditionalExpression */:
+ case 194 /* ConditionalExpression */:
return isCompletedNode(n.whenFalse, sourceFile);
default:
return true;
@@ -65455,7 +70396,7 @@ var ts;
// for the position of the relevant node (or comma).
var syntaxList = ts.forEach(node.parent.getChildren(), function (c) {
// find syntax list that covers the span of the node
- if (c.kind === 292 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) {
+ if (c.kind === 293 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) {
return c;
}
});
@@ -65497,7 +70438,7 @@ var ts;
if (includeJsDocComment === void 0) { includeJsDocComment = false; }
var current = sourceFile;
outer: while (true) {
- if (isToken(current)) {
+ if (ts.isToken(current)) {
// exit early
return current;
}
@@ -65522,8 +70463,8 @@ var ts;
}
}
// find the child that contains 'position'
- for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) {
- var child = current.getChildAt(i);
+ for (var _a = 0, _b = current.getChildren(); _a < _b.length; _a++) {
+ var child = _b[_a];
// all jsDocComment nodes were already visited
if (ts.isJSDocNode(child)) {
continue;
@@ -65547,18 +70488,18 @@ var ts;
}
}
/**
- * The token on the left of the position is the token that strictly includes the position
- * or sits to the left of the cursor if it is on a boundary. For example
- *
- * fo|o -> will return foo
- * foo <comment> |bar -> will return foo
- *
- */
+ * The token on the left of the position is the token that strictly includes the position
+ * or sits to the left of the cursor if it is on a boundary. For example
+ *
+ * fo|o -> will return foo
+ * foo <comment> |bar -> will return foo
+ *
+ */
function findTokenOnLeftOfPosition(file, position) {
// Ideally, getTokenAtPosition should return a token. However, it is currently
// broken, so we do a check to make sure the result was indeed a token.
var tokenAtPosition = getTokenAtPosition(file, position);
- if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
+ if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
return tokenAtPosition;
}
return findPrecedingToken(position, file);
@@ -65567,7 +70508,7 @@ var ts;
function findNextToken(previousToken, parent) {
return find(parent);
function find(n) {
- if (isToken(n) && n.pos === previousToken.end) {
+ if (ts.isToken(n) && n.pos === previousToken.end) {
// this is token that starts at the end of previous token - return it
return n;
}
@@ -65590,7 +70531,7 @@ var ts;
function findPrecedingToken(position, sourceFile, startNode) {
return find(startNode || sourceFile);
function findRightmostToken(n) {
- if (isToken(n)) {
+ if (ts.isToken(n)) {
return n;
}
var children = n.getChildren();
@@ -65598,11 +70539,11 @@ var ts;
return candidate && findRightmostToken(candidate);
}
function find(n) {
- if (isToken(n)) {
+ if (ts.isToken(n)) {
return n;
}
var children = n.getChildren();
- for (var i = 0, len = children.length; i < len; i++) {
+ for (var i = 0; i < children.length; i++) {
var child = children[i];
// condition 'position < child.end' checks if child node end after the position
// in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc'
@@ -65627,7 +70568,7 @@ var ts;
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 261 /* SourceFile */);
+ ts.Debug.assert(startNode !== undefined || n.kind === 264 /* SourceFile */);
// Here we know that none of child token nodes embrace the position,
// the only known case is when position is at the end of the file.
// Try to find the rightmost token in the file without filtering.
@@ -65686,17 +70627,17 @@ var ts;
return true;
}
// <div> { | </div> or <div a={| </div>
- if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 252 /* JsxExpression */) {
+ if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 255 /* JsxExpression */) {
return true;
}
// <div> {
// |
// } < /div>
- if (token && token.kind === 17 /* CloseBraceToken */ && token.parent.kind === 252 /* JsxExpression */) {
+ if (token && token.kind === 17 /* CloseBraceToken */ && token.parent.kind === 255 /* JsxExpression */) {
return true;
}
// <div>|</div>
- if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 249 /* JsxClosingElement */) {
+ if (token.kind === 26 /* LessThanToken */ && token.parent.kind === 251 /* JsxClosingElement */) {
return true;
}
return false;
@@ -65727,10 +70668,10 @@ var ts;
// Internally, we represent the end of the comment at the newline and closing '/', respectively.
return predicate ?
ts.forEach(commentRanges, function (c) { return c.pos < position &&
- (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) &&
+ (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) &&
predicate(c); }) :
ts.forEach(commentRanges, function (c) { return c.pos < position &&
- (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); });
+ (c.kind === 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); });
}
return false;
}
@@ -65751,7 +70692,7 @@ var ts;
*/
function getJsDocTagAtPosition(sourceFile, position) {
var node = ts.getTokenAtPosition(sourceFile, position);
- if (isToken(node)) {
+ if (ts.isToken(node)) {
switch (node.kind) {
case 103 /* VarKeyword */:
case 109 /* LetKeyword */:
@@ -65808,19 +70749,15 @@ var ts;
}
ts.getNodeModifiers = getNodeModifiers;
function getTypeArgumentOrTypeParameterList(node) {
- if (node.kind === 157 /* TypeReference */ || node.kind === 179 /* CallExpression */) {
+ if (node.kind === 158 /* TypeReference */ || node.kind === 180 /* CallExpression */) {
return node.typeArguments;
}
- if (ts.isFunctionLike(node) || node.kind === 226 /* ClassDeclaration */ || node.kind === 227 /* InterfaceDeclaration */) {
+ if (ts.isFunctionLike(node) || node.kind === 228 /* ClassDeclaration */ || node.kind === 229 /* InterfaceDeclaration */) {
return node.typeParameters;
}
return undefined;
}
ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList;
- function isToken(n) {
- return n.kind >= 0 /* FirstToken */ && n.kind <= 140 /* LastToken */;
- }
- ts.isToken = isToken;
function isWord(kind) {
return kind === 70 /* Identifier */ || ts.isKeyword(kind);
}
@@ -65877,18 +70814,18 @@ var ts;
}
ts.compareDataObjects = compareDataObjects;
function isArrayLiteralOrObjectLiteralDestructuringPattern(node) {
- if (node.kind === 175 /* ArrayLiteralExpression */ ||
- node.kind === 176 /* ObjectLiteralExpression */) {
+ if (node.kind === 176 /* ArrayLiteralExpression */ ||
+ node.kind === 177 /* ObjectLiteralExpression */) {
// [a,b,c] from:
// [a, b, c] = someExpression;
- if (node.parent.kind === 192 /* BinaryExpression */ &&
+ if (node.parent.kind === 193 /* BinaryExpression */ &&
node.parent.left === node &&
node.parent.operatorToken.kind === 57 /* EqualsToken */) {
return true;
}
// [a, b, c] from:
// for([a, b, c] of expression)
- if (node.parent.kind === 213 /* ForOfStatement */ &&
+ if (node.parent.kind === 215 /* ForOfStatement */ &&
node.parent.initializer === node) {
return true;
}
@@ -65896,7 +70833,7 @@ var ts;
// [x, [a, b, c] ] = someExpression
// or
// {x, a: {a, b, c} } = someExpression
- if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 257 /* PropertyAssignment */ ? node.parent.parent : node.parent)) {
+ if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 260 /* PropertyAssignment */ ? node.parent.parent : node.parent)) {
return true;
}
}
@@ -65924,12 +70861,47 @@ var ts;
}
}
ts.isInNonReferenceComment = isInNonReferenceComment;
+ function createTextSpanFromNode(node, sourceFile) {
+ return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd());
+ }
+ ts.createTextSpanFromNode = createTextSpanFromNode;
+ function isTypeKeyword(kind) {
+ switch (kind) {
+ case 118 /* AnyKeyword */:
+ case 121 /* BooleanKeyword */:
+ case 129 /* NeverKeyword */:
+ case 132 /* NumberKeyword */:
+ case 133 /* ObjectKeyword */:
+ case 135 /* StringKeyword */:
+ case 136 /* SymbolKeyword */:
+ case 104 /* VoidKeyword */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isTypeKeyword = isTypeKeyword;
+ /** True if the symbol is for an external module, as opposed to a namespace. */
+ function isExternalModuleSymbol(moduleSymbol) {
+ ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */));
+ return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */;
+ }
+ ts.isExternalModuleSymbol = isExternalModuleSymbol;
+ /** Returns `true` the first time it encounters a node and `false` afterwards. */
+ function nodeSeenTracker() {
+ var seen = [];
+ return function (node) {
+ var id = ts.getNodeId(node);
+ return !seen[id] && (seen[id] = true);
+ };
+ }
+ ts.nodeSeenTracker = nodeSeenTracker;
})(ts || (ts = {}));
// Display-part writer helpers
/* @internal */
(function (ts) {
function isFirstDeclarationOfSymbolParameter(symbol) {
- return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 144 /* Parameter */;
+ return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 145 /* Parameter */;
}
ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter;
var displayPartWriter = getDisplayPartWriter();
@@ -65946,13 +70918,15 @@ var ts;
writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); },
writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); },
writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); },
+ writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); },
writeSymbol: writeSymbol,
writeLine: writeLine,
increaseIndent: function () { indent++; },
decreaseIndent: function () { indent--; },
clear: resetWriter,
trackSymbol: ts.noop,
- reportInaccessibleThisError: ts.noop
+ reportInaccessibleThisError: ts.noop,
+ reportIllegalExtends: ts.noop
};
function writeIndent() {
if (lineStart) {
@@ -66105,23 +71079,18 @@ var ts;
function getDeclaredName(typeChecker, symbol, location) {
// If this is an export or import specifier it could have been renamed using the 'as' syntax.
// If so we want to search for whatever is under the cursor.
- if (isImportOrExportSpecifierName(location)) {
- return location.getText();
- }
- else if (ts.isStringOrNumericLiteral(location) &&
- location.parent.kind === 142 /* ComputedPropertyName */) {
+ if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 143 /* ComputedPropertyName */) {
return location.text;
}
// Try to get the local symbol if we're dealing with an 'export default'
// since that symbol has the "true" name.
var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol);
- var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol);
- return name;
+ return typeChecker.symbolToString(localExportDefaultSymbol || symbol);
}
ts.getDeclaredName = getDeclaredName;
function isImportOrExportSpecifierName(location) {
return location.parent &&
- (location.parent.kind === 239 /* ImportSpecifier */ || location.parent.kind === 243 /* ExportSpecifier */) &&
+ (location.parent.kind === 241 /* ImportSpecifier */ || location.parent.kind === 245 /* ExportSpecifier */) &&
location.parent.propertyName === location;
}
ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName;
@@ -66137,7 +71106,6 @@ var ts;
(name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) {
return name.substring(1, length - 1);
}
- ;
return name;
}
ts.stripQuotes = stripQuotes;
@@ -66188,6 +71156,22 @@ var ts;
};
}
ts.sanitizeConfigFile = sanitizeConfigFile;
+ function getFirstNonSpaceCharacterPosition(text, position) {
+ while (ts.isWhiteSpace(text.charCodeAt(position))) {
+ position += 1;
+ }
+ return position;
+ }
+ ts.getFirstNonSpaceCharacterPosition = getFirstNonSpaceCharacterPosition;
+ function getOpenBrace(constructor, sourceFile) {
+ // First token is the open curly, this is where we want to put the 'super' call.
+ return constructor.body.getFirstToken(sourceFile);
+ }
+ ts.getOpenBrace = getOpenBrace;
+ function getOpenBraceOfClassLike(declaration, sourceFile) {
+ return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1);
+ }
+ ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -66236,7 +71220,7 @@ var ts;
function canFollow(keyword1, keyword2) {
if (ts.isAccessibilityModifier(keyword1)) {
if (keyword2 === 124 /* GetKeyword */ ||
- keyword2 === 133 /* SetKeyword */ ||
+ keyword2 === 134 /* SetKeyword */ ||
keyword2 === 122 /* ConstructorKeyword */ ||
keyword2 === 114 /* StaticKeyword */) {
// Allow things like "public get", "public constructor" and "public static".
@@ -66255,9 +71239,9 @@ var ts;
var entries = [];
var dense = classifications.spans;
var lastEnd = 0;
- for (var i = 0, n = dense.length; i < n; i += 3) {
+ for (var i = 0; i < dense.length; i += 3) {
var start = dense[i];
- var length_4 = dense[i + 1];
+ var length_5 = dense[i + 1];
var type = dense[i + 2];
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
@@ -66266,8 +71250,8 @@ var ts;
entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
}
}
- entries.push({ length: length_4, classification: convertClassification(type) });
- lastEnd = start + length_4;
+ entries.push({ length: length_5, classification: convertClassification(type) });
+ lastEnd = start + length_5;
}
var whitespaceLength = text.length - lastEnd;
if (whitespaceLength > 0) {
@@ -66335,7 +71319,7 @@ var ts;
case 5 /* InTemplateMiddleOrTail */:
text = "}\n" + text;
offset = 2;
- // fallthrough
+ // falls through
case 6 /* InTemplateSubstitutionPosition */:
templateStack.push(13 /* TemplateHead */);
break;
@@ -66395,10 +71379,10 @@ var ts;
angleBracketStack--;
}
else if (token === 118 /* AnyKeyword */ ||
- token === 134 /* StringKeyword */ ||
+ token === 135 /* StringKeyword */ ||
token === 132 /* NumberKeyword */ ||
token === 121 /* BooleanKeyword */ ||
- token === 135 /* SymbolKeyword */) {
+ token === 136 /* SymbolKeyword */) {
if (angleBracketStack > 0 && !syntacticClassifierAbsent) {
// If it looks like we're could be in something generic, don't classify this
// as a keyword. We may just get overwritten by the syntactic classifier,
@@ -66570,7 +71554,7 @@ var ts;
}
}
function isKeyword(token) {
- return token >= 71 /* FirstKeyword */ && token <= 140 /* LastKeyword */;
+ return token >= 71 /* FirstKeyword */ && token <= 141 /* LastKeyword */;
}
function classFromKind(token) {
if (isKeyword(token)) {
@@ -66627,10 +71611,10 @@ var ts;
// That means we're calling back into the host around every 1.2k of the file we process.
// Lib.d.ts has similar numbers.
switch (kind) {
- case 230 /* ModuleDeclaration */:
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 225 /* FunctionDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 227 /* FunctionDeclaration */:
cancellationToken.throwIfCancellationRequested();
}
}
@@ -66681,7 +71665,7 @@ var ts;
*/
function hasValueSideModule(symbol) {
return ts.forEach(symbol.declarations, function (declaration) {
- return declaration.kind === 230 /* ModuleDeclaration */ &&
+ return declaration.kind === 232 /* ModuleDeclaration */ &&
ts.getModuleInstanceState(declaration) === 1 /* Instantiated */;
});
}
@@ -66696,7 +71680,7 @@ var ts;
// Only bother calling into the typechecker if this is an identifier that
// could possibly resolve to a type name. This makes classification run
// in a third of the time it would normally take.
- if (classifiableNames[identifier.text]) {
+ if (classifiableNames.get(identifier.text)) {
var symbol = typeChecker.getSymbolAtLocation(node);
if (symbol) {
var type = classifySymbol(symbol, ts.getMeaningFromLocation(node));
@@ -66742,7 +71726,7 @@ var ts;
ts.Debug.assert(classifications.spans.length % 3 === 0);
var dense = classifications.spans;
var result = [];
- for (var i = 0, n = dense.length; i < n; i += 3) {
+ for (var i = 0; i < dense.length; i += 3) {
result.push({
textSpan: ts.createTextSpan(dense[i], dense[i + 1]),
classificationType: getClassificationTypeName(dense[i + 2])
@@ -66845,16 +71829,16 @@ var ts;
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */);
pos = tag.tagName.end;
switch (tag.kind) {
- case 281 /* JSDocParameterTag */:
+ case 285 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 284 /* JSDocTemplateTag */:
+ case 288 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
break;
- case 283 /* JSDocTypeTag */:
+ case 287 /* JSDocTypeTag */:
processElement(tag.typeExpression);
break;
- case 282 /* JSDocReturnTag */:
+ case 286 /* JSDocReturnTag */:
processElement(tag.typeExpression);
break;
}
@@ -66941,22 +71925,22 @@ var ts;
}
function tryClassifyJsxElementName(token) {
switch (token.parent && token.parent.kind) {
- case 248 /* JsxOpeningElement */:
+ case 250 /* JsxOpeningElement */:
if (token.parent.tagName === token) {
return 19 /* jsxOpenTagName */;
}
break;
- case 249 /* JsxClosingElement */:
+ case 251 /* JsxClosingElement */:
if (token.parent.tagName === token) {
return 20 /* jsxCloseTagName */;
}
break;
- case 247 /* JsxSelfClosingElement */:
+ case 249 /* JsxSelfClosingElement */:
if (token.parent.tagName === token) {
return 21 /* jsxSelfClosingTagName */;
}
break;
- case 250 /* JsxAttribute */:
+ case 252 /* JsxAttribute */:
if (token.parent.name === token) {
return 22 /* jsxAttribute */;
}
@@ -66984,17 +71968,17 @@ var ts;
if (token) {
if (tokenKind === 57 /* EqualsToken */) {
// the '=' in a variable declaration is special cased here.
- if (token.parent.kind === 223 /* VariableDeclaration */ ||
- token.parent.kind === 147 /* PropertyDeclaration */ ||
- token.parent.kind === 144 /* Parameter */ ||
- token.parent.kind === 250 /* JsxAttribute */) {
+ if (token.parent.kind === 225 /* VariableDeclaration */ ||
+ token.parent.kind === 148 /* PropertyDeclaration */ ||
+ token.parent.kind === 145 /* Parameter */ ||
+ token.parent.kind === 252 /* JsxAttribute */) {
return 5 /* operator */;
}
}
- if (token.parent.kind === 192 /* BinaryExpression */ ||
- token.parent.kind === 190 /* PrefixUnaryExpression */ ||
- token.parent.kind === 191 /* PostfixUnaryExpression */ ||
- token.parent.kind === 193 /* ConditionalExpression */) {
+ if (token.parent.kind === 193 /* BinaryExpression */ ||
+ token.parent.kind === 191 /* PrefixUnaryExpression */ ||
+ token.parent.kind === 192 /* PostfixUnaryExpression */ ||
+ token.parent.kind === 194 /* ConditionalExpression */) {
return 5 /* operator */;
}
}
@@ -67004,7 +71988,7 @@ var ts;
return 4 /* numericLiteral */;
}
else if (tokenKind === 9 /* StringLiteral */) {
- return token.parent.kind === 250 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */;
+ return token.parent.kind === 252 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */;
}
else if (tokenKind === 11 /* RegularExpressionLiteral */) {
// TODO: we should get another classification type for these literals.
@@ -67020,32 +72004,32 @@ var ts;
else if (tokenKind === 70 /* Identifier */) {
if (token) {
switch (token.parent.kind) {
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
if (token.parent.name === token) {
return 11 /* className */;
}
return;
- case 143 /* TypeParameter */:
+ case 144 /* TypeParameter */:
if (token.parent.name === token) {
return 15 /* typeParameterName */;
}
return;
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
if (token.parent.name === token) {
return 13 /* interfaceName */;
}
return;
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
if (token.parent.name === token) {
return 12 /* enumName */;
}
return;
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
if (token.parent.name === token) {
return 14 /* moduleName */;
}
return;
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
if (token.parent.name === token) {
return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */;
}
@@ -67062,9 +72046,8 @@ var ts;
// Ignore nodes that don't intersect the original span to classify.
if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) {
checkForClassificationCancellation(cancellationToken, element.kind);
- var children = element.getChildren(sourceFile);
- for (var i = 0, n = children.length; i < n; i++) {
- var child = children[i];
+ for (var _i = 0, _a = element.getChildren(sourceFile); _i < _a.length; _i++) {
+ var child = _a[_i];
if (!tryClassifyNode(child)) {
// Recurse into our child nodes.
processElement(child);
@@ -67075,259 +72058,31 @@ var ts;
}
ts.getEncodedSyntacticClassifications = getEncodedSyntacticClassifications;
})(ts || (ts = {}));
-/// <reference path='../compiler/utilities.ts' />
/* @internal */
var ts;
(function (ts) {
var Completions;
(function (Completions) {
- function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) {
- if (ts.isInReferenceComment(sourceFile, position)) {
- return getTripleSlashReferenceCompletion(sourceFile, position);
- }
- if (ts.isInString(sourceFile, position)) {
- return getStringLiteralCompletionEntries(sourceFile, position);
- }
- var completionData = getCompletionData(typeChecker, log, sourceFile, position);
- if (!completionData) {
- return undefined;
- }
- var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName;
- if (isJsDocTagName) {
- // If the current position is a jsDoc tag name, only tag names should be provided for completion
- return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() };
- }
- var entries = [];
- if (ts.isSourceFileJavaScript(sourceFile)) {
- var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true);
- ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames));
- }
- else {
- if (!symbols || symbols.length === 0) {
- if (sourceFile.languageVariant === 1 /* JSX */ &&
- location.parent && location.parent.kind === 249 /* JsxClosingElement */) {
- // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag,
- // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element.
- // For example:
- // var x = <div> </ /*1*/> completion list at "1" will contain "div" with type any
- var tagName = location.parent.parent.openingElement.tagName;
- entries.push({
- name: tagName.text,
- kind: undefined,
- kindModifiers: undefined,
- sortText: "0",
- });
- }
- else {
- return undefined;
- }
- }
- getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true);
- }
- // Add keywords if this is not a member completion list
- if (!isMemberCompletion && !isJsDocTagName) {
- ts.addRange(entries, keywordCompletions);
- }
- return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
- function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) {
- var entries = [];
- var nameTable = ts.getNameTable(sourceFile);
- for (var name_43 in nameTable) {
- // Skip identifiers produced only from the current location
- if (nameTable[name_43] === position) {
- continue;
- }
- if (!uniqueNames[name_43]) {
- uniqueNames[name_43] = name_43;
- var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_43), compilerOptions.target, /*performCharacterChecks*/ true);
- if (displayName) {
- var entry = {
- name: displayName,
- kind: ts.ScriptElementKind.warning,
- kindModifiers: "",
- sortText: "1"
- };
- entries.push(entry);
- }
- }
- }
- return entries;
- }
- function createCompletionEntry(symbol, location, performCharacterChecks) {
- // Try to get a valid display name for this symbol, if we could not find one, then ignore it.
- // We would like to only show things that can be added after a dot, so for instance numeric properties can
- // not be accessed with a dot (a.1 <- invalid)
- var displayName = getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, compilerOptions.target, performCharacterChecks, location);
- if (!displayName) {
- return undefined;
- }
- // TODO(drosen): Right now we just permit *all* semantic meanings when calling
- // 'getSymbolKind' which is permissible given that it is backwards compatible; but
- // really we should consider passing the meaning for the node so that we don't report
- // that a suggestion for a value is an interface. We COULD also just do what
- // 'getSymbolModifiers' does, which is to use the first declaration.
- // Use a 'sortText' of 0' so that all symbol completion entries come before any other
- // entries (like JavaScript identifier entries).
- return {
- name: displayName,
- kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location),
- kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
- sortText: "0",
- };
- }
- function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks) {
- var start = ts.timestamp();
- var uniqueNames = ts.createMap();
- if (symbols) {
- for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) {
- var symbol = symbols_4[_i];
- var entry = createCompletionEntry(symbol, location, performCharacterChecks);
- if (entry) {
- var id = ts.escapeIdentifier(entry.name);
- if (!uniqueNames[id]) {
- entries.push(entry);
- uniqueNames[id] = id;
- }
- }
- }
- }
- log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start));
- return uniqueNames;
- }
- function getStringLiteralCompletionEntries(sourceFile, position) {
- var node = ts.findPrecedingToken(position, sourceFile);
- if (!node || node.kind !== 9 /* StringLiteral */) {
- return undefined;
- }
- if (node.parent.kind === 257 /* PropertyAssignment */ &&
- node.parent.parent.kind === 176 /* ObjectLiteralExpression */ &&
- node.parent.name === node) {
- // Get quoted name of properties of the object literal expression
- // i.e. interface ConfigFiles {
- // 'jspm:dev': string
- // }
- // let files: ConfigFiles = {
- // '/*completion position*/'
- // }
- //
- // function foo(c: ConfigFiles) {}
- // foo({
- // '/*completion position*/'
- // });
- return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent);
- }
- else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) {
- // Get all names of properties on the expression
- // i.e. interface A {
- // 'prop1': string
- // }
- // let a: A;
- // a['/*completion position*/']
- return getStringLiteralCompletionEntriesFromElementAccess(node.parent);
- }
- else if (node.parent.kind === 235 /* ImportDeclaration */ || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, false)) {
- // Get all known external module names or complete a path to a module
- // i.e. import * as ns from "/*completion position*/";
- // import x = require("/*completion position*/");
- // var y = require("/*completion position*/");
- return getStringLiteralCompletionEntriesFromModuleNames(node);
- }
- else {
- var argumentInfo = ts.SignatureHelp.getContainingArgumentInfo(node, position, sourceFile);
- if (argumentInfo) {
- // Get string literal completions from specialized signatures of the target
- // i.e. declare function f(a: 'A');
- // f("/*completion position*/")
- return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo);
- }
- // Get completion for string literal from string literal type
- // i.e. var x: "hi" | "hello" = "/*completion position*/"
- return getStringLiteralCompletionEntriesFromContextualType(node);
- }
- }
- function getStringLiteralCompletionEntriesFromPropertyAssignment(element) {
- var type = typeChecker.getContextualType(element.parent);
- var entries = [];
- if (type) {
- getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false);
- if (entries.length) {
- return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries };
- }
- }
- }
- function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo) {
- var candidates = [];
- var entries = [];
- typeChecker.getResolvedSignature(argumentInfo.invocation, candidates);
- for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) {
- var candidate = candidates_3[_i];
- if (candidate.parameters.length > argumentInfo.argumentIndex) {
- var parameter = candidate.parameters[argumentInfo.argumentIndex];
- addStringLiteralCompletionsFromType(typeChecker.getTypeAtLocation(parameter.valueDeclaration), entries);
- }
- }
- if (entries.length) {
- return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries };
- }
- return undefined;
- }
- function getStringLiteralCompletionEntriesFromElementAccess(node) {
- var type = typeChecker.getTypeAtLocation(node.expression);
- var entries = [];
- if (type) {
- getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false);
- if (entries.length) {
- return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries };
- }
- }
- return undefined;
- }
- function getStringLiteralCompletionEntriesFromContextualType(node) {
- var type = typeChecker.getContextualType(node);
- if (type) {
- var entries_2 = [];
- addStringLiteralCompletionsFromType(type, entries_2);
- if (entries_2.length) {
- return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 };
- }
- }
- return undefined;
- }
- function addStringLiteralCompletionsFromType(type, result) {
- if (!type) {
- return;
- }
- if (type.flags & 65536 /* Union */) {
- ts.forEach(type.types, function (t) { return addStringLiteralCompletionsFromType(t, result); });
- }
- else {
- if (type.flags & 32 /* StringLiteral */) {
- result.push({
- name: type.text,
- kindModifiers: ts.ScriptElementKindModifier.none,
- kind: ts.ScriptElementKind.variableElement,
- sortText: "0"
- });
- }
- }
- }
- function getStringLiteralCompletionEntriesFromModuleNames(node) {
+ var PathCompletions;
+ (function (PathCompletions) {
+ function getStringLiteralCompletionEntriesFromModuleNames(node, compilerOptions, host, typeChecker) {
var literalValue = ts.normalizeSlashes(node.text);
var scriptPath = node.getSourceFile().path;
var scriptDirectory = ts.getDirectoryPath(scriptPath);
var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1);
var entries;
if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) {
+ var extensions = ts.getSupportedExtensions(compilerOptions);
if (compilerOptions.rootDirs) {
- entries = getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ false, span, scriptPath);
+ entries = getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath);
}
else {
- entries = getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ false, span, scriptPath);
+ entries = getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath);
}
}
else {
// Check for node modules
- entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span);
+ entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker);
}
return {
isGlobalCompletion: false,
@@ -67336,6 +72091,7 @@ var ts;
entries: entries
};
}
+ PathCompletions.getStringLiteralCompletionEntriesFromModuleNames = getStringLiteralCompletionEntriesFromModuleNames;
/**
* Takes a script path and returns paths for all potential folders that could be merged with its
* containing folder via the "rootDirs" compiler option
@@ -67355,21 +72111,21 @@ var ts;
// Now find a path for each potential directory that is to be merged with the one containing the script
return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }));
}
- function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, exclude) {
+ function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, compilerOptions, host, exclude) {
var basePath = compilerOptions.project || host.getCurrentDirectory();
var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase);
var result = [];
for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) {
var baseDirectory = baseDirectories_1[_i];
- getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, exclude, result);
+ getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, host, exclude, result);
}
return result;
}
/**
* Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
*/
- function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) {
+ function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, host, exclude, result) {
if (result === void 0) { result = []; }
if (fragment === undefined) {
fragment = "";
@@ -67405,13 +72161,13 @@ var ts;
continue;
}
var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
- if (!foundFiles[foundFileName]) {
- foundFiles[foundFileName] = true;
+ if (!foundFiles.get(foundFileName)) {
+ foundFiles.set(foundFileName, true);
}
}
- for (var foundFile in foundFiles) {
+ ts.forEachKey(foundFiles, function (foundFile) {
result.push(createCompletionEntryForModule(foundFile, ts.ScriptElementKind.scriptElement, span));
- }
+ });
}
// If possible, get folder completion as well
var directories = tryGetDirectories(host, baseDirectory);
@@ -67432,14 +72188,14 @@ var ts;
* Modules from node_modules (i.e. those listed in package.json)
* This includes all files that are found in node_modules/moduleName/ with acceptable file extensions
*/
- function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span) {
+ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span, compilerOptions, host, typeChecker) {
var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths;
var result;
if (baseUrl) {
var fileExtensions = ts.getSupportedExtensions(compilerOptions);
var projectDir = compilerOptions.project || host.getCurrentDirectory();
var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl);
- result = getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span);
+ result = getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host);
if (paths) {
for (var path in paths) {
if (paths.hasOwnProperty(path)) {
@@ -67447,7 +72203,7 @@ var ts;
if (paths[path]) {
for (var _i = 0, _a = paths[path]; _i < _a.length; _i++) {
var pattern = _a[_i];
- for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions); _b < _c.length; _b++) {
+ for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _b < _c.length; _b++) {
var match = _c[_b];
result.push(createCompletionEntryForModule(match, ts.ScriptElementKind.externalModuleName, span));
}
@@ -67468,13 +72224,13 @@ var ts;
result = [];
}
getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result);
- for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions); _d < _e.length; _d++) {
+ for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _d < _e.length; _d++) {
var moduleName = _e[_d];
result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span));
}
return result;
}
- function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions) {
+ function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) {
if (host.readDirectory) {
var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined;
if (parsed) {
@@ -67493,7 +72249,7 @@ var ts;
// that encodes the suffix, but we would have to escape the character "?" which readDirectory
// doesn't support. For now, this is safer but slower
var includeGlob = normalizedSuffix ? "**/*" : "./*";
- var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]);
+ var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]);
if (matches) {
var result = [];
// Trim away prefix and suffix
@@ -67504,8 +72260,8 @@ var ts;
continue;
}
var start = completePrefix.length;
- var length_5 = normalizedMatch.length - start - normalizedSuffix.length;
- result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_5)));
+ var length_6 = normalizedMatch.length - start - normalizedSuffix.length;
+ result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_6)));
}
return result;
}
@@ -67513,7 +72269,7 @@ var ts;
}
return undefined;
}
- function enumeratePotentialNonRelativeModules(fragment, scriptPath, options) {
+ function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) {
// Check If this is a nested module
var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1;
var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined;
@@ -67553,7 +72309,7 @@ var ts;
}
return ts.deduplicate(nonRelativeModules);
}
- function getTripleSlashReferenceCompletion(sourceFile, position) {
+ function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) {
var token = ts.getTokenAtPosition(sourceFile, position);
if (!token) {
return undefined;
@@ -67589,7 +72345,7 @@ var ts;
if (kind === "path") {
// Give completions for a relative path
var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length);
- completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path);
+ completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path);
}
else {
// Give completions based on the typings available
@@ -67599,6 +72355,7 @@ var ts;
}
return completionInfo;
}
+ PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion;
function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) {
if (result === void 0) { result = []; }
// Check for typings specified in compiler options
@@ -67624,7 +72381,7 @@ var ts;
}
if (host.getDirectories) {
// Also get all @types typings installed in visible node_modules directories
- for (var _c = 0, _d = findPackageJsons(scriptPath); _c < _d.length; _c++) {
+ for (var _c = 0, _d = findPackageJsons(scriptPath, host); _c < _d.length; _c++) {
var packageJson = _d[_c];
var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types");
getCompletionEntriesFromDirectories(host, typesDir, span, result);
@@ -67644,7 +72401,7 @@ var ts;
}
}
}
- function findPackageJsons(currentDir) {
+ function findPackageJsons(currentDir, host) {
var paths = [];
var currentConfigPath;
while (true) {
@@ -67652,11 +72409,11 @@ var ts;
if (currentConfigPath) {
paths.push(currentConfigPath);
currentDir = ts.getDirectoryPath(currentConfigPath);
- var parent_13 = ts.getDirectoryPath(currentDir);
- if (currentDir === parent_13) {
+ var parent = ts.getDirectoryPath(currentDir);
+ if (currentDir === parent) {
break;
}
- currentDir = parent_13;
+ currentDir = parent;
}
else {
break;
@@ -67667,7 +72424,7 @@ var ts;
function enumerateNodeModulesVisibleToScript(host, scriptPath) {
var result = [];
if (host.readFile && host.fileExists) {
- for (var _i = 0, _a = findPackageJsons(scriptPath); _i < _a.length; _i++) {
+ for (var _i = 0, _a = findPackageJsons(scriptPath, host); _i < _a.length; _i++) {
var packageJson = _a[_i];
var contents = tryReadingPackageJson(packageJson);
if (!contents) {
@@ -67731,26 +72488,326 @@ var ts;
function normalizeAndPreserveTrailingSlash(path) {
return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(ts.normalizePath(path)) : ts.normalizePath(path);
}
+ /**
+ * Matches a triple slash reference directive with an incomplete string literal for its path. Used
+ * to determine if the caret is currently within the string literal and capture the literal fragment
+ * for completions.
+ * For example, this matches
+ *
+ * /// <reference path="fragment
+ *
+ * but not
+ *
+ * /// <reference path="fragment"
+ */
+ var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\3"]*)$/;
+ var nodeModulesDependencyKeys = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
+ function tryGetDirectories(host, directoryName) {
+ return tryIOAndConsumeErrors(host, host.getDirectories, directoryName);
+ }
+ function tryReadDirectory(host, path, extensions, exclude, include) {
+ return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include);
+ }
+ function tryReadFile(host, path) {
+ return tryIOAndConsumeErrors(host, host.readFile, path);
+ }
+ function tryFileExists(host, path) {
+ return tryIOAndConsumeErrors(host, host.fileExists, path);
+ }
+ function tryDirectoryExists(host, path) {
+ try {
+ return ts.directoryProbablyExists(path, host);
+ }
+ catch (e) { }
+ return undefined;
+ }
+ function tryIOAndConsumeErrors(host, toApply) {
+ var args = [];
+ for (var _i = 2; _i < arguments.length; _i++) {
+ args[_i - 2] = arguments[_i];
+ }
+ try {
+ return toApply && toApply.apply(host, args);
+ }
+ catch (e) { }
+ return undefined;
+ }
+ })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {}));
+ })(Completions = ts.Completions || (ts.Completions = {}));
+})(ts || (ts = {}));
+/// <reference path="./pathCompletions.ts" />
+/* @internal */
+var ts;
+(function (ts) {
+ var Completions;
+ (function (Completions) {
+ function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) {
+ if (ts.isInReferenceComment(sourceFile, position)) {
+ return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host);
+ }
+ if (ts.isInString(sourceFile, position)) {
+ return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log);
+ }
+ var completionData = getCompletionData(typeChecker, log, sourceFile, position);
+ if (!completionData) {
+ return undefined;
+ }
+ var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, requestJsDocTagName = completionData.requestJsDocTagName, requestJsDocTag = completionData.requestJsDocTag;
+ if (requestJsDocTagName) {
+ // If the current position is a jsDoc tag name, only tag names should be provided for completion
+ return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() };
+ }
+ if (requestJsDocTag) {
+ // If the current position is a jsDoc tag, only tags should be provided for completion
+ return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagCompletions() };
+ }
+ var entries = [];
+ if (ts.isSourceFileJavaScript(sourceFile)) {
+ var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log);
+ ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target));
+ }
+ else {
+ if (!symbols || symbols.length === 0) {
+ if (sourceFile.languageVariant === 1 /* JSX */ &&
+ location.parent && location.parent.kind === 251 /* JsxClosingElement */) {
+ // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag,
+ // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element.
+ // For example:
+ // var x = <div> </ /*1*/> completion list at "1" will contain "div" with type any
+ var tagName = location.parent.parent.openingElement.tagName;
+ entries.push({
+ name: tagName.text,
+ kind: undefined,
+ kindModifiers: undefined,
+ sortText: "0",
+ });
+ }
+ else {
+ return undefined;
+ }
+ }
+ getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log);
+ }
+ // Add keywords if this is not a member completion list
+ if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) {
+ ts.addRange(entries, keywordCompletions);
+ }
+ return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries };
}
Completions.getCompletionsAtPosition = getCompletionsAtPosition;
+ function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target) {
+ var entries = [];
+ var nameTable = ts.getNameTable(sourceFile);
+ nameTable.forEach(function (pos, name) {
+ // Skip identifiers produced only from the current location
+ if (pos === position) {
+ return;
+ }
+ if (!uniqueNames.get(name)) {
+ uniqueNames.set(name, name);
+ var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name), target, /*performCharacterChecks*/ true);
+ if (displayName) {
+ var entry = {
+ name: displayName,
+ kind: ts.ScriptElementKind.warning,
+ kindModifiers: "",
+ sortText: "1"
+ };
+ entries.push(entry);
+ }
+ }
+ });
+ return entries;
+ }
+ function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target) {
+ // Try to get a valid display name for this symbol, if we could not find one, then ignore it.
+ // We would like to only show things that can be added after a dot, so for instance numeric properties can
+ // not be accessed with a dot (a.1 <- invalid)
+ var displayName = getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location);
+ if (!displayName) {
+ return undefined;
+ }
+ // TODO(drosen): Right now we just permit *all* semantic meanings when calling
+ // 'getSymbolKind' which is permissible given that it is backwards compatible; but
+ // really we should consider passing the meaning for the node so that we don't report
+ // that a suggestion for a value is an interface. We COULD also just do what
+ // 'getSymbolModifiers' does, which is to use the first declaration.
+ // Use a 'sortText' of 0' so that all symbol completion entries come before any other
+ // entries (like JavaScript identifier entries).
+ return {
+ name: displayName,
+ kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location),
+ kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
+ sortText: "0",
+ };
+ }
+ function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log) {
+ var start = ts.timestamp();
+ var uniqueNames = ts.createMap();
+ if (symbols) {
+ for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) {
+ var symbol = symbols_4[_i];
+ var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target);
+ if (entry) {
+ var id = ts.escapeIdentifier(entry.name);
+ if (!uniqueNames.get(id)) {
+ entries.push(entry);
+ uniqueNames.set(id, id);
+ }
+ }
+ }
+ }
+ log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start));
+ return uniqueNames;
+ }
+ function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) {
+ var node = ts.findPrecedingToken(position, sourceFile);
+ if (!node || node.kind !== 9 /* StringLiteral */) {
+ return undefined;
+ }
+ if (node.parent.kind === 260 /* PropertyAssignment */ &&
+ node.parent.parent.kind === 177 /* ObjectLiteralExpression */ &&
+ node.parent.name === node) {
+ // Get quoted name of properties of the object literal expression
+ // i.e. interface ConfigFiles {
+ // 'jspm:dev': string
+ // }
+ // let files: ConfigFiles = {
+ // '/*completion position*/'
+ // }
+ //
+ // function foo(c: ConfigFiles) {}
+ // foo({
+ // '/*completion position*/'
+ // });
+ return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log);
+ }
+ else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) {
+ // Get all names of properties on the expression
+ // i.e. interface A {
+ // 'prop1': string
+ // }
+ // let a: A;
+ // a['/*completion position*/']
+ return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log);
+ }
+ else if (node.parent.kind === 237 /* ImportDeclaration */ || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node) || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) {
+ // Get all known external module names or complete a path to a module
+ // i.e. import * as ns from "/*completion position*/";
+ // import x = require("/*completion position*/");
+ // var y = require("/*completion position*/");
+ return Completions.PathCompletions.getStringLiteralCompletionEntriesFromModuleNames(node, compilerOptions, host, typeChecker);
+ }
+ else if (isEqualityExpression(node.parent)) {
+ // Get completions from the type of the other operand
+ // i.e. switch (a) {
+ // case '/*completion position*/'
+ // }
+ return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.left === node ? node.parent.right : node.parent.left), typeChecker);
+ }
+ else if (ts.isCaseOrDefaultClause(node.parent)) {
+ // Get completions from the type of the switch expression
+ // i.e. x === '/*completion position'
+ return getStringLiteralCompletionEntriesFromType(typeChecker.getTypeAtLocation(node.parent.parent.parent.expression), typeChecker);
+ }
+ else {
+ var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile);
+ if (argumentInfo) {
+ // Get string literal completions from specialized signatures of the target
+ // i.e. declare function f(a: 'A');
+ // f("/*completion position*/")
+ return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker);
+ }
+ // Get completion for string literal from string literal type
+ // i.e. var x: "hi" | "hello" = "/*completion position*/"
+ return getStringLiteralCompletionEntriesFromType(typeChecker.getContextualType(node), typeChecker);
+ }
+ }
+ function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) {
+ var type = typeChecker.getContextualType(element.parent);
+ var entries = [];
+ if (type) {
+ getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log);
+ if (entries.length) {
+ return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries };
+ }
+ }
+ }
+ function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) {
+ var candidates = [];
+ var entries = [];
+ typeChecker.getResolvedSignature(argumentInfo.invocation, candidates);
+ for (var _i = 0, candidates_3 = candidates; _i < candidates_3.length; _i++) {
+ var candidate = candidates_3[_i];
+ addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker);
+ }
+ if (entries.length) {
+ return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries };
+ }
+ return undefined;
+ }
+ function getStringLiteralCompletionEntriesFromElementAccess(node, typeChecker, target, log) {
+ var type = typeChecker.getTypeAtLocation(node.expression);
+ var entries = [];
+ if (type) {
+ getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log);
+ if (entries.length) {
+ return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries };
+ }
+ }
+ return undefined;
+ }
+ function getStringLiteralCompletionEntriesFromType(type, typeChecker) {
+ if (type) {
+ var entries = [];
+ addStringLiteralCompletionsFromType(type, entries, typeChecker);
+ if (entries.length) {
+ return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries };
+ }
+ }
+ return undefined;
+ }
+ function addStringLiteralCompletionsFromType(type, result, typeChecker) {
+ if (type && type.flags & 16384 /* TypeParameter */) {
+ type = typeChecker.getApparentType(type);
+ }
+ if (!type) {
+ return;
+ }
+ if (type.flags & 65536 /* Union */) {
+ for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
+ var t = _a[_i];
+ addStringLiteralCompletionsFromType(t, result, typeChecker);
+ }
+ }
+ else if (type.flags & 32 /* StringLiteral */) {
+ result.push({
+ name: type.text,
+ kindModifiers: ts.ScriptElementKindModifier.none,
+ kind: ts.ScriptElementKind.variableElement,
+ sortText: "0"
+ });
+ }
+ }
function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) {
// Compute all the completion symbols again.
var completionData = getCompletionData(typeChecker, log, sourceFile, position);
if (completionData) {
- var symbols = completionData.symbols, location_3 = completionData.location;
+ var symbols = completionData.symbols, location_1 = completionData.location;
// Find the symbol with the matching entry name.
// We don't need to perform character checks here because we're only comparing the
// name against 'entryName' (which is known to be good), not building a new
// completion entry.
- var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_3) === entryName ? s : undefined; });
+ var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_1) === entryName ? s : undefined; });
if (symbol) {
- var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_3, location_3, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind;
+ var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_1, location_1, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags;
return {
name: entryName,
kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
kind: symbolKind,
displayParts: displayParts,
- documentation: documentation
+ documentation: documentation,
+ tags: tags
};
}
}
@@ -67762,7 +72819,8 @@ var ts;
kind: ts.ScriptElementKind.keyword,
kindModifiers: ts.ScriptElementKindModifier.none,
displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)],
- documentation: undefined
+ documentation: undefined,
+ tags: undefined
};
}
return undefined;
@@ -67772,19 +72830,22 @@ var ts;
// Compute all the completion symbols again.
var completionData = getCompletionData(typeChecker, log, sourceFile, position);
if (completionData) {
- var symbols = completionData.symbols, location_4 = completionData.location;
+ var symbols = completionData.symbols, location_2 = completionData.location;
// Find the symbol with the matching entry name.
// We don't need to perform character checks here because we're only comparing the
// name against 'entryName' (which is known to be good), not building a new
// completion entry.
- return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_4) === entryName ? s : undefined; });
+ return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; });
}
return undefined;
}
Completions.getCompletionEntrySymbol = getCompletionEntrySymbol;
function getCompletionData(typeChecker, log, sourceFile, position) {
var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile);
- var isJsDocTagName = false;
+ // JsDoc tag-name is just the name of the JSDoc tagname (exclude "@")
+ var requestJsDocTagName = false;
+ // JsDoc tag includes both "@" and tag-name
+ var requestJsDocTag = false;
var start = ts.timestamp();
var currentToken = ts.getTokenAtPosition(sourceFile, position);
log("getCompletionData: Get current token: " + (ts.timestamp() - start));
@@ -67793,10 +72854,32 @@ var ts;
var insideComment = ts.isInsideComment(sourceFile, currentToken, position);
log("getCompletionData: Is inside comment: " + (ts.timestamp() - start));
if (insideComment) {
- // The current position is next to the '@' sign, when no tag name being provided yet.
- // Provide a full list of tag names
- if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
- isJsDocTagName = true;
+ if (ts.hasDocComment(sourceFile, position)) {
+ // The current position is next to the '@' sign, when no tag name being provided yet.
+ // Provide a full list of tag names
+ if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) {
+ requestJsDocTagName = true;
+ }
+ else {
+ // When completion is requested without "@", we will have check to make sure that
+ // there are no comments prefix the request position. We will only allow "*" and space.
+ // e.g
+ // /** |c| /*
+ //
+ // /**
+ // |c|
+ // */
+ //
+ // /**
+ // * |c|
+ // */
+ //
+ // /**
+ // * |c|
+ // */
+ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile);
+ requestJsDocTag = !(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/));
+ }
}
// Completion should work inside certain JsDoc tags. For example:
// /** @type {number | string} */
@@ -67805,12 +72888,12 @@ var ts;
var tag = ts.getJsDocTagAtPosition(sourceFile, position);
if (tag) {
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
- isJsDocTagName = true;
+ requestJsDocTagName = true;
}
switch (tag.kind) {
- case 283 /* JSDocTypeTag */:
- case 281 /* JSDocParameterTag */:
- case 282 /* JSDocReturnTag */:
+ case 287 /* JSDocTypeTag */:
+ case 285 /* JSDocParameterTag */:
+ case 286 /* JSDocReturnTag */:
var tagWithExpression = tag;
if (tagWithExpression.typeExpression) {
insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end;
@@ -67818,8 +72901,8 @@ var ts;
break;
}
}
- if (isJsDocTagName) {
- return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName };
+ if (requestJsDocTagName || requestJsDocTag) {
+ return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag };
}
if (!insideJsDocTagExpression) {
// Proceed if the current position is in jsDoc tag expression; otherwise it is a normal
@@ -67855,13 +72938,13 @@ var ts;
log("Returning an empty list because completion was requested in an invalid position.");
return undefined;
}
- var parent_14 = contextToken.parent, kind = contextToken.kind;
- if (kind === 22 /* DotToken */) {
- if (parent_14.kind === 177 /* PropertyAccessExpression */) {
+ var parent = contextToken.parent;
+ if (contextToken.kind === 22 /* DotToken */) {
+ if (parent.kind === 178 /* PropertyAccessExpression */) {
node = contextToken.parent.expression;
isRightOfDot = true;
}
- else if (parent_14.kind === 141 /* QualifiedName */) {
+ else if (parent.kind === 142 /* QualifiedName */) {
node = contextToken.parent.left;
isRightOfDot = true;
}
@@ -67872,13 +72955,34 @@ var ts;
}
}
else if (sourceFile.languageVariant === 1 /* JSX */) {
- if (kind === 26 /* LessThanToken */) {
- isRightOfOpenTag = true;
- location = contextToken;
+ // <UI.Test /* completion position */ />
+ // If the tagname is a property access expression, we will then walk up to the top most of property access expression.
+ // Then, try to get a JSX container and its associated attributes type.
+ if (parent && parent.kind === 178 /* PropertyAccessExpression */) {
+ contextToken = parent;
+ parent = parent.parent;
}
- else if (kind === 40 /* SlashToken */ && contextToken.parent.kind === 249 /* JsxClosingElement */) {
- isStartingCloseTag = true;
- location = contextToken;
+ switch (parent.kind) {
+ case 251 /* JsxClosingElement */:
+ if (contextToken.kind === 40 /* SlashToken */) {
+ isStartingCloseTag = true;
+ location = contextToken;
+ }
+ break;
+ case 193 /* BinaryExpression */:
+ if (!(parent.left.flags & 32768 /* ThisNodeHasError */)) {
+ // It has a left-hand side, so we're not in an opening JSX tag.
+ break;
+ }
+ // falls through
+ case 249 /* JsxSelfClosingElement */:
+ case 248 /* JsxElement */:
+ case 250 /* JsxOpeningElement */:
+ if (contextToken.kind === 26 /* LessThanToken */) {
+ isRightOfOpenTag = true;
+ location = contextToken;
+ }
+ break;
}
}
}
@@ -67919,13 +73023,13 @@ var ts;
}
}
log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart));
- return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName };
+ return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag };
function getTypeScriptMemberSymbols() {
// Right of dot member completion list
isGlobalCompletion = false;
isMemberCompletion = true;
isNewIdentifierLocation = false;
- if (node.kind === 70 /* Identifier */ || node.kind === 141 /* QualifiedName */ || node.kind === 177 /* PropertyAccessExpression */) {
+ if (node.kind === 70 /* Identifier */ || node.kind === 142 /* QualifiedName */ || node.kind === 178 /* PropertyAccessExpression */) {
var symbol = typeChecker.getSymbolAtLocation(node);
// This is an alias, follow what it aliases
if (symbol && symbol.flags & 8388608 /* Alias */) {
@@ -67981,11 +73085,11 @@ var ts;
}
if (jsxContainer = tryGetContainingJsxElement(contextToken)) {
var attrsType = void 0;
- if ((jsxContainer.kind === 247 /* JsxSelfClosingElement */) || (jsxContainer.kind === 248 /* JsxOpeningElement */)) {
+ if ((jsxContainer.kind === 249 /* JsxSelfClosingElement */) || (jsxContainer.kind === 250 /* JsxOpeningElement */)) {
// Cursor is inside a JSX self-closing element or opening element
- attrsType = typeChecker.getJsxElementAttributesType(jsxContainer);
+ attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer);
if (attrsType) {
- symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes);
+ symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties);
isMemberCompletion = true;
isNewIdentifierLocation = false;
return true;
@@ -68029,9 +73133,9 @@ var ts;
var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
if (scopeNode) {
isGlobalCompletion =
- scopeNode.kind === 261 /* SourceFile */ ||
- scopeNode.kind === 194 /* TemplateExpression */ ||
- scopeNode.kind === 252 /* JsxExpression */ ||
+ scopeNode.kind === 264 /* SourceFile */ ||
+ scopeNode.kind === 195 /* TemplateExpression */ ||
+ scopeNode.kind === 255 /* JsxExpression */ ||
ts.isStatement(scopeNode);
}
/// TODO filter meaning based on the current context
@@ -68064,11 +73168,11 @@ var ts;
return true;
}
if (contextToken.kind === 28 /* GreaterThanToken */ && contextToken.parent) {
- if (contextToken.parent.kind === 248 /* JsxOpeningElement */) {
+ if (contextToken.parent.kind === 250 /* JsxOpeningElement */) {
return true;
}
- if (contextToken.parent.kind === 249 /* JsxClosingElement */ || contextToken.parent.kind === 247 /* JsxSelfClosingElement */) {
- return contextToken.parent.parent && contextToken.parent.parent.kind === 246 /* JsxElement */;
+ if (contextToken.parent.kind === 251 /* JsxClosingElement */ || contextToken.parent.kind === 249 /* JsxSelfClosingElement */) {
+ return contextToken.parent.parent && contextToken.parent.parent.kind === 248 /* JsxElement */;
}
}
return false;
@@ -68078,40 +73182,40 @@ var ts;
var containingNodeKind = previousToken.parent.kind;
switch (previousToken.kind) {
case 25 /* CommaToken */:
- return containingNodeKind === 179 /* CallExpression */ // func( a, |
- || containingNodeKind === 150 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */
- || containingNodeKind === 180 /* NewExpression */ // new C(a, |
- || containingNodeKind === 175 /* ArrayLiteralExpression */ // [a, |
- || containingNodeKind === 192 /* BinaryExpression */ // const x = (a, |
- || containingNodeKind === 158 /* FunctionType */; // var x: (s: string, list|
+ return containingNodeKind === 180 /* CallExpression */ // func( a, |
+ || containingNodeKind === 151 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */
+ || containingNodeKind === 181 /* NewExpression */ // new C(a, |
+ || containingNodeKind === 176 /* ArrayLiteralExpression */ // [a, |
+ || containingNodeKind === 193 /* BinaryExpression */ // const x = (a, |
+ || containingNodeKind === 159 /* FunctionType */; // var x: (s: string, list|
case 18 /* OpenParenToken */:
- return containingNodeKind === 179 /* CallExpression */ // func( |
- || containingNodeKind === 150 /* Constructor */ // constructor( |
- || containingNodeKind === 180 /* NewExpression */ // new C(a|
- || containingNodeKind === 183 /* ParenthesizedExpression */ // const x = (a|
- || containingNodeKind === 166 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */
+ return containingNodeKind === 180 /* CallExpression */ // func( |
+ || containingNodeKind === 151 /* Constructor */ // constructor( |
+ || containingNodeKind === 181 /* NewExpression */ // new C(a|
+ || containingNodeKind === 184 /* ParenthesizedExpression */ // const x = (a|
+ || containingNodeKind === 167 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */
case 20 /* OpenBracketToken */:
- return containingNodeKind === 175 /* ArrayLiteralExpression */ // [ |
- || containingNodeKind === 155 /* IndexSignature */ // [ | : string ]
- || containingNodeKind === 142 /* ComputedPropertyName */; // [ | /* this can become an index signature */
+ return containingNodeKind === 176 /* ArrayLiteralExpression */ // [ |
+ || containingNodeKind === 156 /* IndexSignature */ // [ | : string ]
+ || containingNodeKind === 143 /* ComputedPropertyName */; // [ | /* this can become an index signature */
case 127 /* ModuleKeyword */: // module |
case 128 /* NamespaceKeyword */:
return true;
case 22 /* DotToken */:
- return containingNodeKind === 230 /* ModuleDeclaration */; // module A.|
+ return containingNodeKind === 232 /* ModuleDeclaration */; // module A.|
case 16 /* OpenBraceToken */:
- return containingNodeKind === 226 /* ClassDeclaration */; // class A{ |
+ return containingNodeKind === 228 /* ClassDeclaration */; // class A{ |
case 57 /* EqualsToken */:
- return containingNodeKind === 223 /* VariableDeclaration */ // const x = a|
- || containingNodeKind === 192 /* BinaryExpression */; // x = a|
+ return containingNodeKind === 225 /* VariableDeclaration */ // const x = a|
+ || containingNodeKind === 193 /* BinaryExpression */; // x = a|
case 13 /* TemplateHead */:
- return containingNodeKind === 194 /* TemplateExpression */; // `aa ${|
+ return containingNodeKind === 195 /* TemplateExpression */; // `aa ${|
case 14 /* TemplateMiddle */:
- return containingNodeKind === 202 /* TemplateSpan */; // `aa ${10} dd ${|
+ return containingNodeKind === 204 /* TemplateSpan */; // `aa ${10} dd ${|
case 113 /* PublicKeyword */:
case 111 /* PrivateKeyword */:
case 112 /* ProtectedKeyword */:
- return containingNodeKind === 147 /* PropertyDeclaration */; // class A{ public |
+ return containingNodeKind === 148 /* PropertyDeclaration */; // class A{ public |
}
// Previous token may have been a keyword that was converted to an identifier.
switch (previousToken.getText()) {
@@ -68154,7 +73258,7 @@ var ts;
isMemberCompletion = true;
var typeForObject;
var existingMembers;
- if (objectLikeContainer.kind === 176 /* ObjectLiteralExpression */) {
+ if (objectLikeContainer.kind === 177 /* ObjectLiteralExpression */) {
// We are completing on contextual types, but may also include properties
// other than those within the declared type.
isNewIdentifierLocation = true;
@@ -68164,7 +73268,7 @@ var ts;
typeForObject = typeForObject && typeForObject.getNonNullableType();
existingMembers = objectLikeContainer.properties;
}
- else if (objectLikeContainer.kind === 172 /* ObjectBindingPattern */) {
+ else if (objectLikeContainer.kind === 173 /* ObjectBindingPattern */) {
// We are *only* completing on properties from the type being destructured.
isNewIdentifierLocation = false;
var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent);
@@ -68175,11 +73279,11 @@ var ts;
// Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed -
// type of parameter will flow in from the contextual type of the function
var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type);
- if (!canGetType && rootDeclaration.kind === 144 /* Parameter */) {
+ if (!canGetType && rootDeclaration.kind === 145 /* Parameter */) {
if (ts.isExpression(rootDeclaration.parent)) {
canGetType = !!typeChecker.getContextualType(rootDeclaration.parent);
}
- else if (rootDeclaration.parent.kind === 149 /* MethodDeclaration */ || rootDeclaration.parent.kind === 152 /* SetAccessor */) {
+ else if (rootDeclaration.parent.kind === 150 /* MethodDeclaration */ || rootDeclaration.parent.kind === 153 /* SetAccessor */) {
canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent);
}
}
@@ -68221,9 +73325,9 @@ var ts;
* @returns true if 'symbols' was successfully populated; false otherwise.
*/
function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) {
- var declarationKind = namedImportsOrExports.kind === 238 /* NamedImports */ ?
- 235 /* ImportDeclaration */ :
- 241 /* ExportDeclaration */;
+ var declarationKind = namedImportsOrExports.kind === 240 /* NamedImports */ ?
+ 237 /* ImportDeclaration */ :
+ 243 /* ExportDeclaration */;
var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind);
var moduleSpecifier = importOrExportDeclaration.moduleSpecifier;
if (!moduleSpecifier) {
@@ -68231,12 +73335,13 @@ var ts;
}
isMemberCompletion = true;
isNewIdentifierLocation = false;
- var exports;
- var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier);
- if (moduleSpecifierSymbol) {
- exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol);
+ var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier);
+ if (!moduleSpecifierSymbol) {
+ symbols = ts.emptyArray;
+ return true;
}
- symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : ts.emptyArray;
+ var exports = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol);
+ symbols = filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements);
return true;
}
/**
@@ -68248,9 +73353,9 @@ var ts;
switch (contextToken.kind) {
case 16 /* OpenBraceToken */: // const x = { |
case 25 /* CommaToken */:
- var parent_15 = contextToken.parent;
- if (parent_15 && (parent_15.kind === 176 /* ObjectLiteralExpression */ || parent_15.kind === 172 /* ObjectBindingPattern */)) {
- return parent_15;
+ var parent = contextToken.parent;
+ if (parent && (parent.kind === 177 /* ObjectLiteralExpression */ || parent.kind === 173 /* ObjectBindingPattern */)) {
+ return parent;
}
break;
}
@@ -68267,8 +73372,8 @@ var ts;
case 16 /* OpenBraceToken */: // import { |
case 25 /* CommaToken */:
switch (contextToken.parent.kind) {
- case 238 /* NamedImports */:
- case 242 /* NamedExports */:
+ case 240 /* NamedImports */:
+ case 244 /* NamedExports */:
return contextToken.parent;
}
}
@@ -68277,37 +73382,55 @@ var ts;
}
function tryGetContainingJsxElement(contextToken) {
if (contextToken) {
- var parent_16 = contextToken.parent;
+ var parent = contextToken.parent;
switch (contextToken.kind) {
case 27 /* LessThanSlashToken */:
case 40 /* SlashToken */:
case 70 /* Identifier */:
- case 250 /* JsxAttribute */:
- case 251 /* JsxSpreadAttribute */:
- if (parent_16 && (parent_16.kind === 247 /* JsxSelfClosingElement */ || parent_16.kind === 248 /* JsxOpeningElement */)) {
- return parent_16;
+ case 178 /* PropertyAccessExpression */:
+ case 253 /* JsxAttributes */:
+ case 252 /* JsxAttribute */:
+ case 254 /* JsxSpreadAttribute */:
+ if (parent && (parent.kind === 249 /* JsxSelfClosingElement */ || parent.kind === 250 /* JsxOpeningElement */)) {
+ return parent;
}
- else if (parent_16.kind === 250 /* JsxAttribute */) {
- return parent_16.parent;
+ else if (parent.kind === 252 /* JsxAttribute */) {
+ // Currently we parse JsxOpeningLikeElement as:
+ // JsxOpeningLikeElement
+ // attributes: JsxAttributes
+ // properties: NodeArray<JsxAttributeLike>
+ return parent.parent.parent;
}
break;
// The context token is the closing } or " of an attribute, which means
// its parent is a JsxExpression, whose parent is a JsxAttribute,
// whose parent is a JsxOpeningLikeElement
case 9 /* StringLiteral */:
- if (parent_16 && ((parent_16.kind === 250 /* JsxAttribute */) || (parent_16.kind === 251 /* JsxSpreadAttribute */))) {
- return parent_16.parent;
+ if (parent && ((parent.kind === 252 /* JsxAttribute */) || (parent.kind === 254 /* JsxSpreadAttribute */))) {
+ // Currently we parse JsxOpeningLikeElement as:
+ // JsxOpeningLikeElement
+ // attributes: JsxAttributes
+ // properties: NodeArray<JsxAttributeLike>
+ return parent.parent.parent;
}
break;
case 17 /* CloseBraceToken */:
- if (parent_16 &&
- parent_16.kind === 252 /* JsxExpression */ &&
- parent_16.parent &&
- (parent_16.parent.kind === 250 /* JsxAttribute */)) {
- return parent_16.parent.parent;
+ if (parent &&
+ parent.kind === 255 /* JsxExpression */ &&
+ parent.parent && parent.parent.kind === 252 /* JsxAttribute */) {
+ // Currently we parse JsxOpeningLikeElement as:
+ // JsxOpeningLikeElement
+ // attributes: JsxAttributes
+ // properties: NodeArray<JsxAttributeLike>
+ // each JsxAttribute can have initializer as JsxExpression
+ return parent.parent.parent.parent;
}
- if (parent_16 && parent_16.kind === 251 /* JsxSpreadAttribute */) {
- return parent_16.parent;
+ if (parent && parent.kind === 254 /* JsxSpreadAttribute */) {
+ // Currently we parse JsxOpeningLikeElement as:
+ // JsxOpeningLikeElement
+ // attributes: JsxAttributes
+ // properties: NodeArray<JsxAttributeLike>
+ return parent.parent.parent;
}
break;
}
@@ -68315,20 +73438,17 @@ var ts;
return undefined;
}
function isFunction(kind) {
+ if (!ts.isFunctionLikeKind(kind)) {
+ return false;
+ }
switch (kind) {
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 225 /* FunctionDeclaration */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 155 /* IndexSignature */:
+ case 151 /* Constructor */:
+ case 160 /* ConstructorType */:
+ case 159 /* FunctionType */:
+ return false;
+ default:
return true;
}
- return false;
}
/**
* @returns true if we are certain that the currently edited location must define a new location; false otherwise.
@@ -68337,66 +73457,66 @@ var ts;
var containingNodeKind = contextToken.parent.kind;
switch (contextToken.kind) {
case 25 /* CommaToken */:
- return containingNodeKind === 223 /* VariableDeclaration */ ||
- containingNodeKind === 224 /* VariableDeclarationList */ ||
- containingNodeKind === 205 /* VariableStatement */ ||
- containingNodeKind === 229 /* EnumDeclaration */ ||
+ return containingNodeKind === 225 /* VariableDeclaration */ ||
+ containingNodeKind === 226 /* VariableDeclarationList */ ||
+ containingNodeKind === 207 /* VariableStatement */ ||
+ containingNodeKind === 231 /* EnumDeclaration */ ||
isFunction(containingNodeKind) ||
- containingNodeKind === 226 /* ClassDeclaration */ ||
- containingNodeKind === 197 /* ClassExpression */ ||
- containingNodeKind === 227 /* InterfaceDeclaration */ ||
- containingNodeKind === 173 /* ArrayBindingPattern */ ||
- containingNodeKind === 228 /* TypeAliasDeclaration */; // type Map, K, |
+ containingNodeKind === 228 /* ClassDeclaration */ ||
+ containingNodeKind === 198 /* ClassExpression */ ||
+ containingNodeKind === 229 /* InterfaceDeclaration */ ||
+ containingNodeKind === 174 /* ArrayBindingPattern */ ||
+ containingNodeKind === 230 /* TypeAliasDeclaration */; // type Map, K, |
case 22 /* DotToken */:
- return containingNodeKind === 173 /* ArrayBindingPattern */; // var [.|
+ return containingNodeKind === 174 /* ArrayBindingPattern */; // var [.|
case 55 /* ColonToken */:
- return containingNodeKind === 174 /* BindingElement */; // var {x :html|
+ return containingNodeKind === 175 /* BindingElement */; // var {x :html|
case 20 /* OpenBracketToken */:
- return containingNodeKind === 173 /* ArrayBindingPattern */; // var [x|
+ return containingNodeKind === 174 /* ArrayBindingPattern */; // var [x|
case 18 /* OpenParenToken */:
- return containingNodeKind === 256 /* CatchClause */ ||
+ return containingNodeKind === 259 /* CatchClause */ ||
isFunction(containingNodeKind);
case 16 /* OpenBraceToken */:
- return containingNodeKind === 229 /* EnumDeclaration */ ||
- containingNodeKind === 227 /* InterfaceDeclaration */ ||
- containingNodeKind === 161 /* TypeLiteral */; // const x : { |
+ return containingNodeKind === 231 /* EnumDeclaration */ ||
+ containingNodeKind === 229 /* InterfaceDeclaration */ ||
+ containingNodeKind === 162 /* TypeLiteral */; // const x : { |
case 24 /* SemicolonToken */:
- return containingNodeKind === 146 /* PropertySignature */ &&
+ return containingNodeKind === 147 /* PropertySignature */ &&
contextToken.parent && contextToken.parent.parent &&
- (contextToken.parent.parent.kind === 227 /* InterfaceDeclaration */ ||
- contextToken.parent.parent.kind === 161 /* TypeLiteral */); // const x : { a; |
+ (contextToken.parent.parent.kind === 229 /* InterfaceDeclaration */ ||
+ contextToken.parent.parent.kind === 162 /* TypeLiteral */); // const x : { a; |
case 26 /* LessThanToken */:
- return containingNodeKind === 226 /* ClassDeclaration */ ||
- containingNodeKind === 197 /* ClassExpression */ ||
- containingNodeKind === 227 /* InterfaceDeclaration */ ||
- containingNodeKind === 228 /* TypeAliasDeclaration */ ||
+ return containingNodeKind === 228 /* ClassDeclaration */ ||
+ containingNodeKind === 198 /* ClassExpression */ ||
+ containingNodeKind === 229 /* InterfaceDeclaration */ ||
+ containingNodeKind === 230 /* TypeAliasDeclaration */ ||
isFunction(containingNodeKind);
case 114 /* StaticKeyword */:
- return containingNodeKind === 147 /* PropertyDeclaration */;
+ return containingNodeKind === 148 /* PropertyDeclaration */;
case 23 /* DotDotDotToken */:
- return containingNodeKind === 144 /* Parameter */ ||
+ return containingNodeKind === 145 /* Parameter */ ||
(contextToken.parent && contextToken.parent.parent &&
- contextToken.parent.parent.kind === 173 /* ArrayBindingPattern */); // var [...z|
+ contextToken.parent.parent.kind === 174 /* ArrayBindingPattern */); // var [...z|
case 113 /* PublicKeyword */:
case 111 /* PrivateKeyword */:
case 112 /* ProtectedKeyword */:
- return containingNodeKind === 144 /* Parameter */;
+ return containingNodeKind === 145 /* Parameter */;
case 117 /* AsKeyword */:
- return containingNodeKind === 239 /* ImportSpecifier */ ||
- containingNodeKind === 243 /* ExportSpecifier */ ||
- containingNodeKind === 237 /* NamespaceImport */;
+ return containingNodeKind === 241 /* ImportSpecifier */ ||
+ containingNodeKind === 245 /* ExportSpecifier */ ||
+ containingNodeKind === 239 /* NamespaceImport */;
case 74 /* ClassKeyword */:
case 82 /* EnumKeyword */:
case 108 /* InterfaceKeyword */:
case 88 /* FunctionKeyword */:
case 103 /* VarKeyword */:
case 124 /* GetKeyword */:
- case 133 /* SetKeyword */:
+ case 134 /* SetKeyword */:
case 90 /* ImportKeyword */:
case 109 /* LetKeyword */:
case 75 /* ConstKeyword */:
case 115 /* YieldKeyword */:
- case 136 /* TypeKeyword */:
+ case 137 /* TypeKeyword */:
return true;
}
// Previous token may have been a keyword that was converted to an identifier.
@@ -68444,13 +73564,13 @@ var ts;
if (element.getStart() <= position && position <= element.getEnd()) {
continue;
}
- var name_44 = element.propertyName || element.name;
- existingImportsOrExports[name_44.text] = true;
+ var name = element.propertyName || element.name;
+ existingImportsOrExports.set(name.text, true);
}
- if (!ts.someProperties(existingImportsOrExports)) {
+ if (existingImportsOrExports.size === 0) {
return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; });
}
- return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; });
+ return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports.get(e.name); });
}
/**
* Filters out completion suggestions for named imports or exports.
@@ -68466,12 +73586,12 @@ var ts;
for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) {
var m = existingMembers_1[_i];
// Ignore omitted expressions for missing members
- if (m.kind !== 257 /* PropertyAssignment */ &&
- m.kind !== 258 /* ShorthandPropertyAssignment */ &&
- m.kind !== 174 /* BindingElement */ &&
- m.kind !== 149 /* MethodDeclaration */ &&
- m.kind !== 151 /* GetAccessor */ &&
- m.kind !== 152 /* SetAccessor */) {
+ if (m.kind !== 260 /* PropertyAssignment */ &&
+ m.kind !== 261 /* ShorthandPropertyAssignment */ &&
+ m.kind !== 175 /* BindingElement */ &&
+ m.kind !== 150 /* MethodDeclaration */ &&
+ m.kind !== 152 /* GetAccessor */ &&
+ m.kind !== 153 /* SetAccessor */) {
continue;
}
// If this is the current item we are editing right now, do not filter it out
@@ -68479,7 +73599,7 @@ var ts;
continue;
}
var existingName = void 0;
- if (m.kind === 174 /* BindingElement */ && m.propertyName) {
+ if (m.kind === 175 /* BindingElement */ && m.propertyName) {
// include only identifiers in completion list
if (m.propertyName.kind === 70 /* Identifier */) {
existingName = m.propertyName.text;
@@ -68491,9 +73611,9 @@ var ts;
// things like '__proto__' are not filtered out.
existingName = m.name.text;
}
- existingMemberNames[existingName] = true;
+ existingMemberNames.set(existingName, true);
}
- return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames[m.name]; });
+ return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); });
}
/**
* Filters out completion suggestions from 'symbols' according to existing JSX attributes.
@@ -68509,11 +73629,11 @@ var ts;
if (attr.getStart() <= position && position <= attr.getEnd()) {
continue;
}
- if (attr.kind === 250 /* JsxAttribute */) {
- seenNames[attr.name.text] = true;
+ if (attr.kind === 252 /* JsxAttribute */) {
+ seenNames.set(attr.name.text, true);
}
}
- return ts.filter(symbols, function (a) { return !seenNames[a.name]; });
+ return ts.filter(symbols, function (a) { return !seenNames.get(a.name); });
}
}
/**
@@ -68559,7 +73679,7 @@ var ts;
}
// A cache of completion entries for keywords, these do not change between sessions
var keywordCompletions = [];
- for (var i = 71 /* FirstKeyword */; i <= 140 /* LastKeyword */; i++) {
+ for (var i = 71 /* FirstKeyword */; i <= 141 /* LastKeyword */; i++) {
keywordCompletions.push({
name: ts.tokenToString(i),
kind: ts.ScriptElementKind.keyword,
@@ -68567,49 +73687,14 @@ var ts;
sortText: "0"
});
}
- /**
- * Matches a triple slash reference directive with an incomplete string literal for its path. Used
- * to determine if the caret is currently within the string literal and capture the literal fragment
- * for completions.
- * For example, this matches
- *
- * /// <reference path="fragment
- *
- * but not
- *
- * /// <reference path="fragment"
- */
- var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\3"]*)$/;
- var nodeModulesDependencyKeys = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
- function tryGetDirectories(host, directoryName) {
- return tryIOAndConsumeErrors(host, host.getDirectories, directoryName);
- }
- function tryReadDirectory(host, path, extensions, exclude, include) {
- return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include);
- }
- function tryReadFile(host, path) {
- return tryIOAndConsumeErrors(host, host.readFile, path);
- }
- function tryFileExists(host, path) {
- return tryIOAndConsumeErrors(host, host.fileExists, path);
+ function isEqualityExpression(node) {
+ return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind);
}
- function tryDirectoryExists(host, path) {
- try {
- return ts.directoryProbablyExists(path, host);
- }
- catch (e) { }
- return undefined;
- }
- function tryIOAndConsumeErrors(host, toApply) {
- var args = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- args[_i - 2] = arguments[_i];
- }
- try {
- return toApply && toApply.apply(host, args);
- }
- catch (e) { }
- return undefined;
+ function isEqualityOperatorKind(kind) {
+ return kind === 31 /* EqualsEqualsToken */ ||
+ kind === 32 /* ExclamationEqualsToken */ ||
+ kind === 33 /* EqualsEqualsEqualsToken */ ||
+ kind === 34 /* ExclamationEqualsEqualsToken */;
}
})(Completions = ts.Completions || (ts.Completions = {}));
})(ts || (ts = {}));
@@ -68620,534 +73705,513 @@ var ts;
(function (DocumentHighlights) {
function getDocumentHighlights(typeChecker, cancellationToken, sourceFile, position, sourceFilesToSearch) {
var node = ts.getTouchingWord(sourceFile, position);
+ return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile));
+ }
+ DocumentHighlights.getDocumentHighlights = getDocumentHighlights;
+ function getHighlightSpanForNode(node, sourceFile) {
+ var start = node.getStart(sourceFile);
+ var end = node.getEnd();
+ return {
+ fileName: sourceFile.fileName,
+ textSpan: ts.createTextSpanFromBounds(start, end),
+ kind: ts.HighlightSpanKind.none
+ };
+ }
+ function getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) {
+ var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken);
+ return referenceEntries && convertReferencedSymbols(referenceEntries);
+ }
+ function convertReferencedSymbols(referenceEntries) {
+ var fileNameToDocumentHighlights = ts.createMap();
+ for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
+ var entry = referenceEntries_1[_i];
+ var _a = ts.FindAllReferences.toHighlightSpan(entry), fileName = _a.fileName, span_12 = _a.span;
+ var highlightSpans = fileNameToDocumentHighlights.get(fileName);
+ if (!highlightSpans) {
+ fileNameToDocumentHighlights.set(fileName, highlightSpans = []);
+ }
+ highlightSpans.push(span_12);
+ }
+ return ts.arrayFrom(fileNameToDocumentHighlights.entries(), function (_a) {
+ var fileName = _a[0], highlightSpans = _a[1];
+ return ({ fileName: fileName, highlightSpans: highlightSpans });
+ });
+ }
+ function getSyntacticDocumentHighlights(node, sourceFile) {
+ var highlightSpans = getHighlightSpans(node, sourceFile);
+ if (!highlightSpans || highlightSpans.length === 0) {
+ return undefined;
+ }
+ return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }];
+ }
+ // returns true if 'node' is defined and has a matching 'kind'.
+ function hasKind(node, kind) {
+ return node !== undefined && node.kind === kind;
+ }
+ // Null-propagating 'parent' function.
+ function parent(node) {
+ return node && node.parent;
+ }
+ function getHighlightSpans(node, sourceFile) {
if (!node) {
return undefined;
}
- return getSemanticDocumentHighlights(node) || getSyntacticDocumentHighlights(node);
- function getHighlightSpanForNode(node) {
- var start = node.getStart();
- var end = node.getEnd();
- return {
- fileName: sourceFile.fileName,
- textSpan: ts.createTextSpanFromBounds(start, end),
- kind: ts.HighlightSpanKind.none
- };
+ switch (node.kind) {
+ case 89 /* IfKeyword */:
+ case 81 /* ElseKeyword */:
+ if (hasKind(node.parent, 210 /* IfStatement */)) {
+ return getIfElseOccurrences(node.parent, sourceFile);
+ }
+ break;
+ case 95 /* ReturnKeyword */:
+ if (hasKind(node.parent, 218 /* ReturnStatement */)) {
+ return highlightSpans(getReturnOccurrences(node.parent));
+ }
+ break;
+ case 99 /* ThrowKeyword */:
+ if (hasKind(node.parent, 222 /* ThrowStatement */)) {
+ return highlightSpans(getThrowOccurrences(node.parent));
+ }
+ break;
+ case 101 /* TryKeyword */:
+ case 73 /* CatchKeyword */:
+ case 86 /* FinallyKeyword */:
+ var tryStatement = node.kind === 73 /* CatchKeyword */ ? parent(parent(node)) : parent(node);
+ if (hasKind(tryStatement, 223 /* TryStatement */)) {
+ return highlightSpans(getTryCatchFinallyOccurrences(tryStatement, sourceFile));
+ }
+ break;
+ case 97 /* SwitchKeyword */:
+ if (hasKind(node.parent, 220 /* SwitchStatement */)) {
+ return highlightSpans(getSwitchCaseDefaultOccurrences(node.parent));
+ }
+ break;
+ case 72 /* CaseKeyword */:
+ case 78 /* DefaultKeyword */:
+ if (hasKind(parent(parent(parent(node))), 220 /* SwitchStatement */)) {
+ return highlightSpans(getSwitchCaseDefaultOccurrences(node.parent.parent.parent));
+ }
+ break;
+ case 71 /* BreakKeyword */:
+ case 76 /* ContinueKeyword */:
+ if (hasKind(node.parent, 217 /* BreakStatement */) || hasKind(node.parent, 216 /* ContinueStatement */)) {
+ return highlightSpans(getBreakOrContinueStatementOccurrences(node.parent));
+ }
+ break;
+ case 87 /* ForKeyword */:
+ if (hasKind(node.parent, 213 /* ForStatement */) ||
+ hasKind(node.parent, 214 /* ForInStatement */) ||
+ hasKind(node.parent, 215 /* ForOfStatement */)) {
+ return highlightSpans(getLoopBreakContinueOccurrences(node.parent));
+ }
+ break;
+ case 105 /* WhileKeyword */:
+ case 80 /* DoKeyword */:
+ if (hasKind(node.parent, 212 /* WhileStatement */) || hasKind(node.parent, 211 /* DoStatement */)) {
+ return highlightSpans(getLoopBreakContinueOccurrences(node.parent));
+ }
+ break;
+ case 122 /* ConstructorKeyword */:
+ if (hasKind(node.parent, 151 /* Constructor */)) {
+ return highlightSpans(getConstructorOccurrences(node.parent));
+ }
+ break;
+ case 124 /* GetKeyword */:
+ case 134 /* SetKeyword */:
+ if (hasKind(node.parent, 152 /* GetAccessor */) || hasKind(node.parent, 153 /* SetAccessor */)) {
+ return highlightSpans(getGetAndSetOccurrences(node.parent));
+ }
+ break;
+ default:
+ if (ts.isModifierKind(node.kind) && node.parent &&
+ (ts.isDeclaration(node.parent) || node.parent.kind === 207 /* VariableStatement */)) {
+ return highlightSpans(getModifierOccurrences(node.kind, node.parent));
+ }
}
- function getSemanticDocumentHighlights(node) {
- if (node.kind === 70 /* Identifier */ ||
- node.kind === 98 /* ThisKeyword */ ||
- node.kind === 167 /* ThisType */ ||
- node.kind === 96 /* SuperKeyword */ ||
- node.kind === 9 /* StringLiteral */ ||
- ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) {
- var referencedSymbols = ts.FindAllReferences.getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFilesToSearch, /*findInStrings*/ false, /*findInComments*/ false, /*implementations*/ false);
- return convertReferencedSymbols(referencedSymbols);
+ function highlightSpans(nodes) {
+ return nodes && nodes.map(function (node) { return getHighlightSpanForNode(node, sourceFile); });
+ }
+ }
+ /**
+ * Aggregates all throw-statements within this node *without* crossing
+ * into function boundaries and try-blocks with catch-clauses.
+ */
+ function aggregateOwnedThrowStatements(node) {
+ var statementAccumulator = [];
+ aggregate(node);
+ return statementAccumulator;
+ function aggregate(node) {
+ if (node.kind === 222 /* ThrowStatement */) {
+ statementAccumulator.push(node);
}
- return undefined;
- function convertReferencedSymbols(referencedSymbols) {
- if (!referencedSymbols) {
- return undefined;
+ else if (node.kind === 223 /* TryStatement */) {
+ var tryStatement = node;
+ if (tryStatement.catchClause) {
+ aggregate(tryStatement.catchClause);
}
- var fileNameToDocumentHighlights = ts.createMap();
- var result = [];
- for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) {
- var referencedSymbol = referencedSymbols_1[_i];
- for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) {
- var referenceEntry = _b[_a];
- var fileName = referenceEntry.fileName;
- var documentHighlights = fileNameToDocumentHighlights[fileName];
- if (!documentHighlights) {
- documentHighlights = { fileName: fileName, highlightSpans: [] };
- fileNameToDocumentHighlights[fileName] = documentHighlights;
- result.push(documentHighlights);
- }
- documentHighlights.highlightSpans.push({
- textSpan: referenceEntry.textSpan,
- kind: referenceEntry.isWriteAccess ? ts.HighlightSpanKind.writtenReference : ts.HighlightSpanKind.reference
- });
- }
+ else {
+ // Exceptions thrown within a try block lacking a catch clause
+ // are "owned" in the current context.
+ aggregate(tryStatement.tryBlock);
+ }
+ if (tryStatement.finallyBlock) {
+ aggregate(tryStatement.finallyBlock);
}
- return result;
+ }
+ else if (!ts.isFunctionLike(node)) {
+ ts.forEachChild(node, aggregate);
}
}
- function getSyntacticDocumentHighlights(node) {
- var fileName = sourceFile.fileName;
- var highlightSpans = getHighlightSpans(node);
- if (!highlightSpans || highlightSpans.length === 0) {
- return undefined;
+ }
+ /**
+ * For lack of a better name, this function takes a throw statement and returns the
+ * nearest ancestor that is a try-block (whose try statement has a catch clause),
+ * function-block, or source file.
+ */
+ function getThrowStatementOwner(throwStatement) {
+ var child = throwStatement;
+ while (child.parent) {
+ var parent_2 = child.parent;
+ if (ts.isFunctionBlock(parent_2) || parent_2.kind === 264 /* SourceFile */) {
+ return parent_2;
}
- return [{ fileName: fileName, highlightSpans: highlightSpans }];
- // returns true if 'node' is defined and has a matching 'kind'.
- function hasKind(node, kind) {
- return node !== undefined && node.kind === kind;
+ // A throw-statement is only owned by a try-statement if the try-statement has
+ // a catch clause, and if the throw-statement occurs within the try block.
+ if (parent_2.kind === 223 /* TryStatement */) {
+ var tryStatement = parent_2;
+ if (tryStatement.tryBlock === child && tryStatement.catchClause) {
+ return child;
+ }
}
- // Null-propagating 'parent' function.
- function parent(node) {
- return node && node.parent;
+ child = parent_2;
+ }
+ return undefined;
+ }
+ function aggregateAllBreakAndContinueStatements(node) {
+ var statementAccumulator = [];
+ aggregate(node);
+ return statementAccumulator;
+ function aggregate(node) {
+ if (node.kind === 217 /* BreakStatement */ || node.kind === 216 /* ContinueStatement */) {
+ statementAccumulator.push(node);
}
- function getHighlightSpans(node) {
- if (node) {
- switch (node.kind) {
- case 89 /* IfKeyword */:
- case 81 /* ElseKeyword */:
- if (hasKind(node.parent, 208 /* IfStatement */)) {
- return getIfElseOccurrences(node.parent);
- }
- break;
- case 95 /* ReturnKeyword */:
- if (hasKind(node.parent, 216 /* ReturnStatement */)) {
- return getReturnOccurrences(node.parent);
- }
- break;
- case 99 /* ThrowKeyword */:
- if (hasKind(node.parent, 220 /* ThrowStatement */)) {
- return getThrowOccurrences(node.parent);
- }
- break;
- case 73 /* CatchKeyword */:
- if (hasKind(parent(parent(node)), 221 /* TryStatement */)) {
- return getTryCatchFinallyOccurrences(node.parent.parent);
- }
- break;
- case 101 /* TryKeyword */:
- case 86 /* FinallyKeyword */:
- if (hasKind(parent(node), 221 /* TryStatement */)) {
- return getTryCatchFinallyOccurrences(node.parent);
- }
- break;
- case 97 /* SwitchKeyword */:
- if (hasKind(node.parent, 218 /* SwitchStatement */)) {
- return getSwitchCaseDefaultOccurrences(node.parent);
- }
- break;
- case 72 /* CaseKeyword */:
- case 78 /* DefaultKeyword */:
- if (hasKind(parent(parent(parent(node))), 218 /* SwitchStatement */)) {
- return getSwitchCaseDefaultOccurrences(node.parent.parent.parent);
- }
- break;
- case 71 /* BreakKeyword */:
- case 76 /* ContinueKeyword */:
- if (hasKind(node.parent, 215 /* BreakStatement */) || hasKind(node.parent, 214 /* ContinueStatement */)) {
- return getBreakOrContinueStatementOccurrences(node.parent);
- }
- break;
- case 87 /* ForKeyword */:
- if (hasKind(node.parent, 211 /* ForStatement */) ||
- hasKind(node.parent, 212 /* ForInStatement */) ||
- hasKind(node.parent, 213 /* ForOfStatement */)) {
- return getLoopBreakContinueOccurrences(node.parent);
- }
- break;
- case 105 /* WhileKeyword */:
- case 80 /* DoKeyword */:
- if (hasKind(node.parent, 210 /* WhileStatement */) || hasKind(node.parent, 209 /* DoStatement */)) {
- return getLoopBreakContinueOccurrences(node.parent);
- }
- break;
- case 122 /* ConstructorKeyword */:
- if (hasKind(node.parent, 150 /* Constructor */)) {
- return getConstructorOccurrences(node.parent);
- }
- break;
- case 124 /* GetKeyword */:
- case 133 /* SetKeyword */:
- if (hasKind(node.parent, 151 /* GetAccessor */) || hasKind(node.parent, 152 /* SetAccessor */)) {
- return getGetAndSetOccurrences(node.parent);
- }
- break;
- default:
- if (ts.isModifierKind(node.kind) && node.parent &&
- (ts.isDeclaration(node.parent) || node.parent.kind === 205 /* VariableStatement */)) {
- return getModifierOccurrences(node.kind, node.parent);
- }
- }
- }
- return undefined;
+ else if (!ts.isFunctionLike(node)) {
+ ts.forEachChild(node, aggregate);
}
- /**
- * Aggregates all throw-statements within this node *without* crossing
- * into function boundaries and try-blocks with catch-clauses.
- */
- function aggregateOwnedThrowStatements(node) {
- var statementAccumulator = [];
- aggregate(node);
- return statementAccumulator;
- function aggregate(node) {
- if (node.kind === 220 /* ThrowStatement */) {
- statementAccumulator.push(node);
- }
- else if (node.kind === 221 /* TryStatement */) {
- var tryStatement = node;
- if (tryStatement.catchClause) {
- aggregate(tryStatement.catchClause);
- }
- else {
- // Exceptions thrown within a try block lacking a catch clause
- // are "owned" in the current context.
- aggregate(tryStatement.tryBlock);
- }
- if (tryStatement.finallyBlock) {
- aggregate(tryStatement.finallyBlock);
- }
+ }
+ }
+ function ownsBreakOrContinueStatement(owner, statement) {
+ var actualOwner = getBreakOrContinueOwner(statement);
+ return actualOwner && actualOwner === owner;
+ }
+ function getBreakOrContinueOwner(statement) {
+ for (var node = statement.parent; node; node = node.parent) {
+ switch (node.kind) {
+ case 220 /* SwitchStatement */:
+ if (statement.kind === 216 /* ContinueStatement */) {
+ continue;
}
- else if (!ts.isFunctionLike(node)) {
- ts.forEachChild(node, aggregate);
+ // falls through
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ case 212 /* WhileStatement */:
+ case 211 /* DoStatement */:
+ if (!statement.label || isLabeledBy(node, statement.label.text)) {
+ return node;
}
- }
- }
- /**
- * For lack of a better name, this function takes a throw statement and returns the
- * nearest ancestor that is a try-block (whose try statement has a catch clause),
- * function-block, or source file.
- */
- function getThrowStatementOwner(throwStatement) {
- var child = throwStatement;
- while (child.parent) {
- var parent_17 = child.parent;
- if (ts.isFunctionBlock(parent_17) || parent_17.kind === 261 /* SourceFile */) {
- return parent_17;
- }
- // A throw-statement is only owned by a try-statement if the try-statement has
- // a catch clause, and if the throw-statement occurs within the try block.
- if (parent_17.kind === 221 /* TryStatement */) {
- var tryStatement = parent_17;
- if (tryStatement.tryBlock === child && tryStatement.catchClause) {
- return child;
- }
+ break;
+ default:
+ // Don't cross function boundaries.
+ if (ts.isFunctionLike(node)) {
+ return undefined;
}
- child = parent_17;
- }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function getModifierOccurrences(modifier, declaration) {
+ var container = declaration.parent;
+ // Make sure we only highlight the keyword when it makes sense to do so.
+ if (ts.isAccessibilityModifier(modifier)) {
+ if (!(container.kind === 228 /* ClassDeclaration */ ||
+ container.kind === 198 /* ClassExpression */ ||
+ (declaration.kind === 145 /* Parameter */ && hasKind(container, 151 /* Constructor */)))) {
return undefined;
}
- function aggregateAllBreakAndContinueStatements(node) {
- var statementAccumulator = [];
- aggregate(node);
- return statementAccumulator;
- function aggregate(node) {
- if (node.kind === 215 /* BreakStatement */ || node.kind === 214 /* ContinueStatement */) {
- statementAccumulator.push(node);
- }
- else if (!ts.isFunctionLike(node)) {
- ts.forEachChild(node, aggregate);
- }
- }
+ }
+ else if (modifier === 114 /* StaticKeyword */) {
+ if (!(container.kind === 228 /* ClassDeclaration */ || container.kind === 198 /* ClassExpression */)) {
+ return undefined;
}
- function ownsBreakOrContinueStatement(owner, statement) {
- var actualOwner = getBreakOrContinueOwner(statement);
- return actualOwner && actualOwner === owner;
+ }
+ else if (modifier === 83 /* ExportKeyword */ || modifier === 123 /* DeclareKeyword */) {
+ if (!(container.kind === 233 /* ModuleBlock */ || container.kind === 264 /* SourceFile */)) {
+ return undefined;
}
- function getBreakOrContinueOwner(statement) {
- for (var node_1 = statement.parent; node_1; node_1 = node_1.parent) {
- switch (node_1.kind) {
- case 218 /* SwitchStatement */:
- if (statement.kind === 214 /* ContinueStatement */) {
- continue;
- }
- // Fall through.
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- case 210 /* WhileStatement */:
- case 209 /* DoStatement */:
- if (!statement.label || isLabeledBy(node_1, statement.label.text)) {
- return node_1;
- }
- break;
- default:
- // Don't cross function boundaries.
- if (ts.isFunctionLike(node_1)) {
- return undefined;
- }
- break;
- }
- }
+ }
+ else if (modifier === 116 /* AbstractKeyword */) {
+ if (!(container.kind === 228 /* ClassDeclaration */ || declaration.kind === 228 /* ClassDeclaration */)) {
return undefined;
}
- function getModifierOccurrences(modifier, declaration) {
- var container = declaration.parent;
- // Make sure we only highlight the keyword when it makes sense to do so.
- if (ts.isAccessibilityModifier(modifier)) {
- if (!(container.kind === 226 /* ClassDeclaration */ ||
- container.kind === 197 /* ClassExpression */ ||
- (declaration.kind === 144 /* Parameter */ && hasKind(container, 150 /* Constructor */)))) {
- return undefined;
- }
- }
- else if (modifier === 114 /* StaticKeyword */) {
- if (!(container.kind === 226 /* ClassDeclaration */ || container.kind === 197 /* ClassExpression */)) {
- return undefined;
- }
- }
- else if (modifier === 83 /* ExportKeyword */ || modifier === 123 /* DeclareKeyword */) {
- if (!(container.kind === 231 /* ModuleBlock */ || container.kind === 261 /* SourceFile */)) {
- return undefined;
- }
- }
- else if (modifier === 116 /* AbstractKeyword */) {
- if (!(container.kind === 226 /* ClassDeclaration */ || declaration.kind === 226 /* ClassDeclaration */)) {
- return undefined;
- }
+ }
+ else {
+ // unsupported modifier
+ return undefined;
+ }
+ var keywords = [];
+ var modifierFlag = getFlagFromModifier(modifier);
+ var nodes;
+ switch (container.kind) {
+ case 233 /* ModuleBlock */:
+ case 264 /* SourceFile */:
+ // Container is either a class declaration or the declaration is a classDeclaration
+ if (modifierFlag & 128 /* Abstract */) {
+ nodes = declaration.members.concat(declaration);
}
else {
- // unsupported modifier
- return undefined;
- }
- var keywords = [];
- var modifierFlag = getFlagFromModifier(modifier);
- var nodes;
- switch (container.kind) {
- case 231 /* ModuleBlock */:
- case 261 /* SourceFile */:
- // Container is either a class declaration or the declaration is a classDeclaration
- if (modifierFlag & 128 /* Abstract */) {
- nodes = declaration.members.concat(declaration);
- }
- else {
- nodes = container.statements;
- }
- break;
- case 150 /* Constructor */:
- nodes = container.parameters.concat(container.parent.members);
- break;
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- nodes = container.members;
- // If we're an accessibility modifier, we're in an instance member and should search
- // the constructor's parameter list for instance members as well.
- if (modifierFlag & 28 /* AccessibilityModifier */) {
- var constructor = ts.forEach(container.members, function (member) {
- return member.kind === 150 /* Constructor */ && member;
- });
- if (constructor) {
- nodes = nodes.concat(constructor.parameters);
- }
- }
- else if (modifierFlag & 128 /* Abstract */) {
- nodes = nodes.concat(container);
- }
- break;
- default:
- ts.Debug.fail("Invalid container kind.");
+ nodes = container.statements;
}
- ts.forEach(nodes, function (node) {
- if (ts.getModifierFlags(node) & modifierFlag) {
- ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); });
- }
- });
- return ts.map(keywords, getHighlightSpanForNode);
- function getFlagFromModifier(modifier) {
- switch (modifier) {
- case 113 /* PublicKeyword */:
- return 4 /* Public */;
- case 111 /* PrivateKeyword */:
- return 8 /* Private */;
- case 112 /* ProtectedKeyword */:
- return 16 /* Protected */;
- case 114 /* StaticKeyword */:
- return 32 /* Static */;
- case 83 /* ExportKeyword */:
- return 1 /* Export */;
- case 123 /* DeclareKeyword */:
- return 2 /* Ambient */;
- case 116 /* AbstractKeyword */:
- return 128 /* Abstract */;
- default:
- ts.Debug.fail();
+ break;
+ case 151 /* Constructor */:
+ nodes = container.parameters.concat(container.parent.members);
+ break;
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ nodes = container.members;
+ // If we're an accessibility modifier, we're in an instance member and should search
+ // the constructor's parameter list for instance members as well.
+ if (modifierFlag & 28 /* AccessibilityModifier */) {
+ var constructor = ts.forEach(container.members, function (member) {
+ return member.kind === 151 /* Constructor */ && member;
+ });
+ if (constructor) {
+ nodes = nodes.concat(constructor.parameters);
}
}
- }
- function pushKeywordIf(keywordList, token) {
- var expected = [];
- for (var _i = 2; _i < arguments.length; _i++) {
- expected[_i - 2] = arguments[_i];
+ else if (modifierFlag & 128 /* Abstract */) {
+ nodes = nodes.concat(container);
}
- if (token && ts.contains(expected, token.kind)) {
- keywordList.push(token);
- return true;
- }
- return false;
+ break;
+ default:
+ ts.Debug.fail("Invalid container kind.");
+ }
+ ts.forEach(nodes, function (node) {
+ if (ts.getModifierFlags(node) & modifierFlag) {
+ ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); });
}
- function getGetAndSetOccurrences(accessorDeclaration) {
- var keywords = [];
- tryPushAccessorKeyword(accessorDeclaration.symbol, 151 /* GetAccessor */);
- tryPushAccessorKeyword(accessorDeclaration.symbol, 152 /* SetAccessor */);
- return ts.map(keywords, getHighlightSpanForNode);
- function tryPushAccessorKeyword(accessorSymbol, accessorKind) {
- var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind);
- if (accessor) {
- ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 124 /* GetKeyword */, 133 /* SetKeyword */); });
- }
- }
+ });
+ return keywords;
+ function getFlagFromModifier(modifier) {
+ switch (modifier) {
+ case 113 /* PublicKeyword */:
+ return 4 /* Public */;
+ case 111 /* PrivateKeyword */:
+ return 8 /* Private */;
+ case 112 /* ProtectedKeyword */:
+ return 16 /* Protected */;
+ case 114 /* StaticKeyword */:
+ return 32 /* Static */;
+ case 83 /* ExportKeyword */:
+ return 1 /* Export */;
+ case 123 /* DeclareKeyword */:
+ return 2 /* Ambient */;
+ case 116 /* AbstractKeyword */:
+ return 128 /* Abstract */;
+ default:
+ ts.Debug.fail();
}
- function getConstructorOccurrences(constructorDeclaration) {
- var declarations = constructorDeclaration.symbol.getDeclarations();
- var keywords = [];
- ts.forEach(declarations, function (declaration) {
- ts.forEach(declaration.getChildren(), function (token) {
- return pushKeywordIf(keywords, token, 122 /* ConstructorKeyword */);
- });
- });
- return ts.map(keywords, getHighlightSpanForNode);
- }
- function getLoopBreakContinueOccurrences(loopNode) {
- var keywords = [];
- if (pushKeywordIf(keywords, loopNode.getFirstToken(), 87 /* ForKeyword */, 105 /* WhileKeyword */, 80 /* DoKeyword */)) {
- // If we succeeded and got a do-while loop, then start looking for a 'while' keyword.
- if (loopNode.kind === 209 /* DoStatement */) {
- var loopTokens = loopNode.getChildren();
- for (var i = loopTokens.length - 1; i >= 0; i--) {
- if (pushKeywordIf(keywords, loopTokens[i], 105 /* WhileKeyword */)) {
- break;
- }
- }
- }
- }
- var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement);
- ts.forEach(breaksAndContinues, function (statement) {
- if (ownsBreakOrContinueStatement(loopNode, statement)) {
- pushKeywordIf(keywords, statement.getFirstToken(), 71 /* BreakKeyword */, 76 /* ContinueKeyword */);
- }
- });
- return ts.map(keywords, getHighlightSpanForNode);
- }
- function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) {
- var owner = getBreakOrContinueOwner(breakOrContinueStatement);
- if (owner) {
- switch (owner.kind) {
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- case 209 /* DoStatement */:
- case 210 /* WhileStatement */:
- return getLoopBreakContinueOccurrences(owner);
- case 218 /* SwitchStatement */:
- return getSwitchCaseDefaultOccurrences(owner);
+ }
+ }
+ function pushKeywordIf(keywordList, token) {
+ var expected = [];
+ for (var _i = 2; _i < arguments.length; _i++) {
+ expected[_i - 2] = arguments[_i];
+ }
+ if (token && ts.contains(expected, token.kind)) {
+ keywordList.push(token);
+ return true;
+ }
+ return false;
+ }
+ function getGetAndSetOccurrences(accessorDeclaration) {
+ var keywords = [];
+ tryPushAccessorKeyword(accessorDeclaration.symbol, 152 /* GetAccessor */);
+ tryPushAccessorKeyword(accessorDeclaration.symbol, 153 /* SetAccessor */);
+ return keywords;
+ function tryPushAccessorKeyword(accessorSymbol, accessorKind) {
+ var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind);
+ if (accessor) {
+ ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 124 /* GetKeyword */, 134 /* SetKeyword */); });
+ }
+ }
+ }
+ function getConstructorOccurrences(constructorDeclaration) {
+ var declarations = constructorDeclaration.symbol.getDeclarations();
+ var keywords = [];
+ ts.forEach(declarations, function (declaration) {
+ ts.forEach(declaration.getChildren(), function (token) {
+ return pushKeywordIf(keywords, token, 122 /* ConstructorKeyword */);
+ });
+ });
+ return keywords;
+ }
+ function getLoopBreakContinueOccurrences(loopNode) {
+ var keywords = [];
+ if (pushKeywordIf(keywords, loopNode.getFirstToken(), 87 /* ForKeyword */, 105 /* WhileKeyword */, 80 /* DoKeyword */)) {
+ // If we succeeded and got a do-while loop, then start looking for a 'while' keyword.
+ if (loopNode.kind === 211 /* DoStatement */) {
+ var loopTokens = loopNode.getChildren();
+ for (var i = loopTokens.length - 1; i >= 0; i--) {
+ if (pushKeywordIf(keywords, loopTokens[i], 105 /* WhileKeyword */)) {
+ break;
}
}
- return undefined;
}
- function getSwitchCaseDefaultOccurrences(switchStatement) {
- var keywords = [];
- pushKeywordIf(keywords, switchStatement.getFirstToken(), 97 /* SwitchKeyword */);
- // Go through each clause in the switch statement, collecting the 'case'/'default' keywords.
- ts.forEach(switchStatement.caseBlock.clauses, function (clause) {
- pushKeywordIf(keywords, clause.getFirstToken(), 72 /* CaseKeyword */, 78 /* DefaultKeyword */);
- var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause);
- ts.forEach(breaksAndContinues, function (statement) {
- if (ownsBreakOrContinueStatement(switchStatement, statement)) {
- pushKeywordIf(keywords, statement.getFirstToken(), 71 /* BreakKeyword */);
- }
- });
- });
- return ts.map(keywords, getHighlightSpanForNode);
+ }
+ var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement);
+ ts.forEach(breaksAndContinues, function (statement) {
+ if (ownsBreakOrContinueStatement(loopNode, statement)) {
+ pushKeywordIf(keywords, statement.getFirstToken(), 71 /* BreakKeyword */, 76 /* ContinueKeyword */);
}
- function getTryCatchFinallyOccurrences(tryStatement) {
- var keywords = [];
- pushKeywordIf(keywords, tryStatement.getFirstToken(), 101 /* TryKeyword */);
- if (tryStatement.catchClause) {
- pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 73 /* CatchKeyword */);
- }
- if (tryStatement.finallyBlock) {
- var finallyKeyword = ts.findChildOfKind(tryStatement, 86 /* FinallyKeyword */, sourceFile);
- pushKeywordIf(keywords, finallyKeyword, 86 /* FinallyKeyword */);
- }
- return ts.map(keywords, getHighlightSpanForNode);
+ });
+ return keywords;
+ }
+ function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) {
+ var owner = getBreakOrContinueOwner(breakOrContinueStatement);
+ if (owner) {
+ switch (owner.kind) {
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ case 211 /* DoStatement */:
+ case 212 /* WhileStatement */:
+ return getLoopBreakContinueOccurrences(owner);
+ case 220 /* SwitchStatement */:
+ return getSwitchCaseDefaultOccurrences(owner);
}
- function getThrowOccurrences(throwStatement) {
- var owner = getThrowStatementOwner(throwStatement);
- if (!owner) {
- return undefined;
+ }
+ return undefined;
+ }
+ function getSwitchCaseDefaultOccurrences(switchStatement) {
+ var keywords = [];
+ pushKeywordIf(keywords, switchStatement.getFirstToken(), 97 /* SwitchKeyword */);
+ // Go through each clause in the switch statement, collecting the 'case'/'default' keywords.
+ ts.forEach(switchStatement.caseBlock.clauses, function (clause) {
+ pushKeywordIf(keywords, clause.getFirstToken(), 72 /* CaseKeyword */, 78 /* DefaultKeyword */);
+ var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause);
+ ts.forEach(breaksAndContinues, function (statement) {
+ if (ownsBreakOrContinueStatement(switchStatement, statement)) {
+ pushKeywordIf(keywords, statement.getFirstToken(), 71 /* BreakKeyword */);
}
- var keywords = [];
- ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) {
- pushKeywordIf(keywords, throwStatement.getFirstToken(), 99 /* ThrowKeyword */);
- });
- // 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 (ts.isFunctionBlock(owner)) {
- ts.forEachReturnStatement(owner, function (returnStatement) {
- pushKeywordIf(keywords, returnStatement.getFirstToken(), 95 /* ReturnKeyword */);
- });
+ });
+ });
+ return keywords;
+ }
+ function getTryCatchFinallyOccurrences(tryStatement, sourceFile) {
+ var keywords = [];
+ pushKeywordIf(keywords, tryStatement.getFirstToken(), 101 /* TryKeyword */);
+ if (tryStatement.catchClause) {
+ pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 73 /* CatchKeyword */);
+ }
+ if (tryStatement.finallyBlock) {
+ var finallyKeyword = ts.findChildOfKind(tryStatement, 86 /* FinallyKeyword */, sourceFile);
+ pushKeywordIf(keywords, finallyKeyword, 86 /* FinallyKeyword */);
+ }
+ return keywords;
+ }
+ function getThrowOccurrences(throwStatement) {
+ var owner = getThrowStatementOwner(throwStatement);
+ if (!owner) {
+ return undefined;
+ }
+ var keywords = [];
+ ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) {
+ pushKeywordIf(keywords, throwStatement.getFirstToken(), 99 /* ThrowKeyword */);
+ });
+ // 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 (ts.isFunctionBlock(owner)) {
+ ts.forEachReturnStatement(owner, function (returnStatement) {
+ pushKeywordIf(keywords, returnStatement.getFirstToken(), 95 /* ReturnKeyword */);
+ });
+ }
+ return keywords;
+ }
+ function getReturnOccurrences(returnStatement) {
+ var func = ts.getContainingFunction(returnStatement);
+ // If we didn't find a containing function with a block body, bail out.
+ if (!(func && hasKind(func.body, 206 /* Block */))) {
+ return undefined;
+ }
+ var keywords = [];
+ ts.forEachReturnStatement(func.body, function (returnStatement) {
+ pushKeywordIf(keywords, returnStatement.getFirstToken(), 95 /* ReturnKeyword */);
+ });
+ // Include 'throw' statements that do not occur within a try block.
+ ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) {
+ pushKeywordIf(keywords, throwStatement.getFirstToken(), 99 /* ThrowKeyword */);
+ });
+ return keywords;
+ }
+ function getIfElseOccurrences(ifStatement, sourceFile) {
+ var keywords = [];
+ // Traverse upwards through all parent if-statements linked by their else-branches.
+ while (hasKind(ifStatement.parent, 210 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) {
+ ifStatement = ifStatement.parent;
+ }
+ // Now traverse back down through the else branches, aggregating if/else keywords of if-statements.
+ while (ifStatement) {
+ var children = ifStatement.getChildren();
+ pushKeywordIf(keywords, children[0], 89 /* IfKeyword */);
+ // Generally the 'else' keyword is second-to-last, so we traverse backwards.
+ for (var i = children.length - 1; i >= 0; i--) {
+ if (pushKeywordIf(keywords, children[i], 81 /* ElseKeyword */)) {
+ break;
}
- return ts.map(keywords, getHighlightSpanForNode);
}
- function getReturnOccurrences(returnStatement) {
- var func = ts.getContainingFunction(returnStatement);
- // If we didn't find a containing function with a block body, bail out.
- if (!(func && hasKind(func.body, 204 /* Block */))) {
- return undefined;
- }
- var keywords = [];
- ts.forEachReturnStatement(func.body, function (returnStatement) {
- pushKeywordIf(keywords, returnStatement.getFirstToken(), 95 /* ReturnKeyword */);
- });
- // Include 'throw' statements that do not occur within a try block.
- ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) {
- pushKeywordIf(keywords, throwStatement.getFirstToken(), 99 /* ThrowKeyword */);
- });
- return ts.map(keywords, getHighlightSpanForNode);
- }
- function getIfElseOccurrences(ifStatement) {
- var keywords = [];
- // Traverse upwards through all parent if-statements linked by their else-branches.
- while (hasKind(ifStatement.parent, 208 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) {
- ifStatement = ifStatement.parent;
- }
- // Now traverse back down through the else branches, aggregating if/else keywords of if-statements.
- while (ifStatement) {
- var children = ifStatement.getChildren();
- pushKeywordIf(keywords, children[0], 89 /* IfKeyword */);
- // Generally the 'else' keyword is second-to-last, so we traverse backwards.
- for (var i = children.length - 1; i >= 0; i--) {
- if (pushKeywordIf(keywords, children[i], 81 /* ElseKeyword */)) {
- break;
- }
- }
- if (!hasKind(ifStatement.elseStatement, 208 /* IfStatement */)) {
+ if (!hasKind(ifStatement.elseStatement, 210 /* IfStatement */)) {
+ break;
+ }
+ ifStatement = ifStatement.elseStatement;
+ }
+ var result = [];
+ // We'd like to highlight else/ifs together if they are only separated by whitespace
+ // (i.e. the keywords are separated by no comments, no newlines).
+ for (var i = 0; i < keywords.length; i++) {
+ if (keywords[i].kind === 81 /* ElseKeyword */ && i < keywords.length - 1) {
+ var elseKeyword = keywords[i];
+ var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword.
+ var shouldCombindElseAndIf = true;
+ // Avoid recalculating getStart() by iterating backwards.
+ for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) {
+ if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) {
+ shouldCombindElseAndIf = false;
break;
}
- ifStatement = ifStatement.elseStatement;
}
- var result = [];
- // We'd like to highlight else/ifs together if they are only separated by whitespace
- // (i.e. the keywords are separated by no comments, no newlines).
- for (var i = 0; i < keywords.length; i++) {
- if (keywords[i].kind === 81 /* ElseKeyword */ && i < keywords.length - 1) {
- var elseKeyword = keywords[i];
- var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword.
- var shouldCombindElseAndIf = true;
- // Avoid recalculating getStart() by iterating backwards.
- for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) {
- if (!ts.isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) {
- shouldCombindElseAndIf = false;
- break;
- }
- }
- if (shouldCombindElseAndIf) {
- result.push({
- fileName: fileName,
- textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end),
- kind: ts.HighlightSpanKind.reference
- });
- i++; // skip the next keyword
- continue;
- }
- }
- // Ordinary case: just highlight the keyword.
- result.push(getHighlightSpanForNode(keywords[i]));
+ if (shouldCombindElseAndIf) {
+ result.push({
+ fileName: sourceFile.fileName,
+ textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end),
+ kind: ts.HighlightSpanKind.reference
+ });
+ i++; // skip the next keyword
+ continue;
}
- return result;
}
+ // Ordinary case: just highlight the keyword.
+ result.push(getHighlightSpanForNode(keywords[i], sourceFile));
}
+ return result;
}
- DocumentHighlights.getDocumentHighlights = getDocumentHighlights;
/**
* Whether or not a 'node' is preceded by a label of the given string.
* Note: 'node' cannot be a SourceFile.
*/
function isLabeledBy(node, labelName) {
- for (var owner = node.parent; owner.kind === 219 /* LabeledStatement */; owner = owner.parent) {
+ for (var owner = node.parent; owner.kind === 221 /* LabeledStatement */; owner = owner.parent) {
if (owner.label.text === labelName) {
return true;
}
@@ -69168,15 +74232,15 @@ var ts;
return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths);
}
function getBucketForCompilationSettings(key, createIfMissing) {
- var bucket = buckets[key];
+ var bucket = buckets.get(key);
if (!bucket && createIfMissing) {
- buckets[key] = bucket = ts.createFileMap();
+ buckets.set(key, bucket = ts.createFileMap());
}
return bucket;
}
function reportStats() {
- var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) {
- var entries = buckets[name];
+ var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) {
+ var entries = buckets.get(name);
var sourceFiles = [];
entries.forEachValue(function (key, entry) {
sourceFiles.push({
@@ -69269,41 +74333,764 @@ var ts;
}
ts.createDocumentRegistry = createDocumentRegistry;
})(ts || (ts = {}));
+/* Code for finding imports of an exported symbol. Used only by FindAllReferences. */
/* @internal */
var ts;
(function (ts) {
var FindAllReferences;
(function (FindAllReferences) {
- function findReferencedSymbols(typeChecker, cancellationToken, sourceFiles, sourceFile, position, findInStrings, findInComments) {
- var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
- if (node === sourceFile) {
- return undefined;
+ /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */
+ function createImportTracker(sourceFiles, checker, cancellationToken) {
+ var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken);
+ return function (exportSymbol, exportInfo, isForRename) {
+ var _a = getImportersForExport(sourceFiles, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers;
+ return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename));
+ };
+ }
+ FindAllReferences.createImportTracker = createImportTracker;
+ var ExportKind;
+ (function (ExportKind) {
+ ExportKind[ExportKind["Named"] = 0] = "Named";
+ ExportKind[ExportKind["Default"] = 1] = "Default";
+ ExportKind[ExportKind["ExportEquals"] = 2] = "ExportEquals";
+ })(ExportKind = FindAllReferences.ExportKind || (FindAllReferences.ExportKind = {}));
+ var ImportExport;
+ (function (ImportExport) {
+ ImportExport[ImportExport["Import"] = 0] = "Import";
+ ImportExport[ImportExport["Export"] = 1] = "Export";
+ })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {}));
+ /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */
+ function getImportersForExport(sourceFiles, allDirectImports, _a, checker, cancellationToken) {
+ var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind;
+ var markSeenDirectImport = ts.nodeSeenTracker();
+ var markSeenIndirectUser = ts.nodeSeenTracker();
+ var directImports = [];
+ var isAvailableThroughGlobal = !!exportingModuleSymbol.globalExports;
+ var indirectUserDeclarations = isAvailableThroughGlobal ? undefined : [];
+ handleDirectImports(exportingModuleSymbol);
+ return { directImports: directImports, indirectUsers: getIndirectUsers() };
+ function getIndirectUsers() {
+ if (isAvailableThroughGlobal) {
+ // It has `export as namespace`, so anything could potentially use it.
+ return sourceFiles;
+ }
+ // Module augmentations may use this module's exports without importing it.
+ for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (ts.isExternalModuleAugmentation(decl)) {
+ addIndirectUser(decl);
+ }
+ }
+ // This may return duplicates (if there are multiple module declarations in a single source file, all importing the same thing as a namespace), but `State.markSearchedSymbol` will handle that.
+ return indirectUserDeclarations.map(ts.getSourceFileOfNode);
}
- switch (node.kind) {
- case 8 /* NumericLiteral */:
- if (!ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) {
- break;
+ function handleDirectImports(exportingModuleSymbol) {
+ var theseDirectImports = getDirectImports(exportingModuleSymbol);
+ if (theseDirectImports)
+ for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) {
+ var direct = theseDirectImports_1[_i];
+ if (!markSeenDirectImport(direct)) {
+ continue;
+ }
+ cancellationToken.throwIfCancellationRequested();
+ switch (direct.kind) {
+ case 180 /* CallExpression */:
+ if (!isAvailableThroughGlobal) {
+ var parent = direct.parent;
+ if (exportKind === 2 /* ExportEquals */ && parent.kind === 225 /* VariableDeclaration */) {
+ var name = parent.name;
+ if (name.kind === 70 /* Identifier */) {
+ directImports.push(name);
+ break;
+ }
+ }
+ // Don't support re-exporting 'require()' calls, so just add a single indirect user.
+ addIndirectUser(direct.getSourceFile());
+ }
+ break;
+ case 236 /* ImportEqualsDeclaration */:
+ handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */));
+ break;
+ case 237 /* ImportDeclaration */:
+ var namedBindings = direct.importClause && direct.importClause.namedBindings;
+ if (namedBindings && namedBindings.kind === 239 /* NamespaceImport */) {
+ handleNamespaceImport(direct, namedBindings.name);
+ }
+ else {
+ directImports.push(direct);
+ }
+ break;
+ case 243 /* ExportDeclaration */:
+ if (!direct.exportClause) {
+ // This is `export * from "foo"`, so imports of this module may import the export too.
+ handleDirectImports(getContainingModuleSymbol(direct, checker));
+ }
+ else {
+ // This is `export { foo } from "foo"` and creates an alias symbol, so recursive search will get handle re-exports.
+ directImports.push(direct);
+ }
+ break;
+ }
+ }
+ }
+ function handleNamespaceImport(importDeclaration, name, isReExport) {
+ if (exportKind === 2 /* ExportEquals */) {
+ // This is a direct import, not import-as-namespace.
+ directImports.push(importDeclaration);
+ }
+ else if (!isAvailableThroughGlobal) {
+ var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
+ ts.Debug.assert(sourceFileLike.kind === 264 /* SourceFile */ || sourceFileLike.kind === 232 /* ModuleDeclaration */);
+ if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
+ addIndirectUsers(sourceFileLike);
+ }
+ else {
+ addIndirectUser(sourceFileLike);
+ }
+ }
+ }
+ function addIndirectUser(sourceFileLike) {
+ ts.Debug.assert(!isAvailableThroughGlobal);
+ var isNew = markSeenIndirectUser(sourceFileLike);
+ if (isNew) {
+ indirectUserDeclarations.push(sourceFileLike);
+ }
+ return isNew;
+ }
+ /** Adds a module and all of its transitive dependencies as possible indirect users. */
+ function addIndirectUsers(sourceFileLike) {
+ if (!addIndirectUser(sourceFileLike)) {
+ return;
+ }
+ var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol);
+ ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */));
+ var directImports = getDirectImports(moduleSymbol);
+ if (directImports)
+ for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) {
+ var directImport = directImports_1[_i];
+ addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport));
+ }
+ }
+ function getDirectImports(moduleSymbol) {
+ return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString());
+ }
+ }
+ /**
+ * Given the set of direct imports of a module, we need to find which ones import the particular exported symbol.
+ * The returned `importSearches` will result in the entire source file being searched.
+ * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced.
+ */
+ function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) {
+ var exportName = exportSymbol.name;
+ var importSearches = [];
+ var singleReferences = [];
+ function addSearch(location, symbol) {
+ importSearches.push([location, symbol]);
+ }
+ if (directImports)
+ for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) {
+ var decl = directImports_2[_i];
+ handleImport(decl);
+ }
+ return { importSearches: importSearches, singleReferences: singleReferences };
+ function handleImport(decl) {
+ if (decl.kind === 236 /* ImportEqualsDeclaration */) {
+ if (isExternalModuleImportEquals(decl)) {
+ handleNamespaceImportLike(decl.name);
+ }
+ return;
+ }
+ if (decl.kind === 70 /* Identifier */) {
+ handleNamespaceImportLike(decl);
+ return;
+ }
+ // Ignore if there's a grammar error
+ if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) {
+ return;
+ }
+ if (decl.kind === 243 /* ExportDeclaration */) {
+ searchForNamedImport(decl.exportClause);
+ return;
+ }
+ var importClause = decl.importClause;
+ var namedBindings = importClause.namedBindings;
+ if (namedBindings && namedBindings.kind === 239 /* NamespaceImport */) {
+ handleNamespaceImportLike(namedBindings.name);
+ return;
+ }
+ if (exportKind === 0 /* Named */) {
+ searchForNamedImport(namedBindings);
+ }
+ else {
+ // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals
+ var name = importClause.name;
+ // If a default import has the same name as the default export, allow to rename it.
+ // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
+ if (name && (!isForRename || name.text === symbolName(exportSymbol))) {
+ var defaultImportAlias = checker.getSymbolAtLocation(name);
+ addSearch(name, defaultImportAlias);
+ }
+ // 'default' might be accessed as a named import `{ default as foo }`.
+ if (!isForRename && exportKind === 1 /* Default */) {
+ ts.Debug.assert(exportName === "default");
+ searchForNamedImport(namedBindings);
+ }
+ }
+ }
+ /**
+ * `import x = require("./x") or `import * as x from "./x"`.
+ * An `export =` may be imported by this syntax, so it may be a direct import.
+ * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
+ */
+ function handleNamespaceImportLike(importName) {
+ // Don't rename an import that already has a different name than the export.
+ if (exportKind === 2 /* ExportEquals */ && (!isForRename || importName.text === exportName)) {
+ addSearch(importName, checker.getSymbolAtLocation(importName));
+ }
+ }
+ function searchForNamedImport(namedBindings) {
+ if (namedBindings)
+ for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
+ var element = _a[_i];
+ var name = element.name, propertyName = element.propertyName;
+ if ((propertyName || name).text !== exportName) {
+ continue;
+ }
+ if (propertyName) {
+ // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference.
+ singleReferences.push(propertyName);
+ if (!isForRename) {
+ // Search locally for `bar`.
+ addSearch(name, checker.getSymbolAtLocation(name));
+ }
+ }
+ else {
+ var localSymbol = element.kind === 245 /* ExportSpecifier */ && element.propertyName
+ ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol.
+ : checker.getSymbolAtLocation(name);
+ addSearch(name, localSymbol);
+ }
}
- // Fallthrough
- case 70 /* Identifier */:
- case 98 /* ThisKeyword */:
- // case SyntaxKind.SuperKeyword: TODO:GH#9268
- case 122 /* ConstructorKeyword */:
- case 9 /* StringLiteral */:
- return getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, /*implementations*/ false);
}
- return undefined;
+ }
+ /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */
+ function findNamespaceReExports(sourceFileLike, name, checker) {
+ var namespaceImportSymbol = checker.getSymbolAtLocation(name);
+ return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
+ if (statement.kind !== 243 /* ExportDeclaration */)
+ return;
+ var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier;
+ if (moduleSpecifier || !exportClause)
+ return;
+ for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) {
+ var element = _b[_i];
+ if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) {
+ return true;
+ }
+ }
+ });
+ }
+ /** Returns a map from a module symbol Id to all import statements that directly reference the module. */
+ function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
+ var map = ts.createMap();
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var sourceFile = sourceFiles_4[_i];
+ cancellationToken.throwIfCancellationRequested();
+ forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
+ var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
+ if (moduleSymbol) {
+ var id = ts.getSymbolId(moduleSymbol).toString();
+ var imports = map.get(id);
+ if (!imports) {
+ map.set(id, imports = []);
+ }
+ imports.push(importDecl);
+ }
+ });
+ }
+ return map;
+ }
+ /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */
+ function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
+ return ts.forEach(sourceFileLike.kind === 264 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
+ });
+ }
+ /** Calls `action` for each import, re-export, or require() in a file. */
+ function forEachImport(sourceFile, action) {
+ if (sourceFile.externalModuleIndicator) {
+ for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
+ var moduleSpecifier = _a[_i];
+ action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier);
+ }
+ }
+ else {
+ forEachPossibleImportOrExportStatement(sourceFile, function (statement) {
+ switch (statement.kind) {
+ case 243 /* ExportDeclaration */:
+ case 237 /* ImportDeclaration */: {
+ var decl = statement;
+ if (decl.moduleSpecifier && decl.moduleSpecifier.kind === 9 /* StringLiteral */) {
+ action(decl, decl.moduleSpecifier);
+ }
+ break;
+ }
+ case 236 /* ImportEqualsDeclaration */: {
+ var decl = statement;
+ var moduleReference = decl.moduleReference;
+ if (moduleReference.kind === 247 /* ExternalModuleReference */ &&
+ moduleReference.expression.kind === 9 /* StringLiteral */) {
+ action(decl, moduleReference.expression);
+ }
+ break;
+ }
+ }
+ });
+ if (sourceFile.flags & 65536 /* JavaScriptFile */) {
+ // Find all 'require()' calls.
+ sourceFile.forEachChild(function recur(node) {
+ if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
+ action(node, node.arguments[0]);
+ }
+ else {
+ node.forEachChild(recur);
+ }
+ });
+ }
+ }
+ }
+ function importerFromModuleSpecifier(moduleSpecifier) {
+ var decl = moduleSpecifier.parent;
+ if (decl.kind === 237 /* ImportDeclaration */ || decl.kind === 243 /* ExportDeclaration */) {
+ return decl;
+ }
+ ts.Debug.assert(decl.kind === 247 /* ExternalModuleReference */);
+ return decl.parent;
+ }
+ /**
+ * Given a local reference, we might notice that it's an import/export and recursively search for references of that.
+ * If at an import, look locally for the symbol it imports.
+ * If an an export, look for all imports of it.
+ * This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`.
+ * @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here.
+ */
+ function getImportOrExportSymbol(node, symbol, checker, comingFromExport) {
+ return comingFromExport ? getExport() : getExport() || getImport();
+ function getExport() {
+ var parent = node.parent;
+ if (symbol.flags & 7340032 /* Export */) {
+ if (parent.kind === 178 /* PropertyAccessExpression */) {
+ // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use.
+ // So check that we are at the declaration.
+ return symbol.declarations.some(function (d) { return d === parent; }) && parent.parent.kind === 193 /* BinaryExpression */
+ ? getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ false)
+ : undefined;
+ }
+ else {
+ var exportSymbol = symbol.exportSymbol;
+ ts.Debug.assert(!!exportSymbol);
+ return exportInfo(exportSymbol, getExportKindForDeclaration(parent));
+ }
+ }
+ else {
+ var exportNode = parent.kind === 225 /* VariableDeclaration */ ? ts.getAncestor(parent, 207 /* VariableStatement */) : parent;
+ if (ts.hasModifier(exportNode, 1 /* Export */)) {
+ if (exportNode.kind === 236 /* ImportEqualsDeclaration */ && exportNode.moduleReference === node) {
+ // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement.
+ if (comingFromExport) {
+ return undefined;
+ }
+ var lhsSymbol = checker.getSymbolAtLocation(exportNode.name);
+ return { kind: 0 /* Import */, symbol: lhsSymbol, isNamedImport: false };
+ }
+ else {
+ return exportInfo(symbol, getExportKindForDeclaration(exportNode));
+ }
+ }
+ else if (parent.kind === 242 /* ExportAssignment */) {
+ // Get the symbol for the `export =` node; its parent is the module it's the export of.
+ var exportingModuleSymbol = parent.symbol.parent;
+ ts.Debug.assert(!!exportingModuleSymbol);
+ return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 /* ExportEquals */ } };
+ }
+ else if (parent.kind === 193 /* BinaryExpression */) {
+ return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true);
+ }
+ else if (parent.parent.kind === 193 /* BinaryExpression */) {
+ return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true);
+ }
+ }
+ function getSpecialPropertyExport(node, useLhsSymbol) {
+ var kind;
+ switch (ts.getSpecialPropertyAssignmentKind(node)) {
+ case 1 /* ExportsProperty */:
+ kind = 0 /* Named */;
+ break;
+ case 2 /* ModuleExports */:
+ kind = 2 /* ExportEquals */;
+ break;
+ default:
+ return undefined;
+ }
+ var sym = useLhsSymbol ? checker.getSymbolAtLocation(node.left.name) : symbol;
+ return sym && exportInfo(sym, kind);
+ }
+ }
+ function getImport() {
+ var isImport = isNodeImport(node);
+ if (!isImport)
+ return;
+ // A symbol being imported is always an alias. So get what that aliases to find the local symbol.
+ var importedSymbol = checker.getImmediateAliasedSymbol(symbol);
+ if (importedSymbol) {
+ // Search on the local symbol in the exporting module, not the exported symbol.
+ importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker);
+ // Similarly, skip past the symbol for 'export ='
+ if (importedSymbol.name === "export=") {
+ importedSymbol = checker.getImmediateAliasedSymbol(importedSymbol);
+ }
+ if (symbolName(importedSymbol) === symbol.name) {
+ return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
+ }
+ }
+ }
+ function exportInfo(symbol, kind) {
+ var exportInfo = getExportInfo(symbol, kind, checker);
+ return exportInfo && { kind: 1 /* Export */, symbol: symbol, exportInfo: exportInfo };
+ }
+ // Not meant for use with export specifiers or export assignment.
+ function getExportKindForDeclaration(node) {
+ return ts.hasModifier(node, 512 /* Default */) ? 1 /* Default */ : 0 /* Named */;
+ }
+ }
+ FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol;
+ function isNodeImport(node) {
+ var parent = node.parent;
+ switch (parent.kind) {
+ case 236 /* ImportEqualsDeclaration */:
+ return parent.name === node && isExternalModuleImportEquals(parent)
+ ? { isNamedImport: false }
+ : undefined;
+ case 241 /* ImportSpecifier */:
+ // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`.
+ return parent.propertyName ? undefined : { isNamedImport: true };
+ case 238 /* ImportClause */:
+ case 239 /* NamespaceImport */:
+ ts.Debug.assert(parent.name === node);
+ return { isNamedImport: false };
+ default:
+ return undefined;
+ }
+ }
+ function getExportInfo(exportSymbol, exportKind, checker) {
+ var exportingModuleSymbol = checker.getMergedSymbol(exportSymbol.parent); // Need to get merged symbol in case there's an augmentation.
+ // `export` may appear in a namespace. In that case, just rely on global search.
+ return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
+ }
+ FindAllReferences.getExportInfo = getExportInfo;
+ function symbolName(symbol) {
+ if (symbol.name !== "default") {
+ return symbol.name;
+ }
+ var name = ts.forEach(symbol.declarations, function (_a) {
+ var name = _a.name;
+ return name && name.kind === 70 /* Identifier */ && name.text;
+ });
+ ts.Debug.assert(!!name);
+ return name;
+ }
+ /** If at an export specifier, go to the symbol it refers to. */
+ function skipExportSpecifierSymbol(symbol, checker) {
+ // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
+ if (symbol.declarations)
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var declaration = _a[_i];
+ if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) {
+ return checker.getExportSpecifierLocalTargetSymbol(declaration);
+ }
+ }
+ return symbol;
+ }
+ function getContainingModuleSymbol(importer, checker) {
+ return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol);
+ }
+ function getSourceFileLikeForImportDeclaration(node) {
+ if (node.kind === 180 /* CallExpression */) {
+ return node.getSourceFile();
+ }
+ var parent = node.parent;
+ if (parent.kind === 264 /* SourceFile */) {
+ return parent;
+ }
+ ts.Debug.assert(parent.kind === 233 /* ModuleBlock */ && isAmbientModuleDeclaration(parent.parent));
+ return parent.parent;
+ }
+ function isAmbientModuleDeclaration(node) {
+ return node.kind === 232 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */;
+ }
+ function isExternalModuleImportEquals(_a) {
+ var moduleReference = _a.moduleReference;
+ return moduleReference.kind === 247 /* ExternalModuleReference */ && moduleReference.expression.kind === 9 /* StringLiteral */;
+ }
+ })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
+})(ts || (ts = {}));
+/// <reference path="./importTracker.ts" />
+/* @internal */
+var ts;
+(function (ts) {
+ var FindAllReferences;
+ (function (FindAllReferences) {
+ function nodeEntry(node, isInString) {
+ return { type: "node", node: node, isInString: isInString };
+ }
+ FindAllReferences.nodeEntry = nodeEntry;
+ function findReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position) {
+ var referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position);
+ if (!referencedSymbols || !referencedSymbols.length) {
+ return undefined;
+ }
+ var out = [];
+ for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) {
+ var _a = referencedSymbols_1[_i], definition = _a.definition, references = _a.references;
+ // Only include referenced symbols that have a valid definition.
+ if (definition) {
+ out.push({ definition: definitionToReferencedSymbolDefinitionInfo(definition, checker), references: references.map(toReferenceEntry) });
+ }
+ }
+ return out;
}
FindAllReferences.findReferencedSymbols = findReferencedSymbols;
- function getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, findInStrings, findInComments, implementations) {
- if (!implementations) {
+ function getImplementationsAtPosition(checker, cancellationToken, sourceFiles, sourceFile, position) {
+ var node = ts.getTouchingPropertyName(sourceFile, position);
+ var referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node);
+ return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); });
+ }
+ FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
+ function getImplementationReferenceEntries(typeChecker, cancellationToken, sourceFiles, node) {
+ // If invoked directly on a shorthand property assignment, then return
+ // the declaration of the symbol being assigned (not the symbol being assigned to).
+ if (node.parent.kind === 261 /* ShorthandPropertyAssignment */) {
+ var result_4 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, function (node) { return result_4.push(nodeEntry(node)); });
+ return result_4;
+ }
+ else if (node.kind === 96 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
+ // References to and accesses on the super keyword only have one possible implementation, so no
+ // need to "Find all References"
+ var symbol = typeChecker.getSymbolAtLocation(node);
+ return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)];
+ }
+ else {
+ // Perform "Find all References" and retrieve only those that are implementations
+ return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true });
+ }
+ }
+ function findReferencedEntries(checker, cancellationToken, sourceFiles, sourceFile, position, options) {
+ var x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options));
+ return ts.map(x, toReferenceEntry);
+ }
+ FindAllReferences.findReferencedEntries = findReferencedEntries;
+ function getReferenceEntriesForNode(node, sourceFiles, checker, cancellationToken, options) {
+ if (options === void 0) { options = {}; }
+ return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options));
+ }
+ FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode;
+ function findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options) {
+ var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
+ return FindAllReferences.Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options);
+ }
+ function flattenEntries(referenceSymbols) {
+ return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; });
+ }
+ function definitionToReferencedSymbolDefinitionInfo(def, checker) {
+ var info = (function () {
+ switch (def.type) {
+ case "symbol": {
+ var symbol = def.symbol, node_2 = def.node;
+ var declarations = symbol.declarations;
+ if (!declarations || declarations.length === 0) {
+ return undefined;
+ }
+ var _a = getDefinitionKindAndDisplayParts(symbol, node_2, checker), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
+ var name_3 = displayParts_1.map(function (p) { return p.text; }).join("");
+ return { node: node_2, name: name_3, kind: kind_1, displayParts: displayParts_1 };
+ }
+ case "label": {
+ var node_3 = def.node;
+ return { node: node_3, name: node_3.text, kind: ts.ScriptElementKind.label, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] };
+ }
+ case "keyword": {
+ var node_4 = def.node;
+ var name_4 = ts.tokenToString(node_4.kind);
+ return { node: node_4, name: name_4, kind: ts.ScriptElementKind.keyword, displayParts: [{ text: name_4, kind: ts.ScriptElementKind.keyword }] };
+ }
+ case "this": {
+ var node_5 = def.node;
+ var symbol = checker.getSymbolAtLocation(node_5);
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts;
+ return { node: node_5, name: "this", kind: ts.ScriptElementKind.variableElement, displayParts: displayParts_2 };
+ }
+ case "string": {
+ var node_6 = def.node;
+ return { node: node_6, name: node_6.text, kind: ts.ScriptElementKind.variableElement, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] };
+ }
+ }
+ })();
+ if (!info) {
+ return undefined;
+ }
+ var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts;
+ var sourceFile = node.getSourceFile();
+ return {
+ containerKind: "",
+ containerName: "",
+ fileName: sourceFile.fileName,
+ kind: kind,
+ name: name,
+ textSpan: ts.createTextSpanFromNode(node, sourceFile),
+ displayParts: displayParts
+ };
+ }
+ function getDefinitionKindAndDisplayParts(symbol, node, checker) {
+ var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), ts.getContainerNode(node), node), displayParts = _a.displayParts, symbolKind = _a.symbolKind;
+ return { displayParts: displayParts, kind: symbolKind };
+ }
+ function toReferenceEntry(entry) {
+ if (entry.type === "span") {
+ return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false };
+ }
+ var node = entry.node, isInString = entry.isInString;
+ return {
+ fileName: node.getSourceFile().fileName,
+ textSpan: getTextSpan(node),
+ isWriteAccess: isWriteAccess(node),
+ isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node),
+ isInString: isInString
+ };
+ }
+ function toImplementationLocation(entry, checker) {
+ if (entry.type === "node") {
+ var node = entry.node;
+ return __assign({ textSpan: getTextSpan(node), fileName: node.getSourceFile().fileName }, implementationKindDisplayParts(node, checker));
+ }
+ else {
+ var textSpan = entry.textSpan, fileName = entry.fileName;
+ return { textSpan: textSpan, fileName: fileName, kind: ts.ScriptElementKind.unknown, displayParts: [] };
+ }
+ }
+ function implementationKindDisplayParts(node, checker) {
+ var symbol = checker.getSymbolAtLocation(ts.isDeclaration(node) && node.name ? node.name : node);
+ if (symbol) {
+ return getDefinitionKindAndDisplayParts(symbol, node, checker);
+ }
+ else if (node.kind === 177 /* ObjectLiteralExpression */) {
+ return {
+ kind: ts.ScriptElementKind.interfaceElement,
+ displayParts: [ts.punctuationPart(18 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(19 /* CloseParenToken */)]
+ };
+ }
+ else if (node.kind === 198 /* ClassExpression */) {
+ return {
+ kind: ts.ScriptElementKind.localClassElement,
+ displayParts: [ts.punctuationPart(18 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(19 /* CloseParenToken */)]
+ };
+ }
+ else {
+ return { kind: ts.getNodeKind(node), displayParts: [] };
+ }
+ }
+ function toHighlightSpan(entry) {
+ if (entry.type === "span") {
+ var fileName_1 = entry.fileName, textSpan = entry.textSpan;
+ return { fileName: fileName_1, span: { textSpan: textSpan, kind: ts.HighlightSpanKind.reference } };
+ }
+ var node = entry.node, isInString = entry.isInString;
+ var fileName = entry.node.getSourceFile().fileName;
+ var writeAccess = isWriteAccess(node);
+ var span = {
+ textSpan: getTextSpan(node),
+ kind: writeAccess ? ts.HighlightSpanKind.writtenReference : ts.HighlightSpanKind.reference,
+ isInString: isInString
+ };
+ return { fileName: fileName, span: span };
+ }
+ FindAllReferences.toHighlightSpan = toHighlightSpan;
+ function getTextSpan(node) {
+ var start = node.getStart();
+ var end = node.getEnd();
+ if (node.kind === 9 /* StringLiteral */) {
+ start += 1;
+ end -= 1;
+ }
+ return ts.createTextSpanFromBounds(start, end);
+ }
+ /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */
+ function isWriteAccess(node) {
+ if (node.kind === 70 /* Identifier */ && ts.isDeclarationName(node)) {
+ return true;
+ }
+ var parent = node.parent;
+ if (parent) {
+ if (parent.kind === 192 /* PostfixUnaryExpression */ || parent.kind === 191 /* PrefixUnaryExpression */) {
+ return true;
+ }
+ else if (parent.kind === 193 /* BinaryExpression */ && parent.left === node) {
+ var operator = parent.operatorToken.kind;
+ return 57 /* FirstAssignment */ <= operator && operator <= 69 /* LastAssignment */;
+ }
+ }
+ return false;
+ }
+ })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
+})(ts || (ts = {}));
+/** Encapsulates the core find-all-references algorithm. */
+/* @internal */
+(function (ts) {
+ var FindAllReferences;
+ (function (FindAllReferences) {
+ var Core;
+ (function (Core) {
+ /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
+ function getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options) {
+ if (options === void 0) { options = {}; }
+ if (node.kind === 264 /* SourceFile */) {
+ return undefined;
+ }
+ if (!options.implementations) {
+ var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken);
+ if (special) {
+ return special;
+ }
+ }
+ var symbol = checker.getSymbolAtLocation(node);
+ // Could not find a symbol e.g. unknown identifier
+ if (!symbol) {
+ // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial.
+ if (!options.implementations && node.kind === 9 /* StringLiteral */) {
+ return getReferencesForStringLiteral(node, sourceFiles, cancellationToken);
+ }
+ // Can't have references to something that we have no symbol for.
+ return undefined;
+ }
+ // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol
+ if (!symbol.declarations || !symbol.declarations.length) {
+ return undefined;
+ }
+ return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options);
+ }
+ Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
+ /** getReferencedSymbols for special node kinds. */
+ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) {
+ if (ts.isTypeKeyword(node.kind)) {
+ return getAllReferencesForKeyword(sourceFiles, node.kind, cancellationToken);
+ }
// Labels
if (ts.isLabelName(node)) {
if (ts.isJumpStatementTarget(node)) {
var labelDefinition = ts.getTargetLabel(node.parent, node.text);
// if we have a label definition, look within its statement for references, if not, then
// the label is undefined and we have no results..
- return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined;
+ return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition);
}
else {
// it is a label definition and not a target, search within the parent labeledStatement
@@ -69311,129 +75098,164 @@ var ts;
}
}
if (ts.isThis(node)) {
- return getReferencesForThisKeyword(node, sourceFiles);
+ return getReferencesForThisKeyword(node, sourceFiles, cancellationToken);
}
if (node.kind === 96 /* SuperKeyword */) {
return getReferencesForSuperKeyword(node);
}
- }
- // `getSymbolAtLocation` normally returns the symbol of the class when given the constructor keyword,
- // so we have to specify that we want the constructor symbol.
- var symbol = typeChecker.getSymbolAtLocation(node);
- if (!implementations && !symbol && node.kind === 9 /* StringLiteral */) {
- return getReferencesForStringLiteral(node, sourceFiles);
- }
- // Could not find a symbol e.g. unknown identifier
- if (!symbol) {
- // Can't have references to something that we have no symbol for.
return undefined;
}
- var declarations = symbol.declarations;
- // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol
- if (!declarations || !declarations.length) {
- return undefined;
- }
- var result;
- // Compute the meaning from the location and the symbol it references
- var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), declarations);
- // Get the text to search for.
- // Note: if this is an external module symbol, the name doesn't include quotes.
- var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node));
- // Try to get the smallest valid scope that we can limit our search to;
- // otherwise we'll need to search globally (i.e. include each file).
- var scope = getSymbolScope(symbol);
- // Maps from a symbol ID to the ReferencedSymbol entry in 'result'.
- var symbolToIndex = [];
- if (scope) {
- result = [];
- getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex);
- }
- else {
- var internedName = getInternedName(symbol, node);
- for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) {
- var sourceFile = sourceFiles_8[_i];
- cancellationToken.throwIfCancellationRequested();
- var nameTable = ts.getNameTable(sourceFile);
- if (nameTable[internedName] !== undefined) {
- result = result || [];
- getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex);
+ /** Core find-all-references algorithm for a normal symbol. */
+ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) {
+ symbol = skipPastExportOrImportSpecifier(symbol, node, checker);
+ // Compute the meaning from the location and the symbol it references
+ var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations);
+ var result = [];
+ var state = createState(sourceFiles, node, checker, cancellationToken, searchMeaning, options, result);
+ var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) });
+ // Try to get the smallest valid scope that we can limit our search to;
+ // otherwise we'll need to search globally (i.e. include each file).
+ var scope = getSymbolScope(symbol);
+ if (scope) {
+ getReferencesInContainer(scope, scope.getSourceFile(), search, state);
+ }
+ else {
+ // Global search
+ for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ state.cancellationToken.throwIfCancellationRequested();
+ searchForName(sourceFile, search, state);
}
}
+ return result;
}
- return result;
- function getDefinition(symbol) {
- var info = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, node.getSourceFile(), ts.getContainerNode(node), node);
- var name = ts.map(info.displayParts, function (p) { return p.text; }).join("");
- var declarations = symbol.declarations;
- if (!declarations || declarations.length === 0) {
- return undefined;
+ /** Handle a few special cases relating to export/import specifiers. */
+ function skipPastExportOrImportSpecifier(symbol, node, checker) {
+ var parent = node.parent;
+ if (ts.isExportSpecifier(parent)) {
+ return getLocalSymbolForExportSpecifier(node, symbol, parent, checker);
}
- return {
- containerKind: "",
- containerName: "",
- name: name,
- kind: info.symbolKind,
- fileName: declarations[0].getSourceFile().fileName,
- textSpan: ts.createTextSpan(declarations[0].getStart(), 0),
- displayParts: info.displayParts
- };
+ if (ts.isImportSpecifier(parent) && parent.propertyName === node) {
+ // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import.
+ return checker.getImmediateAliasedSymbol(symbol);
+ }
+ return symbol;
}
- function getAliasSymbolForPropertyNameSymbol(symbol, location) {
- if (symbol.flags & 8388608 /* Alias */) {
- // Default import get alias
- var defaultImport = ts.getDeclarationOfKind(symbol, 236 /* ImportClause */);
- if (defaultImport) {
- return typeChecker.getAliasedSymbol(symbol);
- }
- var importOrExportSpecifier = ts.forEach(symbol.declarations, function (declaration) { return (declaration.kind === 239 /* ImportSpecifier */ ||
- declaration.kind === 243 /* ExportSpecifier */) ? declaration : undefined; });
- if (importOrExportSpecifier &&
- // export { a }
- (!importOrExportSpecifier.propertyName ||
- // export {a as class } where a is location
- importOrExportSpecifier.propertyName === location)) {
- // If Import specifier -> get alias
- // else Export specifier -> get local target
- return importOrExportSpecifier.kind === 239 /* ImportSpecifier */ ?
- typeChecker.getAliasedSymbol(symbol) :
- typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier);
+ function createState(sourceFiles, originalLocation, checker, cancellationToken, searchMeaning, options, result) {
+ var symbolIdToReferences = [];
+ var inheritsFromCache = ts.createMap();
+ // Source file ID → symbol ID → Whether the symbol has been searched for in the source file.
+ var sourceFileToSeenSymbols = [];
+ var isForConstructor = originalLocation.kind === 122 /* ConstructorKeyword */;
+ var importTracker;
+ return __assign({}, options, { sourceFiles: sourceFiles, isForConstructor: isForConstructor, checker: checker, cancellationToken: cancellationToken, searchMeaning: searchMeaning, inheritsFromCache: inheritsFromCache, getImportSearches: getImportSearches, createSearch: createSearch, referenceAdder: referenceAdder, addStringOrCommentReference: addStringOrCommentReference,
+ markSearchedSymbol: markSearchedSymbol, markSeenContainingTypeReference: ts.nodeSeenTracker(), markSeenReExportRHS: ts.nodeSeenTracker() });
+ function getImportSearches(exportSymbol, exportInfo) {
+ if (!importTracker)
+ importTracker = FindAllReferences.createImportTracker(sourceFiles, checker, cancellationToken);
+ return importTracker(exportSymbol, exportInfo, options.isForRename);
+ }
+ function createSearch(location, symbol, comingFrom, searchOptions) {
+ if (searchOptions === void 0) { searchOptions = {}; }
+ // Note: if this is an external module symbol, the name doesn't include quotes.
+ var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b;
+ var escapedText = ts.escapeIdentifier(text);
+ var parents = options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, checker);
+ return { location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, includes: includes };
+ function includes(referenceSymbol) {
+ return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol;
+ }
+ }
+ function referenceAdder(referenceSymbol, searchLocation) {
+ var symbolId = ts.getSymbolId(referenceSymbol);
+ var references = symbolIdToReferences[symbolId];
+ if (!references) {
+ references = symbolIdToReferences[symbolId] = [];
+ result.push({ definition: { type: "symbol", symbol: referenceSymbol, node: searchLocation }, references: references });
+ }
+ return function (node) { return references.push(FindAllReferences.nodeEntry(node)); };
+ }
+ function addStringOrCommentReference(fileName, textSpan) {
+ result.push({
+ definition: undefined,
+ references: [{ type: "span", fileName: fileName, textSpan: textSpan }]
+ });
+ }
+ function markSearchedSymbol(sourceFile, symbol) {
+ var sourceId = ts.getNodeId(sourceFile);
+ var symbolId = ts.getSymbolId(symbol);
+ var seenSymbols = sourceFileToSeenSymbols[sourceId] || (sourceFileToSeenSymbols[sourceId] = []);
+ return !seenSymbols[symbolId] && (seenSymbols[symbolId] = true);
+ }
+ }
+ /** Search for all imports of a given exported symbol using `State.getImportSearches`. */
+ function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) {
+ var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers;
+ // For `import { foo as bar }` just add the reference to `foo`, and don't otherwise search in the file.
+ if (singleReferences.length) {
+ var addRef = state.referenceAdder(exportSymbol, exportLocation);
+ for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
+ var singleRef = singleReferences_1[_i];
+ addRef(singleRef);
+ }
+ }
+ // For each import, find all references to that import in its source file.
+ for (var _b = 0, importSearches_1 = importSearches; _b < importSearches_1.length; _b++) {
+ var _c = importSearches_1[_b], importLocation = _c[0], importSymbol = _c[1];
+ getReferencesInSourceFile(importLocation.getSourceFile(), state.createSearch(importLocation, importSymbol, 1 /* Export */), state);
+ }
+ if (indirectUsers.length) {
+ var indirectSearch = void 0;
+ switch (exportInfo.exportKind) {
+ case 0 /* Named */:
+ indirectSearch = state.createSearch(exportLocation, exportSymbol, 1 /* Export */);
+ break;
+ case 1 /* Default */:
+ // Search for a property access to '.default'. This can't be renamed.
+ indirectSearch = state.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" });
+ break;
+ case 2 /* ExportEquals */:
+ break;
+ }
+ if (indirectSearch) {
+ for (var _d = 0, indirectUsers_1 = indirectUsers; _d < indirectUsers_1.length; _d++) {
+ var indirectUser = indirectUsers_1[_d];
+ searchForName(indirectUser, indirectSearch, state);
+ }
}
}
- return undefined;
}
- function followAliasIfNecessary(symbol, location) {
- return getAliasSymbolForPropertyNameSymbol(symbol, location) || symbol;
+ // Go to the symbol we imported from and find references for it.
+ function searchForImportedSymbol(symbol, state) {
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var declaration = _a[_i];
+ getReferencesInSourceFile(declaration.getSourceFile(), state.createSearch(declaration, symbol, 0 /* Import */), state);
+ }
+ }
+ /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */
+ function searchForName(sourceFile, search, state) {
+ if (ts.getNameTable(sourceFile).get(search.escapedText) !== undefined) {
+ getReferencesInSourceFile(sourceFile, search, state);
+ }
}
- function getPropertySymbolOfDestructuringAssignment(location) {
+ function getPropertySymbolOfDestructuringAssignment(location, checker) {
return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) &&
- typeChecker.getPropertySymbolOfDestructuringAssignment(location);
+ checker.getPropertySymbolOfDestructuringAssignment(location);
}
function isObjectBindingPatternElementWithoutPropertyName(symbol) {
- var bindingElement = ts.getDeclarationOfKind(symbol, 174 /* BindingElement */);
+ var bindingElement = ts.getDeclarationOfKind(symbol, 175 /* BindingElement */);
return bindingElement &&
- bindingElement.parent.kind === 172 /* ObjectBindingPattern */ &&
+ bindingElement.parent.kind === 173 /* ObjectBindingPattern */ &&
!bindingElement.propertyName;
}
- function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol) {
+ function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
if (isObjectBindingPatternElementWithoutPropertyName(symbol)) {
- var bindingElement = ts.getDeclarationOfKind(symbol, 174 /* BindingElement */);
- var typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent);
- return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
+ var bindingElement = ts.getDeclarationOfKind(symbol, 175 /* BindingElement */);
+ var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
+ return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
}
return undefined;
}
- function getInternedName(symbol, location) {
- // If this is an export or import specifier it could have been renamed using the 'as' syntax.
- // If so we want to search for whatever under the cursor.
- if (ts.isImportOrExportSpecifierName(location)) {
- return location.getText();
- }
- // Try to get the local symbol if we're dealing with an 'export default'
- // since that symbol has the "true" name.
- var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol);
- symbol = localExportDefaultSymbol || symbol;
- return ts.stripQuotes(symbol.name);
- }
/**
* Determines the smallest scope in which a symbol may have named references.
* Note that not every construct has been accounted for. This function can
@@ -69445,55 +75267,57 @@ var ts;
function getSymbolScope(symbol) {
// If this is the symbol of a named function expression or named class expression,
// then named references are limited to its own scope.
- var valueDeclaration = symbol.valueDeclaration;
- if (valueDeclaration && (valueDeclaration.kind === 184 /* FunctionExpression */ || valueDeclaration.kind === 197 /* ClassExpression */)) {
+ var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration;
+ if (valueDeclaration && (valueDeclaration.kind === 185 /* FunctionExpression */ || valueDeclaration.kind === 198 /* ClassExpression */)) {
return valueDeclaration;
}
+ if (!declarations) {
+ return undefined;
+ }
// If this is private property or method, the scope is the containing class
- if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) {
- var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (ts.getModifierFlags(d) & 8 /* Private */) ? d : undefined; });
+ if (flags & (4 /* Property */ | 8192 /* Method */)) {
+ var privateDeclaration = ts.find(declarations, function (d) { return !!(ts.getModifierFlags(d) & 8 /* Private */); });
if (privateDeclaration) {
- return ts.getAncestor(privateDeclaration, 226 /* ClassDeclaration */);
+ return ts.getAncestor(privateDeclaration, 228 /* ClassDeclaration */);
}
}
- // If the symbol is an import we would like to find it if we are looking for what it imports.
- // So consider it visible outside its declaration scope.
- if (symbol.flags & 8388608 /* Alias */) {
- return undefined;
- }
// If symbol is of object binding pattern element without property name we would want to
// look for property too and that could be anywhere
if (isObjectBindingPatternElementWithoutPropertyName(symbol)) {
return undefined;
}
- // if this symbol is visible from its parent container, e.g. exported, then bail out
- // if symbol correspond to the union property - bail out
- if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) {
+ // If the symbol has a parent, it's globally visible.
+ // Unless that parent is an external module, then we should only search in the module (and recurse on the export later).
+ // But if the parent is a module that has `export as namespace`, then the symbol *is* globally visible.
+ if (parent && !((parent.flags & 1536 /* Module */) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) {
+ return undefined;
+ }
+ // If this is a synthetic property, it's a property and must be searched for globally.
+ if ((flags & 134217728 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */)) {
return undefined;
}
var scope;
- var declarations = symbol.getDeclarations();
- if (declarations) {
- for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
- var declaration = declarations_7[_i];
- var container = ts.getContainerNode(declaration);
- if (!container) {
- return undefined;
- }
- if (scope && scope !== container) {
- // Different declarations have different containers, bail out
- return undefined;
- }
- if (container.kind === 261 /* SourceFile */ && !ts.isExternalModule(container)) {
- // This is a global variable and not an external module, any declaration defined
- // within this scope is visible outside the file
- return undefined;
- }
- // The search scope is the container node
- scope = container;
+ for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
+ var declaration = declarations_10[_i];
+ var container = ts.getContainerNode(declaration);
+ if (scope && scope !== container) {
+ // Different declarations have different containers, bail out
+ return undefined;
+ }
+ if (!container || container.kind === 264 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ // This is a global variable and not an external module, any declaration defined
+ // within this scope is visible outside the file
+ return undefined;
}
+ // The search scope is the container node
+ scope = container;
}
- return scope;
+ // If symbol.parent, this means we are in an export of an external module. (Otherwise we would have returned `undefined` above.)
+ // For an export of a module, we may be in a declaration file, and it may be accessed elsewhere. E.g.:
+ // declare module "a" { export type T = number; }
+ // declare module "b" { import { T } from "a"; export const x: T; }
+ // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.)
+ return parent ? scope.getSourceFile() : scope;
}
function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) {
var positions = [];
@@ -69508,7 +75332,6 @@ var ts;
var symbolNameLength = symbolName.length;
var position = text.indexOf(symbolName, start);
while (position >= 0) {
- cancellationToken.throwIfCancellationRequested();
// If we are past the end, stop looking
if (position > end)
break;
@@ -69529,279 +75352,320 @@ var ts;
var sourceFile = container.getSourceFile();
var labelName = targetLabel.text;
var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd());
- ts.forEach(possiblePositions, function (position) {
- cancellationToken.throwIfCancellationRequested();
+ for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) {
+ var position = possiblePositions_1[_i];
var node = ts.getTouchingWord(sourceFile, position);
if (!node || node.getWidth() !== labelName.length) {
- return;
+ continue;
}
// Only pick labels that are either the target label, or have a target that is the target label
if (node === targetLabel ||
(ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) {
- references.push(getReferenceEntryFromNode(node));
+ references.push(FindAllReferences.nodeEntry(node));
}
- });
- var definition = {
- containerKind: "",
- containerName: "",
- fileName: targetLabel.getSourceFile().fileName,
- kind: ts.ScriptElementKind.label,
- name: labelName,
- textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()),
- displayParts: [ts.displayPart(labelName, ts.SymbolDisplayPartKind.text)]
- };
- return [{ definition: definition, references: references }];
+ }
+ return [{ definition: { type: "label", node: targetLabel }, references: references }];
}
function isValidReferencePosition(node, searchSymbolName) {
- if (node) {
- // Compare the length so we filter out strict superstrings of the symbol we are looking for
- switch (node.kind) {
- case 70 /* Identifier */:
- return node.getWidth() === searchSymbolName.length;
- case 9 /* StringLiteral */:
- if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) ||
- isNameOfExternalModuleImportOrDeclaration(node)) {
- // For string literals we have two additional chars for the quotes
- return node.getWidth() === searchSymbolName.length + 2;
- }
- break;
- case 8 /* NumericLiteral */:
- if (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) {
- return node.getWidth() === searchSymbolName.length;
- }
- break;
+ // Compare the length so we filter out strict superstrings of the symbol we are looking for
+ switch (node && node.kind) {
+ case 70 /* Identifier */:
+ return node.getWidth() === searchSymbolName.length;
+ case 9 /* StringLiteral */:
+ return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) &&
+ // For string literals we have two additional chars for the quotes
+ node.getWidth() === searchSymbolName.length + 2;
+ case 8 /* NumericLiteral */:
+ return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.getWidth() === searchSymbolName.length;
+ default:
+ return false;
+ }
+ }
+ function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) {
+ var references = [];
+ for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
+ var sourceFile = sourceFiles_5[_i];
+ cancellationToken.throwIfCancellationRequested();
+ addReferencesForKeywordInFile(sourceFile, keywordKind, ts.tokenToString(keywordKind), references);
+ }
+ return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined;
+ }
+ function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) {
+ var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile.getStart(), sourceFile.getEnd());
+ for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) {
+ var position = possiblePositions_2[_i];
+ var referenceLocation = ts.getTouchingPropertyName(sourceFile, position);
+ if (referenceLocation.kind === kind) {
+ references.push(FindAllReferences.nodeEntry(referenceLocation));
}
}
- return false;
}
- /** Search within node "container" for references for a search value, where the search value is defined as a
- * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning).
- * searchLocation: a node where the search value
- */
- function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) {
- var sourceFile = container.getSourceFile();
- var start = findInComments ? container.getFullStart() : container.getStart();
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, start, container.getEnd());
- var parents = getParentSymbolsOfPropertyAccess();
- var inheritsFromCache = ts.createMap();
- if (possiblePositions.length) {
- // Build the set of symbols to search for, initially it has only the current symbol
- var searchSymbols_1 = populateSearchSymbolSet(searchSymbol, searchLocation);
- ts.forEach(possiblePositions, function (position) {
- cancellationToken.throwIfCancellationRequested();
- var referenceLocation = ts.getTouchingPropertyName(sourceFile, position);
- if (!isValidReferencePosition(referenceLocation, searchText)) {
- // This wasn't the start of a token. Check to see if it might be a
- // match in a comment or string if that's what the caller is asking
- // for.
- if (!implementations && ((findInStrings && ts.isInString(sourceFile, position)) ||
- (findInComments && ts.isInNonReferenceComment(sourceFile, position)))) {
- // In the case where we're looking inside comments/strings, we don't have
- // an actual definition. So just use 'undefined' here. Features like
- // 'Rename' won't care (as they ignore the definitions), and features like
- // 'FindReferences' will just filter out these results.
- result.push({
- definition: undefined,
- references: [{
- fileName: sourceFile.fileName,
- textSpan: ts.createTextSpan(position, searchText.length),
- isWriteAccess: false,
- isDefinition: false
- }]
- });
- }
- return;
- }
- if (!(ts.getMeaningFromLocation(referenceLocation) & searchMeaning)) {
- return;
- }
- var referenceSymbol = typeChecker.getSymbolAtLocation(referenceLocation);
- if (referenceSymbol) {
- var referenceSymbolDeclaration = referenceSymbol.valueDeclaration;
- var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration);
- var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation,
- /*searchLocationIsConstructor*/ searchLocation.kind === 122 /* ConstructorKeyword */, parents, inheritsFromCache);
- if (relatedSymbol) {
- addReferenceToRelatedSymbol(referenceLocation, relatedSymbol);
- }
- else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) {
- addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol);
- }
- else if (searchLocation.kind === 122 /* ConstructorKeyword */) {
- findAdditionalConstructorReferences(referenceSymbol, referenceLocation);
- }
- }
- });
+ function getReferencesInSourceFile(sourceFile, search, state) {
+ state.cancellationToken.throwIfCancellationRequested();
+ return getReferencesInContainer(sourceFile, sourceFile, search, state);
+ }
+ /**
+ * Search within node "container" for references for a search value, where the search value is defined as a
+ * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning).
+ * searchLocation: a node where the search value
+ */
+ function getReferencesInContainer(container, sourceFile, search, state) {
+ if (!state.markSearchedSymbol(sourceFile, search.symbol)) {
+ return;
}
- return;
- /* If we are just looking for implementations and this is a property access expression, we need to get the
- * symbol of the local type of the symbol the property is being accessed on. This is because our search
- * symbol may have a different parent symbol if the local type's symbol does not declare the property
- * being accessed (i.e. it is declared in some parent class or interface)
- */
- function getParentSymbolsOfPropertyAccess() {
- if (implementations) {
- var propertyAccessExpression = getPropertyAccessExpressionFromRightHandSide(searchLocation);
- if (propertyAccessExpression) {
- var localParentType = typeChecker.getTypeAtLocation(propertyAccessExpression.expression);
- if (localParentType) {
- if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== searchSymbol.parent) {
- return [localParentType.symbol];
- }
- else if (localParentType.flags & 196608 /* UnionOrIntersection */) {
- return getSymbolsForClassAndInterfaceComponents(localParentType);
- }
- }
- }
+ var start = state.findInComments ? container.getFullStart() : container.getStart();
+ var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, search.text, start, container.getEnd());
+ for (var _i = 0, possiblePositions_3 = possiblePositions; _i < possiblePositions_3.length; _i++) {
+ var position = possiblePositions_3[_i];
+ getReferencesAtLocation(sourceFile, position, search, state);
+ }
+ }
+ function getReferencesAtLocation(sourceFile, position, search, state) {
+ var referenceLocation = ts.getTouchingPropertyName(sourceFile, position);
+ if (!isValidReferencePosition(referenceLocation, search.text)) {
+ // This wasn't the start of a token. Check to see if it might be a
+ // match in a comment or string if that's what the caller is asking
+ // for.
+ if (!state.implementations && (state.findInStrings && ts.isInString(sourceFile, position) || state.findInComments && ts.isInNonReferenceComment(sourceFile, position))) {
+ // In the case where we're looking inside comments/strings, we don't have
+ // an actual definition. So just use 'undefined' here. Features like
+ // 'Rename' won't care (as they ignore the definitions), and features like
+ // 'FindReferences' will just filter out these results.
+ state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length));
}
+ return;
}
- function getPropertyAccessExpressionFromRightHandSide(node) {
- return ts.isRightSideOfPropertyAccess(node) && node.parent;
+ if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) {
+ return;
}
- /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */
- function findAdditionalConstructorReferences(referenceSymbol, referenceLocation) {
- ts.Debug.assert(ts.isClassLike(searchSymbol.valueDeclaration));
- var referenceClass = referenceLocation.parent;
- if (referenceSymbol === searchSymbol && ts.isClassLike(referenceClass)) {
- ts.Debug.assert(referenceClass.name === referenceLocation);
- // This is the class declaration containing the constructor.
- addReferences(findOwnConstructorCalls(searchSymbol));
+ var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
+ if (!referenceSymbol) {
+ return;
+ }
+ var parent = referenceLocation.parent;
+ if (ts.isImportSpecifier(parent) && parent.propertyName === referenceLocation) {
+ // This is added through `singleReferences` in ImportsResult. If we happen to see it again, don't add it again.
+ return;
+ }
+ if (ts.isExportSpecifier(parent)) {
+ ts.Debug.assert(referenceLocation.kind === 70 /* Identifier */);
+ getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state);
+ return;
+ }
+ var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state);
+ if (!relatedSymbol) {
+ getReferenceForShorthandProperty(referenceSymbol, search, state);
+ return;
+ }
+ if (state.isForConstructor) {
+ findConstructorReferences(referenceLocation, sourceFile, search, state);
+ }
+ else {
+ addReference(referenceLocation, relatedSymbol, search.location, state);
+ }
+ getImportOrExportReferences(referenceLocation, referenceSymbol, search, state);
+ }
+ function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state) {
+ var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
+ var exportDeclaration = parent.parent;
+ var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
+ if (!search.includes(localSymbol)) {
+ return;
+ }
+ if (!propertyName) {
+ addRef();
+ }
+ else if (referenceLocation === propertyName) {
+ // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export.
+ // For `export { foo as bar };`, where `foo` is a local, so add it now.
+ if (!exportDeclaration.moduleSpecifier) {
+ addRef();
}
- else {
- // If this class appears in `extends C`, then the extending class' "super" calls are references.
- var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
- if (classExtending && ts.isClassLike(classExtending) && followAliasIfNecessary(referenceSymbol, referenceLocation) === searchSymbol) {
- addReferences(superConstructorAccesses(classExtending));
- }
+ if (!state.isForRename && state.markSeenReExportRHS(name)) {
+ addReference(name, referenceSymbol, name, state);
}
}
- function addReferences(references) {
- if (references.length) {
- var referencedSymbol = getReferencedSymbol(searchSymbol);
- ts.addRange(referencedSymbol.references, ts.map(references, getReferenceEntryFromNode));
+ else {
+ if (state.markSeenReExportRHS(referenceLocation)) {
+ addRef();
}
}
- /** `classSymbol` is the class where the constructor was defined.
- * Reference the constructor and all calls to `new this()`.
+ // For `export { foo as bar }`, rename `foo`, but not `bar`.
+ if (!(referenceLocation === propertyName && state.isForRename)) {
+ var exportKind = referenceLocation.originalKeywordKind === 78 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */;
+ var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker);
+ ts.Debug.assert(!!exportInfo);
+ searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state);
+ }
+ // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
+ if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName) {
+ searchForImportedSymbol(state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier), state);
+ }
+ function addRef() {
+ addReference(referenceLocation, localSymbol, search.location, state);
+ }
+ }
+ function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) {
+ return isExportSpecifierAlias(referenceLocation, exportSpecifier) ? checker.getExportSpecifierLocalTargetSymbol(exportSpecifier) : referenceSymbol;
+ }
+ function isExportSpecifierAlias(referenceLocation, exportSpecifier) {
+ var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name;
+ ts.Debug.assert(propertyName === referenceLocation || name === referenceLocation);
+ if (propertyName) {
+ // Given `export { foo as bar } [from "someModule"]`: It's an alias at `foo`, but at `bar` it's a new symbol.
+ return propertyName === referenceLocation;
+ }
+ else {
+ // `export { foo } from "foo"` is a re-export.
+ // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`.
+ return !parent.parent.moduleSpecifier;
+ }
+ }
+ function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) {
+ var importOrExport = FindAllReferences.getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */);
+ if (!importOrExport)
+ return;
+ var symbol = importOrExport.symbol;
+ if (importOrExport.kind === 0 /* Import */) {
+ if (!state.isForRename || importOrExport.isNamedImport) {
+ searchForImportedSymbol(symbol, state);
+ }
+ }
+ else {
+ // We don't check for `state.isForRename`, even for default exports, because importers that previously matched the export name should be updated to continue matching.
+ searchForImportsOfExport(referenceLocation, symbol, importOrExport.exportInfo, state);
+ }
+ }
+ function getReferenceForShorthandProperty(_a, search, state) {
+ var flags = _a.flags, valueDeclaration = _a.valueDeclaration;
+ var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
+ /*
+ * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment
+ * has two meanings: property name and property value. Therefore when we do findAllReference at the position where
+ * an identifier is declared, the language service should return the position of the variable declaration as well as
+ * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the
+ * position of property accessing, the referenceEntry of such position will be handled in the first case.
*/
- function findOwnConstructorCalls(classSymbol) {
- var result = [];
- for (var _i = 0, _a = classSymbol.members["__constructor"].declarations; _i < _a.length; _i++) {
- var decl = _a[_i];
- ts.Debug.assert(decl.kind === 150 /* Constructor */);
- var ctrKeyword = decl.getChildAt(0);
- ts.Debug.assert(ctrKeyword.kind === 122 /* ConstructorKeyword */);
- result.push(ctrKeyword);
- }
- ts.forEachProperty(classSymbol.exports, function (member) {
- var decl = member.valueDeclaration;
- if (decl && decl.kind === 149 /* MethodDeclaration */) {
- var body = decl.body;
- if (body) {
- forEachDescendantOfKind(body, 98 /* ThisKeyword */, function (thisKeyword) {
- if (ts.isNewExpressionTarget(thisKeyword)) {
- result.push(thisKeyword);
- }
- });
- }
- }
- });
- return result;
+ if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) {
+ addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state);
+ }
+ }
+ function addReference(referenceLocation, relatedSymbol, searchLocation, state) {
+ var addRef = state.referenceAdder(relatedSymbol, searchLocation);
+ if (state.implementations) {
+ addImplementationReferences(referenceLocation, addRef, state);
}
- /** Find references to `super` in the constructor of an extending class. */
- function superConstructorAccesses(cls) {
- var symbol = cls.symbol;
- var ctr = symbol.members["__constructor"];
- if (!ctr) {
- return [];
+ else {
+ addRef(referenceLocation);
+ }
+ }
+ /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */
+ function findConstructorReferences(referenceLocation, sourceFile, search, state) {
+ if (ts.isNewExpressionTarget(referenceLocation)) {
+ addReference(referenceLocation, search.symbol, search.location, state);
+ }
+ var pusher = state.referenceAdder(search.symbol, search.location);
+ if (ts.isClassLike(referenceLocation.parent)) {
+ ts.Debug.assert(referenceLocation.parent.name === referenceLocation);
+ // This is the class declaration containing the constructor.
+ findOwnConstructorReferences(search.symbol, sourceFile, pusher);
+ }
+ else {
+ // If this class appears in `extends C`, then the extending class' "super" calls are references.
+ var classExtending = tryGetClassByExtendingIdentifier(referenceLocation);
+ if (classExtending && ts.isClassLike(classExtending)) {
+ findSuperConstructorAccesses(classExtending, pusher);
}
- var result = [];
- for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) {
- var decl = _a[_i];
- ts.Debug.assert(decl.kind === 150 /* Constructor */);
+ }
+ }
+ function getPropertyAccessExpressionFromRightHandSide(node) {
+ return ts.isRightSideOfPropertyAccess(node) && node.parent;
+ }
+ /**
+ * `classSymbol` is the class where the constructor was defined.
+ * Reference the constructor and all calls to `new this()`.
+ */
+ function findOwnConstructorReferences(classSymbol, sourceFile, addNode) {
+ for (var _i = 0, _a = classSymbol.members.get("__constructor").declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ var ctrKeyword = ts.findChildOfKind(decl, 122 /* ConstructorKeyword */, sourceFile);
+ ts.Debug.assert(decl.kind === 151 /* Constructor */ && !!ctrKeyword);
+ addNode(ctrKeyword);
+ }
+ classSymbol.exports.forEach(function (member) {
+ var decl = member.valueDeclaration;
+ if (decl && decl.kind === 150 /* MethodDeclaration */) {
var body = decl.body;
if (body) {
- forEachDescendantOfKind(body, 96 /* SuperKeyword */, function (node) {
- if (ts.isCallExpressionTarget(node)) {
- result.push(node);
+ forEachDescendantOfKind(body, 98 /* ThisKeyword */, function (thisKeyword) {
+ if (ts.isNewExpressionTarget(thisKeyword)) {
+ addNode(thisKeyword);
}
});
}
}
- ;
- return result;
+ });
+ }
+ /** Find references to `super` in the constructor of an extending class. */
+ function findSuperConstructorAccesses(cls, addNode) {
+ var symbol = cls.symbol;
+ var ctr = symbol.members.get("__constructor");
+ if (!ctr) {
+ return;
}
- function getReferencedSymbol(symbol) {
- var symbolId = ts.getSymbolId(symbol);
- var index = symbolToIndex[symbolId];
- if (index === undefined) {
- index = result.length;
- symbolToIndex[symbolId] = index;
- result.push({
- definition: getDefinition(symbol),
- references: []
+ for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ ts.Debug.assert(decl.kind === 151 /* Constructor */);
+ var body = decl.body;
+ if (body) {
+ forEachDescendantOfKind(body, 96 /* SuperKeyword */, function (node) {
+ if (ts.isCallExpressionTarget(node)) {
+ addNode(node);
+ }
});
}
- return result[index];
- }
- function addReferenceToRelatedSymbol(node, relatedSymbol) {
- var references = getReferencedSymbol(relatedSymbol).references;
- if (implementations) {
- getImplementationReferenceEntryForNode(node, references);
- }
- else {
- references.push(getReferenceEntryFromNode(node));
- }
}
}
- function getImplementationReferenceEntryForNode(refNode, result) {
+ function addImplementationReferences(refNode, addReference, state) {
// Check if we found a function/propertyAssignment/method with an implementation or initializer
if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) {
- result.push(getReferenceEntryFromNode(refNode.parent));
+ addReference(refNode.parent);
+ return;
}
- else if (refNode.kind === 70 /* Identifier */) {
- if (refNode.parent.kind === 258 /* ShorthandPropertyAssignment */) {
- // Go ahead and dereference the shorthand assignment by going to its definition
- getReferenceEntriesForShorthandPropertyAssignment(refNode, typeChecker, result);
- }
- // Check if the node is within an extends or implements clause
- var containingClass = getContainingClassIfInHeritageClause(refNode);
- if (containingClass) {
- result.push(getReferenceEntryFromNode(containingClass));
- return;
- }
- // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface
- var containingTypeReference = getContainingTypeReference(refNode);
- if (containingTypeReference) {
- var parent_18 = containingTypeReference.parent;
- if (ts.isVariableLike(parent_18) && parent_18.type === containingTypeReference && parent_18.initializer && isImplementationExpression(parent_18.initializer)) {
- maybeAdd(getReferenceEntryFromNode(parent_18.initializer));
- }
- else if (ts.isFunctionLike(parent_18) && parent_18.type === containingTypeReference && parent_18.body) {
- if (parent_18.body.kind === 204 /* Block */) {
- ts.forEachReturnStatement(parent_18.body, function (returnStatement) {
- if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) {
- maybeAdd(getReferenceEntryFromNode(returnStatement.expression));
- }
- });
- }
- else if (isImplementationExpression(parent_18.body)) {
- maybeAdd(getReferenceEntryFromNode(parent_18.body));
- }
+ if (refNode.kind !== 70 /* Identifier */) {
+ return;
+ }
+ if (refNode.parent.kind === 261 /* ShorthandPropertyAssignment */) {
+ // Go ahead and dereference the shorthand assignment by going to its definition
+ getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference);
+ }
+ // Check if the node is within an extends or implements clause
+ var containingClass = getContainingClassIfInHeritageClause(refNode);
+ if (containingClass) {
+ addReference(containingClass);
+ return;
+ }
+ // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface
+ var containingTypeReference = getContainingTypeReference(refNode);
+ if (containingTypeReference && state.markSeenContainingTypeReference(containingTypeReference)) {
+ var parent = containingTypeReference.parent;
+ if (ts.isVariableLike(parent) && parent.type === containingTypeReference && parent.initializer && isImplementationExpression(parent.initializer)) {
+ addReference(parent.initializer);
+ }
+ else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) {
+ if (parent.body.kind === 206 /* Block */) {
+ ts.forEachReturnStatement(parent.body, function (returnStatement) {
+ if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) {
+ addReference(returnStatement.expression);
+ }
+ });
}
- else if (ts.isAssertionExpression(parent_18) && isImplementationExpression(parent_18.expression)) {
- maybeAdd(getReferenceEntryFromNode(parent_18.expression));
+ else if (isImplementationExpression(parent.body)) {
+ addReference(parent.body);
}
}
- }
- // Type nodes can contain multiple references to the same type. For example:
- // let x: Foo & (Foo & Bar) = ...
- // Because we are returning the implementation locations and not the identifier locations,
- // duplicate entries would be returned here as each of the type references is part of
- // the same implementation. For that reason, check before we add a new entry
- function maybeAdd(a) {
- if (!ts.forEach(result, function (b) { return a.fileName === b.fileName && a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length; })) {
- result.push(a);
+ else if (ts.isAssertionExpression(parent) && isImplementationExpression(parent.expression)) {
+ addReference(parent.expression);
}
}
}
@@ -69830,12 +75694,12 @@ var ts;
}
function getContainingClassIfInHeritageClause(node) {
if (node && node.parent) {
- if (node.kind === 199 /* ExpressionWithTypeArguments */
- && node.parent.kind === 255 /* HeritageClause */
+ if (node.kind === 200 /* ExpressionWithTypeArguments */
+ && node.parent.kind === 258 /* HeritageClause */
&& ts.isClassLike(node.parent.parent)) {
return node.parent.parent;
}
- else if (node.kind === 70 /* Identifier */ || node.kind === 177 /* PropertyAccessExpression */) {
+ else if (node.kind === 70 /* Identifier */ || node.kind === 178 /* PropertyAccessExpression */) {
return getContainingClassIfInHeritageClause(node.parent);
}
}
@@ -69845,15 +75709,18 @@ var ts;
* Returns true if this is an expression that can be considered an implementation
*/
function isImplementationExpression(node) {
- // Unwrap parentheses
- if (node.kind === 183 /* ParenthesizedExpression */) {
- return isImplementationExpression(node.expression);
+ switch (node.kind) {
+ case 184 /* ParenthesizedExpression */:
+ return isImplementationExpression(node.expression);
+ case 186 /* ArrowFunction */:
+ case 185 /* FunctionExpression */:
+ case 177 /* ObjectLiteralExpression */:
+ case 198 /* ClassExpression */:
+ case 176 /* ArrayLiteralExpression */:
+ return true;
+ default:
+ return false;
}
- return node.kind === 185 /* ArrowFunction */ ||
- node.kind === 184 /* FunctionExpression */ ||
- node.kind === 176 /* ObjectLiteralExpression */ ||
- node.kind === 197 /* ClassExpression */ ||
- node.kind === 175 /* ArrayLiteralExpression */;
}
/**
* Determines if the parent symbol occurs somewhere in the child's ancestry. If the parent symbol
@@ -69874,7 +75741,7 @@ var ts;
* @param parent Another class or interface Symbol
* @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results
*/
- function explicitlyInheritsFrom(child, parent, cachedResults) {
+ function explicitlyInheritsFrom(child, parent, cachedResults, checker) {
var parentIsInterface = parent.getFlags() & 64 /* Interface */;
return searchHierarchy(child);
function searchHierarchy(symbol) {
@@ -69882,11 +75749,12 @@ var ts;
return true;
}
var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent);
- if (key in cachedResults) {
- return cachedResults[key];
+ var cached = cachedResults.get(key);
+ if (cached !== undefined) {
+ return cached;
}
// Set the key so that we don't infinitely recurse
- cachedResults[key] = false;
+ cachedResults.set(key, false);
var inherits = ts.forEach(symbol.getDeclarations(), function (declaration) {
if (ts.isClassLike(declaration)) {
if (parentIsInterface) {
@@ -69902,19 +75770,19 @@ var ts;
}
return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration));
}
- else if (declaration.kind === 227 /* InterfaceDeclaration */) {
+ else if (declaration.kind === 229 /* InterfaceDeclaration */) {
if (parentIsInterface) {
return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference);
}
}
return false;
});
- cachedResults[key] = inherits;
+ cachedResults.set(key, inherits);
return inherits;
}
function searchTypeReference(typeReference) {
if (typeReference) {
- var type = typeChecker.getTypeAtLocation(typeReference);
+ var type = checker.getTypeAtLocation(typeReference);
if (type && type.symbol) {
return searchHierarchy(type.symbol);
}
@@ -69930,13 +75798,13 @@ var ts;
// Whether 'super' occurs in a static context within a class.
var staticFlag = 32 /* Static */;
switch (searchSpaceNode.kind) {
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
@@ -69946,49 +75814,48 @@ var ts;
var references = [];
var sourceFile = searchSpaceNode.getSourceFile();
var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd());
- ts.forEach(possiblePositions, function (position) {
- cancellationToken.throwIfCancellationRequested();
+ for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) {
+ var position = possiblePositions_4[_i];
var node = ts.getTouchingWord(sourceFile, position);
if (!node || node.kind !== 96 /* SuperKeyword */) {
- return;
+ continue;
}
var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false);
// If we have a 'super' container, we must have an enclosing class.
// Now make sure the owning class is the same as the search-space
// and has the same static qualifier as the original 'super's owner.
if (container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) {
- references.push(getReferenceEntryFromNode(node));
+ references.push(FindAllReferences.nodeEntry(node));
}
- });
- var definition = getDefinition(searchSpaceNode.symbol);
- return [{ definition: definition, references: references }];
+ }
+ return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol, node: superKeyword }, references: references }];
}
- function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) {
+ function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) {
var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false);
// Whether 'this' occurs in a static context within a class.
var staticFlag = 32 /* Static */;
switch (searchSpaceNode.kind) {
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
if (ts.isObjectLiteralMethod(searchSpaceNode)) {
break;
}
- // fall through
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ // falls through
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode)) {
return undefined;
}
- // Fall through
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
+ // falls through
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
break;
// Computed properties in classes are not handled here because references to this are illegal,
// so there is no point finding references to them.
@@ -69997,8 +75864,9 @@ var ts;
}
var references = [];
var possiblePositions;
- if (searchSpaceNode.kind === 261 /* SourceFile */) {
+ if (searchSpaceNode.kind === 264 /* SourceFile */) {
ts.forEach(sourceFiles, function (sourceFile) {
+ cancellationToken.throwIfCancellationRequested();
possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd());
getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references);
});
@@ -70008,144 +75876,103 @@ var ts;
possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd());
getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references);
}
- var thisOrSuperSymbol = typeChecker.getSymbolAtLocation(thisOrSuperKeyword);
- var displayParts = thisOrSuperSymbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, thisOrSuperSymbol, thisOrSuperKeyword.getSourceFile(), ts.getContainerNode(thisOrSuperKeyword), thisOrSuperKeyword).displayParts;
return [{
- definition: {
- containerKind: "",
- containerName: "",
- fileName: node.getSourceFile().fileName,
- kind: ts.ScriptElementKind.variableElement,
- name: "this",
- textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()),
- displayParts: displayParts
- },
+ definition: { type: "this", node: thisOrSuperKeyword },
references: references
}];
function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) {
ts.forEach(possiblePositions, function (position) {
- cancellationToken.throwIfCancellationRequested();
var node = ts.getTouchingWord(sourceFile, position);
if (!node || !ts.isThis(node)) {
return;
}
var container = ts.getThisContainer(node, /* includeArrowFunctions */ false);
switch (searchSpaceNode.kind) {
- case 184 /* FunctionExpression */:
- case 225 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 227 /* FunctionDeclaration */:
if (searchSpaceNode.symbol === container.symbol) {
- result.push(getReferenceEntryFromNode(node));
+ result.push(FindAllReferences.nodeEntry(node));
}
break;
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) {
- result.push(getReferenceEntryFromNode(node));
+ result.push(FindAllReferences.nodeEntry(node));
}
break;
- case 197 /* ClassExpression */:
- case 226 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 228 /* ClassDeclaration */:
// Make sure the container belongs to the same class
// and has the appropriate static modifier from the original container.
if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag) {
- result.push(getReferenceEntryFromNode(node));
+ result.push(FindAllReferences.nodeEntry(node));
}
break;
- case 261 /* SourceFile */:
- if (container.kind === 261 /* SourceFile */ && !ts.isExternalModule(container)) {
- result.push(getReferenceEntryFromNode(node));
+ case 264 /* SourceFile */:
+ if (container.kind === 264 /* SourceFile */ && !ts.isExternalModule(container)) {
+ result.push(FindAllReferences.nodeEntry(node));
}
break;
}
});
}
}
- function getReferencesForStringLiteral(node, sourceFiles) {
- var type = ts.getStringLiteralTypeForNode(node, typeChecker);
- if (!type) {
- // nothing to do here. moving on
- return undefined;
- }
+ function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) {
var references = [];
- for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) {
- var sourceFile = sourceFiles_9[_i];
- var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd());
- getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references);
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
+ cancellationToken.throwIfCancellationRequested();
+ var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, node.text, sourceFile.getStart(), sourceFile.getEnd());
+ getReferencesForStringLiteralInFile(sourceFile, node.text, possiblePositions, references);
}
return [{
- definition: {
- containerKind: "",
- containerName: "",
- fileName: node.getSourceFile().fileName,
- kind: ts.ScriptElementKind.variableElement,
- name: type.text,
- textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()),
- displayParts: [ts.displayPart(ts.getTextOfNode(node), ts.SymbolDisplayPartKind.stringLiteral)]
- },
+ definition: { type: "string", node: node },
references: references
}];
- function getReferencesForStringLiteralInFile(sourceFile, searchType, possiblePositions, references) {
- for (var _i = 0, possiblePositions_1 = possiblePositions; _i < possiblePositions_1.length; _i++) {
- var position = possiblePositions_1[_i];
- cancellationToken.throwIfCancellationRequested();
- var node_2 = ts.getTouchingWord(sourceFile, position);
- if (!node_2 || node_2.kind !== 9 /* StringLiteral */) {
- return;
- }
- var type_2 = ts.getStringLiteralTypeForNode(node_2, typeChecker);
- if (type_2 === searchType) {
- references.push(getReferenceEntryFromNode(node_2));
+ function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) {
+ for (var _i = 0, possiblePositions_5 = possiblePositions; _i < possiblePositions_5.length; _i++) {
+ var position = possiblePositions_5[_i];
+ var node_7 = ts.getTouchingWord(sourceFile, position);
+ if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) {
+ references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true));
}
}
}
}
- function populateSearchSymbolSet(symbol, location) {
+ // For certain symbol kinds, we need to include other symbols in the search set.
+ // This is not needed when searching for re-exports.
+ function populateSearchSymbolSet(symbol, location, checker, implementations) {
// The search set contains at least the current symbol
var result = [symbol];
- // If the location is name of property symbol from object literal destructuring pattern
- // Search the property symbol
- // for ( { property: p2 } of elems) { }
- var containingObjectLiteralElement = getContainingObjectLiteralElement(location);
- if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== 258 /* ShorthandPropertyAssignment */) {
- var propertySymbol = getPropertySymbolOfDestructuringAssignment(location);
- if (propertySymbol) {
- result.push(propertySymbol);
- }
- }
- // If the symbol is an alias, add what it aliases to the list
- // import {a} from "mod";
- // export {a}
- // If the symbol is an alias to default declaration, add what it aliases to the list
- // declare "mod" { export default class B { } }
- // import B from "mod";
- //// For export specifiers, the exported name can be referring to a local symbol, e.g.:
- //// import {a} from "mod";
- //// export {a as somethingElse}
- //// We want the *local* declaration of 'a' as declared in the import,
- //// *not* as declared within "mod" (or farther)
- var aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location);
- if (aliasSymbol) {
- result = result.concat(populateSearchSymbolSet(aliasSymbol, location));
- }
- // If the location is in a context sensitive location (i.e. in an object literal) try
- // to get a contextual type for it, and add the property symbol from the contextual
- // type to the search set
+ var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location);
if (containingObjectLiteralElement) {
- ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) {
- ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol));
+ // If the location is name of property symbol from object literal destructuring pattern
+ // Search the property symbol
+ // for ( { property: p2 } of elems) { }
+ if (containingObjectLiteralElement.kind !== 261 /* ShorthandPropertyAssignment */) {
+ var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker);
+ if (propertySymbol) {
+ result.push(propertySymbol);
+ }
+ }
+ // If the location is in a context sensitive location (i.e. in an object literal) try
+ // to get a contextual type for it, and add the property symbol from the contextual
+ // type to the search set
+ ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), function (contextualSymbol) {
+ ts.addRange(result, checker.getRootSymbols(contextualSymbol));
});
/* Because in short-hand property assignment, location has two meaning : property name and as value of the property
- * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of
- * property name and variable declaration of the identifier.
- * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service
- * should show both 'name' in 'obj' and 'name' in variable declaration
- * const name = "Foo";
- * const obj = { name };
- * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment
- * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration
- * will be included correctly.
- */
- var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent);
+ * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of
+ * property name and variable declaration of the identifier.
+ * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service
+ * should show both 'name' in 'obj' and 'name' in variable declaration
+ * const name = "Foo";
+ * const obj = { name };
+ * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment
+ * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration
+ * will be included correctly.
+ */
+ var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent);
if (shorthandValueSymbol) {
result.push(shorthandValueSymbol);
}
@@ -70154,27 +75981,28 @@ var ts;
// we should include both parameter declaration symbol and property declaration symbol
// Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals.
// Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members
- if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 144 /* Parameter */ &&
+ if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 145 /* Parameter */ &&
ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) {
- result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name));
+ ts.addRange(result, checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name));
}
// If this is symbol of binding element without propertyName declaration in Object binding pattern
// Include the property in the search
- var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol);
+ var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
if (bindingElementPropertySymbol) {
result.push(bindingElementPropertySymbol);
}
// If this is a union property, add all the symbols from all its source symbols in all unioned types.
// If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list
- ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) {
+ for (var _i = 0, _a = checker.getRootSymbols(symbol); _i < _a.length; _i++) {
+ var rootSymbol = _a[_i];
if (rootSymbol !== symbol) {
result.push(rootSymbol);
}
// Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions
if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) {
- getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap());
+ getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap(), checker);
}
- });
+ }
return result;
}
/**
@@ -70185,7 +76013,7 @@ var ts;
* @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol.
* The value of previousIterationSymbol is undefined when the function is first called.
*/
- function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) {
+ function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache, checker) {
if (!symbol) {
return;
}
@@ -70200,7 +76028,7 @@ var ts;
// the function will add any found symbol of the property-name, then its sub-routine will call
// getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already
// visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol.
- if (symbol.name in previousIterationSymbolsCache) {
+ if (previousIterationSymbolsCache.has(symbol.name)) {
return;
}
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
@@ -70209,7 +76037,7 @@ var ts;
getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration));
ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference);
}
- else if (declaration.kind === 227 /* InterfaceDeclaration */) {
+ else if (declaration.kind === 229 /* InterfaceDeclaration */) {
ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference);
}
});
@@ -70217,37 +76045,30 @@ var ts;
return;
function getPropertySymbolFromTypeReference(typeReference) {
if (typeReference) {
- var type = typeChecker.getTypeAtLocation(typeReference);
+ var type = checker.getTypeAtLocation(typeReference);
if (type) {
- var propertySymbol = typeChecker.getPropertyOfType(type, propertyName);
+ var propertySymbol = checker.getPropertyOfType(type, propertyName);
if (propertySymbol) {
- result.push.apply(result, typeChecker.getRootSymbols(propertySymbol));
+ result.push.apply(result, checker.getRootSymbols(propertySymbol));
}
// Visit the typeReference as well to see if it directly or indirectly use that property
- previousIterationSymbolsCache[symbol.name] = symbol;
- getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache);
+ previousIterationSymbolsCache.set(symbol.name, symbol);
+ getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache, checker);
}
}
}
}
- function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation, searchLocationIsConstructor, parents, cache) {
- if (ts.contains(searchSymbols, referenceSymbol)) {
- // If we are searching for constructor uses, they must be 'new' expressions.
- return (!searchLocationIsConstructor || ts.isNewExpressionTarget(referenceLocation)) && referenceSymbol;
- }
- // If the reference symbol is an alias, check if what it is aliasing is one of the search
- // symbols but by looking up for related symbol of this alias so it can handle multiple level of indirectness.
- var aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation);
- if (aliasSymbol) {
- return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation, searchLocationIsConstructor, parents, cache);
+ function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) {
+ if (search.includes(referenceSymbol)) {
+ return referenceSymbol;
}
// If the reference location is in an object literal, try to get the contextual type for the
// object literal, lookup the property symbol in the contextual type, and use this symbol to
// compare to our searchSymbol
- var containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation);
+ var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation);
if (containingObjectLiteralElement) {
- var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), function (contextualSymbol) {
- return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; });
+ var contextualSymbol = ts.forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement, state.checker), function (contextualSymbol) {
+ return ts.find(state.checker.getRootSymbols(contextualSymbol), search.includes);
});
if (contextualSymbol) {
return contextualSymbol;
@@ -70256,23 +76077,23 @@ var ts;
// Get the property symbol from the object literal's type and look if thats the search symbol
// In below eg. get 'property' from type of elems iterating type
// for ( { property: p2 } of elems) { }
- var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation);
- if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) {
+ var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, state.checker);
+ if (propertySymbol && search.includes(propertySymbol)) {
return propertySymbol;
}
}
// If the reference location is the binding element and doesn't have property name
// then include the binding element in the related symbols
// let { a } : { a };
- var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol);
- if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) {
+ var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, state.checker);
+ if (bindingElementPropertySymbol && search.includes(bindingElementPropertySymbol)) {
return bindingElementPropertySymbol;
}
// Unwrap symbols to get to the root (e.g. transient symbols as a result of widening)
// Or a union property, use its underlying unioned symbols
- return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) {
+ return ts.forEach(state.checker.getRootSymbols(referenceSymbol), function (rootSymbol) {
// if it is in the list, then we are done
- if (searchSymbols.indexOf(rootSymbol) >= 0) {
+ if (search.includes(rootSymbol)) {
return rootSymbol;
}
// Finally, try all properties with the same name in any type the containing type extended or implemented, and
@@ -70280,20 +76101,18 @@ var ts;
// parent symbol
if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) {
// Parents will only be defined if implementations is true
- if (parents) {
- if (!ts.forEach(parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, cache); })) {
- return undefined;
- }
+ if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, state.checker); })) {
+ return undefined;
}
- var result_4 = [];
- getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_4, /*previousIterationSymbolsCache*/ ts.createMap());
- return ts.forEach(result_4, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; });
+ var result = [];
+ getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap(), state.checker);
+ return ts.find(result, search.includes);
}
return undefined;
});
}
function getNameFromObjectLiteralElement(node) {
- if (node.name.kind === 142 /* ComputedPropertyName */) {
+ if (node.name.kind === 143 /* ComputedPropertyName */) {
var nameExpression = node.name.expression;
// treat computed property names where expression is string/numeric literal as just string/numeric literal
if (ts.isStringOrNumericLiteral(nameExpression)) {
@@ -70303,15 +76122,16 @@ var ts;
}
return node.name.text;
}
- function getPropertySymbolsFromContextualType(node) {
+ /** Gets all symbols for one property. Does not get symbols for every property. */
+ function getPropertySymbolsFromContextualType(node, checker) {
var objectLiteral = node.parent;
- var contextualType = typeChecker.getContextualType(objectLiteral);
+ var contextualType = checker.getContextualType(objectLiteral);
var name = getNameFromObjectLiteralElement(node);
if (name && contextualType) {
var result_5 = [];
- var symbol_2 = contextualType.getProperty(name);
- if (symbol_2) {
- result_5.push(symbol_2);
+ var symbol = contextualType.getProperty(name);
+ if (symbol) {
+ result_5.push(symbol);
}
if (contextualType.flags & 65536 /* Union */) {
ts.forEach(contextualType.types, function (t) {
@@ -70325,13 +76145,14 @@ var ts;
}
return undefined;
}
- /** Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations
- * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class
- * then we need to widen the search to include type positions as well.
- * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated
- * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module)
- * do not intersect in any of the three spaces.
- */
+ /**
+ * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations
+ * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class
+ * then we need to widen the search to include type positions as well.
+ * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated
+ * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module)
+ * do not intersect in any of the three spaces.
+ */
function getIntersectingMeaningFromDeclarations(meaning, declarations) {
if (declarations) {
var lastIterationMeaning = void 0;
@@ -70342,8 +76163,8 @@ var ts;
// To achieve that we will keep iterating until the result stabilizes.
// Remember the last meaning
lastIterationMeaning = meaning;
- for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
- var declaration = declarations_8[_i];
+ for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
+ var declaration = declarations_11[_i];
var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
if (declarationMeaning & meaning) {
meaning |= declarationMeaning;
@@ -70353,143 +76174,93 @@ var ts;
}
return meaning;
}
- }
- FindAllReferences.getReferencedSymbolsForNode = getReferencedSymbolsForNode;
- function convertReferences(referenceSymbols) {
- if (!referenceSymbols) {
- return undefined;
- }
- var referenceEntries = [];
- for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) {
- var referenceSymbol = referenceSymbols_1[_i];
- ts.addRange(referenceEntries, referenceSymbol.references);
- }
- return referenceEntries;
- }
- FindAllReferences.convertReferences = convertReferences;
- function isImplementation(node) {
- if (!node) {
- return false;
- }
- else if (ts.isVariableLike(node)) {
- if (node.initializer) {
- return true;
- }
- else if (node.kind === 223 /* VariableDeclaration */) {
- var parentStatement = getParentStatementOfVariableDeclaration(node);
- return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */);
+ function isImplementation(node) {
+ if (!node) {
+ return false;
}
- }
- else if (ts.isFunctionLike(node)) {
- return !!node.body || ts.hasModifier(node, 2 /* Ambient */);
- }
- else {
- switch (node.kind) {
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 229 /* EnumDeclaration */:
- case 230 /* ModuleDeclaration */:
+ else if (ts.isVariableLike(node)) {
+ if (node.initializer) {
return true;
+ }
+ else if (node.kind === 225 /* VariableDeclaration */) {
+ var parentStatement = getParentStatementOfVariableDeclaration(node);
+ return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */);
+ }
}
+ else if (ts.isFunctionLike(node)) {
+ return !!node.body || ts.hasModifier(node, 2 /* Ambient */);
+ }
+ else {
+ switch (node.kind) {
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 231 /* EnumDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ return true;
+ }
+ }
+ return false;
}
- return false;
- }
- function getParentStatementOfVariableDeclaration(node) {
- if (node.parent && node.parent.parent && node.parent.parent.kind === 205 /* VariableStatement */) {
- ts.Debug.assert(node.parent.kind === 224 /* VariableDeclarationList */);
- return node.parent.parent;
+ function getParentStatementOfVariableDeclaration(node) {
+ if (node.parent && node.parent.parent && node.parent.parent.kind === 207 /* VariableStatement */) {
+ ts.Debug.assert(node.parent.kind === 226 /* VariableDeclarationList */);
+ return node.parent.parent;
+ }
}
- }
- function getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result) {
- var refSymbol = typeChecker.getSymbolAtLocation(node);
- var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration);
- if (shorthandSymbol) {
- for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) {
- var declaration = _a[_i];
- if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) {
- result.push(getReferenceEntryFromNode(declaration));
+ function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) {
+ var refSymbol = checker.getSymbolAtLocation(node);
+ var shorthandSymbol = checker.getShorthandAssignmentValueSymbol(refSymbol.valueDeclaration);
+ if (shorthandSymbol) {
+ for (var _i = 0, _a = shorthandSymbol.getDeclarations(); _i < _a.length; _i++) {
+ var declaration = _a[_i];
+ if (ts.getMeaningFromDeclaration(declaration) & 1 /* Value */) {
+ addReference(declaration);
+ }
}
}
}
- }
- FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment;
- function getReferenceEntryFromNode(node) {
- var start = node.getStart();
- var end = node.getEnd();
- if (node.kind === 9 /* StringLiteral */) {
- start += 1;
- end -= 1;
+ Core.getReferenceEntriesForShorthandPropertyAssignment = getReferenceEntriesForShorthandPropertyAssignment;
+ function forEachDescendantOfKind(node, kind, action) {
+ ts.forEachChild(node, function (child) {
+ if (child.kind === kind) {
+ action(child);
+ }
+ forEachDescendantOfKind(child, kind, action);
+ });
}
- return {
- fileName: node.getSourceFile().fileName,
- textSpan: ts.createTextSpanFromBounds(start, end),
- isWriteAccess: isWriteAccess(node),
- isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node)
- };
- }
- FindAllReferences.getReferenceEntryFromNode = getReferenceEntryFromNode;
- /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */
- function isWriteAccess(node) {
- if (node.kind === 70 /* Identifier */ && ts.isDeclarationName(node)) {
- return true;
+ /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */
+ function tryGetClassByExtendingIdentifier(node) {
+ return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent);
}
- var parent = node.parent;
- if (parent) {
- if (parent.kind === 191 /* PostfixUnaryExpression */ || parent.kind === 190 /* PrefixUnaryExpression */) {
- return true;
- }
- else if (parent.kind === 192 /* BinaryExpression */ && parent.left === node) {
- var operator = parent.operatorToken.kind;
- return 57 /* FirstAssignment */ <= operator && operator <= 69 /* LastAssignment */;
+ function isNameOfExternalModuleImportOrDeclaration(node) {
+ if (node.kind === 9 /* StringLiteral */) {
+ return ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node);
}
+ return false;
}
- return false;
- }
- function forEachDescendantOfKind(node, kind, action) {
- ts.forEachChild(node, function (child) {
- if (child.kind === kind) {
- action(child);
+ /**
+ * If we are just looking for implementations and this is a property access expression, we need to get the
+ * symbol of the local type of the symbol the property is being accessed on. This is because our search
+ * symbol may have a different parent symbol if the local type's symbol does not declare the property
+ * being accessed (i.e. it is declared in some parent class or interface)
+ */
+ function getParentSymbolsOfPropertyAccess(location, symbol, checker) {
+ var propertyAccessExpression = getPropertyAccessExpressionFromRightHandSide(location);
+ if (!propertyAccessExpression) {
+ return undefined;
+ }
+ var localParentType = checker.getTypeAtLocation(propertyAccessExpression.expression);
+ if (!localParentType) {
+ return undefined;
+ }
+ if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== symbol.parent) {
+ return [localParentType.symbol];
+ }
+ else if (localParentType.flags & 196608 /* UnionOrIntersection */) {
+ return getSymbolsForClassAndInterfaceComponents(localParentType);
}
- forEachDescendantOfKind(child, kind, action);
- });
- }
- /**
- * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 }
- */
- function getContainingObjectLiteralElement(node) {
- switch (node.kind) {
- case 9 /* StringLiteral */:
- case 8 /* NumericLiteral */:
- if (node.parent.kind === 142 /* ComputedPropertyName */) {
- return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined;
- }
- // intential fall through
- case 70 /* Identifier */:
- return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined;
- }
- return undefined;
- }
- function isObjectLiteralPropertyDeclaration(node) {
- switch (node.kind) {
- case 257 /* PropertyAssignment */:
- case 258 /* ShorthandPropertyAssignment */:
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- return true;
- }
- return false;
- }
- /** Get `C` given `N` if `N` is in the position `class C extends N` or `class C extends foo.N` where `N` is an identifier. */
- function tryGetClassByExtendingIdentifier(node) {
- return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent);
- }
- function isNameOfExternalModuleImportOrDeclaration(node) {
- if (node.kind === 9 /* StringLiteral */) {
- return ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node);
}
- return false;
- }
+ })(Core = FindAllReferences.Core || (FindAllReferences.Core = {}));
})(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {}));
})(ts || (ts = {}));
/* @internal */
@@ -70510,11 +76281,9 @@ var ts;
// Type reference directives
var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
- var referenceFile = program.getResolvedTypeReferenceDirectives()[typeReferenceDirective.fileName];
- if (referenceFile && referenceFile.resolvedFileName) {
- return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)];
- }
- return undefined;
+ var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
+ return referenceFile && referenceFile.resolvedFileName &&
+ [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)];
}
var node = ts.getTouchingPropertyName(sourceFile, position);
if (node === sourceFile) {
@@ -70524,7 +76293,7 @@ var ts;
if (ts.isJumpStatementTarget(node)) {
var labelName = node.text;
var label = ts.getTargetLabel(node.parent, node.text);
- return label ? [createDefinitionInfo(label, ts.ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined;
+ return label ? [createDefinitionInfoFromName(label, ts.ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined;
}
var typeChecker = program.getTypeChecker();
var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node);
@@ -70550,7 +76319,7 @@ var ts;
//
if (node.kind === 70 /* Identifier */ &&
(node.parent === declaration ||
- (declaration.kind === 239 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 238 /* NamedImports */))) {
+ (declaration.kind === 241 /* ImportSpecifier */ && declaration.parent && declaration.parent.kind === 240 /* NamedImports */))) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
}
@@ -70559,7 +76328,7 @@ var ts;
// go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition
// is performed at the location of property access, we would like to go to definition of the property in the short-hand
// assignment. This case and others are handled by the following code.
- if (node.parent.kind === 258 /* ShorthandPropertyAssignment */) {
+ if (node.parent.kind === 261 /* ShorthandPropertyAssignment */) {
var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration);
if (!shorthandSymbol) {
return [];
@@ -70570,6 +76339,37 @@ var ts;
var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node);
return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); });
}
+ if (ts.isJsxOpeningLikeElement(node.parent)) {
+ // If there are errors when trying to figure out stateless component function, just return the first declaration
+ // For example:
+ // declare function /*firstSource*/MainButton(buttonProps: ButtonProps): JSX.Element;
+ // declare function /*secondSource*/MainButton(linkProps: LinkProps): JSX.Element;
+ // declare function /*thirdSource*/MainButton(props: ButtonProps | LinkProps): JSX.Element;
+ // let opt = <Main/*firstTarget*/Button />; // Error - We get undefined for resolved signature indicating an error, then just return the first declaration
+ var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName;
+ return [createDefinitionInfo(symbol.valueDeclaration, symbolKind, symbolName, containerName)];
+ }
+ // If the current location we want to find its definition is in an object literal, try to get the contextual type for the
+ // object literal, lookup the property symbol in the contextual type, and use this for goto-definition.
+ // For example
+ // interface Props{
+ // /*first*/prop1: number
+ // prop2: boolean
+ // }
+ // function Foo(arg: Props) {}
+ // Foo( { pr/*1*/op1: 10, prop2: true })
+ var element = ts.getContainingObjectLiteralElement(node);
+ if (element) {
+ if (typeChecker.getContextualType(element.parent)) {
+ var result = [];
+ var propertySymbols = ts.getPropertySymbolsFromContextualType(typeChecker, element);
+ for (var _i = 0, propertySymbols_1 = propertySymbols; _i < propertySymbols_1.length; _i++) {
+ var propertySymbol = propertySymbols_1[_i];
+ result.push.apply(result, getDefinitionFromSymbol(typeChecker, propertySymbol, node));
+ }
+ return result;
+ }
+ }
return getDefinitionFromSymbol(typeChecker, symbol, node);
}
GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition;
@@ -70639,31 +76439,47 @@ var ts;
return false;
}
function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) {
+ if (!signatureDeclarations) {
+ return false;
+ }
var declarations = [];
var definition;
- ts.forEach(signatureDeclarations, function (d) {
- if ((selectConstructors && d.kind === 150 /* Constructor */) ||
- (!selectConstructors && (d.kind === 225 /* FunctionDeclaration */ || d.kind === 149 /* MethodDeclaration */ || d.kind === 148 /* MethodSignature */))) {
+ for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) {
+ var d = signatureDeclarations_1[_i];
+ if (selectConstructors ? d.kind === 151 /* Constructor */ : isSignatureDeclaration(d)) {
declarations.push(d);
if (d.body)
definition = d;
}
- });
- if (definition) {
- result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName));
- return true;
}
- else if (declarations.length) {
- result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName));
+ if (declarations.length) {
+ result.push(createDefinitionInfo(definition || ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName));
return true;
}
return false;
}
}
+ function isSignatureDeclaration(node) {
+ switch (node.kind) {
+ case 151 /* Constructor */:
+ case 227 /* FunctionDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */
function createDefinitionInfo(node, symbolKind, symbolName, containerName) {
+ return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName);
+ }
+ /** Creates a DefinitionInfo directly from the name of a declaration. */
+ function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) {
+ var sourceFile = name.getSourceFile();
return {
- fileName: node.getSourceFile().fileName,
- textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()),
+ fileName: sourceFile.fileName,
+ textSpan: ts.createTextSpanFromNode(name, sourceFile),
kind: symbolKind,
name: symbolName,
containerKind: undefined,
@@ -70711,43 +76527,17 @@ var ts;
}
function tryGetSignatureDeclaration(typeChecker, node) {
var callLike = getAncestorCallLikeExpression(node);
- return callLike && typeChecker.getResolvedSignature(callLike).declaration;
- }
- })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {}));
-})(ts || (ts = {}));
-/* @internal */
-var ts;
-(function (ts) {
- var GoToImplementation;
- (function (GoToImplementation) {
- function getImplementationAtPosition(typeChecker, cancellationToken, sourceFiles, node) {
- // If invoked directly on a shorthand property assignment, then return
- // the declaration of the symbol being assigned (not the symbol being assigned to).
- if (node.parent.kind === 258 /* ShorthandPropertyAssignment */) {
- var result = [];
- ts.FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result);
- return result.length > 0 ? result : undefined;
- }
- else if (node.kind === 96 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
- // References to and accesses on the super keyword only have one possible implementation, so no
- // need to "Find all References"
- var symbol = typeChecker.getSymbolAtLocation(node);
- return symbol.valueDeclaration && [ts.FindAllReferences.getReferenceEntryFromNode(symbol.valueDeclaration)];
- }
- else {
- // Perform "Find all References" and retrieve only those that are implementations
- var referencedSymbols = ts.FindAllReferences.getReferencedSymbolsForNode(typeChecker, cancellationToken, node, sourceFiles, /*findInStrings*/ false, /*findInComments*/ false, /*implementations*/ true);
- var result = ts.flatMap(referencedSymbols, function (symbol) {
- return ts.map(symbol.references, function (_a) {
- var textSpan = _a.textSpan, fileName = _a.fileName;
- return ({ textSpan: textSpan, fileName: fileName });
- });
- });
- return result && result.length > 0 ? result : undefined;
+ var signature = callLike && typeChecker.getResolvedSignature(callLike);
+ if (signature) {
+ var decl = signature.declaration;
+ if (decl && isSignatureDeclaration(decl)) {
+ return decl;
+ }
}
+ // Don't go to a function type, go to the value having that type.
+ return undefined;
}
- GoToImplementation.getImplementationAtPosition = getImplementationAtPosition;
- })(GoToImplementation = ts.GoToImplementation || (ts.GoToImplementation = {}));
+ })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
@@ -70777,6 +76567,7 @@ var ts;
"lends",
"link",
"memberOf",
+ "method",
"name",
"namespace",
"param",
@@ -70795,7 +76586,8 @@ var ts;
"prop",
"version"
];
- var jsDocCompletionEntries;
+ var jsDocTagNameCompletionEntries;
+ var jsDocTagCompletionEntries;
function getJsDocCommentsFromDeclarations(declarations) {
// Only collect doc comments from duplicate declarations once:
// In case of a union property there might be same declaration multiple times
@@ -70822,6 +76614,30 @@ var ts;
return documentationComment;
}
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
+ function getJsDocTagsFromDeclarations(declarations) {
+ // Only collect doc comments from duplicate declarations once.
+ var tags = [];
+ forEachUnique(declarations, function (declaration) {
+ var jsDocs = ts.getJSDocs(declaration);
+ if (!jsDocs) {
+ return;
+ }
+ for (var _i = 0, jsDocs_1 = jsDocs; _i < jsDocs_1.length; _i++) {
+ var doc = jsDocs_1[_i];
+ var tagsForDoc = doc.tags;
+ if (tagsForDoc) {
+ tags.push.apply(tags, tagsForDoc.filter(function (tag) { return tag.kind === 283 /* JSDocTag */; }).map(function (jsDocTag) {
+ return {
+ name: jsDocTag.tagName.text,
+ text: jsDocTag.comment
+ };
+ }));
+ }
+ }
+ });
+ return tags;
+ }
+ JsDoc.getJsDocTagsFromDeclarations = getJsDocTagsFromDeclarations;
/**
* Iterates through 'array' by index and performs the callback on each element of array until the callback
* returns a truthy value, then returns that value.
@@ -70829,7 +76645,7 @@ var ts;
*/
function forEachUnique(array, callback) {
if (array) {
- for (var i = 0, len = array.length; i < len; i++) {
+ for (var i = 0; i < array.length; i++) {
if (ts.indexOf(array, array[i]) === i) {
var result = callback(array[i], i);
if (result) {
@@ -70840,8 +76656,8 @@ var ts;
}
return undefined;
}
- function getAllJsDocCompletionEntries() {
- return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
+ function getJSDocTagNameCompletions() {
+ return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
return {
name: tagName,
kind: ts.ScriptElementKind.keyword,
@@ -70850,7 +76666,18 @@ var ts;
};
}));
}
- JsDoc.getAllJsDocCompletionEntries = getAllJsDocCompletionEntries;
+ JsDoc.getJSDocTagNameCompletions = getJSDocTagNameCompletions;
+ function getJSDocTagCompletions() {
+ return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) {
+ return {
+ name: "@" + tagName,
+ kind: ts.ScriptElementKind.keyword,
+ kindModifiers: "",
+ sortText: "0"
+ };
+ }));
+ }
+ JsDoc.getJSDocTagCompletions = getJSDocTagCompletions;
/**
* Checks if position points to a valid position to add JSDoc comments, and if so,
* returns the appropriate template. Otherwise returns an empty string.
@@ -70889,19 +76716,19 @@ var ts;
var commentOwner;
findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) {
switch (commentOwner.kind) {
- case 225 /* FunctionDeclaration */:
- case 149 /* MethodDeclaration */:
- case 150 /* Constructor */:
- case 226 /* ClassDeclaration */:
- case 205 /* VariableStatement */:
+ case 227 /* FunctionDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 151 /* Constructor */:
+ case 228 /* ClassDeclaration */:
+ case 207 /* VariableStatement */:
break findOwner;
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
return undefined;
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
// then we must be somewhere within a dotted namespace name; however we don't
// want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'.
- if (commentOwner.parent.kind === 230 /* ModuleDeclaration */) {
+ if (commentOwner.parent.kind === 232 /* ModuleDeclaration */) {
return undefined;
}
break findOwner;
@@ -70913,14 +76740,21 @@ var ts;
var parameters = getParametersForJsDocOwningNode(commentOwner);
var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position);
var lineStart = sourceFile.getLineStarts()[posLineAndChar.line];
- var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character);
+ // replace non-whitespace characters in prefix with spaces.
+ var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; });
+ var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName);
var docParams = "";
- for (var i = 0, numParams = parameters.length; i < numParams; i++) {
+ for (var i = 0; i < parameters.length; i++) {
var currentName = parameters[i].name;
var paramName = currentName.kind === 70 /* Identifier */ ?
currentName.text :
"param" + i;
- docParams += indentationStr + " * @param " + paramName + newLine;
+ if (isJavaScriptFile) {
+ docParams += indentationStr + " * @param {any} " + paramName + newLine;
+ }
+ else {
+ docParams += indentationStr + " * @param " + paramName + newLine;
+ }
}
// A doc comment consists of the following
// * The opening comment line
@@ -70942,7 +76776,7 @@ var ts;
if (ts.isFunctionLike(commentOwner)) {
return commentOwner.parameters;
}
- if (commentOwner.kind === 205 /* VariableStatement */) {
+ if (commentOwner.kind === 207 /* VariableStatement */) {
var varStatement = commentOwner;
var varDeclarations = varStatement.declarationList.declarations;
if (varDeclarations.length === 1 && varDeclarations[0].initializer) {
@@ -70960,17 +76794,17 @@ var ts;
* @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'.
*/
function getParametersFromRightHandSideOfAssignment(rightHandSide) {
- while (rightHandSide.kind === 183 /* ParenthesizedExpression */) {
+ while (rightHandSide.kind === 184 /* ParenthesizedExpression */) {
rightHandSide = rightHandSide.expression;
}
switch (rightHandSide.kind) {
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
return rightHandSide.parameters;
- case 197 /* ClassExpression */:
+ case 198 /* ClassExpression */:
for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) {
var member = _a[_i];
- if (member.kind === 150 /* Constructor */) {
+ if (member.kind === 151 /* Constructor */) {
return member.parameters;
}
}
@@ -70990,8 +76824,6 @@ var ts;
(function (ts) {
var JsTyping;
(function (JsTyping) {
- ;
- ;
// A map of loose file names to library names
// that we are confident require typings
var safeList;
@@ -71028,7 +76860,7 @@ var ts;
});
if (!safeList) {
var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
- safeList = result.config ? ts.createMap(result.config) : EmptySafeList;
+ safeList = result.config ? ts.createMapFromTemplate(result.config) : EmptySafeList;
}
var filesToWatch = [];
// Directories to search for package.json, bower.json and other typing information
@@ -71047,41 +76879,43 @@ var ts;
getTypingNamesFromJson(packageJsonPath, filesToWatch);
var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
getTypingNamesFromJson(bowerJsonPath, filesToWatch);
+ var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
+ getTypingNamesFromPackagesFolder(bowerComponentsPath);
var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
- getTypingNamesFromNodeModuleFolder(nodeModulesPath);
+ getTypingNamesFromPackagesFolder(nodeModulesPath);
}
getTypingNamesFromSourceFileNames(fileNames);
// add typings for unresolved imports
if (unresolvedImports) {
for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) {
var moduleId = unresolvedImports_1[_a];
- var typingName = moduleId in nodeCoreModules ? "node" : moduleId;
- if (!(typingName in inferredTypings)) {
- inferredTypings[typingName] = undefined;
+ var typingName = nodeCoreModules.has(moduleId) ? "node" : moduleId;
+ if (!inferredTypings.has(typingName)) {
+ inferredTypings.set(typingName, undefined);
}
}
}
// Add the cached typing locations for inferred typings that are already installed
- for (var name_45 in packageNameToTypingLocation) {
- if (name_45 in inferredTypings && !inferredTypings[name_45]) {
- inferredTypings[name_45] = packageNameToTypingLocation[name_45];
+ packageNameToTypingLocation.forEach(function (typingLocation, name) {
+ if (inferredTypings.has(name) && inferredTypings.get(name) === undefined) {
+ inferredTypings.set(name, typingLocation);
}
- }
+ });
// Remove typings that the user has added to the exclude list
for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) {
var excludeTypingName = exclude_1[_b];
- delete inferredTypings[excludeTypingName];
+ inferredTypings.delete(excludeTypingName);
}
var newTypingNames = [];
var cachedTypingPaths = [];
- for (var typing in inferredTypings) {
- if (inferredTypings[typing] !== undefined) {
- cachedTypingPaths.push(inferredTypings[typing]);
+ inferredTypings.forEach(function (inferred, typing) {
+ if (inferred !== undefined) {
+ cachedTypingPaths.push(inferred);
}
else {
newTypingNames.push(typing);
}
- }
+ });
return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
/**
* Merge a given list of typingNames to the inferredTypings map
@@ -71092,8 +76926,8 @@ var ts;
}
for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) {
var typing = typingNames_1[_i];
- if (!(typing in inferredTypings)) {
- inferredTypings[typing] = undefined;
+ if (!inferredTypings.has(typing)) {
+ inferredTypings.set(typing, undefined);
}
}
}
@@ -71132,7 +76966,7 @@ var ts;
var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); });
var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); });
if (safeList !== EmptySafeList) {
- mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; }));
+ mergeTypings(ts.filter(cleanedTypingNames, function (f) { return safeList.has(f); }));
}
var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; });
if (hasJsxFile) {
@@ -71140,20 +76974,22 @@ var ts;
}
}
/**
- * Infer typing names from node_module folder
- * @param nodeModulesPath is the path to the "node_modules" folder
+ * Infer typing names from packages folder (ex: node_module, bower_components)
+ * @param packagesFolderPath is the path to the packages folder
*/
- function getTypingNamesFromNodeModuleFolder(nodeModulesPath) {
+ function getTypingNamesFromPackagesFolder(packagesFolderPath) {
+ filesToWatch.push(packagesFolderPath);
// Todo: add support for ModuleResolutionHost too
- if (!host.directoryExists(nodeModulesPath)) {
+ if (!host.directoryExists(packagesFolderPath)) {
return;
}
var typingNames = [];
- var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
+ var fileNames = host.readDirectory(packagesFolderPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
var fileName = fileNames_2[_i];
var normalizedFileName = ts.normalizePath(fileName);
- if (ts.getBaseFileName(normalizedFileName) !== "package.json") {
+ var baseFileName = ts.getBaseFileName(normalizedFileName);
+ if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
@@ -71164,7 +77000,7 @@ var ts;
// npm 3's package.json contains a "_requiredBy" field
// we should include all the top level module names for npm 2, and only module names whose
// "_requiredBy" field starts with "#" or equals "/" for npm 3.
- if (packageJson._requiredBy &&
+ if (baseFileName === "package.json" && packageJson._requiredBy &&
ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
continue;
}
@@ -71175,7 +77011,7 @@ var ts;
}
if (packageJson.typings) {
var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName));
- inferredTypings[packageJson.name] = absolutePath;
+ inferredTypings.set(packageJson.name, absolutePath);
}
else {
typingNames.push(packageJson.name);
@@ -71195,47 +77031,49 @@ var ts;
function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) {
var patternMatcher = ts.createPatternMatcher(searchValue);
var rawItems = [];
- // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- ts.forEach(sourceFiles, function (sourceFile) {
+ var _loop_4 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) {
- return;
+ return "continue";
}
- var nameToDeclarations = sourceFile.getNamedDeclarations();
- for (var name_46 in nameToDeclarations) {
- var declarations = nameToDeclarations[name_46];
+ ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) {
if (declarations) {
// First do a quick check to see if the name of the declaration matches the
// last portion of the (possibly) dotted name they're searching for.
- var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_46);
+ var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name);
if (!matches) {
- continue;
+ return; // continue to next named declarations
}
- for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
- var declaration = declarations_9[_i];
+ for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) {
+ var declaration = declarations_12[_i];
// It was a match! If the pattern has dots in it, then also see if the
// declaration container matches as well.
if (patternMatcher.patternContainsDots) {
var containers = getContainers(declaration);
if (!containers) {
- return undefined;
+ return true; // Break out of named declarations and go to the next source file.
}
- matches = patternMatcher.getMatches(containers, name_46);
+ matches = patternMatcher.getMatches(containers, name);
if (!matches) {
- continue;
+ return; // continue to next named declarations
}
}
var fileName = sourceFile.fileName;
var matchKind = bestMatchKind(matches);
- rawItems.push({ name: name_46, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration });
+ rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration });
}
}
- }
- });
+ });
+ };
+ // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
+ for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
+ var sourceFile = sourceFiles_7[_i];
+ _loop_4(sourceFile);
+ }
// Remove imports when the imported declaration is already in the list and has the same name.
rawItems = ts.filter(rawItems, function (item) {
var decl = item.declaration;
- if (decl.kind === 236 /* ImportClause */ || decl.kind === 239 /* ImportSpecifier */ || decl.kind === 234 /* ImportEqualsDeclaration */) {
+ if (decl.kind === 238 /* ImportClause */ || decl.kind === 241 /* ImportSpecifier */ || decl.kind === 236 /* ImportEqualsDeclaration */) {
var importer = checker.getSymbolAtLocation(decl.name);
var imported = checker.getAliasedSymbol(importer);
return importer.name !== imported.name;
@@ -71277,7 +77115,7 @@ var ts;
if (text !== undefined) {
containers.unshift(text);
}
- else if (declaration.name.kind === 142 /* ComputedPropertyName */) {
+ else if (declaration.name.kind === 143 /* ComputedPropertyName */) {
return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true);
}
else {
@@ -71298,7 +77136,7 @@ var ts;
}
return true;
}
- if (expression.kind === 177 /* PropertyAccessExpression */) {
+ if (expression.kind === 178 /* PropertyAccessExpression */) {
var propertyAccess = expression;
if (includeLastPortion) {
containers.unshift(propertyAccess.name.text);
@@ -71311,7 +77149,7 @@ var ts;
var containers = [];
// First, if we started with a computed property name, then add all but the last
// portion into the container array.
- if (declaration.name.kind === 142 /* ComputedPropertyName */) {
+ if (declaration.name.kind === 143 /* ComputedPropertyName */) {
if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) {
return undefined;
}
@@ -71357,7 +77195,7 @@ var ts;
matchKind: ts.PatternMatchKind[rawItem.matchKind],
isCaseSensitive: rawItem.isCaseSensitive,
fileName: rawItem.fileName,
- textSpan: ts.createTextSpanFromBounds(declaration.getStart(), declaration.getEnd()),
+ textSpan: ts.createTextSpanFromNode(declaration),
// TODO(jfreeman): What should be the containerName when the container has a computed name?
containerName: container && container.name ? container.name.text : "",
containerKind: container && container.name ? ts.getNodeKind(container) : ""
@@ -71373,22 +77211,61 @@ var ts;
(function (ts) {
var NavigationBar;
(function (NavigationBar) {
- function getNavigationBarItems(sourceFile) {
+ /**
+ * Matches all whitespace characters in a string. Eg:
+ *
+ * "app.
+ *
+ * onactivated"
+ *
+ * matches because of the newline, whereas
+ *
+ * "app.onactivated"
+ *
+ * does not match.
+ */
+ var whiteSpaceRegex = /\s+/g;
+ // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`.
+ var curCancellationToken;
+ var curSourceFile;
+ /**
+ * For performance, we keep navigation bar parents on a stack rather than passing them through each recursion.
+ * `parent` is the current parent and is *not* stored in parentsStack.
+ * `startNode` sets a new parent and `endNode` returns to the previous parent.
+ */
+ var parentsStack = [];
+ var parent;
+ // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance.
+ var emptyChildItemArray = [];
+ function getNavigationBarItems(sourceFile, cancellationToken) {
+ curCancellationToken = cancellationToken;
curSourceFile = sourceFile;
- var result = ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem);
- curSourceFile = undefined;
- return result;
+ try {
+ return ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem);
+ }
+ finally {
+ reset();
+ }
}
NavigationBar.getNavigationBarItems = getNavigationBarItems;
- function getNavigationTree(sourceFile) {
+ function getNavigationTree(sourceFile, cancellationToken) {
+ curCancellationToken = cancellationToken;
curSourceFile = sourceFile;
- var result = convertToTree(rootNavigationBarNode(sourceFile));
- curSourceFile = undefined;
- return result;
+ try {
+ return convertToTree(rootNavigationBarNode(sourceFile));
+ }
+ finally {
+ reset();
+ }
}
NavigationBar.getNavigationTree = getNavigationTree;
- // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`.
- var curSourceFile;
+ function reset() {
+ curSourceFile = undefined;
+ curCancellationToken = undefined;
+ parentsStack = [];
+ parent = undefined;
+ emptyChildItemArray = [];
+ }
function nodeText(node) {
return node.getText(curSourceFile);
}
@@ -71403,13 +77280,6 @@ var ts;
parent.children = [child];
}
}
- /*
- For performance, we keep navigation bar parents on a stack rather than passing them through each recursion.
- `parent` is the current parent and is *not* stored in parentsStack.
- `startNode` sets a new parent and `endNode` returns to the previous parent.
- */
- var parentsStack = [];
- var parent;
function rootNavigationBarNode(sourceFile) {
ts.Debug.assert(!parentsStack.length);
var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 };
@@ -71460,11 +77330,12 @@ var ts;
}
/** Look for navigation bar items in node's subtree, adding them to the current `parent`. */
function addChildrenRecursively(node) {
+ curCancellationToken.throwIfCancellationRequested();
if (!node || ts.isToken(node)) {
return;
}
switch (node.kind) {
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
// Get parameter properties, and treat them as being on the *same* level as the constructor, not under it.
var ctr = node;
addNodeWithRecursiveChild(ctr, ctr.body);
@@ -71476,21 +77347,21 @@ var ts;
}
}
break;
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 148 /* MethodSignature */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 149 /* MethodSignature */:
if (!ts.hasDynamicName(node)) {
addNodeWithRecursiveChild(node, node.body);
}
break;
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
if (!ts.hasDynamicName(node)) {
addLeafNode(node);
}
break;
- case 236 /* ImportClause */:
+ case 238 /* ImportClause */:
var importClause = node;
// Handle default import case e.g.:
// import d from "mod";
@@ -71502,7 +77373,7 @@ var ts;
// import {a, b as B} from "mod";
var namedBindings = importClause.namedBindings;
if (namedBindings) {
- if (namedBindings.kind === 237 /* NamespaceImport */) {
+ if (namedBindings.kind === 239 /* NamespaceImport */) {
addLeafNode(namedBindings);
}
else {
@@ -71513,12 +77384,12 @@ var ts;
}
}
break;
- case 174 /* BindingElement */:
- case 223 /* VariableDeclaration */:
+ case 175 /* BindingElement */:
+ case 225 /* VariableDeclaration */:
var decl = node;
- var name_47 = decl.name;
- if (ts.isBindingPattern(name_47)) {
- addChildrenRecursively(name_47);
+ var name = decl.name;
+ if (ts.isBindingPattern(name)) {
+ addChildrenRecursively(name);
}
else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) {
// For `const x = function() {}`, just use the function node, not the const.
@@ -71528,12 +77399,12 @@ var ts;
addNodeWithRecursiveChild(decl, decl.initializer);
}
break;
- case 185 /* ArrowFunction */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
addNodeWithRecursiveChild(node, node.body);
break;
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
startNode(node);
for (var _d = 0, _e = node.members; _d < _e.length; _d++) {
var member = _e[_d];
@@ -71543,9 +77414,9 @@ var ts;
}
endNode();
break;
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 227 /* InterfaceDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 229 /* InterfaceDeclaration */:
startNode(node);
for (var _f = 0, _g = node.members; _f < _g.length; _f++) {
var member = _g[_f];
@@ -71553,21 +77424,21 @@ var ts;
}
endNode();
break;
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
addNodeWithRecursiveChild(node, getInteriorModule(node).body);
break;
- case 243 /* ExportSpecifier */:
- case 234 /* ImportEqualsDeclaration */:
- case 155 /* IndexSignature */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 228 /* TypeAliasDeclaration */:
+ case 245 /* ExportSpecifier */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 156 /* IndexSignature */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 230 /* TypeAliasDeclaration */:
addLeafNode(node);
break;
default:
ts.forEach(node.jsDoc, function (jsDoc) {
ts.forEach(jsDoc.tags, function (tag) {
- if (tag.kind === 285 /* JSDocTypedefTag */) {
+ if (tag.kind === 289 /* JSDocTypedefTag */) {
addLeafNode(tag);
}
});
@@ -71585,9 +77456,9 @@ var ts;
// Anonymous items are never merged.
return true;
}
- var itemsWithSameName = nameToItems[name];
+ var itemsWithSameName = nameToItems.get(name);
if (!itemsWithSameName) {
- nameToItems[name] = child;
+ nameToItems.set(name, child);
return true;
}
if (itemsWithSameName instanceof Array) {
@@ -71605,7 +77476,7 @@ var ts;
if (tryMerge(itemWithSameName, child)) {
return false;
}
- nameToItems[name] = [itemWithSameName, child];
+ nameToItems.set(name, [itemWithSameName, child]);
return true;
}
function tryMerge(a, b) {
@@ -71618,14 +77489,14 @@ var ts;
});
/** a and b have the same name, but they may not be mergeable. */
function shouldReallyMerge(a, b) {
- return a.kind === b.kind && (a.kind !== 230 /* ModuleDeclaration */ || areSameModule(a, b));
+ return a.kind === b.kind && (a.kind !== 232 /* ModuleDeclaration */ || areSameModule(a, b));
// 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, b) {
if (a.body.kind !== b.body.kind) {
return false;
}
- if (a.body.kind !== 230 /* ModuleDeclaration */) {
+ if (a.body.kind !== 232 /* ModuleDeclaration */) {
return true;
}
return areSameModule(a.body, b.body);
@@ -71653,39 +77524,20 @@ var ts;
function compareChildren(child1, child2) {
var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node);
if (name1 && name2) {
- var cmp = localeCompareFix(name1, name2);
+ var cmp = ts.compareStringsCaseInsensitive(name1, name2);
return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2);
}
else {
return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2);
}
}
- // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B".
- var localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0;
- var localeCompareFix = localeCompareIsCorrect ? ts.collator.compare : function (a, b) {
- // This isn't perfect, but it passes all of our tests.
- for (var i = 0; i < Math.min(a.length, b.length); i++) {
- var chA = a.charAt(i), chB = b.charAt(i);
- if (chA === "\"" && chB === "'") {
- return 1;
- }
- if (chA === "'" && chB === "\"") {
- return -1;
- }
- var cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase());
- if (cmp !== 0) {
- return cmp;
- }
- }
- return a.length - b.length;
- };
/**
* This differs from getItemName because this is just used for sorting.
* We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like.
* So `new()` can still come before an `aardvark` method.
*/
function tryGetName(node) {
- if (node.kind === 230 /* ModuleDeclaration */) {
+ if (node.kind === 232 /* ModuleDeclaration */) {
return getModuleName(node);
}
var decl = node;
@@ -71693,18 +77545,18 @@ var ts;
return ts.getPropertyNameForPropertyNameNode(decl.name);
}
switch (node.kind) {
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 197 /* ClassExpression */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 198 /* ClassExpression */:
return getFunctionOrClassName(node);
- case 285 /* JSDocTypedefTag */:
+ case 289 /* JSDocTypedefTag */:
return getJSDocTypedefTagName(node);
default:
return undefined;
}
}
function getItemName(node) {
- if (node.kind === 230 /* ModuleDeclaration */) {
+ if (node.kind === 232 /* ModuleDeclaration */) {
return getModuleName(node);
}
var name = node.name;
@@ -71715,16 +77567,16 @@ var ts;
}
}
switch (node.kind) {
- case 261 /* SourceFile */:
+ case 264 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
: "<global>";
- case 185 /* ArrowFunction */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
+ case 186 /* ArrowFunction */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
if (ts.getModifierFlags(node) & 512 /* Default */) {
return "default";
}
@@ -71732,15 +77584,15 @@ var ts;
// (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the
// navigation bar.
return getFunctionOrClassName(node);
- case 150 /* Constructor */:
+ case 151 /* Constructor */:
return "constructor";
- case 154 /* ConstructSignature */:
+ case 155 /* ConstructSignature */:
return "new()";
- case 153 /* CallSignature */:
+ case 154 /* CallSignature */:
return "()";
- case 155 /* IndexSignature */:
+ case 156 /* IndexSignature */:
return "[]";
- case 285 /* JSDocTypedefTag */:
+ case 289 /* JSDocTypedefTag */:
return getJSDocTypedefTagName(node);
default:
return "<unknown>";
@@ -71752,7 +77604,7 @@ var ts;
}
else {
var parentNode = node.parent && node.parent.parent;
- if (parentNode && parentNode.kind === 205 /* VariableStatement */) {
+ if (parentNode && parentNode.kind === 207 /* VariableStatement */) {
if (parentNode.declarationList.declarations.length > 0) {
var nameIdentifier = parentNode.declarationList.declarations[0].name;
if (nameIdentifier.kind === 70 /* Identifier */) {
@@ -71781,24 +77633,24 @@ var ts;
return topLevel;
function isTopLevel(item) {
switch (navigationBarNodeKind(item)) {
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 229 /* EnumDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 230 /* ModuleDeclaration */:
- case 261 /* SourceFile */:
- case 228 /* TypeAliasDeclaration */:
- case 285 /* JSDocTypedefTag */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 231 /* EnumDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ case 264 /* SourceFile */:
+ case 230 /* TypeAliasDeclaration */:
+ case 289 /* JSDocTypedefTag */:
return true;
- case 150 /* Constructor */:
- case 149 /* MethodDeclaration */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 223 /* VariableDeclaration */:
+ case 151 /* Constructor */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 225 /* VariableDeclaration */:
return hasSomeImportantChild(item);
- case 185 /* ArrowFunction */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
return isTopLevelFunctionDeclaration(item);
default:
return false;
@@ -71808,10 +77660,10 @@ var ts;
return false;
}
switch (navigationBarNodeKind(item.parent)) {
- case 231 /* ModuleBlock */:
- case 261 /* SourceFile */:
- case 149 /* MethodDeclaration */:
- case 150 /* Constructor */:
+ case 233 /* ModuleBlock */:
+ case 264 /* SourceFile */:
+ case 150 /* MethodDeclaration */:
+ case 151 /* Constructor */:
return true;
default:
return hasSomeImportantChild(item);
@@ -71820,18 +77672,16 @@ var ts;
function hasSomeImportantChild(item) {
return ts.forEach(item.children, function (child) {
var childKind = navigationBarNodeKind(child);
- return childKind !== 223 /* VariableDeclaration */ && childKind !== 174 /* BindingElement */;
+ return childKind !== 225 /* VariableDeclaration */ && childKind !== 175 /* BindingElement */;
});
}
}
}
- // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance.
- var emptyChildItemArray = [];
function convertToTree(n) {
return {
text: getItemName(n.node),
kind: ts.getNodeKind(n.node),
- kindModifiers: ts.getNodeModifiers(n.node),
+ kindModifiers: getModifiers(n.node),
spans: getSpans(n),
childItems: ts.map(n.children, convertToTree)
};
@@ -71840,7 +77690,7 @@ var ts;
return {
text: getItemName(n.node),
kind: ts.getNodeKind(n.node),
- kindModifiers: ts.getNodeModifiers(n.node),
+ kindModifiers: getModifiers(n.node),
spans: getSpans(n),
childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray,
indent: n.indent,
@@ -71878,7 +77728,7 @@ var ts;
// Otherwise, we need to aggregate each identifier to build up the qualified name.
var result = [];
result.push(moduleDeclaration.name.text);
- while (moduleDeclaration.body && moduleDeclaration.body.kind === 230 /* ModuleDeclaration */) {
+ while (moduleDeclaration.body && moduleDeclaration.body.kind === 232 /* ModuleDeclaration */) {
moduleDeclaration = moduleDeclaration.body;
result.push(moduleDeclaration.name.text);
}
@@ -71889,28 +77739,34 @@ var ts;
* We store 'A' as associated with a NavNode, and use getModuleName to traverse down again.
*/
function getInteriorModule(decl) {
- return decl.body.kind === 230 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl;
+ return decl.body.kind === 232 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl;
}
function isComputedProperty(member) {
- return !member.name || member.name.kind === 142 /* ComputedPropertyName */;
+ return !member.name || member.name.kind === 143 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 261 /* SourceFile */
+ return node.kind === 264 /* SourceFile */
? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd())
- : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd());
+ : ts.createTextSpanFromNode(node, curSourceFile);
+ }
+ function getModifiers(node) {
+ if (node.parent && node.parent.kind === 225 /* VariableDeclaration */) {
+ node = node.parent;
+ }
+ return ts.getNodeModifiers(node);
}
function getFunctionOrClassName(node) {
if (node.name && ts.getFullWidth(node.name) > 0) {
return ts.declarationNameToString(node.name);
}
- else if (node.parent.kind === 223 /* VariableDeclaration */) {
+ else if (node.parent.kind === 225 /* VariableDeclaration */) {
return ts.declarationNameToString(node.parent.name);
}
- else if (node.parent.kind === 192 /* BinaryExpression */ &&
+ else if (node.parent.kind === 193 /* BinaryExpression */ &&
node.parent.operatorToken.kind === 57 /* EqualsToken */) {
return nodeText(node.parent.left).replace(whiteSpaceRegex, "");
}
- else if (node.parent.kind === 257 /* PropertyAssignment */ && node.parent.name) {
+ else if (node.parent.kind === 260 /* PropertyAssignment */ && node.parent.name) {
return nodeText(node.parent.name);
}
else if (ts.getModifierFlags(node) & 512 /* Default */) {
@@ -71921,22 +77777,8 @@ var ts;
}
}
function isFunctionOrClassExpression(node) {
- return node.kind === 184 /* FunctionExpression */ || node.kind === 185 /* ArrowFunction */ || node.kind === 197 /* ClassExpression */;
+ return node.kind === 185 /* FunctionExpression */ || node.kind === 186 /* ArrowFunction */ || node.kind === 198 /* ClassExpression */;
}
- /**
- * Matches all whitespace characters in a string. Eg:
- *
- * "app.
- *
- * onactivated"
- *
- * matches because of the newline, whereas
- *
- * "app.onactivated"
- *
- * does not match.
- */
- var whiteSpaceRegex = /\s+/g;
})(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {}));
})(ts || (ts = {}));
/* @internal */
@@ -71944,29 +77786,29 @@ var ts;
(function (ts) {
var OutliningElementsCollector;
(function (OutliningElementsCollector) {
- function collectElements(sourceFile) {
+ function collectElements(sourceFile, cancellationToken) {
var elements = [];
var collapseText = "...";
function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) {
if (hintSpanNode && startElement && endElement) {
- var span_12 = {
+ var span_13 = {
textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end),
- hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end),
+ hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile),
bannerText: collapseText,
autoCollapse: autoCollapse
};
- elements.push(span_12);
+ elements.push(span_13);
}
}
function addOutliningSpanComments(commentSpan, autoCollapse) {
if (commentSpan) {
- var span_13 = {
+ var span_14 = {
textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
- elements.push(span_13);
+ elements.push(span_14);
}
}
function addOutliningForLeadingCommentsForNode(n) {
@@ -71978,6 +77820,7 @@ var ts;
var singleLineCommentCount = 0;
for (var _i = 0, comments_4 = comments; _i < comments_4.length; _i++) {
var currentComment = comments_4[_i];
+ cancellationToken.throwIfCancellationRequested();
// For single line comments, combine consecutive ones (2 or more) into
// a single span from the start of the first till the end of the last
if (currentComment.kind === 2 /* SingleLineCommentTrivia */) {
@@ -72003,19 +77846,20 @@ var ts;
// Only outline spans of two or more consecutive single line comments
if (count > 1) {
var multipleSingleLineComments = {
+ kind: 2 /* SingleLineCommentTrivia */,
pos: start,
end: end,
- kind: 2 /* SingleLineCommentTrivia */
};
addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false);
}
}
function autoCollapse(node) {
- return ts.isFunctionBlock(node) && node.parent.kind !== 185 /* ArrowFunction */;
+ return ts.isFunctionBlock(node) && node.parent.kind !== 186 /* ArrowFunction */;
}
var depth = 0;
var maxDepth = 20;
function walk(n) {
+ cancellationToken.throwIfCancellationRequested();
if (depth > maxDepth) {
return;
}
@@ -72023,30 +77867,30 @@ var ts;
addOutliningForLeadingCommentsForNode(n);
}
switch (n.kind) {
- case 204 /* Block */:
+ case 206 /* Block */:
if (!ts.isFunctionBlock(n)) {
- var parent_19 = n.parent;
+ var parent = n.parent;
var openBrace = ts.findChildOfKind(n, 16 /* OpenBraceToken */, sourceFile);
var closeBrace = ts.findChildOfKind(n, 17 /* CloseBraceToken */, sourceFile);
// Check if the block is standalone, or 'attached' to some parent statement.
// If the latter, we want to collapse the block, but consider its hint span
// to be the entire span of the parent.
- if (parent_19.kind === 209 /* DoStatement */ ||
- parent_19.kind === 212 /* ForInStatement */ ||
- parent_19.kind === 213 /* ForOfStatement */ ||
- parent_19.kind === 211 /* ForStatement */ ||
- parent_19.kind === 208 /* IfStatement */ ||
- parent_19.kind === 210 /* WhileStatement */ ||
- parent_19.kind === 217 /* WithStatement */ ||
- parent_19.kind === 256 /* CatchClause */) {
- addOutliningSpan(parent_19, openBrace, closeBrace, autoCollapse(n));
+ if (parent.kind === 211 /* DoStatement */ ||
+ parent.kind === 214 /* ForInStatement */ ||
+ parent.kind === 215 /* ForOfStatement */ ||
+ parent.kind === 213 /* ForStatement */ ||
+ parent.kind === 210 /* IfStatement */ ||
+ parent.kind === 212 /* WhileStatement */ ||
+ parent.kind === 219 /* WithStatement */ ||
+ parent.kind === 259 /* CatchClause */) {
+ addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
break;
}
- if (parent_19.kind === 221 /* TryStatement */) {
+ if (parent.kind === 223 /* TryStatement */) {
// Could be the try-block, or the finally-block.
- var tryStatement = parent_19;
+ var tryStatement = parent;
if (tryStatement.tryBlock === n) {
- addOutliningSpan(parent_19, openBrace, closeBrace, autoCollapse(n));
+ addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
break;
}
else if (tryStatement.finallyBlock === n) {
@@ -72056,36 +77900,37 @@ var ts;
break;
}
}
+ // fall through.
}
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
- var span_14 = ts.createTextSpanFromBounds(n.getStart(), n.end);
+ var span_15 = ts.createTextSpanFromNode(n);
elements.push({
- textSpan: span_14,
- hintSpan: span_14,
+ textSpan: span_15,
+ hintSpan: span_15,
bannerText: collapseText,
autoCollapse: autoCollapse(n)
});
break;
}
- // Fallthrough.
- case 231 /* ModuleBlock */: {
+ // falls through
+ case 233 /* ModuleBlock */: {
var openBrace = ts.findChildOfKind(n, 16 /* OpenBraceToken */, sourceFile);
var closeBrace = ts.findChildOfKind(n, 17 /* CloseBraceToken */, sourceFile);
addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n));
break;
}
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
- case 229 /* EnumDeclaration */:
- case 176 /* ObjectLiteralExpression */:
- case 232 /* CaseBlock */: {
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 177 /* ObjectLiteralExpression */:
+ case 234 /* CaseBlock */: {
var openBrace = ts.findChildOfKind(n, 16 /* OpenBraceToken */, sourceFile);
var closeBrace = ts.findChildOfKind(n, 17 /* CloseBraceToken */, sourceFile);
addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n));
break;
}
- case 175 /* ArrayLiteralExpression */:
+ case 176 /* ArrayLiteralExpression */:
var openBracket = ts.findChildOfKind(n, 20 /* OpenBracketToken */, sourceFile);
var closeBracket = ts.findChildOfKind(n, 21 /* CloseBracketToken */, sourceFile);
addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n));
@@ -72181,10 +78026,11 @@ var ts;
return totalMatch;
}
function getWordSpans(word) {
- if (!(word in stringToWordSpans)) {
- stringToWordSpans[word] = breakIntoWordSpans(word);
+ var spans = stringToWordSpans.get(word);
+ if (!spans) {
+ stringToWordSpans.set(word, spans = breakIntoWordSpans(word));
}
- return stringToWordSpans[word];
+ return spans;
}
function matchTextChunk(candidate, chunk, punctuationStripped) {
var index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
@@ -72212,10 +78058,10 @@ var ts;
// But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
var wordSpans = getWordSpans(candidate);
for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) {
- var span_15 = wordSpans_1[_i];
- if (partStartsWith(candidate, span_15, chunk.text, /*ignoreCase:*/ true)) {
+ var span_16 = wordSpans_1[_i];
+ if (partStartsWith(candidate, span_16, chunk.text, /*ignoreCase:*/ true)) {
return createPatternMatch(PatternMatchKind.substring, punctuationStripped,
- /*isCaseSensitive:*/ partStartsWith(candidate, span_15, chunk.text, /*ignoreCase:*/ false));
+ /*isCaseSensitive:*/ partStartsWith(candidate, span_16, chunk.text, /*ignoreCase:*/ false));
}
}
}
@@ -72465,7 +78311,8 @@ var ts;
}
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(string, value) {
- for (var i = 0, n = string.length - value.length; i <= n; i++) {
+ var n = string.length - value.length;
+ for (var i = 0; i <= n; i++) {
if (startsWithIgnoringCase(string, value, i)) {
return i;
}
@@ -72474,7 +78321,7 @@ var ts;
}
// Assumes 'value' is already lowercase.
function startsWithIgnoringCase(string, value, start) {
- for (var i = 0, n = value.length; i < n; i++) {
+ for (var i = 0; i < value.length; i++) {
var ch1 = toLowerCase(string.charCodeAt(i + start));
var ch2 = value.charCodeAt(i);
if (ch1 !== ch2) {
@@ -72546,7 +78393,7 @@ var ts;
function breakIntoSpans(identifier, word) {
var result = [];
var wordStart = 0;
- for (var i = 1, n = identifier.length; i < n; i++) {
+ for (var i = 1; i < identifier.length; i++) {
var lastIsDigit = isDigit(identifier.charCodeAt(i - 1));
var currentIsDigit = isDigit(identifier.charCodeAt(i));
var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i);
@@ -72758,7 +78605,7 @@ var ts;
else {
if (token === 70 /* Identifier */ || ts.isKeyword(token)) {
token = nextToken();
- if (token === 138 /* FromKeyword */) {
+ if (token === 139 /* FromKeyword */) {
token = nextToken();
if (token === 9 /* StringLiteral */) {
// import d from "mod";
@@ -72789,7 +78636,7 @@ var ts;
}
if (token === 17 /* CloseBraceToken */) {
token = nextToken();
- if (token === 138 /* FromKeyword */) {
+ if (token === 139 /* FromKeyword */) {
token = nextToken();
if (token === 9 /* StringLiteral */) {
// import {a as A} from "mod";
@@ -72805,7 +78652,7 @@ var ts;
token = nextToken();
if (token === 70 /* Identifier */ || ts.isKeyword(token)) {
token = nextToken();
- if (token === 138 /* FromKeyword */) {
+ if (token === 139 /* FromKeyword */) {
token = nextToken();
if (token === 9 /* StringLiteral */) {
// import * as NS from "mod"
@@ -72835,7 +78682,7 @@ var ts;
}
if (token === 17 /* CloseBraceToken */) {
token = nextToken();
- if (token === 138 /* FromKeyword */) {
+ if (token === 139 /* FromKeyword */) {
token = nextToken();
if (token === 9 /* StringLiteral */) {
// export {a as A} from "mod";
@@ -72847,7 +78694,7 @@ var ts;
}
else if (token === 38 /* AsteriskToken */) {
token = nextToken();
- if (token === 138 /* FromKeyword */) {
+ if (token === 139 /* FromKeyword */) {
token = nextToken();
if (token === 9 /* StringLiteral */) {
// export * from "mod"
@@ -72999,93 +78846,89 @@ var ts;
var Rename;
(function (Rename) {
function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) {
- var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName));
+ var getCanonicalDefaultLibName = ts.memoize(function () { return getCanonicalFileName(ts.normalizePath(defaultLibFileName)); });
var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true);
- if (node) {
- if (node.kind === 70 /* Identifier */ ||
- node.kind === 9 /* StringLiteral */ ||
- ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) ||
- ts.isThis(node)) {
- var symbol = typeChecker.getSymbolAtLocation(node);
- // Only allow a symbol to be renamed if it actually has at least one declaration.
- if (symbol) {
- var declarations = symbol.getDeclarations();
- if (declarations && declarations.length > 0) {
- // Disallow rename for elements that are defined in the standard TypeScript library.
- if (ts.forEach(declarations, isDefinedInLibraryFile)) {
- return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library));
- }
- var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node));
- var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
- if (kind) {
- return {
- canRename: true,
- kind: kind,
- displayName: displayName,
- localizedErrorMessage: undefined,
- fullDisplayName: typeChecker.getFullyQualifiedName(symbol),
- kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
- triggerSpan: createTriggerSpanForNode(node, sourceFile)
- };
- }
- }
- }
- else if (node.kind === 9 /* StringLiteral */) {
- var type = ts.getStringLiteralTypeForNode(node, typeChecker);
- if (type) {
- if (isDefinedInLibraryFile(node)) {
- return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library));
- }
- else {
- var displayName = ts.stripQuotes(type.text);
- return {
- canRename: true,
- kind: ts.ScriptElementKind.variableElement,
- displayName: displayName,
- localizedErrorMessage: undefined,
- fullDisplayName: displayName,
- kindModifiers: ts.ScriptElementKindModifier.none,
- triggerSpan: createTriggerSpanForNode(node, sourceFile)
- };
- }
- }
- }
+ var renameInfo = node && nodeIsEligibleForRename(node)
+ ? getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile)
+ : undefined;
+ return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element);
+ function isDefinedInLibraryFile(declaration) {
+ if (!defaultLibFileName) {
+ return false;
}
+ var sourceFile = declaration.getSourceFile();
+ var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName));
+ return canonicalName === getCanonicalDefaultLibName();
}
- return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element));
- function getRenameInfoError(localizedErrorMessage) {
- return {
- canRename: false,
- localizedErrorMessage: localizedErrorMessage,
- displayName: undefined,
- fullDisplayName: undefined,
- kind: undefined,
- kindModifiers: undefined,
- triggerSpan: undefined
- };
- }
- function isDefinedInLibraryFile(declaration) {
- if (defaultLibFileName) {
- var sourceFile_1 = declaration.getSourceFile();
- var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_1.fileName));
- if (canonicalName === canonicalDefaultLibName) {
- return true;
+ }
+ Rename.getRenameInfo = getRenameInfo;
+ function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) {
+ var symbol = typeChecker.getSymbolAtLocation(node);
+ // Only allow a symbol to be renamed if it actually has at least one declaration.
+ if (symbol) {
+ var declarations = symbol.getDeclarations();
+ if (declarations && declarations.length > 0) {
+ // Disallow rename for elements that are defined in the standard TypeScript library.
+ if (ts.some(declarations, isDefinedInLibraryFile)) {
+ return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
+ }
+ // Cannot rename `default` as in `import { default as foo } from "./someModule";
+ if (node.kind === 70 /* Identifier */ &&
+ node.originalKeywordKind === 78 /* DefaultKeyword */ &&
+ symbol.parent.flags & 1536 /* Module */) {
+ return undefined;
}
+ var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node));
+ var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
+ return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined;
}
- return false;
}
- function createTriggerSpanForNode(node, sourceFile) {
- var start = node.getStart(sourceFile);
- var width = node.getWidth(sourceFile);
- if (node.kind === 9 /* StringLiteral */) {
- // Exclude the quotes
- start += 1;
- width -= 2;
+ else if (node.kind === 9 /* StringLiteral */) {
+ if (isDefinedInLibraryFile(node)) {
+ return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library);
}
- return ts.createTextSpan(start, width);
+ var displayName = ts.stripQuotes(node.text);
+ return getRenameInfoSuccess(displayName, displayName, ts.ScriptElementKind.variableElement, ts.ScriptElementKindModifier.none, node, sourceFile);
}
}
- Rename.getRenameInfo = getRenameInfo;
+ function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) {
+ return {
+ canRename: true,
+ kind: kind,
+ displayName: displayName,
+ localizedErrorMessage: undefined,
+ fullDisplayName: fullDisplayName,
+ kindModifiers: kindModifiers,
+ triggerSpan: createTriggerSpanForNode(node, sourceFile)
+ };
+ }
+ function getRenameInfoError(diagnostic) {
+ return {
+ canRename: false,
+ localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic),
+ displayName: undefined,
+ fullDisplayName: undefined,
+ kind: undefined,
+ kindModifiers: undefined,
+ triggerSpan: undefined
+ };
+ }
+ function createTriggerSpanForNode(node, sourceFile) {
+ var start = node.getStart(sourceFile);
+ var width = node.getWidth(sourceFile);
+ if (node.kind === 9 /* StringLiteral */) {
+ // Exclude the quotes
+ start += 1;
+ width -= 2;
+ }
+ return ts.createTextSpan(start, width);
+ }
+ function nodeIsEligibleForRename(node) {
+ return node.kind === 70 /* Identifier */ ||
+ node.kind === 9 /* StringLiteral */ ||
+ ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) ||
+ ts.isThis(node);
+ }
})(Rename = ts.Rename || (ts.Rename = {}));
})(ts || (ts = {}));
///<reference path='services.ts' />
@@ -73140,7 +78983,7 @@ var ts;
// stack++;
// break;
// case TypeScript.SyntaxKind.CommaToken:
- // if (stack == 0) {
+ // if (stack === 0) {
// argumentIndex++;
// }
// break;
@@ -73232,6 +79075,7 @@ var ts;
ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments";
ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments";
ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments";
+ ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments";
})(ArgumentListKind = SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {}));
function getSignatureHelpItems(program, sourceFile, position, cancellationToken) {
var typeChecker = program.getTypeChecker();
@@ -73263,7 +79107,7 @@ var ts;
}
SignatureHelp.getSignatureHelpItems = getSignatureHelpItems;
function createJavaScriptSignatureHelpItems(argumentInfo, program) {
- if (argumentInfo.invocation.kind !== 179 /* CallExpression */) {
+ if (argumentInfo.invocation.kind !== 180 /* CallExpression */) {
return undefined;
}
// See if we can find some symbol with the call expression name that has call signatures.
@@ -73271,7 +79115,7 @@ var ts;
var expression = callExpression.expression;
var name = expression.kind === 70 /* Identifier */
? expression
- : expression.kind === 177 /* PropertyAccessExpression */
+ : expression.kind === 178 /* PropertyAccessExpression */
? expression.name
: undefined;
if (!name || !name.text) {
@@ -73281,10 +79125,10 @@ var ts;
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
var nameToDeclarations = sourceFile.getNamedDeclarations();
- var declarations = nameToDeclarations[name.text];
+ var declarations = nameToDeclarations.get(name.text);
if (declarations) {
- for (var _b = 0, declarations_10 = declarations; _b < declarations_10.length; _b++) {
- var declaration = declarations_10[_b];
+ for (var _b = 0, declarations_13 = declarations; _b < declarations_13.length; _b++) {
+ var declaration = declarations_13[_b];
var symbol = declaration.symbol;
if (symbol) {
var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration);
@@ -73304,21 +79148,21 @@ var ts;
* in the argument of an invocation; returns undefined otherwise.
*/
function getImmediatelyContainingArgumentInfo(node, position, sourceFile) {
- if (node.parent.kind === 179 /* CallExpression */ || node.parent.kind === 180 /* NewExpression */) {
+ if (node.parent.kind === 180 /* CallExpression */ || node.parent.kind === 181 /* NewExpression */) {
var callExpression = node.parent;
// There are 3 cases to handle:
- // 1. The token introduces a list, and should begin a sig help session
+ // 1. The token introduces a list, and should begin a signature help session
// 2. The token is either not associated with a list, or ends a list, so the session should end
- // 3. The token is buried inside a list, and should give sig help
+ // 3. The token is buried inside a list, and should give signature help
//
// The following are examples of each:
//
// Case 1:
- // foo<#T, U>(#a, b) -> The token introduces a list, and should begin a sig help session
+ // foo<#T, U>(#a, b) -> The token introduces a list, and should begin a signature help session
// Case 2:
// fo#o<T, U>#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should end
// Case 3:
- // foo<T#, U#>(a#, #b#) -> The token is buried inside a list, and should give sig help
+ // foo<T#, U#>(a#, #b#) -> The token is buried inside a list, and should give signature help
// Find out if 'node' is an argument, a type argument, or neither
if (node.kind === 26 /* LessThanToken */ ||
node.kind === 18 /* OpenParenToken */) {
@@ -73337,7 +79181,7 @@ var ts;
}
// findListItemInfo can return undefined if we are not in parent's argument list
// or type argument list. This includes cases where the cursor is:
- // - To the right of the closing paren, non-substitution template, or template tail.
+ // - To the right of the closing parenthesis, non-substitution template, or template tail.
// - Between the type arguments and the arguments (greater than token)
// - On the target of the call (parent.func)
// - On the 'new' keyword in a 'new' expression
@@ -73358,25 +79202,25 @@ var ts;
}
return undefined;
}
- else if (node.kind === 12 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 181 /* TaggedTemplateExpression */) {
+ else if (node.kind === 12 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 182 /* TaggedTemplateExpression */) {
// Check if we're actually inside the template;
// otherwise we'll fall out and return undefined.
if (ts.isInsideTemplateLiteral(node, position)) {
return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile);
}
}
- else if (node.kind === 13 /* TemplateHead */ && node.parent.parent.kind === 181 /* TaggedTemplateExpression */) {
+ else if (node.kind === 13 /* TemplateHead */ && node.parent.parent.kind === 182 /* TaggedTemplateExpression */) {
var templateExpression = node.parent;
var tagExpression = templateExpression.parent;
- ts.Debug.assert(templateExpression.kind === 194 /* TemplateExpression */);
+ ts.Debug.assert(templateExpression.kind === 195 /* TemplateExpression */);
var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1;
return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
}
- else if (node.parent.kind === 202 /* TemplateSpan */ && node.parent.parent.parent.kind === 181 /* TaggedTemplateExpression */) {
+ else if (node.parent.kind === 204 /* TemplateSpan */ && node.parent.parent.parent.kind === 182 /* TaggedTemplateExpression */) {
var templateSpan = node.parent;
var templateExpression = templateSpan.parent;
var tagExpression = templateExpression.parent;
- ts.Debug.assert(templateExpression.kind === 194 /* TemplateExpression */);
+ ts.Debug.assert(templateExpression.kind === 195 /* TemplateExpression */);
// If we're just after a template tail, don't show signature help.
if (node.kind === 15 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) {
return undefined;
@@ -73385,8 +79229,25 @@ var ts;
var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position);
return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile);
}
+ else if (node.parent && ts.isJsxOpeningLikeElement(node.parent)) {
+ // Provide a signature help for JSX opening element or JSX self-closing element.
+ // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems")
+ // i.e
+ // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... }
+ // <MainButton /*signatureHelp*/
+ var attributeSpanStart = node.parent.attributes.getFullStart();
+ var attributeSpanEnd = ts.skipTrivia(sourceFile.text, node.parent.attributes.getEnd(), /*stopAfterLineBreak*/ false);
+ return {
+ kind: 3 /* JSXAttributesArguments */,
+ invocation: node.parent,
+ argumentsSpan: ts.createTextSpan(attributeSpanStart, attributeSpanEnd - attributeSpanStart),
+ argumentIndex: 0,
+ argumentCount: 1
+ };
+ }
return undefined;
}
+ SignatureHelp.getImmediatelyContainingArgumentInfo = getImmediatelyContainingArgumentInfo;
function getArgumentIndex(argumentsList, node) {
// The list we got back can include commas. In the presence of errors it may
// also just have nodes without commas. For example "Foo(a b c)" will have 3
@@ -73422,7 +79283,7 @@ var ts;
//
// Note: this subtlety only applies to the last comma. If you had "Foo(a,," then
// we'll have: 'a' '<comma>' '<missing>'
- // That will give us 2 non-commas. We then add one for the last comma, givin us an
+ // That will give us 2 non-commas. We then add one for the last comma, giving us an
// arg count of 3.
var listChildren = argumentsList.getChildren();
var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 25 /* CommaToken */; });
@@ -73494,7 +79355,7 @@ var ts;
//
// This is because a Missing node has no width. However, what we actually want is to include trivia
// leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail.
- if (template.kind === 194 /* TemplateExpression */) {
+ if (template.kind === 195 /* TemplateExpression */) {
var lastSpan = ts.lastOrUndefined(template.templateSpans);
if (lastSpan.literal.getFullWidth() === 0) {
applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false);
@@ -73503,7 +79364,7 @@ var ts;
return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node, position, sourceFile) {
- for (var n = node; n.kind !== 261 /* SourceFile */; n = n.parent) {
+ for (var n = node; n.kind !== 264 /* SourceFile */; n = n.parent) {
if (ts.isFunctionBlock(n)) {
return undefined;
}
@@ -73516,6 +79377,7 @@ var ts;
if (argumentInfo) {
return argumentInfo;
}
+ // TODO: Handle generic call with incomplete syntax
}
return undefined;
}
@@ -73596,7 +79458,8 @@ var ts;
suffixDisplayParts: suffixDisplayParts,
separatorDisplayParts: [ts.punctuationPart(25 /* CommaToken */), ts.spacePart()],
parameters: signatureHelpParameters,
- documentation: candidateSignature.getDocumentationComment()
+ documentation: candidateSignature.getDocumentationComment(),
+ tags: candidateSignature.getJsDocTags()
};
});
var argumentIndex = argumentListInfo.argumentIndex;
@@ -73646,9 +79509,9 @@ var ts;
(function (SymbolDisplay) {
// TODO(drosen): use contextual SemanticMeaning.
function getSymbolKind(typeChecker, symbol, location) {
- var flags = symbol.getFlags();
+ var flags = symbol.flags;
if (flags & 32 /* Class */)
- return ts.getDeclarationOfKind(symbol, 197 /* ClassExpression */) ?
+ return ts.getDeclarationOfKind(symbol, 198 /* ClassExpression */) ?
ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement;
if (flags & 384 /* Enum */)
return ts.ScriptElementKind.enumElement;
@@ -73658,12 +79521,12 @@ var ts;
return ts.ScriptElementKind.interfaceElement;
if (flags & 262144 /* TypeParameter */)
return ts.ScriptElementKind.typeParameterElement;
- var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location);
+ var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location);
if (result === ts.ScriptElementKind.unknown) {
if (flags & 262144 /* TypeParameter */)
return ts.ScriptElementKind.typeParameterElement;
if (flags & 8 /* EnumMember */)
- return ts.ScriptElementKind.variableElement;
+ return ts.ScriptElementKind.enumMemberElement;
if (flags & 8388608 /* Alias */)
return ts.ScriptElementKind.alias;
if (flags & 1536 /* Module */)
@@ -73672,7 +79535,7 @@ var ts;
return result;
}
SymbolDisplay.getSymbolKind = getSymbolKind;
- function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, flags, location) {
+ function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) {
if (typeChecker.isUndefinedSymbol(symbol)) {
return ts.ScriptElementKind.variableElement;
}
@@ -73682,6 +79545,7 @@ var ts;
if (location.kind === 98 /* ThisKeyword */ && ts.isExpression(location)) {
return ts.ScriptElementKind.parameterElement;
}
+ var flags = symbol.flags;
if (flags & 3 /* Variable */) {
if (ts.isFirstDeclarationOfSymbolParameter(symbol)) {
return ts.ScriptElementKind.parameterElement;
@@ -73705,7 +79569,7 @@ var ts;
if (flags & 16384 /* Constructor */)
return ts.ScriptElementKind.constructorImplementationElement;
if (flags & 4 /* Property */) {
- if (flags & 268435456 /* SyntheticProperty */) {
+ if (flags & 134217728 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) {
// If union property is result of union of non method (property/accessors/variables), it is labeled as property
var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) {
var rootSymbolFlags = rootSymbol.getFlags();
@@ -73725,6 +79589,9 @@ var ts;
}
return unionPropertyKind;
}
+ if (location.parent && ts.isJsxAttribute(location.parent)) {
+ return ts.ScriptElementKind.jsxAttribute;
+ }
return ts.ScriptElementKind.memberVariableElement;
}
return ts.ScriptElementKind.unknown;
@@ -73740,8 +79607,9 @@ var ts;
if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); }
var displayParts = [];
var documentation;
+ var tags;
var symbolFlags = symbol.flags;
- var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, symbolFlags, location);
+ var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location);
var hasAddedSymbolInfo;
var isThisExpression = location.kind === 98 /* ThisKeyword */ && ts.isExpression(location);
var type;
@@ -73754,7 +79622,7 @@ var ts;
var signature = void 0;
type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location);
if (type) {
- if (location.parent && location.parent.kind === 177 /* PropertyAccessExpression */) {
+ if (location.parent && location.parent.kind === 178 /* PropertyAccessExpression */) {
var right = location.parent.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)) {
@@ -73762,21 +79630,24 @@ var ts;
}
}
// try get the call/construct signature from the type if it matches
- var callExpression = void 0;
- if (location.kind === 179 /* CallExpression */ || location.kind === 180 /* NewExpression */) {
- callExpression = location;
+ var callExpressionLike = void 0;
+ if (location.kind === 180 /* CallExpression */ || location.kind === 181 /* NewExpression */) {
+ callExpressionLike = location;
}
else if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location)) {
- callExpression = location.parent;
+ callExpressionLike = location.parent;
+ }
+ else if (location.parent && ts.isJsxOpeningLikeElement(location.parent) && ts.isFunctionLike(symbol.valueDeclaration)) {
+ callExpressionLike = location.parent;
}
- if (callExpression) {
+ if (callExpressionLike) {
var candidateSignatures = [];
- signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures);
+ signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures);
if (!signature && candidateSignatures.length) {
// Use the first candidate:
signature = candidateSignatures[0];
}
- var useConstructSignatures = callExpression.kind === 180 /* NewExpression */ || callExpression.expression.kind === 96 /* SuperKeyword */;
+ var useConstructSignatures = callExpressionLike.kind === 181 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 96 /* SuperKeyword */);
var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures();
if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) {
// Get the first signature if there is one -- allSignatures may contain
@@ -73803,6 +79674,7 @@ var ts;
addPrefixForAnyFunctionOrVar(symbol, symbolKind);
}
switch (symbolKind) {
+ case ts.ScriptElementKind.jsxAttribute:
case ts.ScriptElementKind.memberVariableElement:
case ts.ScriptElementKind.variableElement:
case ts.ScriptElementKind.constElement:
@@ -73829,24 +79701,24 @@ var ts;
}
}
else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) ||
- (location.kind === 122 /* ConstructorKeyword */ && location.parent.kind === 150 /* Constructor */)) {
+ (location.kind === 122 /* ConstructorKeyword */ && location.parent.kind === 151 /* Constructor */)) {
// get the signature from the declaration and write it
var functionDeclaration = location.parent;
- var allSignatures = functionDeclaration.kind === 150 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures();
+ var allSignatures = functionDeclaration.kind === 151 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures();
if (!typeChecker.isImplementationOfOverload(functionDeclaration)) {
signature = typeChecker.getSignatureFromDeclaration(functionDeclaration);
}
else {
signature = allSignatures[0];
}
- if (functionDeclaration.kind === 150 /* Constructor */) {
+ if (functionDeclaration.kind === 151 /* Constructor */) {
// show (constructor) Type(...) signature
symbolKind = ts.ScriptElementKind.constructorImplementationElement;
addPrefixForAnyFunctionOrVar(type.symbol, symbolKind);
}
else {
// (function/method) symbol(..signature)
- addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 153 /* CallSignature */ &&
+ addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 154 /* CallSignature */ &&
!(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind);
}
addSignatureDisplayParts(signature, allSignatures);
@@ -73855,7 +79727,7 @@ var ts;
}
}
if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) {
- if (ts.getDeclarationOfKind(symbol, 197 /* ClassExpression */)) {
+ if (ts.getDeclarationOfKind(symbol, 198 /* ClassExpression */)) {
// Special case for class expressions because we would like to indicate that
// the class name is local to the class body (similar to function expression)
// (local class) class <className>
@@ -73878,7 +79750,7 @@ var ts;
}
if (symbolFlags & 524288 /* TypeAlias */) {
addNewLineIfDisplayPartsExist();
- displayParts.push(ts.keywordPart(136 /* TypeKeyword */));
+ displayParts.push(ts.keywordPart(137 /* TypeKeyword */));
displayParts.push(ts.spacePart());
addFullSymbolName(symbol);
writeTypeParametersOfSymbol(symbol, sourceFile);
@@ -73899,7 +79771,7 @@ var ts;
}
if (symbolFlags & 1536 /* Module */) {
addNewLineIfDisplayPartsExist();
- var declaration = ts.getDeclarationOfKind(symbol, 230 /* ModuleDeclaration */);
+ var declaration = ts.getDeclarationOfKind(symbol, 232 /* ModuleDeclaration */);
var isNamespace = declaration && declaration.name && declaration.name.kind === 70 /* Identifier */;
displayParts.push(ts.keywordPart(isNamespace ? 128 /* NamespaceKeyword */ : 127 /* ModuleKeyword */));
displayParts.push(ts.spacePart());
@@ -73920,28 +79792,28 @@ var ts;
}
else {
// Method/function type parameter
- var declaration = ts.getDeclarationOfKind(symbol, 143 /* TypeParameter */);
+ var declaration = ts.getDeclarationOfKind(symbol, 144 /* TypeParameter */);
ts.Debug.assert(declaration !== undefined);
declaration = declaration.parent;
if (declaration) {
if (ts.isFunctionLikeKind(declaration.kind)) {
addInPrefix();
var signature = typeChecker.getSignatureFromDeclaration(declaration);
- if (declaration.kind === 154 /* ConstructSignature */) {
+ if (declaration.kind === 155 /* ConstructSignature */) {
displayParts.push(ts.keywordPart(93 /* NewKeyword */));
displayParts.push(ts.spacePart());
}
- else if (declaration.kind !== 153 /* CallSignature */ && declaration.name) {
+ else if (declaration.kind !== 154 /* CallSignature */ && declaration.name) {
addFullSymbolName(declaration.symbol);
}
ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */));
}
- else if (declaration.kind === 228 /* TypeAliasDeclaration */) {
+ else if (declaration.kind === 230 /* TypeAliasDeclaration */) {
// Type alias type parameter
// For example
// type list<T> = T[]; // Both T will go through same code path
addInPrefix();
- displayParts.push(ts.keywordPart(136 /* TypeKeyword */));
+ displayParts.push(ts.keywordPart(137 /* TypeKeyword */));
displayParts.push(ts.spacePart());
addFullSymbolName(declaration.symbol);
writeTypeParametersOfSymbol(declaration.symbol, sourceFile);
@@ -73950,9 +79822,10 @@ var ts;
}
}
if (symbolFlags & 8 /* EnumMember */) {
+ symbolKind = ts.ScriptElementKind.enumMemberElement;
addPrefixForAnyFunctionOrVar(symbol, "enum member");
var declaration = symbol.declarations[0];
- if (declaration.kind === 260 /* EnumMember */) {
+ if (declaration.kind === 263 /* EnumMember */) {
var constantValue = typeChecker.getConstantValue(declaration);
if (constantValue !== undefined) {
displayParts.push(ts.spacePart());
@@ -73964,7 +79837,7 @@ var ts;
}
if (symbolFlags & 8388608 /* Alias */) {
addNewLineIfDisplayPartsExist();
- if (symbol.declarations[0].kind === 233 /* NamespaceExportDeclaration */) {
+ if (symbol.declarations[0].kind === 235 /* NamespaceExportDeclaration */) {
displayParts.push(ts.keywordPart(83 /* ExportKeyword */));
displayParts.push(ts.spacePart());
displayParts.push(ts.keywordPart(128 /* NamespaceKeyword */));
@@ -73975,7 +79848,7 @@ var ts;
displayParts.push(ts.spacePart());
addFullSymbolName(symbol);
ts.forEach(symbol.declarations, function (declaration) {
- if (declaration.kind === 234 /* ImportEqualsDeclaration */) {
+ if (declaration.kind === 236 /* ImportEqualsDeclaration */) {
var importEqualsDeclaration = declaration;
if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) {
displayParts.push(ts.spacePart());
@@ -74011,6 +79884,7 @@ var ts;
}
// For properties, variables and local vars: show the type
if (symbolKind === ts.ScriptElementKind.memberVariableElement ||
+ symbolKind === ts.ScriptElementKind.jsxAttribute ||
symbolFlags & 3 /* Variable */ ||
symbolKind === ts.ScriptElementKind.localVariableElement ||
isThisExpression) {
@@ -74044,14 +79918,15 @@ var ts;
}
if (!documentation) {
documentation = symbol.getDocumentationComment();
+ tags = symbol.getJsDocTags();
if (documentation.length === 0 && symbol.flags & 4 /* Property */) {
- // For some special property access expressions like `experts.foo = foo` or `module.exports.foo = foo`
+ // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo`
// there documentation comments might be attached to the right hand side symbol of their declarations.
// The pattern of such special property access is that the parent symbol is the symbol of the file.
- if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 261 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 264 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
- if (!declaration.parent || declaration.parent.kind !== 192 /* BinaryExpression */) {
+ if (!declaration.parent || declaration.parent.kind !== 193 /* BinaryExpression */) {
continue;
}
var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right);
@@ -74059,6 +79934,7 @@ var ts;
continue;
}
documentation = rhsSymbol.getDocumentationComment();
+ tags = rhsSymbol.getJsDocTags();
if (documentation.length > 0) {
break;
}
@@ -74066,7 +79942,7 @@ var ts;
}
}
}
- return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind };
+ return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags };
function addNewLineIfDisplayPartsExist() {
if (displayParts.length) {
displayParts.push(ts.lineBreakPart());
@@ -74117,6 +79993,7 @@ var ts;
displayParts.push(ts.punctuationPart(19 /* CloseParenToken */));
}
documentation = signature.getDocumentationComment();
+ tags = signature.getJsDocTags();
}
function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) {
var typeParameterParts = ts.mapToDisplayParts(function (writer) {
@@ -74132,16 +80009,16 @@ var ts;
}
return ts.forEach(symbol.declarations, function (declaration) {
// Function expressions are local
- if (declaration.kind === 184 /* FunctionExpression */) {
+ if (declaration.kind === 185 /* FunctionExpression */) {
return true;
}
- if (declaration.kind !== 223 /* VariableDeclaration */ && declaration.kind !== 225 /* FunctionDeclaration */) {
+ if (declaration.kind !== 225 /* VariableDeclaration */ && declaration.kind !== 227 /* FunctionDeclaration */) {
return false;
}
// If the parent is not sourceFile or module block it is local variable
- for (var parent_20 = declaration.parent; !ts.isFunctionBlock(parent_20); parent_20 = parent_20.parent) {
+ for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
// Reached source file or module block
- if (parent_20.kind === 261 /* SourceFile */ || parent_20.kind === 231 /* ModuleBlock */) {
+ if (parent.kind === 264 /* SourceFile */ || parent.kind === 233 /* ModuleBlock */) {
return false;
}
}
@@ -74194,7 +80071,7 @@ var ts;
sourceFile.moduleName = transpileOptions.moduleName;
}
if (transpileOptions.renamedDependencies) {
- sourceFile.renamedDependencies = ts.createMap(transpileOptions.renamedDependencies);
+ sourceFile.renamedDependencies = ts.createMapFromTemplate(transpileOptions.renamedDependencies);
}
var newLine = ts.getNewLineCharacter(options);
// Output
@@ -74246,13 +80123,14 @@ var ts;
ts.transpile = transpile;
var commandLineOptionsStringToEnum;
/** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */
+ /*@internal*/
function fixupCompilerOptions(options, diagnostics) {
// Lazily create this value to fix module loading errors.
commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) {
- return typeof o.type === "object" && !ts.forEachProperty(o.type, function (v) { return typeof v !== "number"; });
+ return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.clone(options);
- var _loop_4 = function (opt) {
+ var _loop_5 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -74263,7 +80141,7 @@ var ts;
options[opt.name] = ts.parseCustomTypeOption(opt, value, diagnostics);
}
else {
- if (!ts.forEachProperty(opt.type, function (v) { return v === value; })) {
+ if (!ts.forEachEntry(opt.type, function (v) { return v === value; })) {
// Supplied value isn't a valid enum value.
diagnostics.push(ts.createCompilerDiagnosticForInvalidCustomType(opt));
}
@@ -74271,10 +80149,11 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_4(opt);
+ _loop_5(opt);
}
return options;
}
+ ts.fixupCompilerOptions = fixupCompilerOptions;
})(ts || (ts = {}));
/// <reference path="formatting.ts"/>
/// <reference path="..\..\compiler\scanner.ts"/>
@@ -74298,10 +80177,10 @@ var ts;
ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
})(ScanAction || (ScanAction = {}));
- function getFormattingScanner(sourceFile, startPos, endPos) {
+ function getFormattingScanner(text, languageVariant, startPos, endPos) {
ts.Debug.assert(scanner === undefined, "Scanner should be undefined");
- scanner = sourceFile.languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner;
- scanner.setText(sourceFile.text);
+ scanner = languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner;
+ scanner.setText(text);
scanner.setTextPos(startPos);
var wasNewLine = true;
var leadingTrivia;
@@ -74379,10 +80258,10 @@ var ts;
function shouldRescanJsxIdentifier(node) {
if (node.parent) {
switch (node.parent.kind) {
- case 250 /* JsxAttribute */:
- case 248 /* JsxOpeningElement */:
- case 249 /* JsxClosingElement */:
- case 247 /* JsxSelfClosingElement */:
+ case 252 /* JsxAttribute */:
+ case 250 /* JsxOpeningElement */:
+ case 251 /* JsxClosingElement */:
+ case 249 /* JsxSelfClosingElement */:
return node.kind === 70 /* Identifier */;
}
}
@@ -74503,8 +80382,8 @@ var ts;
}
function isOnToken() {
ts.Debug.assert(scanner !== undefined);
- var current = (lastTokenInfo && lastTokenInfo.token.kind) || scanner.getToken();
- var startPos = (lastTokenInfo && lastTokenInfo.token.pos) || scanner.getStartPos();
+ var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken();
+ var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos();
return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current);
}
// when containing node in the tree is token
@@ -74794,11 +80673,11 @@ var ts;
this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
// Space after }.
- this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */));
+ this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared.TokenRange.FromRange(0 /* FirstToken */, 141 /* LastToken */, [19 /* CloseParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */));
// Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied
this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 81 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* CloseBraceToken */, 105 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
- this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([19 /* CloseParenToken */, 21 /* CloseBracketToken */, 25 /* CommaToken */, 24 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
+ this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([21 /* CloseBracketToken */, 25 /* CommaToken */, 24 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
// No space for dot
this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 22 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(22 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
@@ -74815,10 +80694,10 @@ var ts;
this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([19 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 80 /* DoKeyword */, 101 /* TryKeyword */, 86 /* FinallyKeyword */, 81 /* ElseKeyword */]);
this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */);
// Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}.
- this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */));
- this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */));
- this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */));
- this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 8 /* Delete */));
+ this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2 /* Space */));
+ this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsBraceWrappedContext), 2 /* Space */));
+ this.NoSpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
+ this.NoSpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* OpenBraceToken */, 17 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */));
// Insert new line after { and before } in multi-line contexts.
this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */));
@@ -74848,6 +80727,7 @@ var ts;
this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([109 /* LetKeyword */, 75 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */));
this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */));
this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(88 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */));
+ this.SpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 2 /* Space */));
this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */));
this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(104 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */));
this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(95 /* ReturnKeyword */, 24 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
@@ -74858,18 +80738,19 @@ var ts;
this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([101 /* TryKeyword */, 86 /* FinallyKeyword */]), 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
// get x() {}
// set x(val) {}
- this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([124 /* GetKeyword */, 133 /* SetKeyword */]), 70 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */));
+ this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([124 /* GetKeyword */, 134 /* SetKeyword */]), 70 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */));
// Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options.
this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */));
this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */));
// TypeScript-specific higher priority rules
// Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses
+ this.SpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(122 /* ConstructorKeyword */, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(122 /* ConstructorKeyword */, 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
// Use of module as a function call. e.g.: import m2 = module("m2");
this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([127 /* ModuleKeyword */, 131 /* RequireKeyword */]), 18 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
// Add a space around certain TypeScript keywords
- this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([116 /* AbstractKeyword */, 74 /* ClassKeyword */, 123 /* DeclareKeyword */, 78 /* DefaultKeyword */, 82 /* EnumKeyword */, 83 /* ExportKeyword */, 84 /* ExtendsKeyword */, 124 /* GetKeyword */, 107 /* ImplementsKeyword */, 90 /* ImportKeyword */, 108 /* InterfaceKeyword */, 127 /* ModuleKeyword */, 128 /* NamespaceKeyword */, 111 /* PrivateKeyword */, 113 /* PublicKeyword */, 112 /* ProtectedKeyword */, 133 /* SetKeyword */, 114 /* StaticKeyword */, 136 /* TypeKeyword */, 138 /* FromKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
- this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([84 /* ExtendsKeyword */, 107 /* ImplementsKeyword */, 138 /* FromKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
+ this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([116 /* AbstractKeyword */, 74 /* ClassKeyword */, 123 /* DeclareKeyword */, 78 /* DefaultKeyword */, 82 /* EnumKeyword */, 83 /* ExportKeyword */, 84 /* ExtendsKeyword */, 124 /* GetKeyword */, 107 /* ImplementsKeyword */, 90 /* ImportKeyword */, 108 /* InterfaceKeyword */, 127 /* ModuleKeyword */, 128 /* NamespaceKeyword */, 111 /* PrivateKeyword */, 113 /* PublicKeyword */, 112 /* ProtectedKeyword */, 130 /* ReadonlyKeyword */, 134 /* SetKeyword */, 114 /* StaticKeyword */, 137 /* TypeKeyword */, 139 /* FromKeyword */, 126 /* KeyOfKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
+ this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([84 /* ExtendsKeyword */, 107 /* ImplementsKeyword */, 139 /* FromKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
// Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 16 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */));
// Lambda expressions
@@ -74889,7 +80770,7 @@ var ts;
// decorators
this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 56 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 2 /* Space */));
this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(56 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
- this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([116 /* AbstractKeyword */, 70 /* Identifier */, 83 /* ExportKeyword */, 78 /* DefaultKeyword */, 74 /* ClassKeyword */, 114 /* StaticKeyword */, 113 /* PublicKeyword */, 111 /* PrivateKeyword */, 112 /* ProtectedKeyword */, 124 /* GetKeyword */, 133 /* SetKeyword */, 20 /* OpenBracketToken */, 38 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */));
+ this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([116 /* AbstractKeyword */, 70 /* Identifier */, 83 /* ExportKeyword */, 78 /* DefaultKeyword */, 74 /* ClassKeyword */, 114 /* StaticKeyword */, 113 /* PublicKeyword */, 111 /* PrivateKeyword */, 112 /* ProtectedKeyword */, 124 /* GetKeyword */, 134 /* SetKeyword */, 20 /* OpenBracketToken */, 38 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */));
this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(88 /* FunctionKeyword */, 38 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */));
this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(38 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([70 /* Identifier */, 18 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */));
this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(115 /* YieldKeyword */, 38 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */));
@@ -74905,6 +80786,8 @@ var ts;
this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement = new formatting.Rule(formatting.RuleDescriptor.create1(40 /* SlashToken */, 28 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxSelfClosingElementContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
this.NoSpaceBeforeEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 57 /* EqualsToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
this.NoSpaceAfterEqualInJsxAttribute = new formatting.Rule(formatting.RuleDescriptor.create3(57 /* EqualsToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsJsxAttributeContext, Rules.IsNonJsxSameLineTokenContext), 8 /* Delete */));
+ // No space before non-null assertion operator
+ this.NoSpaceBeforeNonNullAssertionOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 50 /* ExclamationToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNonNullAssertionContext), 8 /* Delete */));
// These rules are higher in priority than user-configurable rules.
this.HighPriorityCommonRules = [
this.IgnoreBeforeComment, this.IgnoreAfterLineComment,
@@ -74935,7 +80818,7 @@ var ts;
this.SpaceBeforeJsxAttribute, this.SpaceBeforeSlashInJsxOpeningElement, this.NoSpaceBeforeGreaterThanTokenInJsxOpeningElement,
this.NoSpaceBeforeEqualInJsxAttribute, this.NoSpaceAfterEqualInJsxAttribute,
// TypeScript-specific rules
- this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport,
+ this.NoSpaceAfterModuleImport,
this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords,
this.SpaceAfterModuleName,
this.SpaceBeforeArrow, this.SpaceAfterArrow,
@@ -74950,6 +80833,7 @@ var ts;
this.SpaceBeforeAt,
this.NoSpaceAfterAt,
this.SpaceAfterDecorator,
+ this.NoSpaceBeforeNonNullAssertionOperator
];
// These rules are lower in priority than user-configurable rules.
this.LowPriorityCommonRules = [
@@ -74959,7 +80843,6 @@ var ts;
this.NoSpaceBeforeOpenBracket,
this.NoSpaceAfterCloseBracket,
this.SpaceAfterSemicolon,
- this.NoSpaceBeforeOpenParenInFuncDecl,
this.SpaceBetweenStatements, this.SpaceAfterTryFinally
];
///
@@ -75017,9 +80900,9 @@ var ts;
}
Rules.prototype.getRuleName = function (rule) {
var o = this;
- for (var name_48 in o) {
- if (o[name_48] === rule) {
- return name_48;
+ for (var name in o) {
+ if (o[name] === rule) {
+ return name;
}
}
throw new Error("Unknown rule");
@@ -75028,42 +80911,44 @@ var ts;
/// Contexts
///
Rules.IsForContext = function (context) {
- return context.contextNode.kind === 211 /* ForStatement */;
+ return context.contextNode.kind === 213 /* ForStatement */;
};
Rules.IsNotForContext = function (context) {
return !Rules.IsForContext(context);
};
Rules.IsBinaryOpContext = function (context) {
switch (context.contextNode.kind) {
- case 192 /* BinaryExpression */:
- case 193 /* ConditionalExpression */:
- case 200 /* AsExpression */:
- case 243 /* ExportSpecifier */:
- case 239 /* ImportSpecifier */:
- case 156 /* TypePredicate */:
- case 164 /* UnionType */:
- case 165 /* IntersectionType */:
+ case 193 /* BinaryExpression */:
+ case 194 /* ConditionalExpression */:
+ case 201 /* AsExpression */:
+ case 245 /* ExportSpecifier */:
+ case 241 /* ImportSpecifier */:
+ case 157 /* TypePredicate */:
+ case 165 /* UnionType */:
+ case 166 /* IntersectionType */:
return true;
// equals in binding elements: function foo([[x, y] = [1, 2]])
- case 174 /* BindingElement */:
+ case 175 /* BindingElement */:
// equals in type X = ...
- case 228 /* TypeAliasDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
// equal in import a = module('a');
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
// equal in let a = 0;
- case 223 /* VariableDeclaration */:
+ case 225 /* VariableDeclaration */:
// equal in p = 0;
- case 144 /* Parameter */:
- case 260 /* EnumMember */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 145 /* Parameter */:
+ case 263 /* EnumMember */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
return context.currentTokenSpan.kind === 57 /* EqualsToken */ || context.nextTokenSpan.kind === 57 /* EqualsToken */;
// "in" keyword in for (let x in []) { }
- case 212 /* ForInStatement */:
+ case 214 /* ForInStatement */:
+ // "in" keyword in [P in keyof T]: T[P]
+ case 144 /* TypeParameter */:
return context.currentTokenSpan.kind === 91 /* InKeyword */ || context.nextTokenSpan.kind === 91 /* InKeyword */;
// Technically, "of" is not a binary operator, but format it the same way as "in"
- case 213 /* ForOfStatement */:
- return context.currentTokenSpan.kind === 140 /* OfKeyword */ || context.nextTokenSpan.kind === 140 /* OfKeyword */;
+ case 215 /* ForOfStatement */:
+ return context.currentTokenSpan.kind === 141 /* OfKeyword */ || context.nextTokenSpan.kind === 141 /* OfKeyword */;
}
return false;
};
@@ -75071,7 +80956,7 @@ var ts;
return !Rules.IsBinaryOpContext(context);
};
Rules.IsConditionalOperatorContext = function (context) {
- return context.contextNode.kind === 193 /* ConditionalExpression */;
+ return context.contextNode.kind === 194 /* ConditionalExpression */;
};
Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) {
//// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction.
@@ -75092,6 +80977,9 @@ var ts;
//// * ) and { are on different lines. We only need to format if the block is multiline context. So in this case we format.
return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context);
};
+ Rules.IsBraceWrappedContext = function (context) {
+ return context.contextNode.kind === 173 /* ObjectBindingPattern */ || Rules.IsSingleLineBlockContext(context);
+ };
// This check is done before an open brace in a control construct, a function, or a typescript block declaration
Rules.IsBeforeMultilineBlockContext = function (context) {
return Rules.IsBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine());
@@ -75115,97 +81003,103 @@ var ts;
return true;
}
switch (node.kind) {
- case 204 /* Block */:
- case 232 /* CaseBlock */:
- case 176 /* ObjectLiteralExpression */:
- case 231 /* ModuleBlock */:
+ case 206 /* Block */:
+ case 234 /* CaseBlock */:
+ case 177 /* ObjectLiteralExpression */:
+ case 233 /* ModuleBlock */:
return true;
}
return false;
};
Rules.IsFunctionDeclContext = function (context) {
switch (context.contextNode.kind) {
- case 225 /* FunctionDeclaration */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 227 /* FunctionDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
// case SyntaxKind.MemberFunctionDeclaration:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
// case SyntaxKind.MethodSignature:
- case 153 /* CallSignature */:
- case 184 /* FunctionExpression */:
- case 150 /* Constructor */:
- case 185 /* ArrowFunction */:
+ case 154 /* CallSignature */:
+ case 185 /* FunctionExpression */:
+ case 151 /* Constructor */:
+ case 186 /* ArrowFunction */:
// case SyntaxKind.ConstructorDeclaration:
// case SyntaxKind.SimpleArrowFunctionExpression:
// case SyntaxKind.ParenthesizedArrowFunctionExpression:
- case 227 /* InterfaceDeclaration */:
+ case 229 /* InterfaceDeclaration */:
return true;
}
return false;
};
Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) {
- return context.contextNode.kind === 225 /* FunctionDeclaration */ || context.contextNode.kind === 184 /* FunctionExpression */;
+ return context.contextNode.kind === 227 /* FunctionDeclaration */ || context.contextNode.kind === 185 /* FunctionExpression */;
};
Rules.IsTypeScriptDeclWithBlockContext = function (context) {
return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode);
};
Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) {
switch (node.kind) {
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 227 /* InterfaceDeclaration */:
- case 229 /* EnumDeclaration */:
- case 161 /* TypeLiteral */:
- case 230 /* ModuleDeclaration */:
- case 241 /* ExportDeclaration */:
- case 242 /* NamedExports */:
- case 235 /* ImportDeclaration */:
- case 238 /* NamedImports */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 229 /* InterfaceDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 162 /* TypeLiteral */:
+ case 232 /* ModuleDeclaration */:
+ case 243 /* ExportDeclaration */:
+ case 244 /* NamedExports */:
+ case 237 /* ImportDeclaration */:
+ case 240 /* NamedImports */:
return true;
}
return false;
};
Rules.IsAfterCodeBlockContext = function (context) {
switch (context.currentTokenParent.kind) {
- case 226 /* ClassDeclaration */:
- case 230 /* ModuleDeclaration */:
- case 229 /* EnumDeclaration */:
- case 204 /* Block */:
- case 256 /* CatchClause */:
- case 231 /* ModuleBlock */:
- case 218 /* SwitchStatement */:
+ case 228 /* ClassDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 259 /* CatchClause */:
+ case 233 /* ModuleBlock */:
+ case 220 /* SwitchStatement */:
return true;
+ case 206 /* Block */: {
+ var blockParent = context.currentTokenParent.parent;
+ if (blockParent.kind !== 186 /* ArrowFunction */ &&
+ blockParent.kind !== 185 /* FunctionExpression */) {
+ return true;
+ }
+ }
}
return false;
};
Rules.IsControlDeclContext = function (context) {
switch (context.contextNode.kind) {
- case 208 /* IfStatement */:
- case 218 /* SwitchStatement */:
- case 211 /* ForStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- case 210 /* WhileStatement */:
- case 221 /* TryStatement */:
- case 209 /* DoStatement */:
- case 217 /* WithStatement */:
+ case 210 /* IfStatement */:
+ case 220 /* SwitchStatement */:
+ case 213 /* ForStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ case 212 /* WhileStatement */:
+ case 223 /* TryStatement */:
+ case 211 /* DoStatement */:
+ case 219 /* WithStatement */:
// TODO
// case SyntaxKind.ElseClause:
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return true;
default:
return false;
}
};
Rules.IsObjectContext = function (context) {
- return context.contextNode.kind === 176 /* ObjectLiteralExpression */;
+ return context.contextNode.kind === 177 /* ObjectLiteralExpression */;
};
Rules.IsFunctionCallContext = function (context) {
- return context.contextNode.kind === 179 /* CallExpression */;
+ return context.contextNode.kind === 180 /* CallExpression */;
};
Rules.IsNewContext = function (context) {
- return context.contextNode.kind === 180 /* NewExpression */;
+ return context.contextNode.kind === 181 /* NewExpression */;
};
Rules.IsFunctionCallOrNewContext = function (context) {
return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context);
@@ -75217,25 +81111,25 @@ var ts;
return context.nextTokenSpan.kind !== 21 /* CloseBracketToken */;
};
Rules.IsArrowFunctionContext = function (context) {
- return context.contextNode.kind === 185 /* ArrowFunction */;
+ return context.contextNode.kind === 186 /* ArrowFunction */;
};
Rules.IsNonJsxSameLineTokenContext = function (context) {
return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */;
};
Rules.IsNonJsxElementContext = function (context) {
- return context.contextNode.kind !== 246 /* JsxElement */;
+ return context.contextNode.kind !== 248 /* JsxElement */;
};
Rules.IsJsxExpressionContext = function (context) {
- return context.contextNode.kind === 252 /* JsxExpression */;
+ return context.contextNode.kind === 255 /* JsxExpression */;
};
Rules.IsNextTokenParentJsxAttribute = function (context) {
- return context.nextTokenParent.kind === 250 /* JsxAttribute */;
+ return context.nextTokenParent.kind === 252 /* JsxAttribute */;
};
Rules.IsJsxAttributeContext = function (context) {
- return context.contextNode.kind === 250 /* JsxAttribute */;
+ return context.contextNode.kind === 252 /* JsxAttribute */;
};
Rules.IsJsxSelfClosingElementContext = function (context) {
- return context.contextNode.kind === 247 /* JsxSelfClosingElement */;
+ return context.contextNode.kind === 249 /* JsxSelfClosingElement */;
};
Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) {
return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context);
@@ -75250,41 +81144,42 @@ var ts;
while (ts.isPartOfExpression(node)) {
node = node.parent;
}
- return node.kind === 145 /* Decorator */;
+ return node.kind === 146 /* Decorator */;
};
Rules.IsStartOfVariableDeclarationList = function (context) {
- return context.currentTokenParent.kind === 224 /* VariableDeclarationList */ &&
+ return context.currentTokenParent.kind === 226 /* VariableDeclarationList */ &&
context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
};
Rules.IsNotFormatOnEnter = function (context) {
return context.formattingRequestKind !== 2 /* FormatOnEnter */;
};
Rules.IsModuleDeclContext = function (context) {
- return context.contextNode.kind === 230 /* ModuleDeclaration */;
+ return context.contextNode.kind === 232 /* ModuleDeclaration */;
};
Rules.IsObjectTypeContext = function (context) {
- return context.contextNode.kind === 161 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration;
+ return context.contextNode.kind === 162 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration;
};
Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) {
if (token.kind !== 26 /* LessThanToken */ && token.kind !== 28 /* GreaterThanToken */) {
return false;
}
switch (parent.kind) {
- case 157 /* TypeReference */:
- case 182 /* TypeAssertionExpression */:
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 227 /* InterfaceDeclaration */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
- case 199 /* ExpressionWithTypeArguments */:
+ case 158 /* TypeReference */:
+ case 183 /* TypeAssertionExpression */:
+ case 230 /* TypeAliasDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 229 /* InterfaceDeclaration */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
+ case 200 /* ExpressionWithTypeArguments */:
return true;
default:
return false;
@@ -75295,13 +81190,16 @@ var ts;
Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent);
};
Rules.IsTypeAssertionContext = function (context) {
- return context.contextNode.kind === 182 /* TypeAssertionExpression */;
+ return context.contextNode.kind === 183 /* TypeAssertionExpression */;
};
Rules.IsVoidOpContext = function (context) {
- return context.currentTokenSpan.kind === 104 /* VoidKeyword */ && context.currentTokenParent.kind === 188 /* VoidExpression */;
+ return context.currentTokenSpan.kind === 104 /* VoidKeyword */ && context.currentTokenParent.kind === 189 /* VoidExpression */;
};
Rules.IsYieldOrYieldStarWithOperand = function (context) {
- return context.contextNode.kind === 195 /* YieldExpression */ && context.contextNode.expression !== undefined;
+ return context.contextNode.kind === 196 /* YieldExpression */ && context.contextNode.expression !== undefined;
+ };
+ Rules.IsNonNullAssertionContext = function (context) {
+ return context.contextNode.kind === 202 /* NonNullExpression */;
};
return Rules;
}());
@@ -75325,7 +81223,7 @@ var ts;
return result;
};
RulesMap.prototype.Initialize = function (rules) {
- this.mapRowLength = 140 /* LastToken */ + 1;
+ this.mapRowLength = 141 /* LastToken */ + 1;
this.map = new Array(this.mapRowLength * this.mapRowLength); // new Array<RulesBucket>(this.mapRowLength * this.mapRowLength);
// This array is used only during construction of the rulesbucket in the map
var rulesBucketConstructionStateList = new Array(this.map.length); // new Array<RulesBucketConstructionState>(this.map.length);
@@ -75339,7 +81237,7 @@ var ts;
});
};
RulesMap.prototype.GetRuleBucketIndex = function (row, column) {
- ts.Debug.assert(row <= 140 /* LastKeyword */ && column <= 140 /* LastKeyword */, "Must compute formatting context from tokens");
+ ts.Debug.assert(row <= 141 /* LastKeyword */ && column <= 141 /* LastKeyword */, "Must compute formatting context from tokens");
var rulesBucketIndex = (row * this.mapRowLength) + column;
return rulesBucketIndex;
};
@@ -75520,7 +81418,7 @@ var ts;
}
TokenAllAccess.prototype.GetTokens = function () {
var result = [];
- for (var token = 0 /* FirstToken */; token <= 140 /* LastToken */; token++) {
+ for (var token = 0 /* FirstToken */; token <= 141 /* LastToken */; token++) {
result.push(token);
}
return result;
@@ -75564,9 +81462,9 @@ var ts;
}());
TokenRange.Any = TokenRange.AllTokens();
TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */]));
- TokenRange.Keywords = TokenRange.FromRange(71 /* FirstKeyword */, 140 /* LastKeyword */);
+ TokenRange.Keywords = TokenRange.FromRange(71 /* FirstKeyword */, 141 /* LastKeyword */);
TokenRange.BinaryOperators = TokenRange.FromRange(26 /* FirstBinaryOperator */, 69 /* LastBinaryOperator */);
- TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([91 /* InKeyword */, 92 /* InstanceOfKeyword */, 140 /* OfKeyword */, 117 /* AsKeyword */, 125 /* IsKeyword */]);
+ TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([91 /* InKeyword */, 92 /* InstanceOfKeyword */, 141 /* OfKeyword */, 117 /* AsKeyword */, 125 /* IsKeyword */]);
TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([42 /* PlusPlusToken */, 43 /* MinusMinusToken */, 51 /* TildeToken */, 50 /* ExclamationToken */]);
TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 70 /* Identifier */, 18 /* OpenParenToken */, 20 /* OpenBracketToken */, 16 /* OpenBraceToken */, 98 /* ThisKeyword */, 93 /* NewKeyword */]);
TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 18 /* OpenParenToken */, 98 /* ThisKeyword */, 93 /* NewKeyword */]);
@@ -75574,7 +81472,7 @@ var ts;
TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 18 /* OpenParenToken */, 98 /* ThisKeyword */, 93 /* NewKeyword */]);
TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([70 /* Identifier */, 19 /* CloseParenToken */, 21 /* CloseBracketToken */, 93 /* NewKeyword */]);
TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]);
- TokenRange.TypeNames = TokenRange.FromTokens([70 /* Identifier */, 132 /* NumberKeyword */, 134 /* StringKeyword */, 121 /* BooleanKeyword */, 135 /* SymbolKeyword */, 104 /* VoidKeyword */, 118 /* AnyKeyword */]);
+ TokenRange.TypeNames = TokenRange.FromTokens([70 /* Identifier */, 132 /* NumberKeyword */, 135 /* StringKeyword */, 121 /* BooleanKeyword */, 136 /* SymbolKeyword */, 104 /* VoidKeyword */, 118 /* AnyKeyword */]);
Shared.TokenRange = TokenRange;
})(Shared = formatting.Shared || (formatting.Shared = {}));
})(formatting = ts.formatting || (ts.formatting = {}));
@@ -75610,6 +81508,9 @@ var ts;
RulesProvider.prototype.getRulesMap = function () {
return this.rulesMap;
};
+ RulesProvider.prototype.getFormatOptions = function () {
+ return this.options;
+ };
RulesProvider.prototype.ensureUpToDate = function (options) {
if (!this.options || !ts.compareDataObjects(this.options, options)) {
var activeRules = this.createActiveRules(options);
@@ -75621,6 +81522,12 @@ var ts;
};
RulesProvider.prototype.createActiveRules = function (options) {
var rules = this.globalRules.HighPriorityCommonRules.slice(0);
+ if (options.insertSpaceAfterConstructor) {
+ rules.push(this.globalRules.SpaceAfterConstructor);
+ }
+ else {
+ rules.push(this.globalRules.NoSpaceAfterConstructor);
+ }
if (options.insertSpaceAfterCommaDelimiter) {
rules.push(this.globalRules.SpaceAfterComma);
}
@@ -75701,6 +81608,12 @@ var ts;
rules.push(this.globalRules.NoSpaceBeforeBinaryOperator);
rules.push(this.globalRules.NoSpaceAfterBinaryOperator);
}
+ if (options.insertSpaceBeforeFunctionParenthesis) {
+ rules.push(this.globalRules.SpaceBeforeOpenParenInFuncDecl);
+ }
+ else {
+ rules.push(this.globalRules.NoSpaceBeforeOpenParenInFuncDecl);
+ }
if (options.placeOpenBraceOnNewLineForControlBlocks) {
rules.push(this.globalRules.NewLineBeforeOpenBraceInControl);
}
@@ -75833,17 +81746,17 @@ var ts;
// i.e. parent is class declaration with the list of members and node is one of members.
function isListElement(parent, node) {
switch (parent.kind) {
- case 226 /* ClassDeclaration */:
- case 227 /* InterfaceDeclaration */:
+ case 228 /* ClassDeclaration */:
+ case 229 /* InterfaceDeclaration */:
return ts.rangeContainsRange(parent.members, node);
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
var body = parent.body;
- return body && body.kind === 231 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 261 /* SourceFile */:
- case 204 /* Block */:
- case 231 /* ModuleBlock */:
+ return body && body.kind === 233 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
+ case 264 /* SourceFile */:
+ case 206 /* Block */:
+ case 233 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return ts.rangeContainsRange(parent.block.statements, node);
}
return false;
@@ -75863,9 +81776,9 @@ var ts;
}
}
/** formatting is not applied to ranges that contain parse errors.
- * This function will return a predicate that for a given text range will tell
- * if there are any parse errors that overlap with the range.
- */
+ * This function will return a predicate that for a given text range will tell
+ * if there are any parse errors that overlap with the range.
+ */
function prepareRangeContainsErrorFunction(errors, originalRange) {
if (!errors.length) {
return rangeHasNoErrors;
@@ -75903,10 +81816,10 @@ var ts;
}
}
/**
- * Start of the original range might fall inside the comment - scanner will not yield appropriate results
- * This function will look for token that is located before the start of target range
- * and return its end as start position for the scanner.
- */
+ * Start of the original range might fall inside the comment - scanner will not yield appropriate results
+ * This function will look for token that is located before the start of target range
+ * and return its end as start position for the scanner.
+ */
function getScanStartPosition(enclosingNode, originalRange, sourceFile) {
var start = enclosingNode.getStart(sourceFile);
if (start === originalRange.pos && enclosingNode.end === originalRange.end) {
@@ -75956,14 +81869,21 @@ var ts;
}
return 0;
}
+ /* @internal */
+ function formatNode(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) {
+ var range = { pos: 0, end: sourceFileLike.text.length };
+ return formatSpanWorker(range, node, initialIndentation, delta, formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end), rulesProvider.getFormatOptions(), rulesProvider, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors
+ sourceFileLike);
+ }
+ formatting.formatNode = formatNode;
function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) {
- var rangeContainsError = prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange);
- // formatting context is used by rules provider
- var formattingContext = new formatting.FormattingContext(sourceFile, requestKind);
// find the smallest node that fully wraps the range and compute the initial indentation for the node
var enclosingNode = findEnclosingNode(originalRange, sourceFile);
- var formattingScanner = formatting.getFormattingScanner(sourceFile, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end);
- var initialIndentation = formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options);
+ return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options), getOwnOrInheritedDelta(enclosingNode, options, sourceFile), formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end), options, rulesProvider, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile);
+ }
+ function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, options, rulesProvider, requestKind, rangeContainsError, sourceFile) {
+ // formatting context is used by rules provider
+ var formattingContext = new formatting.FormattingContext(sourceFile, requestKind);
var previousRangeHasError;
var previousRange;
var previousParent;
@@ -75978,13 +81898,12 @@ var ts;
if (enclosingNode.decorators) {
undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line;
}
- var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile);
processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
}
if (!formattingScanner.isOnToken()) {
var leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
if (leadingTrivia) {
- processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined);
+ processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined);
trimTrailingWhitespacesForRemainingRange();
}
}
@@ -75992,12 +81911,12 @@ var ts;
return edits;
// local functions
/** Tries to compute the indentation for a list element.
- * If list element is not in range then
- * function will pick its actual indentation
- * so it can be pushed downstream as inherited indentation.
- * If list element is in the range - its indentation will be equal
- * to inherited indentation from its predecessors.
- */
+ * If list element is not in range then
+ * function will pick its actual indentation
+ * so it can be pushed downstream as inherited indentation.
+ * If list element is in the range - its indentation will be equal
+ * to inherited indentation from its predecessors.
+ */
function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) {
if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) ||
ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) {
@@ -76048,20 +81967,19 @@ var ts;
return node.modifiers[0].kind;
}
switch (node.kind) {
- case 226 /* ClassDeclaration */: return 74 /* ClassKeyword */;
- case 227 /* InterfaceDeclaration */: return 108 /* InterfaceKeyword */;
- case 225 /* FunctionDeclaration */: return 88 /* FunctionKeyword */;
- case 229 /* EnumDeclaration */: return 229 /* EnumDeclaration */;
- case 151 /* GetAccessor */: return 124 /* GetKeyword */;
- case 152 /* SetAccessor */: return 133 /* SetKeyword */;
- case 149 /* MethodDeclaration */:
+ case 228 /* ClassDeclaration */: return 74 /* ClassKeyword */;
+ case 229 /* InterfaceDeclaration */: return 108 /* InterfaceKeyword */;
+ case 227 /* FunctionDeclaration */: return 88 /* FunctionKeyword */;
+ case 231 /* EnumDeclaration */: return 231 /* EnumDeclaration */;
+ case 152 /* GetAccessor */: return 124 /* GetKeyword */;
+ case 153 /* SetAccessor */: return 134 /* SetKeyword */;
+ case 150 /* MethodDeclaration */:
if (node.asteriskToken) {
return 38 /* AsteriskToken */;
- } /*
- fall-through
- */
- case 147 /* PropertyDeclaration */:
- case 144 /* Parameter */:
+ }
+ // falls through
+ case 148 /* PropertyDeclaration */:
+ case 145 /* Parameter */:
return node.name.kind;
}
}
@@ -76091,18 +82009,31 @@ var ts;
// open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent
case 16 /* OpenBraceToken */:
case 17 /* CloseBraceToken */:
- case 20 /* OpenBracketToken */:
- case 21 /* CloseBracketToken */:
case 18 /* OpenParenToken */:
case 19 /* CloseParenToken */:
case 81 /* ElseKeyword */:
case 105 /* WhileKeyword */:
case 56 /* AtToken */:
return indentation;
- default:
- // if token line equals to the line of containing node (this is a first token in the node) - use node indentation
- return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation;
+ case 40 /* SlashToken */:
+ case 28 /* GreaterThanToken */: {
+ if (container.kind === 250 /* JsxOpeningElement */ ||
+ container.kind === 251 /* JsxClosingElement */ ||
+ container.kind === 249 /* JsxSelfClosingElement */) {
+ return indentation;
+ }
+ break;
+ }
+ case 20 /* OpenBracketToken */:
+ case 21 /* CloseBracketToken */: {
+ if (container.kind !== 171 /* MappedType */) {
+ return indentation;
+ }
+ break;
+ }
}
+ // if token line equals to the line of containing node (this is a first token in the node) - use node indentation
+ return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation;
},
getIndentation: function () { return indentation; },
getDelta: function (child) { return getEffectiveDelta(delta, child); },
@@ -76125,7 +82056,7 @@ var ts;
};
function getEffectiveDelta(delta, child) {
// Delta value should be zero when the node explicitly prevents indentation of the child node
- return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0;
+ return formatting.SmartIndenter.nodeWillIndentChild(node, child, /*indentByDefault*/ true) ? delta : 0;
}
}
function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) {
@@ -76158,7 +82089,7 @@ var ts;
if (tokenInfo.token.end > node.end) {
break;
}
- consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation);
+ consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node);
}
function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) {
var childStartPos = child.getStart(sourceFile);
@@ -76192,7 +82123,7 @@ var ts;
// stop when formatting scanner advances past the beginning of the child
break;
}
- consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation);
+ consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node);
}
if (!formattingScanner.isOnToken()) {
return inheritedIndentation;
@@ -76205,11 +82136,11 @@ var ts;
consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
return inheritedIndentation;
}
- var effectiveParentStartLine = child.kind === 145 /* Decorator */ ? childStartLine : undecoratedParentStartLine;
+ var effectiveParentStartLine = child.kind === 146 /* Decorator */ ? childStartLine : undecoratedParentStartLine;
var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta);
childContextNode = node;
- if (isFirstListItem && parent.kind === 175 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) {
+ if (isFirstListItem && parent.kind === 176 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) {
inheritedIndentation = childIndentation.indentation;
}
return inheritedIndentation;
@@ -76232,11 +82163,11 @@ var ts;
startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine);
listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta);
- consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation);
+ consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent);
}
else {
// consume any tokens that precede the list as child elements of 'node' using its indentation scope
- consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation);
+ consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent);
}
}
}
@@ -76254,7 +82185,7 @@ var ts;
// without this check close paren will be interpreted as list end token for function expression which is wrong
if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) {
// consume list end token
- consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation);
+ consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent);
}
}
}
@@ -76461,7 +82392,7 @@ var ts;
}
// shift all parts on the delta size
var delta = indentation - nonWhitespaceColumnInFirstPart.column;
- for (var i = startIndex, len = parts.length; i < len; i++, startLine++) {
+ for (var i = startIndex; i < parts.length; i++, startLine++) {
var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile);
var nonWhitespaceCharacterAndColumn = i === 0
? nonWhitespaceColumnInFirstPart
@@ -76566,12 +82497,12 @@ var ts;
}
function getOpenTokenForList(node, list) {
switch (node.kind) {
- case 150 /* Constructor */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 185 /* ArrowFunction */:
+ case 151 /* Constructor */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 186 /* ArrowFunction */:
if (node.typeParameters === list) {
return 26 /* LessThanToken */;
}
@@ -76579,8 +82510,8 @@ var ts;
return 18 /* OpenParenToken */;
}
break;
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
if (node.typeArguments === list) {
return 26 /* LessThanToken */;
}
@@ -76588,7 +82519,7 @@ var ts;
return 18 /* OpenParenToken */;
}
break;
- case 157 /* TypeReference */:
+ case 158 /* TypeReference */:
if (node.typeArguments === list) {
return 26 /* LessThanToken */;
}
@@ -76668,7 +82599,20 @@ var ts;
(function (Value) {
Value[Value["Unknown"] = -1] = "Unknown";
})(Value || (Value = {}));
- function getIndentation(position, sourceFile, options) {
+ /**
+ * Computed indentation for a given position in source file
+ * @param position - position in file
+ * @param sourceFile - target source file
+ * @param options - set of editor options that control indentation
+ * @param assumeNewLineBeforeCloseBrace - false when getIndentation is called on the text from the real source file.
+ * true - when we need to assume that position is on the newline. This is usefult for codefixes, i.e.
+ * function f() {
+ * |}
+ * when inserting some text after open brace we would like to get the value of indentation as if newline was already there.
+ * However by default indentation at position | will be 0 so 'assumeNewLineBeforeCloseBrace' allows to override this behavior,
+ */
+ function getIndentation(position, sourceFile, options, assumeNewLineBeforeCloseBrace) {
+ if (assumeNewLineBeforeCloseBrace === void 0) { assumeNewLineBeforeCloseBrace = false; }
if (position > sourceFile.text.length) {
return getBaseIndentation(options); // past EOF
}
@@ -76704,7 +82648,7 @@ var ts;
var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile);
return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options);
}
- if (precedingToken.kind === 25 /* CommaToken */ && precedingToken.parent.kind !== 192 /* BinaryExpression */) {
+ if (precedingToken.kind === 25 /* CommaToken */ && precedingToken.parent.kind !== 193 /* BinaryExpression */) {
// previous token is comma that separates items in list - find the previous item and try to derive indentation from it
var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
if (actualIndentation !== -1 /* Unknown */) {
@@ -76720,8 +82664,10 @@ var ts;
while (current) {
if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) {
currentStart = getStartLineAndCharacterForNode(current, sourceFile);
- if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) {
- indentationDelta = 0;
+ var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile);
+ if (nextTokenKind !== 0 /* Unknown */) {
+ // handle cases when codefix is about to be inserted before the close brace
+ indentationDelta = assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0;
}
else {
indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0;
@@ -76827,20 +82773,26 @@ var ts;
// - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
// - parent and child are not on the same line
var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) &&
- (parent.kind === 261 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 264 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options);
}
+ var NextTokenKind;
+ (function (NextTokenKind) {
+ NextTokenKind[NextTokenKind["Unknown"] = 0] = "Unknown";
+ NextTokenKind[NextTokenKind["OpenBrace"] = 1] = "OpenBrace";
+ NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
+ })(NextTokenKind || (NextTokenKind = {}));
function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
var nextToken = ts.findNextToken(precedingToken, current);
if (!nextToken) {
- return false;
+ return 0 /* Unknown */;
}
if (nextToken.kind === 16 /* OpenBraceToken */) {
// open braces are always indented at the parent level
- return true;
+ return 1 /* OpenBrace */;
}
else if (nextToken.kind === 17 /* CloseBraceToken */) {
// close braces are indented at the parent level if they are located on the same line with cursor
@@ -76852,15 +82804,15 @@ var ts;
// class A {
// $}
var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line;
- return lineAtPosition === nextTokenStartLine;
+ return lineAtPosition === nextTokenStartLine ? 2 /* CloseBrace */ : 0 /* Unknown */;
}
- return false;
+ return 0 /* Unknown */;
}
function getStartLineAndCharacterForNode(n, sourceFile) {
return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
}
function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) {
- if (parent.kind === 208 /* IfStatement */ && parent.elseStatement === child) {
+ if (parent.kind === 210 /* IfStatement */ && parent.elseStatement === child) {
var elseKeyword = ts.findChildOfKind(parent, 81 /* ElseKeyword */, sourceFile);
ts.Debug.assert(elseKeyword !== undefined);
var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
@@ -76869,53 +82821,49 @@ var ts;
return false;
}
SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement;
+ function getListIfStartEndIsInListRange(list, start, end) {
+ return list && ts.rangeContainsStartEnd(list, start, end) ? list : undefined;
+ }
function getContainingList(node, sourceFile) {
if (node.parent) {
switch (node.parent.kind) {
- case 157 /* TypeReference */:
- if (node.parent.typeArguments &&
- ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) {
- return node.parent.typeArguments;
- }
- break;
- case 176 /* ObjectLiteralExpression */:
+ case 158 /* TypeReference */:
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd());
+ case 177 /* ObjectLiteralExpression */:
return node.parent.properties;
- case 175 /* ArrayLiteralExpression */:
+ case 176 /* ArrayLiteralExpression */:
return node.parent.elements;
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */: {
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 154 /* CallSignature */:
+ case 151 /* Constructor */:
+ case 160 /* ConstructorType */:
+ case 155 /* ConstructSignature */: {
var start = node.getStart(sourceFile);
- if (node.parent.typeParameters &&
- ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) {
- return node.parent.typeParameters;
- }
- if (ts.rangeContainsStartEnd(node.parent.parameters, start, node.getEnd())) {
- return node.parent.parameters;
- }
- break;
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) ||
+ getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd());
}
- case 180 /* NewExpression */:
- case 179 /* CallExpression */: {
+ case 228 /* ClassDeclaration */:
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd());
+ case 181 /* NewExpression */:
+ case 180 /* CallExpression */: {
var start = node.getStart(sourceFile);
- if (node.parent.typeArguments &&
- ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) {
- return node.parent.typeArguments;
- }
- if (node.parent.arguments &&
- ts.rangeContainsStartEnd(node.parent.arguments, start, node.getEnd())) {
- return node.parent.arguments;
- }
- break;
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) ||
+ getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd());
}
+ case 226 /* VariableDeclarationList */:
+ return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd());
+ case 240 /* NamedImports */:
+ case 244 /* NamedExports */:
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd());
}
}
return undefined;
}
+ SmartIndenter.getContainingList = getContainingList;
function getActualIndentationForListItem(node, sourceFile, options) {
var containingList = getContainingList(node, sourceFile);
return containingList ? getActualIndentationFromList(containingList) : -1 /* Unknown */;
@@ -76930,8 +82878,8 @@ var ts;
if (node.kind === 19 /* CloseParenToken */) {
return -1 /* Unknown */;
}
- if (node.parent && (node.parent.kind === 179 /* CallExpression */ ||
- node.parent.kind === 180 /* NewExpression */) &&
+ if (node.parent && (node.parent.kind === 180 /* CallExpression */ ||
+ node.parent.kind === 181 /* NewExpression */) &&
node.parent.expression !== node) {
var fullCallOrNewExpression = node.parent.expression;
var startingExpression = getStartingExpression(fullCallOrNewExpression);
@@ -76949,10 +82897,10 @@ var ts;
function getStartingExpression(node) {
while (true) {
switch (node.kind) {
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
- case 177 /* PropertyAccessExpression */:
- case 178 /* ElementAccessExpression */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
+ case 178 /* PropertyAccessExpression */:
+ case 179 /* ElementAccessExpression */:
node = node.expression;
break;
default:
@@ -77016,48 +82964,49 @@ var ts;
SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn;
function nodeContentIsAlwaysIndented(kind) {
switch (kind) {
- case 207 /* ExpressionStatement */:
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 227 /* InterfaceDeclaration */:
- case 229 /* EnumDeclaration */:
- case 228 /* TypeAliasDeclaration */:
- case 175 /* ArrayLiteralExpression */:
- case 204 /* Block */:
- case 231 /* ModuleBlock */:
- case 176 /* ObjectLiteralExpression */:
- case 161 /* TypeLiteral */:
- case 163 /* TupleType */:
- case 232 /* CaseBlock */:
- case 254 /* DefaultClause */:
- case 253 /* CaseClause */:
- case 183 /* ParenthesizedExpression */:
- case 177 /* PropertyAccessExpression */:
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
- case 205 /* VariableStatement */:
- case 223 /* VariableDeclaration */:
- case 240 /* ExportAssignment */:
- case 216 /* ReturnStatement */:
- case 193 /* ConditionalExpression */:
- case 173 /* ArrayBindingPattern */:
- case 172 /* ObjectBindingPattern */:
- case 248 /* JsxOpeningElement */:
- case 247 /* JsxSelfClosingElement */:
- case 252 /* JsxExpression */:
- case 148 /* MethodSignature */:
- case 153 /* CallSignature */:
- case 154 /* ConstructSignature */:
- case 144 /* Parameter */:
- case 158 /* FunctionType */:
- case 159 /* ConstructorType */:
- case 166 /* ParenthesizedType */:
- case 181 /* TaggedTemplateExpression */:
- case 189 /* AwaitExpression */:
- case 242 /* NamedExports */:
- case 238 /* NamedImports */:
- case 243 /* ExportSpecifier */:
- case 239 /* ImportSpecifier */:
+ case 209 /* ExpressionStatement */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 229 /* InterfaceDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
+ case 176 /* ArrayLiteralExpression */:
+ case 206 /* Block */:
+ case 233 /* ModuleBlock */:
+ case 177 /* ObjectLiteralExpression */:
+ case 162 /* TypeLiteral */:
+ case 171 /* MappedType */:
+ case 164 /* TupleType */:
+ case 234 /* CaseBlock */:
+ case 257 /* DefaultClause */:
+ case 256 /* CaseClause */:
+ case 184 /* ParenthesizedExpression */:
+ case 178 /* PropertyAccessExpression */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
+ case 207 /* VariableStatement */:
+ case 225 /* VariableDeclaration */:
+ case 242 /* ExportAssignment */:
+ case 218 /* ReturnStatement */:
+ case 194 /* ConditionalExpression */:
+ case 174 /* ArrayBindingPattern */:
+ case 173 /* ObjectBindingPattern */:
+ case 250 /* JsxOpeningElement */:
+ case 249 /* JsxSelfClosingElement */:
+ case 255 /* JsxExpression */:
+ case 149 /* MethodSignature */:
+ case 154 /* CallSignature */:
+ case 155 /* ConstructSignature */:
+ case 145 /* Parameter */:
+ case 159 /* FunctionType */:
+ case 160 /* ConstructorType */:
+ case 167 /* ParenthesizedType */:
+ case 182 /* TaggedTemplateExpression */:
+ case 190 /* AwaitExpression */:
+ case 244 /* NamedExports */:
+ case 240 /* NamedImports */:
+ case 245 /* ExportSpecifier */:
+ case 241 /* ImportSpecifier */:
return true;
}
return false;
@@ -77066,27 +83015,27 @@ var ts;
function nodeWillIndentChild(parent, child, indentByDefault) {
var childKind = child ? child.kind : 0 /* Unknown */;
switch (parent.kind) {
- case 209 /* DoStatement */:
- case 210 /* WhileStatement */:
- case 212 /* ForInStatement */:
- case 213 /* ForOfStatement */:
- case 211 /* ForStatement */:
- case 208 /* IfStatement */:
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 149 /* MethodDeclaration */:
- case 185 /* ArrowFunction */:
- case 150 /* Constructor */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- return childKind !== 204 /* Block */;
- case 241 /* ExportDeclaration */:
- return childKind !== 242 /* NamedExports */;
- case 235 /* ImportDeclaration */:
- return childKind !== 236 /* ImportClause */ ||
- (child.namedBindings && child.namedBindings.kind !== 238 /* NamedImports */);
- case 246 /* JsxElement */:
- return childKind !== 249 /* JsxClosingElement */;
+ case 211 /* DoStatement */:
+ case 212 /* WhileStatement */:
+ case 214 /* ForInStatement */:
+ case 215 /* ForOfStatement */:
+ case 213 /* ForStatement */:
+ case 210 /* IfStatement */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 150 /* MethodDeclaration */:
+ case 186 /* ArrowFunction */:
+ case 151 /* Constructor */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ return childKind !== 206 /* Block */;
+ case 243 /* ExportDeclaration */:
+ return childKind !== 244 /* NamedExports */;
+ case 237 /* ImportDeclaration */:
+ return childKind !== 238 /* ImportClause */ ||
+ (child.namedBindings && child.namedBindings.kind !== 240 /* NamedImports */);
+ case 248 /* JsxElement */:
+ return childKind !== 251 /* JsxClosingElement */;
}
// No explicit rule for given nodes so the result will follow the default value argument
return indentByDefault;
@@ -77105,9 +83054,588 @@ var ts;
/* @internal */
var ts;
(function (ts) {
+ var textChanges;
+ (function (textChanges) {
+ /**
+ * Currently for simplicity we store recovered positions on the node itself.
+ * It can be changed to side-table later if we decide that current design is too invasive.
+ */
+ function getPos(n) {
+ return n["__pos"];
+ }
+ function setPos(n, pos) {
+ n["__pos"] = pos;
+ }
+ function getEnd(n) {
+ return n["__end"];
+ }
+ function setEnd(n, end) {
+ n["__end"] = end;
+ }
+ var Position;
+ (function (Position) {
+ Position[Position["FullStart"] = 0] = "FullStart";
+ Position[Position["Start"] = 1] = "Start";
+ })(Position = textChanges.Position || (textChanges.Position = {}));
+ function skipWhitespacesAndLineBreaks(text, start) {
+ return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ }
+ function hasCommentsBeforeLineBreak(text, start) {
+ var i = start;
+ while (i < text.length) {
+ var ch = text.charCodeAt(i);
+ if (ts.isWhiteSpaceSingleLine(ch)) {
+ i++;
+ continue;
+ }
+ return ch === 47 /* slash */;
+ }
+ return false;
+ }
+ function getSeparatorCharacter(separator) {
+ return ts.tokenToString(separator.kind);
+ }
+ textChanges.getSeparatorCharacter = getSeparatorCharacter;
+ function getAdjustedStartPosition(sourceFile, node, options, position) {
+ if (options.useNonAdjustedStartPosition) {
+ return node.getFullStart();
+ }
+ var fullStart = node.getFullStart();
+ var start = node.getStart(sourceFile);
+ if (fullStart === start) {
+ return start;
+ }
+ var fullStartLine = ts.getLineStartPositionForPosition(fullStart, sourceFile);
+ var startLine = ts.getLineStartPositionForPosition(start, sourceFile);
+ if (startLine === fullStartLine) {
+ // full start and start of the node are on the same line
+ // a, b;
+ // ^ ^
+ // | start
+ // fullstart
+ // when b is replaced - we usually want to keep the leading trvia
+ // when b is deleted - we delete it
+ return position === Position.Start ? start : fullStart;
+ }
+ // get start position of the line following the line that contains fullstart position
+ var adjustedStartPosition = ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, fullStartLine) + 1, sourceFile);
+ // skip whitespaces/newlines
+ adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition);
+ return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
+ }
+ textChanges.getAdjustedStartPosition = getAdjustedStartPosition;
+ function getAdjustedEndPosition(sourceFile, node, options) {
+ if (options.useNonAdjustedEndPosition) {
+ return node.getEnd();
+ }
+ var end = node.getEnd();
+ var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
+ // check if last character before newPos is linebreak
+ // if yes - considered all skipped trivia to be trailing trivia of the node
+ return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
+ ? newEnd
+ : end;
+ }
+ textChanges.getAdjustedEndPosition = getAdjustedEndPosition;
+ /**
+ * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element
+ */
+ function isSeparator(node, candidate) {
+ return candidate && node.parent && (candidate.kind === 25 /* CommaToken */ || (candidate.kind === 24 /* SemicolonToken */ && node.parent.kind === 177 /* ObjectLiteralExpression */));
+ }
+ function spaces(count) {
+ var s = "";
+ for (var i = 0; i < count; i++) {
+ s += " ";
+ }
+ return s;
+ }
+ var ChangeTracker = (function () {
+ function ChangeTracker(newLine, rulesProvider, validator) {
+ this.newLine = newLine;
+ this.rulesProvider = rulesProvider;
+ this.validator = validator;
+ this.changes = [];
+ this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine });
+ }
+ ChangeTracker.fromCodeFixContext = function (context) {
+ return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.rulesProvider);
+ };
+ ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) {
+ if (options === void 0) { options = {}; }
+ var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart);
+ var endPosition = getAdjustedEndPosition(sourceFile, node, options);
+ this.changes.push({ sourceFile: sourceFile, options: options, range: { pos: startPosition, end: endPosition } });
+ return this;
+ };
+ ChangeTracker.prototype.deleteRange = function (sourceFile, range) {
+ this.changes.push({ sourceFile: sourceFile, range: range });
+ return this;
+ };
+ ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) {
+ if (options === void 0) { options = {}; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
+ var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
+ this.changes.push({ sourceFile: sourceFile, options: options, range: { pos: startPosition, end: endPosition } });
+ return this;
+ };
+ ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) {
+ var containingList = ts.formatting.SmartIndenter.getContainingList(node, sourceFile);
+ if (!containingList) {
+ ts.Debug.fail("node is not a list element");
+ return this;
+ }
+ var index = containingList.indexOf(node);
+ if (index < 0) {
+ return this;
+ }
+ if (containingList.length === 1) {
+ this.deleteNode(sourceFile, node);
+ return this;
+ }
+ if (index !== containingList.length - 1) {
+ var nextToken = ts.getTokenAtPosition(sourceFile, node.end);
+ if (nextToken && isSeparator(node, nextToken)) {
+ // find first non-whitespace position in the leading trivia of the node
+ var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ var nextElement = containingList[index + 1];
+ /// find first non-whitespace position in the leading trivia of the next node
+ var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ // shift next node so its first non-whitespace position will be moved to the first non-whitespace position of the deleted node
+ this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
+ }
+ }
+ else {
+ var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end);
+ if (previousToken && isSeparator(node, previousToken)) {
+ this.deleteNodeRange(sourceFile, previousToken, node);
+ }
+ }
+ return this;
+ };
+ ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
+ if (options === void 0) { options = {}; }
+ this.changes.push({ sourceFile: sourceFile, range: range, options: options, node: newNode });
+ return this;
+ };
+ ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
+ if (options === void 0) { options = {}; }
+ var startPosition = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start);
+ var endPosition = getAdjustedEndPosition(sourceFile, oldNode, options);
+ this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: endPosition } });
+ return this;
+ };
+ ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
+ if (options === void 0) { options = {}; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start);
+ var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
+ this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: endPosition } });
+ return this;
+ };
+ ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) {
+ if (options === void 0) { options = {}; }
+ this.changes.push({ sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } });
+ return this;
+ };
+ ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, options) {
+ if (options === void 0) { options = {}; }
+ var startPosition = getAdjustedStartPosition(sourceFile, before, options, Position.Start);
+ this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: startPosition, end: startPosition } });
+ return this;
+ };
+ ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode, options) {
+ if (options === void 0) { options = {}; }
+ if ((ts.isStatementButNotDeclaration(after)) ||
+ after.kind === 148 /* PropertyDeclaration */ ||
+ after.kind === 147 /* PropertySignature */ ||
+ after.kind === 149 /* MethodSignature */) {
+ // check if previous statement ends with semicolon
+ // if not - insert semicolon to preserve the code from changing the meaning due to ASI
+ if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) {
+ this.changes.push({
+ sourceFile: sourceFile,
+ options: {},
+ range: { pos: after.end, end: after.end },
+ node: ts.createToken(24 /* SemicolonToken */)
+ });
+ }
+ }
+ var endPosition = getAdjustedEndPosition(sourceFile, after, options);
+ this.changes.push({ sourceFile: sourceFile, options: options, useIndentationFromFile: true, node: newNode, range: { pos: endPosition, end: endPosition } });
+ return this;
+ };
+ /**
+ * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
+ * i.e. arguments in arguments lists, parameters in parameter lists etc.
+ * Note that separators are part of the node in statements and class elements.
+ */
+ ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) {
+ var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile);
+ if (!containingList) {
+ ts.Debug.fail("node is not a list element");
+ return this;
+ }
+ var index = containingList.indexOf(after);
+ if (index < 0) {
+ return this;
+ }
+ var end = after.getEnd();
+ if (index !== containingList.length - 1) {
+ // any element except the last one
+ // use next sibling as an anchor
+ var nextToken = ts.getTokenAtPosition(sourceFile, after.end);
+ if (nextToken && isSeparator(after, nextToken)) {
+ // for list
+ // a, b, c
+ // create change for adding 'e' after 'a' as
+ // - find start of next element after a (it is b)
+ // - use this start as start and end position in final change
+ // - build text of change by formatting the text of node + separator + whitespace trivia of b
+ // in multiline case it will work as
+ // a,
+ // b,
+ // c,
+ // result - '*' denotes leading trivia that will be inserted after new text (displayed as '#')
+ // a,*
+ // ***insertedtext<separator>#
+ // ###b,
+ // c,
+ // find line and character of the next element
+ var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart()));
+ // find line and character of the token that precedes next element (usually it is separator)
+ var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end);
+ var prefix = void 0;
+ var startPos = void 0;
+ if (lineAndCharOfNextToken.line === lineAndCharOfNextElement.line) {
+ // next element is located on the same line with separator:
+ // a,$$$$b
+ // ^ ^
+ // | |-next element
+ // |-separator
+ // where $$$ is some leading trivia
+ // for a newly inserted node we'll maintain the same relative position comparing to separator and replace leading trivia with spaces
+ // a, x,$$$$b
+ // ^ ^ ^
+ // | | |-next element
+ // | |-new inserted node padded with spaces
+ // |-separator
+ startPos = nextToken.end;
+ prefix = spaces(lineAndCharOfNextElement.character - lineAndCharOfNextToken.character);
+ }
+ else {
+ // next element is located on different line that separator
+ // let insert position be the beginning of the line that contains next element
+ startPos = ts.getStartPositionOfLine(lineAndCharOfNextElement.line, sourceFile);
+ }
+ this.changes.push({
+ sourceFile: sourceFile,
+ range: { pos: startPos, end: containingList[index + 1].getStart(sourceFile) },
+ node: newNode,
+ useIndentationFromFile: true,
+ options: {
+ prefix: prefix,
+ // write separator and leading trivia of the next element as suffix
+ suffix: "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile))
+ }
+ });
+ }
+ }
+ else {
+ var afterStart = after.getStart(sourceFile);
+ var afterStartLinePosition = ts.getLineStartPositionForPosition(afterStart, sourceFile);
+ var separator = void 0;
+ var multilineList = false;
+ // insert element after the last element in the list that has more than one item
+ // pick the element preceding the after element to:
+ // - pick the separator
+ // - determine if list is a multiline
+ if (containingList.length === 1) {
+ // if list has only one element then we'll format is as multiline if node has comment in trailing trivia, or as singleline otherwise
+ // i.e. var x = 1 // this is x
+ // | new element will be inserted at this position
+ separator = 25 /* CommaToken */;
+ }
+ else {
+ // element has more than one element, pick separator from the list
+ var tokenBeforeInsertPosition = ts.findPrecedingToken(after.pos, sourceFile);
+ separator = isSeparator(after, tokenBeforeInsertPosition) ? tokenBeforeInsertPosition.kind : 25 /* CommaToken */;
+ // determine if list is multiline by checking lines of after element and element that precedes it.
+ var afterMinusOneStartLinePosition = ts.getLineStartPositionForPosition(containingList[index - 1].getStart(sourceFile), sourceFile);
+ multilineList = afterMinusOneStartLinePosition !== afterStartLinePosition;
+ }
+ if (hasCommentsBeforeLineBreak(sourceFile.text, after.end)) {
+ // in this case we'll always treat containing list as multiline
+ multilineList = true;
+ }
+ if (multilineList) {
+ // insert separator immediately following the 'after' node to preserve comments in trailing trivia
+ this.changes.push({
+ sourceFile: sourceFile,
+ range: { pos: end, end: end },
+ node: ts.createToken(separator),
+ options: {}
+ });
+ // use the same indentation as 'after' item
+ var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.rulesProvider.getFormatOptions());
+ // insert element before the line break on the line that contains 'after' element
+ var insertPos = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ false);
+ if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) {
+ insertPos--;
+ }
+ this.changes.push({
+ sourceFile: sourceFile,
+ range: { pos: insertPos, end: insertPos },
+ node: newNode,
+ options: { indentation: indentation, prefix: this.newLineCharacter }
+ });
+ }
+ else {
+ this.changes.push({
+ sourceFile: sourceFile,
+ range: { pos: end, end: end },
+ node: newNode,
+ options: { prefix: ts.tokenToString(separator) + " " }
+ });
+ }
+ }
+ return this;
+ };
+ ChangeTracker.prototype.getChanges = function () {
+ var _this = this;
+ var changesPerFile = ts.createFileMap();
+ // group changes per file
+ for (var _i = 0, _a = this.changes; _i < _a.length; _i++) {
+ var c = _a[_i];
+ var changesInFile = changesPerFile.get(c.sourceFile.path);
+ if (!changesInFile) {
+ changesPerFile.set(c.sourceFile.path, changesInFile = []);
+ }
+ changesInFile.push(c);
+ }
+ // convert changes
+ var fileChangesList = [];
+ changesPerFile.forEachValue(function (path) {
+ var changesInFile = changesPerFile.get(path);
+ var sourceFile = changesInFile[0].sourceFile;
+ var fileTextChanges = { fileName: sourceFile.fileName, textChanges: [] };
+ for (var _i = 0, _a = ChangeTracker.normalize(changesInFile); _i < _a.length; _i++) {
+ var c = _a[_i];
+ fileTextChanges.textChanges.push({
+ span: _this.computeSpan(c, sourceFile),
+ newText: _this.computeNewText(c, sourceFile)
+ });
+ }
+ fileChangesList.push(fileTextChanges);
+ });
+ return fileChangesList;
+ };
+ ChangeTracker.prototype.computeSpan = function (change, _sourceFile) {
+ return ts.createTextSpanFromBounds(change.range.pos, change.range.end);
+ };
+ ChangeTracker.prototype.computeNewText = function (change, sourceFile) {
+ if (!change.node) {
+ // deletion case
+ return "";
+ }
+ var options = change.options || {};
+ var nonFormattedText = getNonformattedText(change.node, sourceFile, this.newLine);
+ if (this.validator) {
+ this.validator(nonFormattedText);
+ }
+ var formatOptions = this.rulesProvider.getFormatOptions();
+ var pos = change.range.pos;
+ var posStartsLine = ts.getLineStartPositionForPosition(pos, sourceFile) === pos;
+ var initialIndentation = change.options.indentation !== undefined
+ ? change.options.indentation
+ : change.useIndentationFromFile
+ ? ts.formatting.SmartIndenter.getIndentation(change.range.pos, sourceFile, formatOptions, posStartsLine || (change.options.prefix === this.newLineCharacter))
+ : 0;
+ var delta = change.options.delta !== undefined
+ ? change.options.delta
+ : ts.formatting.SmartIndenter.shouldIndentChildNode(change.node)
+ ? formatOptions.indentSize
+ : 0;
+ var text = applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, this.rulesProvider);
+ // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line
+ // however keep indentation if it is was forced
+ text = posStartsLine || change.options.indentation !== undefined ? text : text.replace(/^\s+/, "");
+ return (options.prefix || "") + text + (options.suffix || "");
+ };
+ ChangeTracker.normalize = function (changes) {
+ // order changes by start position
+ var normalized = ts.stableSort(changes, function (a, b) { return a.range.pos - b.range.pos; });
+ // verify that change intervals do not overlap, except possibly at end points.
+ for (var i = 0; i < normalized.length - 2; i++) {
+ ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos);
+ }
+ return normalized;
+ };
+ return ChangeTracker;
+ }());
+ textChanges.ChangeTracker = ChangeTracker;
+ function getNonformattedText(node, sourceFile, newLine) {
+ var options = { newLine: newLine, target: sourceFile.languageVersion };
+ var writer = new Writer(ts.getNewLineCharacter(options));
+ var printer = ts.createPrinter(options, writer);
+ printer.writeNode(3 /* Unspecified */, node, sourceFile, writer);
+ return { text: writer.getText(), node: assignPositionsToNode(node) };
+ }
+ textChanges.getNonformattedText = getNonformattedText;
+ function applyFormatting(nonFormattedText, sourceFile, initialIndentation, delta, rulesProvider) {
+ var lineMap = ts.computeLineStarts(nonFormattedText.text);
+ var file = {
+ text: nonFormattedText.text,
+ lineMap: lineMap,
+ getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); }
+ };
+ var changes = ts.formatting.formatNode(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider);
+ return applyChanges(nonFormattedText.text, changes);
+ }
+ textChanges.applyFormatting = applyFormatting;
+ function applyChanges(text, changes) {
+ for (var i = changes.length - 1; i >= 0; i--) {
+ var change = changes[i];
+ text = "" + text.substring(0, change.span.start) + change.newText + text.substring(ts.textSpanEnd(change.span));
+ }
+ return text;
+ }
+ textChanges.applyChanges = applyChanges;
+ function isTrivia(s) {
+ return ts.skipTrivia(s, 0) === s.length;
+ }
+ var nullTransformationContext = {
+ enableEmitNotification: ts.noop,
+ enableSubstitution: ts.noop,
+ endLexicalEnvironment: function () { return undefined; },
+ getCompilerOptions: ts.notImplemented,
+ getEmitHost: ts.notImplemented,
+ getEmitResolver: ts.notImplemented,
+ hoistFunctionDeclaration: ts.noop,
+ hoistVariableDeclaration: ts.noop,
+ isEmitNotificationEnabled: ts.notImplemented,
+ isSubstitutionEnabled: ts.notImplemented,
+ onEmitNode: ts.noop,
+ onSubstituteNode: ts.notImplemented,
+ readEmitHelpers: ts.notImplemented,
+ requestEmitHelper: ts.noop,
+ resumeLexicalEnvironment: ts.noop,
+ startLexicalEnvironment: ts.noop,
+ suspendLexicalEnvironment: ts.noop
+ };
+ function assignPositionsToNode(node) {
+ var visited = ts.visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode);
+ // create proxy node for non synthesized nodes
+ var newNode = ts.nodeIsSynthesized(visited)
+ ? visited
+ : (Proxy.prototype = visited, new Proxy());
+ newNode.pos = getPos(node);
+ newNode.end = getEnd(node);
+ return newNode;
+ function Proxy() { }
+ }
+ function assignPositionsToNodeArray(nodes, visitor, test, start, count) {
+ var visited = ts.visitNodes(nodes, visitor, test, start, count);
+ if (!visited) {
+ return visited;
+ }
+ // clone nodearray if necessary
+ var nodeArray = visited === nodes ? ts.createNodeArray(visited.slice(0)) : visited;
+ nodeArray.pos = getPos(nodes);
+ nodeArray.end = getEnd(nodes);
+ return nodeArray;
+ }
+ var Writer = (function () {
+ function Writer(newLine) {
+ var _this = this;
+ this.lastNonTriviaPosition = 0;
+ this.writer = ts.createTextWriter(newLine);
+ this.onEmitNode = function (hint, node, printCallback) {
+ if (node) {
+ setPos(node, _this.lastNonTriviaPosition);
+ }
+ printCallback(hint, node);
+ if (node) {
+ setEnd(node, _this.lastNonTriviaPosition);
+ }
+ };
+ this.onBeforeEmitNodeArray = function (nodes) {
+ if (nodes) {
+ setPos(nodes, _this.lastNonTriviaPosition);
+ }
+ };
+ this.onAfterEmitNodeArray = function (nodes) {
+ if (nodes) {
+ setEnd(nodes, _this.lastNonTriviaPosition);
+ }
+ };
+ }
+ Writer.prototype.setLastNonTriviaPosition = function (s, force) {
+ if (force || !isTrivia(s)) {
+ this.lastNonTriviaPosition = this.writer.getTextPos();
+ var i = 0;
+ while (ts.isWhiteSpace(s.charCodeAt(s.length - i - 1))) {
+ i++;
+ }
+ // trim trailing whitespaces
+ this.lastNonTriviaPosition -= i;
+ }
+ };
+ Writer.prototype.write = function (s) {
+ this.writer.write(s);
+ this.setLastNonTriviaPosition(s, /*force*/ false);
+ };
+ Writer.prototype.writeTextOfNode = function (text, node) {
+ this.writer.writeTextOfNode(text, node);
+ };
+ Writer.prototype.writeLine = function () {
+ this.writer.writeLine();
+ };
+ Writer.prototype.increaseIndent = function () {
+ this.writer.increaseIndent();
+ };
+ Writer.prototype.decreaseIndent = function () {
+ this.writer.decreaseIndent();
+ };
+ Writer.prototype.getText = function () {
+ return this.writer.getText();
+ };
+ Writer.prototype.rawWrite = function (s) {
+ this.writer.rawWrite(s);
+ this.setLastNonTriviaPosition(s, /*force*/ false);
+ };
+ Writer.prototype.writeLiteral = function (s) {
+ this.writer.writeLiteral(s);
+ this.setLastNonTriviaPosition(s, /*force*/ true);
+ };
+ Writer.prototype.getTextPos = function () {
+ return this.writer.getTextPos();
+ };
+ Writer.prototype.getLine = function () {
+ return this.writer.getLine();
+ };
+ Writer.prototype.getColumn = function () {
+ return this.writer.getColumn();
+ };
+ Writer.prototype.getIndent = function () {
+ return this.writer.getIndent();
+ };
+ Writer.prototype.isAtStartOfLine = function () {
+ return this.writer.isAtStartOfLine();
+ };
+ Writer.prototype.reset = function () {
+ this.writer.reset();
+ this.lastNonTriviaPosition = 0;
+ };
+ return Writer;
+ }());
+ })(textChanges = ts.textChanges || (ts.textChanges = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
var codefix;
(function (codefix) {
- var codeFixes = ts.createMap();
+ var codeFixes = [];
function registerCodeFix(action) {
ts.forEach(action.errorCodes, function (error) {
var fixes = codeFixes[error];
@@ -77142,25 +83670,226 @@ var ts;
(function (ts) {
var codefix;
(function (codefix) {
- function getOpenBraceEnd(constructor, sourceFile) {
- // First token is the open curly, this is where we want to put the 'super' call.
- return constructor.body.getFirstToken(sourceFile).getEnd();
+ codefix.registerCodeFix({
+ errorCodes: [ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code],
+ getCodeActions: getActionForClassLikeIncorrectImplementsInterface
+ });
+ function getActionForClassLikeIncorrectImplementsInterface(context) {
+ var sourceFile = context.sourceFile;
+ var start = context.span.start;
+ var token = ts.getTokenAtPosition(sourceFile, start);
+ var checker = context.program.getTypeChecker();
+ var classDeclaration = ts.getContainingClass(token);
+ if (!classDeclaration) {
+ return undefined;
+ }
+ var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile);
+ var classType = checker.getTypeAtLocation(classDeclaration);
+ var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(classDeclaration);
+ var hasNumericIndexSignature = !!checker.getIndexTypeOfType(classType, 1 /* Number */);
+ var hasStringIndexSignature = !!checker.getIndexTypeOfType(classType, 0 /* String */);
+ var result = [];
+ for (var _i = 0, implementedTypeNodes_2 = implementedTypeNodes; _i < implementedTypeNodes_2.length; _i++) {
+ var implementedTypeNode = implementedTypeNodes_2[_i];
+ // Note that this is ultimately derived from a map indexed by symbol names,
+ // so duplicates cannot occur.
+ var implementedType = checker.getTypeAtLocation(implementedTypeNode);
+ var implementedTypeSymbols = checker.getPropertiesOfType(implementedType);
+ var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); });
+ var newNodes = [];
+ createAndAddMissingIndexSignatureDeclaration(implementedType, 1 /* Number */, hasNumericIndexSignature, newNodes);
+ createAndAddMissingIndexSignatureDeclaration(implementedType, 0 /* String */, hasStringIndexSignature, newNodes);
+ newNodes = newNodes.concat(codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker));
+ var message = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]);
+ if (newNodes.length > 0) {
+ pushAction(result, newNodes, message);
+ }
+ }
+ return result;
+ function createAndAddMissingIndexSignatureDeclaration(type, kind, hasIndexSigOfKind, newNodes) {
+ if (hasIndexSigOfKind) {
+ return;
+ }
+ var indexInfoOfKind = checker.getIndexInfoOfType(type, kind);
+ if (!indexInfoOfKind) {
+ return;
+ }
+ var newIndexSignatureDeclaration = checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration);
+ newNodes.push(newIndexSignatureDeclaration);
+ }
+ function pushAction(result, newNodes, description) {
+ var newAction = {
+ description: description,
+ changes: codefix.newNodesToChanges(newNodes, openBrace, context)
+ };
+ result.push(newAction);
+ }
}
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
codefix.registerCodeFix({
- errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code],
- getCodeActions: function (context) {
- var sourceFile = context.sourceFile;
- var token = ts.getTokenAtPosition(sourceFile, context.span.start);
- if (token.kind !== 122 /* ConstructorKeyword */) {
- return undefined;
+ errorCodes: [ts.Diagnostics.Property_0_does_not_exist_on_type_1.code],
+ getCodeActions: getActionsForAddMissingMember
+ });
+ function getActionsForAddMissingMember(context) {
+ var sourceFile = context.sourceFile;
+ var start = context.span.start;
+ // This is the identifier of the missing property. eg:
+ // this.missing = 1;
+ // ^^^^^^^
+ var token = ts.getTokenAtPosition(sourceFile, start);
+ if (token.kind !== 70 /* Identifier */) {
+ return undefined;
+ }
+ if (!ts.isPropertyAccessExpression(token.parent) || token.parent.expression.kind !== 98 /* ThisKeyword */) {
+ return undefined;
+ }
+ var classMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false);
+ if (!ts.isClassElement(classMemberDeclaration)) {
+ return undefined;
+ }
+ var classDeclaration = classMemberDeclaration.parent;
+ if (!classDeclaration || !ts.isClassLike(classDeclaration)) {
+ return undefined;
+ }
+ var isStatic = ts.hasModifier(classMemberDeclaration, 32 /* Static */);
+ return ts.isInJavaScriptFile(sourceFile) ? getActionsForAddMissingMemberInJavaScriptFile() : getActionsForAddMissingMemberInTypeScriptFile();
+ function getActionsForAddMissingMemberInJavaScriptFile() {
+ var memberName = token.getText();
+ if (isStatic) {
+ if (classDeclaration.kind === 198 /* ClassExpression */) {
+ return undefined;
+ }
+ var className = classDeclaration.name.getText();
+ return [{
+ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [memberName]),
+ changes: [{
+ fileName: sourceFile.fileName,
+ textChanges: [{
+ span: { start: classDeclaration.getEnd(), length: 0 },
+ newText: "" + context.newLineCharacter + className + "." + memberName + " = undefined;" + context.newLineCharacter
+ }]
+ }]
+ }];
}
- var newPosition = getOpenBraceEnd(token.parent, sourceFile);
- return [{
- description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call),
- changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }]
+ else {
+ var classConstructor = ts.getFirstConstructorWithBody(classDeclaration);
+ if (!classConstructor) {
+ return undefined;
+ }
+ return [{
+ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [memberName]),
+ changes: [{
+ fileName: sourceFile.fileName,
+ textChanges: [{
+ span: { start: classConstructor.body.getEnd() - 1, length: 0 },
+ newText: "this." + memberName + " = undefined;" + context.newLineCharacter
+ }]
+ }]
+ }];
+ }
+ }
+ function getActionsForAddMissingMemberInTypeScriptFile() {
+ var typeNode;
+ if (token.parent.parent.kind === 193 /* BinaryExpression */) {
+ var binaryExpression = token.parent.parent;
+ var checker = context.program.getTypeChecker();
+ var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(binaryExpression.right)));
+ typeNode = checker.typeToTypeNode(widenedType, classDeclaration);
+ }
+ typeNode = typeNode || ts.createKeywordTypeNode(118 /* AnyKeyword */);
+ var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile);
+ var property = ts.createProperty(
+ /*decorators*/ undefined,
+ /*modifiers*/ isStatic ? [ts.createToken(114 /* StaticKeyword */)] : undefined, token.getText(sourceFile),
+ /*questionToken*/ undefined, typeNode,
+ /*initializer*/ undefined);
+ var propertyChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context);
+ propertyChangeTracker.insertNodeAfter(sourceFile, openBrace, property, { suffix: context.newLineCharacter });
+ var actions = [{
+ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_declaration_for_missing_property_0), [token.getText()]),
+ changes: propertyChangeTracker.getChanges()
}];
+ if (!isStatic) {
+ var stringTypeNode = ts.createKeywordTypeNode(135 /* StringKeyword */);
+ var indexingParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, "x",
+ /*questionToken*/ undefined, stringTypeNode,
+ /*initializer*/ undefined);
+ var indexSignature = ts.createIndexSignatureDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, [indexingParameter], typeNode);
+ var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context);
+ indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter });
+ actions.push({
+ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_missing_property_0), [token.getText()]),
+ changes: indexSignatureChangeTracker.getChanges()
+ });
+ }
+ return actions;
}
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ codefix.registerCodeFix({
+ errorCodes: [ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code],
+ getCodeActions: getActionForClassLikeMissingAbstractMember
+ });
+ codefix.registerCodeFix({
+ errorCodes: [ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code],
+ getCodeActions: getActionForClassLikeMissingAbstractMember
});
+ function getActionForClassLikeMissingAbstractMember(context) {
+ var sourceFile = context.sourceFile;
+ var start = context.span.start;
+ // This is the identifier in the case of a class declaration
+ // or the class keyword token in the case of a class expression.
+ var token = ts.getTokenAtPosition(sourceFile, start);
+ var checker = context.program.getTypeChecker();
+ if (ts.isClassLike(token.parent)) {
+ var classDeclaration = token.parent;
+ var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration);
+ var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode);
+ // Note that this is ultimately derived from a map indexed by symbol names,
+ // so duplicates cannot occur.
+ var extendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType);
+ var abstractAndNonPrivateExtendsSymbols = extendsSymbols.filter(symbolPointsToNonPrivateAndAbstractMember);
+ var newNodes = codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker);
+ var changes = codefix.newNodesToChanges(newNodes, ts.getOpenBraceOfClassLike(classDeclaration, sourceFile), context);
+ if (changes && changes.length > 0) {
+ return [{
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class),
+ changes: changes
+ }];
+ }
+ }
+ return undefined;
+ }
+ function symbolPointsToNonPrivateAndAbstractMember(symbol) {
+ var decls = symbol.getDeclarations();
+ ts.Debug.assert(!!(decls && decls.length > 0));
+ var flags = ts.getModifierFlags(decls[0]);
+ return !(flags & 8 /* Private */) && !!(flags & 128 /* Abstract */);
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
codefix.registerCodeFix({
errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code],
getCodeActions: function (context) {
@@ -77174,9 +83903,9 @@ var ts;
if (!superCall) {
return undefined;
}
- // figure out if the this access is actuall inside the supercall
+ // figure out if the `this` access is actually inside the supercall
// i.e. super(this.a), since in that case we won't suggest a fix
- if (superCall.expression && superCall.expression.kind == 179 /* CallExpression */) {
+ if (superCall.expression && superCall.expression.kind === 180 /* CallExpression */) {
var arguments_1 = superCall.expression.arguments;
for (var i = 0; i < arguments_1.length; i++) {
if (arguments_1[i].expression === token) {
@@ -77184,23 +83913,15 @@ var ts;
}
}
}
- var newPosition = getOpenBraceEnd(constructor, sourceFile);
- var changes = [{
- fileName: sourceFile.fileName, textChanges: [{
- newText: superCall.getText(sourceFile),
- span: { start: newPosition, length: 0 }
- },
- {
- newText: "",
- span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) }
- }]
- }];
+ var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context);
+ changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter });
+ changeTracker.deleteNode(sourceFile, superCall);
return [{
description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor),
- changes: changes
+ changes: changeTracker.getChanges()
}];
function findSuperCall(n) {
- if (n.kind === 207 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) {
+ if (n.kind === 209 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) {
return n;
}
if (ts.isFunctionLike(n)) {
@@ -77217,6 +83938,265 @@ var ts;
(function (ts) {
var codefix;
(function (codefix) {
+ codefix.registerCodeFix({
+ errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code],
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile;
+ var token = ts.getTokenAtPosition(sourceFile, context.span.start);
+ if (token.kind !== 122 /* ConstructorKeyword */) {
+ return undefined;
+ }
+ var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context);
+ var superCall = ts.createStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray));
+ changeTracker.insertNodeAfter(sourceFile, ts.getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter });
+ return [{
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call),
+ changes: changeTracker.getChanges()
+ }];
+ }
+ });
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ codefix.registerCodeFix({
+ errorCodes: [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code],
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile;
+ var start = context.span.start;
+ var token = ts.getTokenAtPosition(sourceFile, start);
+ var classDeclNode = ts.getContainingClass(token);
+ if (!(token.kind === 70 /* Identifier */ && ts.isClassLike(classDeclNode))) {
+ return undefined;
+ }
+ var heritageClauses = classDeclNode.heritageClauses;
+ if (!(heritageClauses && heritageClauses.length > 0)) {
+ return undefined;
+ }
+ var extendsToken = heritageClauses[0].getFirstToken();
+ if (!(extendsToken && extendsToken.kind === 84 /* ExtendsKeyword */)) {
+ return undefined;
+ }
+ var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context);
+ changeTracker.replaceNode(sourceFile, extendsToken, ts.createToken(107 /* ImplementsKeyword */));
+ // We replace existing keywords with commas.
+ for (var i = 1; i < heritageClauses.length; i++) {
+ var keywordToken = heritageClauses[i].getFirstToken();
+ if (keywordToken) {
+ changeTracker.replaceNode(sourceFile, keywordToken, ts.createToken(25 /* CommaToken */));
+ }
+ }
+ var result = [{
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements),
+ changes: changeTracker.getChanges()
+ }];
+ return result;
+ }
+ });
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ codefix.registerCodeFix({
+ errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code],
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile;
+ var token = ts.getTokenAtPosition(sourceFile, context.span.start);
+ if (token.kind !== 70 /* Identifier */) {
+ return undefined;
+ }
+ var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context);
+ changeTracker.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token));
+ return [{
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable),
+ changes: changeTracker.getChanges()
+ }];
+ }
+ });
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ codefix.registerCodeFix({
+ errorCodes: [
+ ts.Diagnostics._0_is_declared_but_never_used.code,
+ ts.Diagnostics.Property_0_is_declared_but_never_used.code
+ ],
+ getCodeActions: function (context) {
+ var sourceFile = context.sourceFile;
+ var start = context.span.start;
+ var token = ts.getTokenAtPosition(sourceFile, start);
+ // this handles var ["computed"] = 12;
+ if (token.kind === 20 /* OpenBracketToken */) {
+ token = ts.getTokenAtPosition(sourceFile, start + 1);
+ }
+ switch (token.kind) {
+ case 70 /* Identifier */:
+ switch (token.parent.kind) {
+ case 225 /* VariableDeclaration */:
+ switch (token.parent.parent.parent.kind) {
+ case 213 /* ForStatement */:
+ var forStatement = token.parent.parent.parent;
+ var forInitializer = forStatement.initializer;
+ if (forInitializer.declarations.length === 1) {
+ return deleteNode(forInitializer);
+ }
+ else {
+ return deleteNodeInList(token.parent);
+ }
+ case 215 /* ForOfStatement */:
+ var forOfStatement = token.parent.parent.parent;
+ if (forOfStatement.initializer.kind === 226 /* VariableDeclarationList */) {
+ var forOfInitializer = forOfStatement.initializer;
+ return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral());
+ }
+ break;
+ case 214 /* ForInStatement */:
+ // There is no valid fix in the case of:
+ // for .. in
+ return undefined;
+ case 259 /* CatchClause */:
+ var catchClause = token.parent.parent;
+ var parameter = catchClause.variableDeclaration.getChildren()[0];
+ return deleteNode(parameter);
+ default:
+ var variableStatement = token.parent.parent.parent;
+ if (variableStatement.declarationList.declarations.length === 1) {
+ return deleteNode(variableStatement);
+ }
+ else {
+ return deleteNodeInList(token.parent);
+ }
+ }
+ // TODO: #14885
+ // falls through
+ case 144 /* TypeParameter */:
+ var typeParameters = token.parent.parent.typeParameters;
+ if (typeParameters.length === 1) {
+ var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1);
+ if (!previousToken || previousToken.kind !== 26 /* LessThanToken */) {
+ return deleteRange(typeParameters);
+ }
+ var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end);
+ if (!nextToken || nextToken.kind !== 28 /* GreaterThanToken */) {
+ return deleteRange(typeParameters);
+ }
+ return deleteNodeRange(previousToken, nextToken);
+ }
+ else {
+ return deleteNodeInList(token.parent);
+ }
+ case 145 /* Parameter */:
+ var functionDeclaration = token.parent.parent;
+ if (functionDeclaration.parameters.length === 1) {
+ return deleteNode(token.parent);
+ }
+ else {
+ return deleteNodeInList(token.parent);
+ }
+ // handle case where 'import a = A;'
+ case 236 /* ImportEqualsDeclaration */:
+ var importEquals = ts.getAncestor(token, 236 /* ImportEqualsDeclaration */);
+ return deleteNode(importEquals);
+ case 241 /* ImportSpecifier */:
+ var namedImports = token.parent.parent;
+ if (namedImports.elements.length === 1) {
+ // Only 1 import and it is unused. So the entire declaration should be removed.
+ var importSpec = ts.getAncestor(token, 237 /* ImportDeclaration */);
+ return deleteNode(importSpec);
+ }
+ else {
+ // delete import specifier
+ return deleteNodeInList(token.parent);
+ }
+ // handle case where "import d, * as ns from './file'"
+ // or "'import {a, b as ns} from './file'"
+ case 238 /* ImportClause */:
+ var importClause = token.parent;
+ if (!importClause.namedBindings) {
+ var importDecl = ts.getAncestor(importClause, 237 /* ImportDeclaration */);
+ return deleteNode(importDecl);
+ }
+ else {
+ // import |d,| * as ns from './file'
+ var start_4 = importClause.name.getStart(sourceFile);
+ var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end);
+ if (nextToken && nextToken.kind === 25 /* CommaToken */) {
+ // shift first non-whitespace position after comma to the start position of the node
+ return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) });
+ }
+ else {
+ return deleteNode(importClause.name);
+ }
+ }
+ case 239 /* NamespaceImport */:
+ var namespaceImport = token.parent;
+ if (namespaceImport.name === token && !namespaceImport.parent.name) {
+ var importDecl = ts.getAncestor(namespaceImport, 237 /* ImportDeclaration */);
+ return deleteNode(importDecl);
+ }
+ else {
+ var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1);
+ if (previousToken && previousToken.kind === 25 /* CommaToken */) {
+ var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart);
+ return deleteRange({ pos: startPosition, end: namespaceImport.end });
+ }
+ return deleteRange(namespaceImport);
+ }
+ }
+ break;
+ case 148 /* PropertyDeclaration */:
+ case 239 /* NamespaceImport */:
+ return deleteNode(token.parent);
+ }
+ if (ts.isDeclarationName(token)) {
+ return deleteNode(token.parent);
+ }
+ else if (ts.isLiteralComputedPropertyDeclarationName(token)) {
+ return deleteNode(token.parent.parent);
+ }
+ else {
+ return undefined;
+ }
+ function deleteNode(n) {
+ return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNode(sourceFile, n));
+ }
+ function deleteRange(range) {
+ return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteRange(sourceFile, range));
+ }
+ function deleteNodeInList(n) {
+ return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNodeInList(sourceFile, n));
+ }
+ function deleteNodeRange(start, end) {
+ return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).deleteNodeRange(sourceFile, start, end));
+ }
+ function replaceNode(n, newNode) {
+ return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode));
+ }
+ function makeChange(changeTracker) {
+ return [{
+ description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }),
+ changes: changeTracker.getChanges()
+ }];
+ }
+ }
+ });
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
var ModuleSpecifierComparison;
(function (ModuleSpecifierComparison) {
ModuleSpecifierComparison[ModuleSpecifierComparison["Better"] = 0] = "Better";
@@ -77225,18 +84205,19 @@ var ts;
})(ModuleSpecifierComparison || (ModuleSpecifierComparison = {}));
var ImportCodeActionMap = (function () {
function ImportCodeActionMap() {
- this.symbolIdToActionMap = ts.createMap();
+ this.symbolIdToActionMap = [];
}
ImportCodeActionMap.prototype.addAction = function (symbolId, newAction) {
if (!newAction) {
return;
}
- if (!this.symbolIdToActionMap[symbolId]) {
+ var actions = this.symbolIdToActionMap[symbolId];
+ if (!actions) {
this.symbolIdToActionMap[symbolId] = [newAction];
return;
}
if (newAction.kind === "CodeChange") {
- this.symbolIdToActionMap[symbolId].push(newAction);
+ actions.push(newAction);
return;
}
var updatedNewImports = [];
@@ -77249,12 +84230,13 @@ var ts;
}
switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) {
case ModuleSpecifierComparison.Better:
- // the new one is not worth considering if it is a new improt.
+ // the new one is not worth considering if it is a new import.
// However if it is instead a insertion into existing import, the user might want to use
// the module specifier even it is worse by our standards. So keep it.
if (newAction.kind === "NewImport") {
return;
}
+ // falls through
case ModuleSpecifierComparison.Equal:
// the current one is safe. But it is still possible that the new one is worse
// than another existing one. For example, you may have new imports from "./foo/bar"
@@ -77280,8 +84262,8 @@ var ts;
};
ImportCodeActionMap.prototype.getAllActions = function () {
var result = [];
- for (var symbolId in this.symbolIdToActionMap) {
- result = ts.concatenate(result, this.symbolIdToActionMap[symbolId]);
+ for (var key in this.symbolIdToActionMap) {
+ result = ts.concatenate(result, this.symbolIdToActionMap[key]);
}
return result;
};
@@ -77313,7 +84295,11 @@ var ts;
return ImportCodeActionMap;
}());
codefix.registerCodeFix({
- errorCodes: [ts.Diagnostics.Cannot_find_name_0.code],
+ errorCodes: [
+ ts.Diagnostics.Cannot_find_name_0.code,
+ ts.Diagnostics.Cannot_find_namespace_0.code,
+ ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code
+ ],
getCodeActions: function (context) {
var sourceFile = context.sourceFile;
var checker = context.program.getTypeChecker();
@@ -77323,18 +84309,22 @@ var ts;
var name = token.getText();
var symbolIdActionMap = new ImportCodeActionMap();
// this is a module id -> module import declaration map
- var cachedImportDeclarations = ts.createMap();
- var cachedNewImportInsertPosition;
- var allPotentialModules = checker.getAmbientModules();
+ var cachedImportDeclarations = [];
+ var lastImportDeclaration;
+ var currentTokenMeaning = ts.getMeaningFromLocation(token);
+ if (context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) {
+ var symbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(token));
+ return getCodeActionForImport(symbol, /*isDefault*/ false, /*isNamespaceImport*/ true);
+ }
+ var candidateModules = checker.getAmbientModules();
for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) {
var otherSourceFile = allSourceFiles_1[_i];
if (otherSourceFile !== sourceFile && ts.isExternalOrCommonJsModule(otherSourceFile)) {
- allPotentialModules.push(otherSourceFile.symbol);
+ candidateModules.push(otherSourceFile.symbol);
}
}
- var currentTokenMeaning = ts.getMeaningFromLocation(token);
- for (var _a = 0, allPotentialModules_1 = allPotentialModules; _a < allPotentialModules_1.length; _a++) {
- var moduleSymbol = allPotentialModules_1[_a];
+ for (var _a = 0, candidateModules_1 = candidateModules; _a < candidateModules_1.length; _a++) {
+ var moduleSymbol = candidateModules_1[_a];
context.cancellationToken.throwIfCancellationRequested();
// check the default export
var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol);
@@ -77356,8 +84346,9 @@ var ts;
return symbolIdActionMap.getAllActions();
function getImportDeclarations(moduleSymbol) {
var moduleSymbolId = getUniqueSymbolId(moduleSymbol);
- if (cachedImportDeclarations[moduleSymbolId]) {
- return cachedImportDeclarations[moduleSymbolId];
+ var cached = cachedImportDeclarations[moduleSymbolId];
+ if (cached) {
+ return cached;
}
var existingDeclarations = [];
for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
@@ -77372,10 +84363,10 @@ var ts;
function getImportDeclaration(moduleSpecifier) {
var node = moduleSpecifier;
while (node) {
- if (node.kind === 235 /* ImportDeclaration */) {
+ if (node.kind === 237 /* ImportDeclaration */) {
return node;
}
- if (node.kind === 234 /* ImportEqualsDeclaration */) {
+ if (node.kind === 236 /* ImportEqualsDeclaration */) {
return node;
}
node = node.parent;
@@ -77393,7 +84384,7 @@ var ts;
var declarations = symbol.getDeclarations();
return declarations ? ts.some(symbol.declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }) : false;
}
- function getCodeActionForImport(moduleSymbol, isDefault) {
+ function getCodeActionForImport(moduleSymbol, isDefault, isNamespaceImport) {
var existingDeclarations = getImportDeclarations(moduleSymbol);
if (existingDeclarations.length > 0) {
// With an existing import statement, there are more than one actions the user can do.
@@ -77419,11 +84410,11 @@ var ts;
var namespaceImportDeclaration;
var namedImportDeclaration;
var existingModuleSpecifier;
- for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
- var declaration = declarations_11[_i];
- if (declaration.kind === 235 /* ImportDeclaration */) {
+ for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) {
+ var declaration = declarations_14[_i];
+ if (declaration.kind === 237 /* ImportDeclaration */) {
var namedBindings = declaration.importClause && declaration.importClause.namedBindings;
- if (namedBindings && namedBindings.kind === 237 /* NamespaceImport */) {
+ if (namedBindings && namedBindings.kind === 239 /* NamespaceImport */) {
// case:
// import * as ns from "foo"
namespaceImportDeclaration = declaration;
@@ -77447,15 +84438,15 @@ var ts;
if (namespaceImportDeclaration) {
actions.push(getCodeActionForNamespaceImport(namespaceImportDeclaration));
}
- if (namedImportDeclaration && namedImportDeclaration.importClause &&
+ if (!isNamespaceImport && namedImportDeclaration && namedImportDeclaration.importClause &&
(namedImportDeclaration.importClause.name || namedImportDeclaration.importClause.namedBindings)) {
/**
* If the existing import declaration already has a named import list, just
* insert the identifier into that list.
*/
- var textChange = getTextChangeForImportClause(namedImportDeclaration.importClause);
+ var fileTextChanges = getTextChangeForImportClause(namedImportDeclaration.importClause);
var moduleSpecifierWithoutQuotes = ts.stripQuotes(namedImportDeclaration.moduleSpecifier.getText());
- actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], textChange.newText, textChange.span, sourceFile.fileName, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes));
+ actions.push(createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [name, moduleSpecifierWithoutQuotes], fileTextChanges, "InsertingIntoExistingImport", moduleSpecifierWithoutQuotes));
}
else {
// we need to create a new import statement, but the existing module specifier can be reused.
@@ -77463,55 +84454,35 @@ var ts;
}
return actions;
function getModuleSpecifierFromImportEqualsDeclaration(declaration) {
- if (declaration.moduleReference && declaration.moduleReference.kind === 245 /* ExternalModuleReference */) {
+ if (declaration.moduleReference && declaration.moduleReference.kind === 247 /* ExternalModuleReference */) {
return declaration.moduleReference.expression.getText();
}
return declaration.moduleReference.getText();
}
function getTextChangeForImportClause(importClause) {
- var newImportText = isDefault ? "default as " + name : name;
var importList = importClause.namedBindings;
+ var newImportSpecifier = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name));
// case 1:
// original text: import default from "module"
// change to: import default, { name } from "module"
- if (!importList && importClause.name) {
- var start = importClause.name.getEnd();
- return {
- newText: ", { " + newImportText + " }",
- span: { start: start, length: 0 }
- };
- }
// case 2:
// original text: import {} from "module"
// change to: import { name } from "module"
- if (importList.elements.length === 0) {
- var start = importList.getStart();
- return {
- newText: "{ " + newImportText + " }",
- span: { start: start, length: importList.getEnd() - start }
- };
+ if (!importList || importList.elements.length === 0) {
+ var newImportClause = ts.createImportClause(importClause.name, ts.createNamedImports([newImportSpecifier]));
+ return createChangeTracker().replaceNode(sourceFile, importClause, newImportClause).getChanges();
}
- // case 3:
- // original text: import { foo, bar } from "module"
- // change to: import { foo, bar, name } from "module"
- var insertPoint = importList.elements[importList.elements.length - 1].getEnd();
/**
* If the import list has one import per line, preserve that. Otherwise, insert on same line as last element
* import {
* foo
* } from "./module";
*/
- var startLine = ts.getLineOfLocalPosition(sourceFile, importList.getStart());
- var endLine = ts.getLineOfLocalPosition(sourceFile, importList.getEnd());
- var oneImportPerLine = endLine - startLine > importList.elements.length;
- return {
- newText: "," + (oneImportPerLine ? context.newLineCharacter : " ") + newImportText,
- span: { start: insertPoint, length: 0 }
- };
+ return createChangeTracker().insertNodeInListAfter(sourceFile, importList.elements[importList.elements.length - 1], newImportSpecifier).getChanges();
}
function getCodeActionForNamespaceImport(declaration) {
var namespacePrefix;
- if (declaration.kind === 235 /* ImportDeclaration */) {
+ if (declaration.kind === 237 /* ImportDeclaration */) {
namespacePrefix = declaration.importClause.namedBindings.name.getText();
}
else {
@@ -77528,47 +84499,52 @@ var ts;
* namespace instead of altering the import declaration. For example, "foo" would
* become "ns.foo"
*/
- return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], namespacePrefix + ".", { start: token.getStart(), length: 0 }, sourceFile.fileName, "CodeChange");
+ return createCodeAction(ts.Diagnostics.Change_0_to_1, [name, namespacePrefix + "." + name], createChangeTracker().replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), name)).getChanges(), "CodeChange");
}
}
function getCodeActionForNewImport(moduleSpecifier) {
- if (!cachedNewImportInsertPosition) {
+ if (!lastImportDeclaration) {
// insert after any existing imports
- var lastModuleSpecifierEnd = -1;
- for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
- var moduleSpecifier_1 = _a[_i];
- var end = moduleSpecifier_1.getEnd();
- if (!lastModuleSpecifierEnd || end > lastModuleSpecifierEnd) {
- lastModuleSpecifierEnd = end;
+ for (var i = sourceFile.statements.length - 1; i >= 0; i--) {
+ var statement = sourceFile.statements[i];
+ if (statement.kind === 236 /* ImportEqualsDeclaration */ || statement.kind === 237 /* ImportDeclaration */) {
+ lastImportDeclaration = statement;
+ break;
}
}
- cachedNewImportInsertPosition = lastModuleSpecifierEnd > 0 ? sourceFile.getLineEndOfPosition(lastModuleSpecifierEnd) : sourceFile.getStart();
}
var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport());
- var importStatementText = isDefault
- ? "import " + name + " from \"" + moduleSpecifierWithoutQuotes + "\""
- : "import { " + name + " } from \"" + moduleSpecifierWithoutQuotes + "\"";
+ var changeTracker = createChangeTracker();
+ var importClause = isDefault
+ ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined)
+ : isNamespaceImport
+ ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(name)))
+ : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))]));
+ var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes));
+ if (!lastImportDeclaration) {
+ changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter });
+ }
+ else {
+ changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter });
+ }
// if this file doesn't have any import statements, insert an import statement and then insert a new line
// between the only import statement and user code. Otherwise just insert the statement because chances
// are there are already a new line seperating code and import statements.
- var newText = cachedNewImportInsertPosition === sourceFile.getStart()
- ? importStatementText + ";" + context.newLineCharacter + context.newLineCharacter
- : "" + context.newLineCharacter + importStatementText + ";";
- return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], newText, { start: cachedNewImportInsertPosition, length: 0 }, sourceFile.fileName, "NewImport", moduleSpecifierWithoutQuotes);
+ return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes);
function getModuleSpecifierForNewImport() {
- var fileName = sourceFile.path;
- var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().path;
+ var fileName = sourceFile.fileName;
+ var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName;
var sourceDirectory = ts.getDirectoryPath(fileName);
var options = context.program.getCompilerOptions();
return tryGetModuleNameFromAmbientModule() ||
- tryGetModuleNameFromBaseUrl() ||
- tryGetModuleNameFromRootDirs() ||
tryGetModuleNameFromTypeRoots() ||
tryGetModuleNameAsNodeModule() ||
+ tryGetModuleNameFromBaseUrl() ||
+ tryGetModuleNameFromRootDirs() ||
ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory));
function tryGetModuleNameFromAmbientModule() {
- if (moduleSymbol.valueDeclaration.kind !== 261 /* SourceFile */) {
+ if (moduleSymbol.valueDeclaration.kind !== 264 /* SourceFile */) {
return moduleSymbol.name;
}
}
@@ -77576,11 +84552,11 @@ var ts;
if (!options.baseUrl) {
return undefined;
}
- var normalizedBaseUrl = ts.toPath(options.baseUrl, ts.getDirectoryPath(options.baseUrl), getCanonicalFileName);
- var relativeName = tryRemoveParentDirectoryName(moduleFileName, normalizedBaseUrl);
+ var relativeName = getRelativePathIfInDirectory(moduleFileName, options.baseUrl);
if (!relativeName) {
return undefined;
}
+ var relativeNameWithIndex = ts.removeFileExtension(relativeName);
relativeName = removeExtensionAndIndexPostFix(relativeName);
if (options.paths) {
for (var key in options.paths) {
@@ -77600,7 +84576,7 @@ var ts;
return key.replace("\*", matchedStar);
}
}
- else if (pattern === relativeName) {
+ else if (pattern === relativeName || pattern === relativeNameWithIndex) {
return key;
}
}
@@ -77610,9 +84586,8 @@ var ts;
}
function tryGetModuleNameFromRootDirs() {
if (options.rootDirs) {
- var normalizedRootDirs = ts.map(options.rootDirs, function (rootDir) { return ts.toPath(rootDir, /*basePath*/ undefined, getCanonicalFileName); });
- var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, normalizedRootDirs);
- var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, normalizedRootDirs);
+ var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, options.rootDirs);
+ var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, options.rootDirs);
if (normalizedTargetPath !== undefined) {
var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath) : normalizedTargetPath;
return ts.removeFileExtension(relativePath);
@@ -77676,7 +84651,7 @@ var ts;
function getPathRelativeToRootDirs(path, rootDirs) {
for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) {
var rootDir = rootDirs_2[_i];
- var relativeName = tryRemoveParentDirectoryName(path, rootDir);
+ var relativeName = getRelativePathIfInDirectory(path, rootDir);
if (relativeName !== undefined) {
return relativeName;
}
@@ -77690,25 +84665,23 @@ var ts;
}
return fileName;
}
+ function getRelativePathIfInDirectory(path, directoryPath) {
+ var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
+ return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath;
+ }
function getRelativePath(path, directoryPath) {
- var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false);
+ var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath;
}
- function tryRemoveParentDirectoryName(path, parentDirectory) {
- var index = path.indexOf(parentDirectory);
- if (index === 0) {
- return ts.endsWith(parentDirectory, ts.directorySeparator)
- ? path.substring(parentDirectory.length)
- : path.substring(parentDirectory.length + 1);
- }
- return undefined;
- }
}
}
- function createCodeAction(description, diagnosticArgs, newText, span, fileName, kind, moduleSpecifier) {
+ function createChangeTracker() {
+ return ts.textChanges.ChangeTracker.fromCodeFixContext(context);
+ }
+ function createCodeAction(description, diagnosticArgs, changes, kind, moduleSpecifier) {
return {
description: ts.formatMessage.apply(undefined, [undefined, description].concat(diagnosticArgs)),
- changes: [{ fileName: fileName, textChanges: [{ newText: newText, span: span }] }],
+ changes: changes,
kind: kind,
moduleSpecifier: moduleSpecifier
};
@@ -77723,155 +84696,275 @@ var ts;
var codefix;
(function (codefix) {
codefix.registerCodeFix({
- errorCodes: [
- ts.Diagnostics._0_is_declared_but_never_used.code,
- ts.Diagnostics.Property_0_is_declared_but_never_used.code
- ],
- getCodeActions: function (context) {
- var sourceFile = context.sourceFile;
- var start = context.span.start;
- var token = ts.getTokenAtPosition(sourceFile, start);
- // this handles var ["computed"] = 12;
- if (token.kind === 20 /* OpenBracketToken */) {
- token = ts.getTokenAtPosition(sourceFile, start + 1);
- }
- switch (token.kind) {
- case 70 /* Identifier */:
- switch (token.parent.kind) {
- case 223 /* VariableDeclaration */:
- switch (token.parent.parent.parent.kind) {
- case 211 /* ForStatement */:
- var forStatement = token.parent.parent.parent;
- var forInitializer = forStatement.initializer;
- if (forInitializer.declarations.length === 1) {
- return createCodeFix("", forInitializer.pos, forInitializer.end - forInitializer.pos);
- }
- else {
- return removeSingleItem(forInitializer.declarations, token);
- }
- case 213 /* ForOfStatement */:
- var forOfStatement = token.parent.parent.parent;
- if (forOfStatement.initializer.kind === 224 /* VariableDeclarationList */) {
- var forOfInitializer = forOfStatement.initializer;
- return createCodeFix("{}", forOfInitializer.declarations[0].pos, forOfInitializer.declarations[0].end - forOfInitializer.declarations[0].pos);
- }
- break;
- case 212 /* ForInStatement */:
- // There is no valid fix in the case of:
- // for .. in
- return undefined;
- case 256 /* CatchClause */:
- var catchClause = token.parent.parent;
- var parameter = catchClause.variableDeclaration.getChildren()[0];
- return createCodeFix("", parameter.pos, parameter.end - parameter.pos);
- default:
- var variableStatement = token.parent.parent.parent;
- if (variableStatement.declarationList.declarations.length === 1) {
- return createCodeFix("", variableStatement.pos, variableStatement.end - variableStatement.pos);
- }
- else {
- var declarations = variableStatement.declarationList.declarations;
- return removeSingleItem(declarations, token);
- }
- }
- case 143 /* TypeParameter */:
- var typeParameters = token.parent.parent.typeParameters;
- if (typeParameters.length === 1) {
- return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 2);
- }
- else {
- return removeSingleItem(typeParameters, token);
- }
- case 144 /* Parameter */:
- var functionDeclaration = token.parent.parent;
- if (functionDeclaration.parameters.length === 1) {
- return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
- }
- else {
- return removeSingleItem(functionDeclaration.parameters, token);
- }
- // handle case where 'import a = A;'
- case 234 /* ImportEqualsDeclaration */:
- var importEquals = findImportDeclaration(token);
- return createCodeFix("", importEquals.pos, importEquals.end - importEquals.pos);
- case 239 /* ImportSpecifier */:
- var namedImports = token.parent.parent;
- if (namedImports.elements.length === 1) {
- // Only 1 import and it is unused. So the entire declaration should be removed.
- var importSpec = findImportDeclaration(token);
- return createCodeFix("", importSpec.pos, importSpec.end - importSpec.pos);
- }
- else {
- return removeSingleItem(namedImports.elements, token);
- }
- // handle case where "import d, * as ns from './file'"
- // or "'import {a, b as ns} from './file'"
- case 236 /* ImportClause */:
- var importClause = token.parent;
- if (!importClause.namedBindings) {
- var importDecl = findImportDeclaration(importClause);
- return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos);
- }
- else {
- return createCodeFix("", importClause.name.pos, importClause.namedBindings.pos - importClause.name.pos);
- }
- case 237 /* NamespaceImport */:
- var namespaceImport = token.parent;
- if (namespaceImport.name == token && !namespaceImport.parent.name) {
- var importDecl = findImportDeclaration(namespaceImport);
- return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos);
- }
- else {
- var start_4 = namespaceImport.parent.name.end;
- return createCodeFix("", start_4, namespaceImport.parent.namedBindings.end - start_4);
- }
- }
- break;
- case 147 /* PropertyDeclaration */:
- return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
- case 237 /* NamespaceImport */:
- return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
- }
- if (ts.isDeclarationName(token)) {
- return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
- }
- else if (ts.isLiteralComputedPropertyDeclarationName(token)) {
- return createCodeFix("", token.parent.parent.pos, token.parent.parent.end - token.parent.parent.pos);
- }
- else {
- return undefined;
- }
- function findImportDeclaration(token) {
- var importDecl = token;
- while (importDecl.kind != 235 /* ImportDeclaration */ && importDecl.parent) {
- importDecl = importDecl.parent;
- }
- return importDecl;
+ errorCodes: getApplicableDiagnosticCodes(),
+ getCodeActions: getDisableJsDiagnosticsCodeActions
+ });
+ function getApplicableDiagnosticCodes() {
+ var allDiagnostcs = ts.Diagnostics;
+ return Object.keys(allDiagnostcs)
+ .filter(function (d) { return allDiagnostcs[d] && allDiagnostcs[d].category === ts.DiagnosticCategory.Error; })
+ .map(function (d) { return allDiagnostcs[d].code; });
+ }
+ function getIgnoreCommentLocationForLocation(sourceFile, position, newLineCharacter) {
+ var line = ts.getLineAndCharacterOfPosition(sourceFile, position).line;
+ var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile);
+ var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition);
+ // First try to see if we can put the '// @ts-ignore' on the previous line.
+ // We need to make sure that we are not in the middle of a string literal or a comment.
+ // We also want to check if the previous line holds a comment for a node on the next line
+ // if so, we do not want to separate the node from its comment if we can.
+ if (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) {
+ var token = ts.getTouchingToken(sourceFile, startPosition);
+ var tokenLeadingCommnets = ts.getLeadingCommentRangesOfNode(token, sourceFile);
+ if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) {
+ return {
+ span: { start: startPosition, length: 0 },
+ newText: "// @ts-ignore" + newLineCharacter
+ };
}
- function createCodeFix(newText, start, length) {
- return [{
- description: ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_unused_identifiers),
- changes: [{
- fileName: sourceFile.fileName,
- textChanges: [{ newText: newText, span: { start: start, length: length } }]
+ }
+ // If all fails, add an extra new line immediatlly before the error span.
+ return {
+ span: { start: position, length: 0 },
+ newText: (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter
+ };
+ }
+ function getDisableJsDiagnosticsCodeActions(context) {
+ var sourceFile = context.sourceFile, program = context.program, newLineCharacter = context.newLineCharacter, span = context.span;
+ if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
+ return undefined;
+ }
+ return [{
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message),
+ changes: [{
+ fileName: sourceFile.fileName,
+ textChanges: [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)]
+ }]
+ },
+ {
+ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file),
+ changes: [{
+ fileName: sourceFile.fileName,
+ textChanges: [{
+ span: {
+ start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0,
+ length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0
+ },
+ newText: "// @ts-nocheck" + newLineCharacter
}]
- }];
+ }]
+ }];
+ }
+ })(codefix = ts.codefix || (ts.codefix = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var codefix;
+ (function (codefix) {
+ function newNodesToChanges(newNodes, insertAfter, context) {
+ var sourceFile = context.sourceFile;
+ var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context);
+ for (var _i = 0, newNodes_1 = newNodes; _i < newNodes_1.length; _i++) {
+ var newNode = newNodes_1[_i];
+ changeTracker.insertNodeAfter(sourceFile, insertAfter, newNode, { suffix: context.newLineCharacter });
+ }
+ var changes = changeTracker.getChanges();
+ if (!ts.some(changes)) {
+ return changes;
+ }
+ ts.Debug.assert(changes.length === 1);
+ var consolidatedChanges = [{
+ fileName: changes[0].fileName,
+ textChanges: [{
+ span: changes[0].textChanges[0].span,
+ newText: changes[0].textChanges.reduce(function (prev, cur) { return prev + cur.newText; }, "")
+ }]
+ }];
+ return consolidatedChanges;
+ }
+ codefix.newNodesToChanges = newNodesToChanges;
+ /**
+ * Finds members of the resolved type that are missing in the class pointed to by class decl
+ * and generates source code for the missing members.
+ * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for.
+ * @returns Empty string iff there are no member insertions.
+ */
+ function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker) {
+ var classMembers = classDeclaration.symbol.members;
+ var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.getName()); });
+ var newNodes = [];
+ for (var _i = 0, missingMembers_1 = missingMembers; _i < missingMembers_1.length; _i++) {
+ var symbol = missingMembers_1[_i];
+ var newNode = createNewNodeForMemberSymbol(symbol, classDeclaration, checker);
+ if (newNode) {
+ if (Array.isArray(newNode)) {
+ newNodes = newNodes.concat(newNode);
+ }
+ else {
+ newNodes.push(newNode);
+ }
}
- function removeSingleItem(elements, token) {
- if (elements[0] === token.parent) {
- return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos + 1);
+ }
+ return newNodes;
+ }
+ codefix.createMissingMemberNodes = createMissingMemberNodes;
+ /**
+ * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`.
+ */
+ function createNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker) {
+ var declarations = symbol.getDeclarations();
+ if (!(declarations && declarations.length)) {
+ return undefined;
+ }
+ var declaration = declarations[0];
+ // Clone name to remove leading trivia.
+ var name = ts.getSynthesizedClone(declaration.name);
+ var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration));
+ var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined;
+ var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
+ var optional = !!(symbol.flags & 67108864 /* Optional */);
+ switch (declaration.kind) {
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 147 /* PropertySignature */:
+ case 148 /* PropertyDeclaration */:
+ var typeNode = checker.typeToTypeNode(type, enclosingDeclaration);
+ var property = ts.createProperty(
+ /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(54 /* QuestionToken */) : undefined, typeNode,
+ /*initializer*/ undefined);
+ return property;
+ case 149 /* MethodSignature */:
+ case 150 /* MethodDeclaration */:
+ // The signature for the implementation appears as an entry in `signatures` iff
+ // there is only one signature.
+ // If there are overloads and an implementation signature, it appears as an
+ // extra declaration that isn't a signature for `type`.
+ // If there is more than one overload but no implementation signature
+ // (eg: an abstract method or interface declaration), there is a 1-1
+ // correspondence of declarations and signatures.
+ var signatures = checker.getSignaturesOfType(type, 0 /* Call */);
+ if (!ts.some(signatures)) {
+ return undefined;
+ }
+ if (declarations.length === 1) {
+ ts.Debug.assert(signatures.length === 1);
+ var signature = signatures[0];
+ return signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody());
+ }
+ var signatureDeclarations = [];
+ for (var i = 0; i < signatures.length; i++) {
+ var signature = signatures[i];
+ var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration);
+ if (methodDeclaration) {
+ signatureDeclarations.push(methodDeclaration);
+ }
+ }
+ if (declarations.length > signatures.length) {
+ var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]);
+ var methodDeclaration = signatureToMethodDeclaration(signature, enclosingDeclaration, createStubbedMethodBody());
+ if (methodDeclaration) {
+ signatureDeclarations.push(methodDeclaration);
+ }
}
else {
- return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 1);
+ ts.Debug.assert(declarations.length === signatures.length);
+ var methodImplementingSignatures = createMethodImplementingSignatures(signatures, name, optional, modifiers);
+ signatureDeclarations.push(methodImplementingSignatures);
}
+ return signatureDeclarations;
+ default:
+ return undefined;
+ }
+ function signatureToMethodDeclaration(signature, enclosingDeclaration, body) {
+ var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 150 /* MethodDeclaration */, enclosingDeclaration);
+ if (signatureDeclaration) {
+ signatureDeclaration.decorators = undefined;
+ signatureDeclaration.modifiers = modifiers;
+ signatureDeclaration.name = name;
+ signatureDeclaration.questionToken = optional ? ts.createToken(54 /* QuestionToken */) : undefined;
+ signatureDeclaration.body = body;
}
+ return signatureDeclaration;
}
- });
+ }
+ function createMethodImplementingSignatures(signatures, name, optional, modifiers) {
+ /** This is *a* signature with the maximal number of arguments,
+ * such that if there is a "maximal" signature without rest arguments,
+ * this is one of them.
+ */
+ var maxArgsSignature = signatures[0];
+ var minArgumentCount = signatures[0].minArgumentCount;
+ var someSigHasRestParameter = false;
+ for (var i = 0; i < signatures.length; i++) {
+ var sig = signatures[i];
+ minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
+ if (sig.hasRestParameter) {
+ someSigHasRestParameter = true;
+ }
+ if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) {
+ maxArgsSignature = sig;
+ }
+ }
+ var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0);
+ var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.getName(); });
+ var parameters = [];
+ for (var i = 0; i < maxNonRestArgs; i++) {
+ var anyType = ts.createKeywordTypeNode(118 /* AnyKeyword */);
+ var newParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, maxArgsParameterSymbolNames[i],
+ /*questionToken*/ i >= minArgumentCount ? ts.createToken(54 /* QuestionToken */) : undefined, anyType,
+ /*initializer*/ undefined);
+ parameters.push(newParameter);
+ }
+ if (someSigHasRestParameter) {
+ var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(118 /* AnyKeyword */));
+ var restParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, ts.createToken(23 /* DotDotDotToken */), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest",
+ /*questionToken*/ maxNonRestArgs >= minArgumentCount ? ts.createToken(54 /* QuestionToken */) : undefined, anyArrayType,
+ /*initializer*/ undefined);
+ parameters.push(restParameter);
+ }
+ return createStubbedMethod(modifiers, name, optional,
+ /*typeParameters*/ undefined, parameters,
+ /*returnType*/ undefined);
+ }
+ function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) {
+ return ts.createMethodDeclaration(
+ /*decorators*/ undefined, modifiers,
+ /*asteriskToken*/ undefined, name, optional ? ts.createToken(54 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody());
+ }
+ codefix.createStubbedMethod = createStubbedMethod;
+ function createStubbedMethodBody() {
+ return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"),
+ /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.")]))],
+ /*multiline*/ true);
+ }
+ function createVisibilityModifier(flags) {
+ if (flags & 4 /* Public */) {
+ return ts.createToken(113 /* PublicKeyword */);
+ }
+ else if (flags & 16 /* Protected */) {
+ return ts.createToken(112 /* ProtectedKeyword */);
+ }
+ return undefined;
+ }
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
-///<reference path='superFixes.ts' />
-///<reference path='importFixes.ts' />
-///<reference path='unusedIdentifierFixes.ts' />
+/// <reference path="fixClassIncorrectlyImplementsInterface.ts" />
+/// <reference path="fixAddMissingMember.ts" />
+/// <reference path="fixClassDoesntImplementInheritedAbstractMember.ts" />
+/// <reference path="fixClassSuperMustPrecedeThisAccess.ts" />
+/// <reference path="fixConstructorForDerivedNeedSuperCall.ts" />
+/// <reference path="fixExtendsInterfaceBecomesImplements.ts" />
+/// <reference path="fixForgottenThisPropertyAccess.ts" />
+/// <reference path='unusedIdentifierFixes.ts' />
+/// <reference path='importFixes.ts' />
+/// <reference path='disableJsDiagnostics.ts' />
+/// <reference path='helpers.ts' />
/// <reference path="..\compiler\program.ts"/>
/// <reference path="..\compiler\commandLineParser.ts"/>
/// <reference path='types.ts' />
@@ -77883,7 +84976,6 @@ var ts;
/// <reference path='documentRegistry.ts' />
/// <reference path='findAllReferences.ts' />
/// <reference path='goToDefinition.ts' />
-/// <reference path='goToImplementation.ts' />
/// <reference path='jsDoc.ts' />
/// <reference path='jsTyping.ts' />
/// <reference path='navigateTo.ts' />
@@ -77897,14 +84989,15 @@ var ts;
/// <reference path='transpile.ts' />
/// <reference path='formatting\formatting.ts' />
/// <reference path='formatting\smartIndenter.ts' />
-/// <reference path='codefixes\codeFixProvider.ts' />
+/// <reference path='textChanges.ts' />
+/// <reference path='codeFixProvider.ts' />
/// <reference path='codefixes\fixes.ts' />
var ts;
(function (ts) {
/** The version of the language service API */
ts.servicesVersion = "0.5";
function createNode(kind, pos, end, parent) {
- var node = kind >= 141 /* FirstNode */ ? new NodeObject(kind, pos, end) :
+ var node = kind >= 142 /* FirstNode */ ? new NodeObject(kind, pos, end) :
kind === 70 /* Identifier */ ? new IdentifierObject(70 /* Identifier */, pos, end) :
new TokenObject(kind, pos, end);
node.parent = parent;
@@ -77962,11 +85055,11 @@ var ts;
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
- var list = createNode(292 /* SyntaxList */, nodes.pos, nodes.end, this);
+ var list = createNode(293 /* SyntaxList */, nodes.pos, nodes.end, this);
list._children = [];
var pos = nodes.pos;
- for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
- var node = nodes_7[_i];
+ for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) {
+ var node = nodes_9[_i];
if (pos < node.pos) {
pos = this.addSyntheticNodes(list._children, pos, node.pos);
}
@@ -77981,11 +85074,11 @@ var ts;
NodeObject.prototype.createChildren = function (sourceFile) {
var _this = this;
var children;
- if (this.kind >= 141 /* FirstNode */) {
+ if (this.kind >= 142 /* FirstNode */) {
ts.scanner.setText((sourceFile || this.getSourceFile()).text);
children = [];
var pos_3 = this.pos;
- var useJSDocScanner_1 = this.kind >= 278 /* FirstJSDocTagNode */ && this.kind <= 291 /* LastJSDocTagNode */;
+ var useJSDocScanner_1 = this.kind >= 282 /* FirstJSDocTagNode */ && this.kind <= 292 /* LastJSDocTagNode */;
var processNode = function (node) {
var isJSDocTagNode = ts.isJSDocTag(node);
if (!isJSDocTagNode && pos_3 < node.pos) {
@@ -78042,8 +85135,10 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = children[0];
- return child.kind < 141 /* FirstNode */ ? child : child.getFirstToken(sourceFile);
+ var child = ts.find(children, function (kid) { return kid.kind < 266 /* FirstJSDocNode */ || kid.kind > 292 /* LastJSDocNode */; });
+ return child.kind < 142 /* FirstNode */ ?
+ child :
+ child.getFirstToken(sourceFile);
};
NodeObject.prototype.getLastToken = function (sourceFile) {
var children = this.getChildren(sourceFile);
@@ -78051,7 +85146,10 @@ var ts;
if (!child) {
return undefined;
}
- return child.kind < 141 /* FirstNode */ ? child : child.getLastToken(sourceFile);
+ return child.kind < 142 /* FirstNode */ ? child : child.getLastToken(sourceFile);
+ };
+ NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) {
+ return ts.forEachChild(this, cbNode, cbNodeArray);
};
return NodeObject;
}());
@@ -78105,6 +85203,9 @@ var ts;
TokenOrIdentifierObject.prototype.getLastToken = function () {
return undefined;
};
+ TokenOrIdentifierObject.prototype.forEachChild = function () {
+ return undefined;
+ };
return TokenOrIdentifierObject;
}());
var SymbolObject = (function () {
@@ -78127,6 +85228,12 @@ var ts;
}
return this.documentationComment;
};
+ SymbolObject.prototype.getJsDocTags = function () {
+ if (this.tags === undefined) {
+ this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations);
+ }
+ return this.tags;
+ };
return SymbolObject;
}());
var TokenObject = (function (_super) {
@@ -78210,6 +85317,12 @@ var ts;
}
return this.documentationComment;
};
+ SignatureObject.prototype.getJsDocTags = function () {
+ if (this.jsDocTags === undefined) {
+ this.jsDocTags = this.declaration ? ts.JsDoc.getJsDocTagsFromDeclarations([this.declaration]) : [];
+ }
+ return this.jsDocTags;
+ };
return SignatureObject;
}());
var SourceFileObject = (function (_super) {
@@ -78250,17 +85363,21 @@ var ts;
return this.namedDeclarations;
};
SourceFileObject.prototype.computeNamedDeclarations = function () {
- var result = ts.createMap();
+ var result = ts.createMultiMap();
ts.forEachChild(this, visit);
return result;
function addDeclaration(declaration) {
var name = getDeclarationName(declaration);
if (name) {
- ts.multiMapAdd(result, name, declaration);
+ result.add(name, declaration);
}
}
function getDeclarations(name) {
- return result[name] || (result[name] = []);
+ var declarations = result.get(name);
+ if (!declarations) {
+ result.set(name, declarations = []);
+ }
+ return declarations;
}
function getDeclarationName(declaration) {
if (declaration.name) {
@@ -78268,9 +85385,9 @@ var ts;
if (result_7 !== undefined) {
return result_7;
}
- if (declaration.name.kind === 142 /* ComputedPropertyName */) {
+ if (declaration.name.kind === 143 /* ComputedPropertyName */) {
var expr = declaration.name.expression;
- if (expr.kind === 177 /* PropertyAccessExpression */) {
+ if (expr.kind === 178 /* PropertyAccessExpression */) {
return expr.name.text;
}
return getTextOfIdentifierOrLiteral(expr);
@@ -78290,10 +85407,10 @@ var ts;
}
function visit(node) {
switch (node.kind) {
- case 225 /* FunctionDeclaration */:
- case 184 /* FunctionExpression */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
+ case 227 /* FunctionDeclaration */:
+ case 185 /* FunctionExpression */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
var functionDeclaration = node;
var declarationName = getDeclarationName(functionDeclaration);
if (declarationName) {
@@ -78310,35 +85427,35 @@ var ts;
else {
declarations.push(functionDeclaration);
}
- ts.forEachChild(node, visit);
}
+ ts.forEachChild(node, visit);
break;
- case 226 /* ClassDeclaration */:
- case 197 /* ClassExpression */:
- case 227 /* InterfaceDeclaration */:
- case 228 /* TypeAliasDeclaration */:
- case 229 /* EnumDeclaration */:
- case 230 /* ModuleDeclaration */:
- case 234 /* ImportEqualsDeclaration */:
- case 243 /* ExportSpecifier */:
- case 239 /* ImportSpecifier */:
- case 234 /* ImportEqualsDeclaration */:
- case 236 /* ImportClause */:
- case 237 /* NamespaceImport */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 161 /* TypeLiteral */:
+ case 228 /* ClassDeclaration */:
+ case 198 /* ClassExpression */:
+ case 229 /* InterfaceDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 232 /* ModuleDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 245 /* ExportSpecifier */:
+ case 241 /* ImportSpecifier */:
+ case 236 /* ImportEqualsDeclaration */:
+ case 238 /* ImportClause */:
+ case 239 /* NamespaceImport */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 162 /* TypeLiteral */:
addDeclaration(node);
ts.forEachChild(node, visit);
break;
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
// Only consider parameter properties
if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
break;
}
- // fall through
- case 223 /* VariableDeclaration */:
- case 174 /* BindingElement */: {
+ // falls through
+ case 225 /* VariableDeclaration */:
+ case 175 /* BindingElement */: {
var decl = node;
if (ts.isBindingPattern(decl.name)) {
ts.forEachChild(decl.name, visit);
@@ -78347,19 +85464,20 @@ var ts;
if (decl.initializer)
visit(decl.initializer);
}
- case 260 /* EnumMember */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ // falls through
+ case 263 /* EnumMember */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
addDeclaration(node);
break;
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
// Handle named exports case e.g.:
// export {a, b as B} from "mod";
if (node.exportClause) {
ts.forEach(node.exportClause.elements, visit);
}
break;
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
var importClause = node.importClause;
if (importClause) {
// Handle default import case e.g.:
@@ -78371,7 +85489,7 @@ var ts;
// import * as NS from "mod";
// import {a, b as B} from "mod";
if (importClause.namedBindings) {
- if (importClause.namedBindings.kind === 237 /* NamespaceImport */) {
+ if (importClause.namedBindings.kind === 239 /* NamespaceImport */) {
addDeclaration(importClause.namedBindings);
}
else {
@@ -78620,6 +85738,36 @@ var ts;
};
return CancellationTokenObject;
}());
+ /* @internal */
+ /** A cancellation that throttles calls to the host */
+ var ThrottledCancellationToken = (function () {
+ function ThrottledCancellationToken(hostCancellationToken, throttleWaitMilliseconds) {
+ if (throttleWaitMilliseconds === void 0) { throttleWaitMilliseconds = 20; }
+ this.hostCancellationToken = hostCancellationToken;
+ this.throttleWaitMilliseconds = throttleWaitMilliseconds;
+ // Store when we last tried to cancel. Checking cancellation can be expensive (as we have
+ // to marshall over to the host layer). So we only bother actually checking once enough
+ // time has passed.
+ this.lastCancellationCheckTime = 0;
+ }
+ ThrottledCancellationToken.prototype.isCancellationRequested = function () {
+ var time = ts.timestamp();
+ var duration = Math.abs(time - this.lastCancellationCheckTime);
+ if (duration >= this.throttleWaitMilliseconds) {
+ // Check no more than once every throttle wait milliseconds
+ this.lastCancellationCheckTime = time;
+ return this.hostCancellationToken.isCancellationRequested();
+ }
+ return false;
+ };
+ ThrottledCancellationToken.prototype.throwIfCancellationRequested = function () {
+ if (this.isCancellationRequested()) {
+ throw new ts.OperationCanceledException();
+ }
+ };
+ return ThrottledCancellationToken;
+ }());
+ ts.ThrottledCancellationToken = ThrottledCancellationToken;
function createLanguageService(host, documentRegistry) {
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
var syntaxTreeCache = new SyntaxTreeCache(host);
@@ -78801,6 +85949,7 @@ var ts;
ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + path);
return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
}
+ // We didn't already have the file. Fall through and acquire it from the registry.
}
// Could not find this file in the old program, create a new SourceFile for it.
return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
@@ -78901,10 +86050,10 @@ var ts;
// Try getting just type at this position and show
switch (node.kind) {
case 70 /* Identifier */:
- case 177 /* PropertyAccessExpression */:
- case 141 /* QualifiedName */:
+ case 178 /* PropertyAccessExpression */:
+ case 142 /* QualifiedName */:
case 98 /* ThisKeyword */:
- case 167 /* ThisType */:
+ case 168 /* ThisType */:
case 96 /* SuperKeyword */:
// For the identifiers/this/super etc get the type at position
var type = typeChecker.getTypeAtLocation(node);
@@ -78914,7 +86063,8 @@ var ts;
kindModifiers: ts.ScriptElementKindModifier.none,
textSpan: ts.createTextSpan(node.getStart(), node.getWidth()),
displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)),
- documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined
+ documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined,
+ tags: type.symbol ? type.symbol.getJsDocTags() : undefined
};
}
}
@@ -78926,7 +86076,8 @@ var ts;
kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol),
textSpan: ts.createTextSpan(node.getStart(), node.getWidth()),
displayParts: displayPartsDocumentationsAndKind.displayParts,
- documentation: displayPartsDocumentationsAndKind.documentation
+ documentation: displayPartsDocumentationsAndKind.documentation,
+ tags: displayPartsDocumentationsAndKind.tags
};
}
/// Goto definition
@@ -78934,22 +86085,23 @@ var ts;
synchronizeHostData();
return ts.GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position);
}
- /// Goto implementation
- function getImplementationAtPosition(fileName, position) {
- synchronizeHostData();
- return ts.GoToImplementation.getImplementationAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), ts.getTouchingPropertyName(getValidSourceFile(fileName), position));
- }
function getTypeDefinitionAtPosition(fileName, position) {
synchronizeHostData();
return ts.GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position);
}
+ /// Goto implementation
+ function getImplementationAtPosition(fileName, position) {
+ synchronizeHostData();
+ return ts.FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
+ }
+ /// References and Occurrences
function getOccurrencesAtPosition(fileName, position) {
var results = getOccurrencesAtPositionCore(fileName, position);
if (results) {
- var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName));
+ var sourceFile_1 = getCanonicalFileName(ts.normalizeSlashes(fileName));
// Get occurrences only supports reporting occurrences for the file queried. So
// filter down to that list.
- results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; });
+ results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_1; });
}
return results;
}
@@ -78959,9 +86111,7 @@ var ts;
var sourceFile = getValidSourceFile(fileName);
return ts.DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch);
}
- /// References and Occurrences
function getOccurrencesAtPositionCore(fileName, position) {
- synchronizeHostData();
return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName]));
function convertDocumentHighlights(documentHighlights) {
if (!documentHighlights) {
@@ -78976,7 +86126,8 @@ var ts;
fileName: entry.fileName,
textSpan: highlightSpan.textSpan,
isWriteAccess: highlightSpan.kind === ts.HighlightSpanKind.writtenReference,
- isDefinition: false
+ isDefinition: false,
+ isInString: highlightSpan.isInString,
});
}
}
@@ -78984,21 +86135,18 @@ var ts;
}
}
function findRenameLocations(fileName, position, findInStrings, findInComments) {
- var referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments);
- return ts.FindAllReferences.convertReferences(referencedSymbols);
+ return getReferences(fileName, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true });
}
function getReferencesAtPosition(fileName, position) {
- var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false);
- return ts.FindAllReferences.convertReferences(referencedSymbols);
+ return getReferences(fileName, position);
}
- function findReferences(fileName, position) {
- var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings*/ false, /*findInComments*/ false);
- // Only include referenced symbols that have a valid definition.
- return ts.filter(referencedSymbols, function (rs) { return !!rs.definition; });
+ function getReferences(fileName, position, options) {
+ synchronizeHostData();
+ return ts.FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options);
}
- function findReferencedSymbols(fileName, position, findInStrings, findInComments) {
+ function findReferences(fileName, position) {
synchronizeHostData();
- return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments);
+ return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
}
/// NavigateTo
function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) {
@@ -79017,7 +86165,8 @@ var ts;
text: data
});
}
- var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles);
+ var customTransformers = host.getCustomTransformers && host.getCustomTransformers();
+ var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
return {
outputFiles: outputFiles,
emitSkipped: emitOutput.emitSkipped
@@ -79047,15 +86196,15 @@ var ts;
return;
}
switch (node.kind) {
- case 177 /* PropertyAccessExpression */:
- case 141 /* QualifiedName */:
+ case 178 /* PropertyAccessExpression */:
+ case 142 /* QualifiedName */:
case 9 /* StringLiteral */:
case 85 /* FalseKeyword */:
case 100 /* TrueKeyword */:
case 94 /* NullKeyword */:
case 96 /* SuperKeyword */:
case 98 /* ThisKeyword */:
- case 167 /* ThisType */:
+ case 168 /* ThisType */:
case 70 /* Identifier */:
break;
// Cant create the text span
@@ -79072,7 +86221,7 @@ var ts;
// If this is name of a module declarations, check if this is right side of dotted module name
// 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 === 230 /* ModuleDeclaration */ &&
+ if (nodeForStartPos.parent.parent.kind === 232 /* ModuleDeclaration */ &&
nodeForStartPos.parent.parent.body === nodeForStartPos.parent) {
// Use parent module declarations name for start pos
nodeForStartPos = nodeForStartPos.parent.parent.name;
@@ -79095,10 +86244,10 @@ var ts;
return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position);
}
function getNavigationBarItems(fileName) {
- return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName));
+ return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
}
function getNavigationTree(fileName) {
- return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName));
+ return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName), cancellationToken);
}
function isTsOrTsxFile(fileName) {
var kind = ts.getScriptKind(fileName, host);
@@ -79131,7 +86280,7 @@ var ts;
function getOutliningSpans(fileName) {
// doesn't use compiler - no need to synchronize with host
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
- return ts.OutliningElementsCollector.collectElements(sourceFile);
+ return ts.OutliningElementsCollector.collectElements(sourceFile, cancellationToken);
}
function getBraceMatchingAtPosition(fileName, position) {
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
@@ -79209,13 +86358,13 @@ var ts;
}
return [];
}
- function getCodeFixesAtPosition(fileName, start, end, errorCodes) {
+ function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) {
synchronizeHostData();
var sourceFile = getValidSourceFile(fileName);
var span = { start: start, length: end - start };
var newLineChar = ts.getNewLineOrDefaultFromHost(host);
var allFixes = [];
- ts.forEach(errorCodes, function (error) {
+ ts.forEach(ts.deduplicate(errorCodes), function (error) {
cancellationToken.throwIfCancellationRequested();
var context = {
errorCode: error,
@@ -79224,7 +86373,8 @@ var ts;
program: program,
newLineCharacter: newLineChar,
host: host,
- cancellationToken: cancellationToken
+ cancellationToken: cancellationToken,
+ rulesProvider: getRuleProvider(formatOptions)
};
var fixes = ts.codefix.getFixes(context);
if (fixes) {
@@ -79248,7 +86398,7 @@ var ts;
}
var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
// Check if in a context where we don't want to perform any insertion
- if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position)) {
+ if (ts.isInString(sourceFile, position)) {
return false;
}
if (ts.isInsideJsxElementOrAttribute(sourceFile, position)) {
@@ -79304,7 +86454,7 @@ var ts;
continue;
}
var descriptor = undefined;
- for (var i = 0, n = descriptors.length; i < n; i++) {
+ for (var i = 0; i < descriptors.length; i++) {
if (matchArray[i + firstDescriptorCaptureIndex]) {
descriptor = descriptors[i];
}
@@ -79435,6 +86585,7 @@ var ts;
}
ts.createLanguageService = createLanguageService;
/* @internal */
+ /** Names in the name table are escaped, so an identifier `__foo` will have a name table entry `___foo`. */
function getNameTable(sourceFile) {
if (!sourceFile.nameTable) {
initializeNameTable(sourceFile);
@@ -79449,7 +86600,7 @@ var ts;
function walk(node) {
switch (node.kind) {
case 70 /* Identifier */:
- nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1;
+ setNameTable(node.text, node);
break;
case 9 /* StringLiteral */:
case 8 /* NumericLiteral */:
@@ -79458,10 +86609,10 @@ var ts;
// then we want 'something' to be in the name table. Similarly, if we have
// "a['propname']" then we want to store "propname" in the name table.
if (ts.isDeclarationName(node) ||
- node.parent.kind === 245 /* ExternalModuleReference */ ||
+ node.parent.kind === 247 /* ExternalModuleReference */ ||
isArgumentOfElementAccessExpression(node) ||
ts.isLiteralComputedPropertyDeclarationName(node)) {
- nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1;
+ setNameTable(node.text, node);
}
break;
default:
@@ -79474,18 +86625,79 @@ var ts;
}
}
}
+ function setNameTable(text, node) {
+ nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1);
+ }
+ }
+ function isObjectLiteralElement(node) {
+ switch (node.kind) {
+ case 252 /* JsxAttribute */:
+ case 254 /* JsxSpreadAttribute */:
+ case 260 /* PropertyAssignment */:
+ case 261 /* ShorthandPropertyAssignment */:
+ case 150 /* MethodDeclaration */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 }
+ */
+ /* @internal */
+ function getContainingObjectLiteralElement(node) {
+ switch (node.kind) {
+ case 9 /* StringLiteral */:
+ case 8 /* NumericLiteral */:
+ if (node.parent.kind === 143 /* ComputedPropertyName */) {
+ return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined;
+ }
+ // falls through
+ case 70 /* Identifier */:
+ return isObjectLiteralElement(node.parent) &&
+ (node.parent.parent.kind === 177 /* ObjectLiteralExpression */ || node.parent.parent.kind === 253 /* JsxAttributes */) &&
+ node.parent.name === node ? node.parent : undefined;
+ }
+ return undefined;
+ }
+ ts.getContainingObjectLiteralElement = getContainingObjectLiteralElement;
+ /* @internal */
+ function getPropertySymbolsFromContextualType(typeChecker, node) {
+ var objectLiteral = node.parent;
+ var contextualType = typeChecker.getContextualType(objectLiteral);
+ var name = ts.getTextOfPropertyName(node.name);
+ if (name && contextualType) {
+ var result_8 = [];
+ var symbol = contextualType.getProperty(name);
+ if (contextualType.flags & 65536 /* Union */) {
+ ts.forEach(contextualType.types, function (t) {
+ var symbol = t.getProperty(name);
+ if (symbol) {
+ result_8.push(symbol);
+ }
+ });
+ return result_8;
+ }
+ if (symbol) {
+ result_8.push(symbol);
+ return result_8;
+ }
+ }
+ return undefined;
}
+ ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType;
function isArgumentOfElementAccessExpression(node) {
return node &&
node.parent &&
- node.parent.kind === 178 /* ElementAccessExpression */ &&
+ node.parent.kind === 179 /* ElementAccessExpression */ &&
node.parent.argumentExpression === node;
}
/**
- * Get the path of the default library files (lib.d.ts) as distributed with the typescript
- * node package.
- * The functionality is not supported if the ts module is consumed outside of a node module.
- */
+ * Get the path of the default library files (lib.d.ts) as distributed with the typescript
+ * node package.
+ * The functionality is not supported if the ts module is consumed outside of a node module.
+ */
function getDefaultLibFilePath(options) {
// Check __dirname is defined and that we are on a node.js system.
if (typeof __dirname !== "undefined") {
@@ -79494,10 +86706,7 @@ var ts;
throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. ");
}
ts.getDefaultLibFilePath = getDefaultLibFilePath;
- function initializeServices() {
- ts.objectAllocator = getServicesObjectAllocator();
- }
- initializeServices();
+ ts.objectAllocator = getServicesObjectAllocator();
})(ts || (ts = {}));
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.
@@ -79562,113 +86771,114 @@ var ts;
function spanInNode(node) {
if (node) {
switch (node.kind) {
- case 205 /* VariableStatement */:
+ case 207 /* VariableStatement */:
// Span on first variable declaration
return spanInVariableDeclaration(node.declarationList.declarations[0]);
- case 223 /* VariableDeclaration */:
- case 147 /* PropertyDeclaration */:
- case 146 /* PropertySignature */:
+ case 225 /* VariableDeclaration */:
+ case 148 /* PropertyDeclaration */:
+ case 147 /* PropertySignature */:
return spanInVariableDeclaration(node);
- case 144 /* Parameter */:
+ case 145 /* Parameter */:
return spanInParameterDeclaration(node);
- case 225 /* FunctionDeclaration */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 150 /* Constructor */:
- case 184 /* FunctionExpression */:
- case 185 /* ArrowFunction */:
+ case 227 /* FunctionDeclaration */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 151 /* Constructor */:
+ case 185 /* FunctionExpression */:
+ case 186 /* ArrowFunction */:
return spanInFunctionDeclaration(node);
- case 204 /* Block */:
+ case 206 /* Block */:
if (ts.isFunctionBlock(node)) {
return spanInFunctionBlock(node);
}
- // Fall through
- case 231 /* ModuleBlock */:
+ // falls through
+ case 233 /* ModuleBlock */:
return spanInBlock(node);
- case 256 /* CatchClause */:
+ case 259 /* CatchClause */:
return spanInBlock(node.block);
- case 207 /* ExpressionStatement */:
+ case 209 /* ExpressionStatement */:
// span on the expression
return textSpan(node.expression);
- case 216 /* ReturnStatement */:
+ case 218 /* ReturnStatement */:
// span on return keyword and expression if present
return textSpan(node.getChildAt(0), node.expression);
- case 210 /* WhileStatement */:
+ case 212 /* WhileStatement */:
// Span on while(...)
return textSpanEndingAtNextToken(node, node.expression);
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
// span in statement of the do statement
return spanInNode(node.statement);
- case 222 /* DebuggerStatement */:
+ case 224 /* DebuggerStatement */:
// span on debugger keyword
return textSpan(node.getChildAt(0));
- case 208 /* IfStatement */:
+ case 210 /* IfStatement */:
// set on if(..) span
return textSpanEndingAtNextToken(node, node.expression);
- case 219 /* LabeledStatement */:
+ case 221 /* LabeledStatement */:
// span in statement
return spanInNode(node.statement);
- case 215 /* BreakStatement */:
- case 214 /* ContinueStatement */:
+ case 217 /* BreakStatement */:
+ case 216 /* ContinueStatement */:
// On break or continue keyword and label if present
return textSpan(node.getChildAt(0), node.label);
- case 211 /* ForStatement */:
+ case 213 /* ForStatement */:
return spanInForStatement(node);
- case 212 /* ForInStatement */:
+ case 214 /* ForInStatement */:
// span of for (a in ...)
return textSpanEndingAtNextToken(node, node.expression);
- case 213 /* ForOfStatement */:
+ case 215 /* ForOfStatement */:
// span in initializer
return spanInInitializerOfForLike(node);
- case 218 /* SwitchStatement */:
+ case 220 /* SwitchStatement */:
// span on switch(...)
return textSpanEndingAtNextToken(node, node.expression);
- case 253 /* CaseClause */:
- case 254 /* DefaultClause */:
+ case 256 /* CaseClause */:
+ case 257 /* DefaultClause */:
// span in first statement of the clause
return spanInNode(node.statements[0]);
- case 221 /* TryStatement */:
+ case 223 /* TryStatement */:
// span in try block
return spanInBlock(node.tryBlock);
- case 220 /* ThrowStatement */:
+ case 222 /* ThrowStatement */:
// span in throw ...
return textSpan(node, node.expression);
- case 240 /* ExportAssignment */:
+ case 242 /* ExportAssignment */:
// span on export = id
return textSpan(node, node.expression);
- case 234 /* ImportEqualsDeclaration */:
+ case 236 /* ImportEqualsDeclaration */:
// import statement without including semicolon
return textSpan(node, node.moduleReference);
- case 235 /* ImportDeclaration */:
+ case 237 /* ImportDeclaration */:
// import statement without including semicolon
return textSpan(node, node.moduleSpecifier);
- case 241 /* ExportDeclaration */:
+ case 243 /* ExportDeclaration */:
// import statement without including semicolon
return textSpan(node, node.moduleSpecifier);
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
// span on complete module if it is instantiated
if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
return undefined;
}
- case 226 /* ClassDeclaration */:
- case 229 /* EnumDeclaration */:
- case 260 /* EnumMember */:
- case 174 /* BindingElement */:
+ // falls through
+ case 228 /* ClassDeclaration */:
+ case 231 /* EnumDeclaration */:
+ case 263 /* EnumMember */:
+ case 175 /* BindingElement */:
// span on complete node
return textSpan(node);
- case 217 /* WithStatement */:
+ case 219 /* WithStatement */:
// span in statement
return spanInNode(node.statement);
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
return spanInNodeArray(node.parent.decorators);
- case 172 /* ObjectBindingPattern */:
- case 173 /* ArrayBindingPattern */:
+ case 173 /* ObjectBindingPattern */:
+ case 174 /* ArrayBindingPattern */:
return spanInBindingPattern(node);
// No breakpoint in interface, type alias
- case 227 /* InterfaceDeclaration */:
- case 228 /* TypeAliasDeclaration */:
+ case 229 /* InterfaceDeclaration */:
+ case 230 /* TypeAliasDeclaration */:
return undefined;
// Tokens:
case 24 /* SemicolonToken */:
@@ -79698,7 +86908,7 @@ var ts;
case 73 /* CatchKeyword */:
case 86 /* FinallyKeyword */:
return spanInNextNode(node);
- case 140 /* OfKeyword */:
+ case 141 /* OfKeyword */:
return spanInOfKeyword(node);
default:
// Destructuring pattern in destructuring assignment
@@ -79711,13 +86921,13 @@ var ts;
// a or ...c or d: x from
// [a, b, ...c] or { a, b } or { d: x } from destructuring pattern
if ((node.kind === 70 /* Identifier */ ||
- node.kind == 196 /* SpreadElement */ ||
- node.kind === 257 /* PropertyAssignment */ ||
- node.kind === 258 /* ShorthandPropertyAssignment */) &&
+ node.kind === 197 /* SpreadElement */ ||
+ node.kind === 260 /* PropertyAssignment */ ||
+ node.kind === 261 /* ShorthandPropertyAssignment */) &&
ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
return textSpan(node);
}
- if (node.kind === 192 /* BinaryExpression */) {
+ if (node.kind === 193 /* BinaryExpression */) {
var binaryExpression = node;
// Set breakpoint in destructuring pattern if its destructuring assignment
// [a, b, c] or {a, b, c} of
@@ -79740,22 +86950,22 @@ var ts;
}
if (ts.isPartOfExpression(node)) {
switch (node.parent.kind) {
- case 209 /* DoStatement */:
+ case 211 /* DoStatement */:
// Set span as if on while keyword
return spanInPreviousNode(node);
- case 145 /* Decorator */:
+ case 146 /* Decorator */:
// Set breakpoint on the decorator emit
return spanInNode(node.parent);
- case 211 /* ForStatement */:
- case 213 /* ForOfStatement */:
+ case 213 /* ForStatement */:
+ case 215 /* ForOfStatement */:
return textSpan(node);
- case 192 /* BinaryExpression */:
+ case 193 /* BinaryExpression */:
if (node.parent.operatorToken.kind === 25 /* CommaToken */) {
// If this is a comma expression, the breakpoint is possible in this expression
return textSpan(node);
}
break;
- case 185 /* ArrowFunction */:
+ case 186 /* ArrowFunction */:
if (node.parent.body === node) {
// If this is body of arrow function, it is allowed to have the breakpoint
return textSpan(node);
@@ -79764,13 +86974,13 @@ var ts;
}
}
// If this is name of property assignment, set breakpoint in the initializer
- if (node.parent.kind === 257 /* PropertyAssignment */ &&
+ if (node.parent.kind === 260 /* PropertyAssignment */ &&
node.parent.name === node &&
!ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
return spanInNode(node.parent.initializer);
}
// Breakpoint in type assertion goes to its operand
- if (node.parent.kind === 182 /* TypeAssertionExpression */ && node.parent.type === node) {
+ if (node.parent.kind === 183 /* TypeAssertionExpression */ && node.parent.type === node) {
return spanInNextNode(node.parent.type);
}
// return type of function go to previous token
@@ -79778,8 +86988,8 @@ var ts;
return spanInPreviousNode(node);
}
// initializer of variable/parameter declaration go to previous node
- if ((node.parent.kind === 223 /* VariableDeclaration */ ||
- node.parent.kind === 144 /* Parameter */)) {
+ if ((node.parent.kind === 225 /* VariableDeclaration */ ||
+ node.parent.kind === 145 /* Parameter */)) {
var paramOrVarDecl = node.parent;
if (paramOrVarDecl.initializer === node ||
paramOrVarDecl.type === node ||
@@ -79787,7 +86997,7 @@ var ts;
return spanInPreviousNode(node);
}
}
- if (node.parent.kind === 192 /* BinaryExpression */) {
+ if (node.parent.kind === 193 /* BinaryExpression */) {
var binaryExpression = node.parent;
if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) &&
(binaryExpression.right === node ||
@@ -79801,8 +87011,8 @@ var ts;
}
}
function textSpanFromVariableDeclaration(variableDeclaration) {
- var declarations = variableDeclaration.parent.declarations;
- if (declarations && declarations[0] === variableDeclaration) {
+ if (variableDeclaration.parent.kind === 226 /* VariableDeclarationList */ &&
+ variableDeclaration.parent.declarations[0] === variableDeclaration) {
// First declaration - include let keyword
return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
}
@@ -79813,7 +87023,7 @@ var ts;
}
function spanInVariableDeclaration(variableDeclaration) {
// If declaration of for in statement, just set the span in parent
- if (variableDeclaration.parent.parent.kind === 212 /* ForInStatement */) {
+ if (variableDeclaration.parent.parent.kind === 214 /* ForInStatement */) {
return spanInNode(variableDeclaration.parent.parent);
}
// If this is a destructuring pattern, set breakpoint in binding pattern
@@ -79824,11 +87034,11 @@ var ts;
// or its declaration from 'for of'
if (variableDeclaration.initializer ||
ts.hasModifier(variableDeclaration, 1 /* Export */) ||
- variableDeclaration.parent.parent.kind === 213 /* ForOfStatement */) {
+ variableDeclaration.parent.parent.kind === 215 /* ForOfStatement */) {
return textSpanFromVariableDeclaration(variableDeclaration);
}
- var declarations = variableDeclaration.parent.declarations;
- if (declarations && declarations[0] !== variableDeclaration) {
+ if (variableDeclaration.parent.kind === 226 /* VariableDeclarationList */ &&
+ variableDeclaration.parent.declarations[0] !== variableDeclaration) {
// If we cannot set breakpoint on this declaration, set it on previous one
// Because the variable declaration may be binding pattern and
// we would like to set breakpoint in last binding element if that's the case,
@@ -79864,7 +87074,7 @@ var ts;
}
function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) {
return ts.hasModifier(functionDeclaration, 1 /* Export */) ||
- (functionDeclaration.parent.kind === 226 /* ClassDeclaration */ && functionDeclaration.kind !== 150 /* Constructor */);
+ (functionDeclaration.parent.kind === 228 /* ClassDeclaration */ && functionDeclaration.kind !== 151 /* Constructor */);
}
function spanInFunctionDeclaration(functionDeclaration) {
// No breakpoints in the function signature
@@ -79887,25 +87097,26 @@ var ts;
}
function spanInBlock(block) {
switch (block.parent.kind) {
- case 230 /* ModuleDeclaration */:
+ case 232 /* ModuleDeclaration */:
if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) {
return undefined;
}
+ // falls through
// Set on parent if on same line otherwise on first statement
- case 210 /* WhileStatement */:
- case 208 /* IfStatement */:
- case 212 /* ForInStatement */:
+ case 212 /* WhileStatement */:
+ case 210 /* IfStatement */:
+ case 214 /* ForInStatement */:
return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);
// Set span on previous token if it starts on same line otherwise on the first statement of the block
- case 211 /* ForStatement */:
- case 213 /* ForOfStatement */:
+ case 213 /* ForStatement */:
+ case 215 /* ForOfStatement */:
return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
}
// Default action is to set on first statement
return spanInNode(block.statements[0]);
}
function spanInInitializerOfForLike(forLikeStatement) {
- if (forLikeStatement.initializer.kind === 224 /* VariableDeclarationList */) {
+ if (forLikeStatement.initializer.kind === 226 /* VariableDeclarationList */) {
// Declaration list - set breakpoint in first declaration
var variableDeclarationList = forLikeStatement.initializer;
if (variableDeclarationList.declarations.length > 0) {
@@ -79930,23 +87141,23 @@ var ts;
}
function spanInBindingPattern(bindingPattern) {
// Set breakpoint in first binding element
- var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 198 /* OmittedExpression */ ? element : undefined; });
+ var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 199 /* OmittedExpression */ ? element : undefined; });
if (firstBindingElement) {
return spanInNode(firstBindingElement);
}
// Empty binding pattern of binding element, set breakpoint on binding element
- if (bindingPattern.parent.kind === 174 /* BindingElement */) {
+ if (bindingPattern.parent.kind === 175 /* BindingElement */) {
return textSpan(bindingPattern.parent);
}
// Variable declaration is used as the span
return textSpanFromVariableDeclaration(bindingPattern.parent);
}
function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) {
- ts.Debug.assert(node.kind !== 173 /* ArrayBindingPattern */ && node.kind !== 172 /* ObjectBindingPattern */);
- var elements = node.kind === 175 /* ArrayLiteralExpression */ ?
+ ts.Debug.assert(node.kind !== 174 /* ArrayBindingPattern */ && node.kind !== 173 /* ObjectBindingPattern */);
+ var elements = node.kind === 176 /* ArrayLiteralExpression */ ?
node.elements :
node.properties;
- var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 198 /* OmittedExpression */ ? element : undefined; });
+ var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 199 /* OmittedExpression */ ? element : undefined; });
if (firstBindingElement) {
return spanInNode(firstBindingElement);
}
@@ -79954,18 +87165,18 @@ var ts;
// just nested element in another destructuring assignment
// set breakpoint on assignment when parent is destructuring assignment
// Otherwise set breakpoint for this element
- return textSpan(node.parent.kind === 192 /* BinaryExpression */ ? node.parent : node);
+ return textSpan(node.parent.kind === 193 /* BinaryExpression */ ? node.parent : node);
}
// Tokens:
function spanInOpenBraceToken(node) {
switch (node.parent.kind) {
- case 229 /* EnumDeclaration */:
+ case 231 /* EnumDeclaration */:
var enumDeclaration = node.parent;
return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));
- case 226 /* ClassDeclaration */:
+ case 228 /* ClassDeclaration */:
var classDeclaration = node.parent;
return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));
- case 232 /* CaseBlock */:
+ case 234 /* CaseBlock */:
return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]);
}
// Default to parent node
@@ -79973,24 +87184,25 @@ var ts;
}
function spanInCloseBraceToken(node) {
switch (node.parent.kind) {
- case 231 /* ModuleBlock */:
+ case 233 /* ModuleBlock */:
// If this is not an instantiated module block, no bp span
if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) {
return undefined;
}
- case 229 /* EnumDeclaration */:
- case 226 /* ClassDeclaration */:
+ // falls through
+ case 231 /* EnumDeclaration */:
+ case 228 /* ClassDeclaration */:
// Span on close brace token
return textSpan(node);
- case 204 /* Block */:
+ case 206 /* Block */:
if (ts.isFunctionBlock(node.parent)) {
// Span on close brace token
return textSpan(node);
}
- // fall through
- case 256 /* CatchClause */:
+ // falls through
+ case 259 /* CatchClause */:
return spanInNode(ts.lastOrUndefined(node.parent.statements));
- case 232 /* CaseBlock */:
+ case 234 /* CaseBlock */:
// breakpoint in last statement of the last clause
var caseBlock = node.parent;
var lastClause = ts.lastOrUndefined(caseBlock.clauses);
@@ -79998,7 +87210,7 @@ var ts;
return spanInNode(ts.lastOrUndefined(lastClause.statements));
}
return undefined;
- case 172 /* ObjectBindingPattern */:
+ case 173 /* ObjectBindingPattern */:
// Breakpoint in last binding element or binding pattern if it contains no elements
var bindingPattern = node.parent;
return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
@@ -80014,7 +87226,7 @@ var ts;
}
function spanInCloseBracketToken(node) {
switch (node.parent.kind) {
- case 173 /* ArrayBindingPattern */:
+ case 174 /* ArrayBindingPattern */:
// Breakpoint in last binding element or binding pattern if it contains no elements
var bindingPattern = node.parent;
return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern);
@@ -80029,12 +87241,12 @@ var ts;
}
}
function spanInOpenParenToken(node) {
- if (node.parent.kind === 209 /* DoStatement */ ||
- node.parent.kind === 179 /* CallExpression */ ||
- node.parent.kind === 180 /* NewExpression */) {
+ if (node.parent.kind === 211 /* DoStatement */ ||
+ node.parent.kind === 180 /* CallExpression */ ||
+ node.parent.kind === 181 /* NewExpression */) {
return spanInPreviousNode(node);
}
- if (node.parent.kind === 183 /* ParenthesizedExpression */) {
+ if (node.parent.kind === 184 /* ParenthesizedExpression */) {
return spanInNextNode(node);
}
// Default to parent node
@@ -80043,21 +87255,21 @@ var ts;
function spanInCloseParenToken(node) {
// Is this close paren token of parameter list, set span in previous token
switch (node.parent.kind) {
- case 184 /* FunctionExpression */:
- case 225 /* FunctionDeclaration */:
- case 185 /* ArrowFunction */:
- case 149 /* MethodDeclaration */:
- case 148 /* MethodSignature */:
- case 151 /* GetAccessor */:
- case 152 /* SetAccessor */:
- case 150 /* Constructor */:
- case 210 /* WhileStatement */:
- case 209 /* DoStatement */:
- case 211 /* ForStatement */:
- case 213 /* ForOfStatement */:
- case 179 /* CallExpression */:
- case 180 /* NewExpression */:
- case 183 /* ParenthesizedExpression */:
+ case 185 /* FunctionExpression */:
+ case 227 /* FunctionDeclaration */:
+ case 186 /* ArrowFunction */:
+ case 150 /* MethodDeclaration */:
+ case 149 /* MethodSignature */:
+ case 152 /* GetAccessor */:
+ case 153 /* SetAccessor */:
+ case 151 /* Constructor */:
+ case 212 /* WhileStatement */:
+ case 211 /* DoStatement */:
+ case 213 /* ForStatement */:
+ case 215 /* ForOfStatement */:
+ case 180 /* CallExpression */:
+ case 181 /* NewExpression */:
+ case 184 /* ParenthesizedExpression */:
return spanInPreviousNode(node);
// Default to parent node
default:
@@ -80067,20 +87279,20 @@ var ts;
function spanInColonToken(node) {
// Is this : specifying return annotation of the function declaration
if (ts.isFunctionLike(node.parent) ||
- node.parent.kind === 257 /* PropertyAssignment */ ||
- node.parent.kind === 144 /* Parameter */) {
+ node.parent.kind === 260 /* PropertyAssignment */ ||
+ node.parent.kind === 145 /* Parameter */) {
return spanInPreviousNode(node);
}
return spanInNode(node.parent);
}
function spanInGreaterThanOrLessThanToken(node) {
- if (node.parent.kind === 182 /* TypeAssertionExpression */) {
+ if (node.parent.kind === 183 /* TypeAssertionExpression */) {
return spanInNextNode(node);
}
return spanInNode(node.parent);
}
function spanInWhileKeyword(node) {
- if (node.parent.kind === 209 /* DoStatement */) {
+ if (node.parent.kind === 211 /* DoStatement */) {
// Set span on while expression
return textSpanEndingAtNextToken(node, node.parent.expression);
}
@@ -80088,7 +87300,7 @@ var ts;
return spanInNode(node.parent);
}
function spanInOfKeyword(node) {
- if (node.parent.kind === 213 /* ForOfStatement */) {
+ if (node.parent.kind === 215 /* ForOfStatement */) {
// Set using next token
return spanInNextNode(node);
}
@@ -80100,6 +87312,26 @@ var ts;
BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation;
})(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {}));
})(ts || (ts = {}));
+/// <reference path="..\compiler\transformer.ts"/>
+/// <reference path="transpile.ts"/>
+var ts;
+(function (ts) {
+ /**
+ * Transform one or more nodes using the supplied transformers.
+ * @param source A single `Node` or an array of `Node` objects.
+ * @param transformers An array of `TransformerFactory` callbacks used to process the transformation.
+ * @param compilerOptions Optional compiler options.
+ */
+ function transform(source, transformers, compilerOptions) {
+ var diagnostics = [];
+ compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics);
+ var nodes = ts.isArray(source) ? source : [source];
+ var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true);
+ result.diagnostics = ts.concatenate(result.diagnostics, diagnostics);
+ return result;
+ }
+ ts.transform = transform;
+})(ts || (ts = {}));
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
@@ -80141,8 +87373,7 @@ var ts;
ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) {
var oldSnapshotShim = oldSnapshot;
var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
- // TODO: should this be '==='?
- if (encoded == null) {
+ if (encoded === null) {
return null;
}
var decoded = JSON.parse(encoded);
@@ -80215,11 +87446,13 @@ var ts;
};
LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () {
var settingsJson = this.shimHost.getCompilationSettings();
- // TODO: should this be '==='?
- if (settingsJson == null || settingsJson == "") {
+ if (settingsJson === null || settingsJson === "") {
throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
}
- return JSON.parse(settingsJson);
+ var compilerOptions = JSON.parse(settingsJson);
+ // permit language service to handle all files (filtering should be performed on the host side)
+ compilerOptions.allowNonTsExtensions = true;
+ return compilerOptions;
};
LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () {
var encoded = this.shimHost.getScriptFileNames();
@@ -80242,7 +87475,7 @@ var ts;
};
LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () {
var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
- if (diagnosticMessagesJson == null || diagnosticMessagesJson == "") {
+ if (diagnosticMessagesJson === null || diagnosticMessagesJson === "") {
return null;
}
try {
@@ -80255,7 +87488,7 @@ var ts;
};
LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () {
var hostCancellationToken = this.shimHost.getCancellationToken();
- return new ThrottledCancellationToken(hostCancellationToken);
+ return new ts.ThrottledCancellationToken(hostCancellationToken);
};
LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () {
return this.shimHost.getCurrentDirectory();
@@ -80279,27 +87512,6 @@ var ts;
return LanguageServiceShimHostAdapter;
}());
ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter;
- /** A cancellation that throttles calls to the host */
- var ThrottledCancellationToken = (function () {
- function ThrottledCancellationToken(hostCancellationToken) {
- this.hostCancellationToken = hostCancellationToken;
- // Store when we last tried to cancel. Checking cancellation can be expensive (as we have
- // to marshall over to the host layer). So we only bother actually checking once enough
- // time has passed.
- this.lastCancellationCheckTime = 0;
- }
- ThrottledCancellationToken.prototype.isCancellationRequested = function () {
- var time = ts.timestamp();
- var duration = Math.abs(time - this.lastCancellationCheckTime);
- if (duration > 10) {
- // Check no more than once every 10 ms.
- this.lastCancellationCheckTime = time;
- return this.hostCancellationToken.isCancellationRequested();
- }
- return false;
- };
- return ThrottledCancellationToken;
- }());
var CoreServicesShimHostAdapter = (function () {
function CoreServicesShimHostAdapter(shimHost) {
var _this = this;
@@ -80727,12 +87939,6 @@ var ts;
var compilerOptions = JSON.parse(compilerOptionsJson);
var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host);
var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined;
- if (resolvedFileName && !compilerOptions.allowJs && ts.fileExtensionIs(resolvedFileName, ".js")) {
- return {
- resolvedFileName: undefined,
- failedLookupLocations: []
- };
- }
return {
resolvedFileName: resolvedFileName,
failedLookupLocations: result.failedLookupLocations
@@ -80877,7 +88083,7 @@ var ts;
this._shims.push(shim);
};
TypeScriptServicesFactory.prototype.unregisterShim = function (shim) {
- for (var i = 0, n = this._shims.length; i < n; i++) {
+ for (var i = 0; i < this._shims.length; i++) {
if (this._shims[i] === shim) {
delete this._shims[i];
return;
@@ -80906,4 +88112,4 @@ var TypeScript;
// 'toolsVersion' gets consumed by the managed side, so it's not unused.
// TODO: it should be moved into a namespace though.
/* @internal */
-var toolsVersion = "2.2";
+var toolsVersion = "2.3";