- }
- function parseJsxText() {
- var node = createNode(11 /* JsxText */);
- node.text = scanner.getTokenValue();
- node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
- currentToken = scanner.scanJsxToken();
- return finishNode(node);
- }
- function parseJsxChild(openingTag, token) {
- switch (token) {
- case 1 /* EndOfFileToken */:
- // If we hit EOF, issue the error at the tag that lacks the closing element
- // rather than at the end of the file (which is useless)
- if (ts.isJsxOpeningFragment(openingTag)) {
- parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
- }
- else {
- // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
- // or to cover only 'Foo' in < Foo >
- var tag = openingTag.tagName;
- var start = ts.skipTrivia(sourceText, tag.pos);
- parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
- }
- return undefined;
- case 30 /* LessThanSlashToken */:
- case 7 /* ConflictMarkerTrivia */:
- return undefined;
- case 11 /* JsxText */:
- case 12 /* JsxTextAllWhiteSpaces */:
- return parseJsxText();
- case 18 /* OpenBraceToken */:
- return parseJsxExpression(/*inExpressionContext*/ false);
- case 29 /* LessThanToken */:
- return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
- default:
- return ts.Debug.assertNever(token);
- }
- }
- function parseJsxChildren(openingTag) {
- var list = [];
- var listPos = getNodePos();
- var saveParsingContext = parsingContext;
- parsingContext |= 1 << 14 /* JsxChildren */;
- while (true) {
- var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
- if (!child)
- break;
- list.push(child);
- }
- parsingContext = saveParsingContext;
- return createNodeArray(list, listPos);
- }
- function parseJsxAttributes() {
- var jsxAttributes = createNode(274 /* JsxAttributes */);
- jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
- return finishNode(jsxAttributes);
- }
- function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
- var fullStart = scanner.getStartPos();
- parseExpected(29 /* LessThanToken */);
- if (token() === 31 /* GreaterThanToken */) {
- // See below for explanation of scanJsxText
- var node_1 = createNode(271 /* JsxOpeningFragment */, fullStart);
- scanJsxText();
- return finishNode(node_1);
- }
- var tagName = parseJsxElementName();
- var typeArguments = tryParseTypeArguments();
- var attributes = parseJsxAttributes();
- var node;
- if (token() === 31 /* 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(268 /* JsxOpeningElement */, fullStart);
- scanJsxText();
- }
- else {
- parseExpected(43 /* SlashToken */);
- if (inExpressionContext) {
- parseExpected(31 /* GreaterThanToken */);
- }
- else {
- parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
- scanJsxText();
- }
- node = createNode(267 /* JsxSelfClosingElement */, fullStart);
- }
- node.tagName = tagName;
- node.typeArguments = typeArguments;
- node.attributes = attributes;
- return finishNode(node);
- }
- function parseJsxElementName() {
- scanJsxIdentifier();
- // JsxElement can have name in the form of
- // propertyAccessExpression
- // primaryExpression in the form of an identifier and "this" keyword
- // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
- // We only want to consider "this" as a primaryExpression
- var expression = token() === 104 /* ThisKeyword */ ?
- parseTokenNode() : parseIdentifierName();
- while (parseOptional(24 /* DotToken */)) {
- var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
- propertyAccess.expression = expression;
- propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false);
- expression = finishNode(propertyAccess);
- }
- return expression;
- }
- function parseJsxExpression(inExpressionContext) {
- var node = createNode(276 /* JsxExpression */);
- if (!parseExpected(18 /* OpenBraceToken */)) {
- return undefined;
- }
- if (token() !== 19 /* CloseBraceToken */) {
- node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
- // Only an AssignmentExpression is valid here per the JSX spec,
- // but we can unambiguously parse a comma sequence and provide
- // a better error message in grammar checking.
- node.expression = parseExpression();
- }
- if (inExpressionContext) {
- parseExpected(19 /* CloseBraceToken */);
- }
- else {
- if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
- scanJsxText();
- }
- }
- return finishNode(node);
- }
- function parseJsxAttribute() {
- if (token() === 18 /* OpenBraceToken */) {
- return parseJsxSpreadAttribute();
- }
- scanJsxIdentifier();
- var node = createNode(273 /* JsxAttribute */);
- node.name = parseIdentifierName();
- if (token() === 62 /* EqualsToken */) {
- switch (scanJsxAttributeValue()) {
- case 10 /* StringLiteral */:
- node.initializer = parseLiteralNode();
- break;
- default:
- node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
- break;
- }
- }
- return finishNode(node);
- }
- function parseJsxSpreadAttribute() {
- var node = createNode(275 /* JsxSpreadAttribute */);
- parseExpected(18 /* OpenBraceToken */);
- parseExpected(25 /* DotDotDotToken */);
- node.expression = parseExpression();
- parseExpected(19 /* CloseBraceToken */);
- return finishNode(node);
- }
- function parseJsxClosingElement(inExpressionContext) {
- var node = createNode(269 /* JsxClosingElement */);
- parseExpected(30 /* LessThanSlashToken */);
- node.tagName = parseJsxElementName();
- if (inExpressionContext) {
- parseExpected(31 /* GreaterThanToken */);
- }
- else {
- parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
- scanJsxText();
- }
- return finishNode(node);
- }
- function parseJsxClosingFragment(inExpressionContext) {
- var node = createNode(272 /* JsxClosingFragment */);
- parseExpected(30 /* LessThanSlashToken */);
- if (ts.tokenIsIdentifierOrKeyword(token())) {
- parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
- }
- if (inExpressionContext) {
- parseExpected(31 /* GreaterThanToken */);
- }
- else {
- parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
- scanJsxText();
- }
- return finishNode(node);
- }
- function parseTypeAssertion() {
- var node = createNode(199 /* TypeAssertionExpression */);
- parseExpected(29 /* LessThanToken */);
- node.type = parseType();
- parseExpected(31 /* GreaterThanToken */);
- node.expression = parseSimpleUnaryExpression();
- return finishNode(node);
- }
- function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
- nextToken();
- return ts.tokenIsIdentifierOrKeyword(token())
- || token() === 22 /* OpenBracketToken */
- || isTemplateStartOfTaggedTemplate();
- }
- function isStartOfOptionalPropertyOrElementAccessChain() {
- return token() === 28 /* QuestionDotToken */
- && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
- }
- function tryReparseOptionalChain(node) {
- if (node.flags & 32 /* OptionalChain */) {
- return true;
- }
- // check for an optional chain in a non-null expression
- if (ts.isNonNullExpression(node)) {
- var expr = node.expression;
- while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
- expr = expr.expression;
- }
- if (expr.flags & 32 /* OptionalChain */) {
- // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
- while (ts.isNonNullExpression(node)) {
- node.flags |= 32 /* OptionalChain */;
- node = node.expression;
- }
- return true;
- }
- }
- return false;
- }
- function parsePropertyAccessExpressionRest(expression, questionDotToken) {
- var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
- propertyAccess.expression = expression;
- propertyAccess.questionDotToken = questionDotToken;
- propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
- if (questionDotToken || tryReparseOptionalChain(expression)) {
- propertyAccess.flags |= 32 /* OptionalChain */;
- if (ts.isPrivateIdentifier(propertyAccess.name)) {
- parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
- }
- }
- return finishNode(propertyAccess);
- }
- function parseElementAccessExpressionRest(expression, questionDotToken) {
- var indexedAccess = createNode(195 /* ElementAccessExpression */, expression.pos);
- indexedAccess.expression = expression;
- indexedAccess.questionDotToken = questionDotToken;
- if (token() === 23 /* CloseBracketToken */) {
- indexedAccess.argumentExpression = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
- }
- else {
- var argument = allowInAnd(parseExpression);
- if (ts.isStringOrNumericLiteralLike(argument)) {
- argument.text = internIdentifier(argument.text);
- }
- indexedAccess.argumentExpression = argument;
- }
- parseExpected(23 /* CloseBracketToken */);
- if (questionDotToken || tryReparseOptionalChain(expression)) {
- indexedAccess.flags |= 32 /* OptionalChain */;
- }
- return finishNode(indexedAccess);
- }
- function parseMemberExpressionRest(expression, allowOptionalChain) {
- while (true) {
- var questionDotToken = void 0;
- var isPropertyAccess = false;
- if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
- questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
- isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
- }
- else {
- isPropertyAccess = parseOptional(24 /* DotToken */);
- }
- if (isPropertyAccess) {
- expression = parsePropertyAccessExpressionRest(expression, questionDotToken);
- continue;
- }
- if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
- nextToken();
- var nonNullExpression = createNode(218 /* 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 ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
- expression = parseElementAccessExpressionRest(expression, questionDotToken);
- continue;
- }
- if (isTemplateStartOfTaggedTemplate()) {
- expression = parseTaggedTemplateRest(expression, questionDotToken, /*typeArguments*/ undefined);
- continue;
- }
- return expression;
- }
- }
- function isTemplateStartOfTaggedTemplate() {
- return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
- }
- function parseTaggedTemplateRest(tag, questionDotToken, typeArguments) {
- var tagExpression = createNode(198 /* TaggedTemplateExpression */, tag.pos);
- tagExpression.tag = tag;
- tagExpression.questionDotToken = questionDotToken;
- tagExpression.typeArguments = typeArguments;
- tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */
- ? (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode())
- : parseTemplateExpression(/*isTaggedTemplate*/ true);
- if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
- tagExpression.flags |= 32 /* OptionalChain */;
- }
- return finishNode(tagExpression);
- }
- function parseCallExpressionRest(expression) {
- while (true) {
- expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
- var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
- // handle 'foo<<T>()'
- if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
- // See if this is the start of a generic invocation. If so, consume it and
- // keep checking for postfix expressions. Otherwise, it's just a '<' that's
- // part of an arithmetic expression. Break out so we consume it higher in the
- // stack.
- var typeArguments = tryParse(parseTypeArgumentsInExpression);
- if (typeArguments) {
- if (isTemplateStartOfTaggedTemplate()) {
- expression = parseTaggedTemplateRest(expression, questionDotToken, typeArguments);
- continue;
- }
- var callExpr = createNode(196 /* CallExpression */, expression.pos);
- callExpr.expression = expression;
- callExpr.questionDotToken = questionDotToken;
- callExpr.typeArguments = typeArguments;
- callExpr.arguments = parseArgumentList();
- if (questionDotToken || tryReparseOptionalChain(expression)) {
- callExpr.flags |= 32 /* OptionalChain */;
- }
- expression = finishNode(callExpr);
- continue;
- }
- }
- else if (token() === 20 /* OpenParenToken */) {
- var callExpr = createNode(196 /* CallExpression */, expression.pos);
- callExpr.expression = expression;
- callExpr.questionDotToken = questionDotToken;
- callExpr.arguments = parseArgumentList();
- if (questionDotToken || tryReparseOptionalChain(expression)) {
- callExpr.flags |= 32 /* OptionalChain */;
- }
- expression = finishNode(callExpr);
- continue;
- }
- if (questionDotToken) {
- // We failed to parse anything, so report a missing identifier here.
- var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
- propertyAccess.expression = expression;
- propertyAccess.questionDotToken = questionDotToken;
- propertyAccess.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
- propertyAccess.flags |= 32 /* OptionalChain */;
- expression = finishNode(propertyAccess);
- }
- break;
- }
- return expression;
- }
- function parseArgumentList() {
- parseExpected(20 /* OpenParenToken */);
- var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
- parseExpected(21 /* CloseParenToken */);
- return result;
- }
- function parseTypeArgumentsInExpression() {
- if (reScanLessThanToken() !== 29 /* LessThanToken */) {
- return undefined;
- }
- nextToken();
- var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
- if (!parseExpected(31 /* GreaterThanToken */)) {
- // If it doesn't have the closing `>` then it's definitely not an type argument list.
- return undefined;
- }
- // If we have a '<', then only parse this as a argument list if the type arguments
- // are complete and we have an open paren. if we don't, rewind and return nothing.
- return typeArguments && canFollowTypeArgumentsInExpression()
- ? typeArguments
- : undefined;
- }
- function canFollowTypeArgumentsInExpression() {
- switch (token()) {
- case 20 /* OpenParenToken */: // foo<x>(
- case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
- case 15 /* TemplateHead */: // foo<T> `...${100}...`
- // these are the only tokens can legally follow a type argument
- // list. So we definitely want to treat them as type arg lists.
- // falls through
- case 24 /* DotToken */: // foo<x>.
- case 21 /* CloseParenToken */: // foo<x>)
- case 23 /* CloseBracketToken */: // foo<x>]
- case 58 /* ColonToken */: // foo<x>:
- case 26 /* SemicolonToken */: // foo<x>;
- case 57 /* QuestionToken */: // foo<x>?
- case 34 /* EqualsEqualsToken */: // foo<x> ==
- case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
- case 35 /* ExclamationEqualsToken */: // foo<x> !=
- case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
- case 55 /* AmpersandAmpersandToken */: // foo<x> &&
- case 56 /* BarBarToken */: // foo<x> ||
- case 60 /* QuestionQuestionToken */: // foo<x> ??
- case 52 /* CaretToken */: // foo<x> ^
- case 50 /* AmpersandToken */: // foo<x> &
- case 51 /* BarToken */: // foo<x> |
- case 19 /* CloseBraceToken */: // foo<x> }
- case 1 /* EndOfFileToken */: // foo<x>
- // these cases can't legally follow a type arg list. However, they're not legal
- // expressions either. The user is probably in the middle of a generic type. So
- // treat it as such.
- return true;
- case 27 /* CommaToken */: // foo<x>,
- case 18 /* OpenBraceToken */: // foo<x> {
- // We don't want to treat these as type arguments. Otherwise we'll parse this
- // as an invocation expression. Instead, we want to parse out the expression
- // in isolation from the type arguments.
- // falls through
- default:
- // Anything else treat as an expression.
- return false;
- }
- }
- function parsePrimaryExpression() {
- switch (token()) {
- case 8 /* NumericLiteral */:
- case 9 /* BigIntLiteral */:
- case 10 /* StringLiteral */:
- case 14 /* NoSubstitutionTemplateLiteral */:
- return parseLiteralNode();
- case 104 /* ThisKeyword */:
- case 102 /* SuperKeyword */:
- case 100 /* NullKeyword */:
- case 106 /* TrueKeyword */:
- case 91 /* FalseKeyword */:
- return parseTokenNode();
- case 20 /* OpenParenToken */:
- return parseParenthesizedExpression();
- case 22 /* OpenBracketToken */:
- return parseArrayLiteralExpression();
- case 18 /* OpenBraceToken */:
- return parseObjectLiteralExpression();
- case 126 /* AsyncKeyword */:
- // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
- // If we encounter `async [no LineTerminator here] function` then this is an async
- // function; otherwise, its an identifier.
- if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
- break;
- }
- return parseFunctionExpression();
- case 80 /* ClassKeyword */:
- return parseClassExpression();
- case 94 /* FunctionKeyword */:
- return parseFunctionExpression();
- case 99 /* NewKeyword */:
- return parseNewExpressionOrNewDotTarget();
- case 43 /* SlashToken */:
- case 67 /* SlashEqualsToken */:
- if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
- return parseLiteralNode();
- }
- break;
- case 15 /* TemplateHead */:
- return parseTemplateExpression(/* isTaggedTemplate */ false);
- }
- return parseIdentifier(ts.Diagnostics.Expression_expected);
- }
- function parseParenthesizedExpression() {
- var node = createNodeWithJSDoc(200 /* ParenthesizedExpression */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- return finishNode(node);
- }
- function parseSpreadElement() {
- var node = createNode(213 /* SpreadElement */);
- parseExpected(25 /* DotDotDotToken */);
- node.expression = parseAssignmentExpressionOrHigher();
- return finishNode(node);
- }
- function parseArgumentOrArrayLiteralElement() {
- return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
- token() === 27 /* CommaToken */ ? createNode(215 /* OmittedExpression */) :
- parseAssignmentExpressionOrHigher();
- }
- function parseArgumentExpression() {
- return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
- }
- function parseArrayLiteralExpression() {
- var node = createNode(192 /* ArrayLiteralExpression */);
- parseExpected(22 /* OpenBracketToken */);
- if (scanner.hasPrecedingLineBreak()) {
- node.multiLine = true;
- }
- node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
- parseExpected(23 /* CloseBracketToken */);
- return finishNode(node);
- }
- function parseObjectLiteralElement() {
- var node = createNodeWithJSDoc(0 /* Unknown */);
- if (parseOptionalToken(25 /* DotDotDotToken */)) {
- node.kind = 283 /* SpreadAssignment */;
- node.expression = parseAssignmentExpressionOrHigher();
- return finishNode(node);
- }
- node.decorators = parseDecorators();
- node.modifiers = parseModifiers();
- if (parseContextualModifier(131 /* GetKeyword */)) {
- return parseAccessorDeclaration(node, 163 /* GetAccessor */);
- }
- if (parseContextualModifier(142 /* SetKeyword */)) {
- return parseAccessorDeclaration(node, 164 /* SetAccessor */);
- }
- var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
- var tokenIsIdentifier = isIdentifier();
- node.name = parsePropertyName();
- // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
- node.questionToken = parseOptionalToken(57 /* QuestionToken */);
- node.exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
- if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
- return parseMethodDeclaration(node, asteriskToken);
- }
- // check if it is short-hand property assignment or normal property assignment
- // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
- // CoverInitializedName[Yield] :
- // IdentifierReference[?Yield] Initializer[In, ?Yield]
- // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
- var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
- if (isShorthandPropertyAssignment) {
- node.kind = 282 /* ShorthandPropertyAssignment */;
- var equalsToken = parseOptionalToken(62 /* EqualsToken */);
- if (equalsToken) {
- node.equalsToken = equalsToken;
- node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
- }
- }
- else {
- node.kind = 281 /* PropertyAssignment */;
- parseExpected(58 /* ColonToken */);
- node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
- }
- return finishNode(node);
- }
- function parseObjectLiteralExpression() {
- var node = createNode(193 /* ObjectLiteralExpression */);
- var openBracePosition = scanner.getTokenPos();
- parseExpected(18 /* OpenBraceToken */);
- if (scanner.hasPrecedingLineBreak()) {
- node.multiLine = true;
- }
- node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
- if (!parseExpected(19 /* CloseBraceToken */)) {
- var lastError = ts.lastOrUndefined(parseDiagnostics);
- if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
- ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
- }
- }
- return finishNode(node);
- }
- function parseFunctionExpression() {
- // GeneratorExpression:
- // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
- //
- // FunctionExpression:
- // function BindingIdentifier[opt](FormalParameters){ FunctionBody }
- var saveDecoratorContext = inDecoratorContext();
- if (saveDecoratorContext) {
- setDecoratorContext(/*val*/ false);
- }
- var node = createNodeWithJSDoc(201 /* FunctionExpression */);
- node.modifiers = parseModifiers();
- parseExpected(94 /* FunctionKeyword */);
- node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
- var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
- var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
- node.name =
- isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
- isGenerator ? doInYieldContext(parseOptionalIdentifier) :
- isAsync ? doInAwaitContext(parseOptionalIdentifier) :
- parseOptionalIdentifier();
- fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
- node.body = parseFunctionBlock(isGenerator | isAsync);
- if (saveDecoratorContext) {
- setDecoratorContext(/*val*/ true);
- }
- return finishNode(node);
- }
- function parseOptionalIdentifier() {
- return isIdentifier() ? parseIdentifier() : undefined;
- }
- function parseNewExpressionOrNewDotTarget() {
- var fullStart = scanner.getStartPos();
- parseExpected(99 /* NewKeyword */);
- if (parseOptional(24 /* DotToken */)) {
- var node_2 = createNode(219 /* MetaProperty */, fullStart);
- node_2.keywordToken = 99 /* NewKeyword */;
- node_2.name = parseIdentifierName();
- return finishNode(node_2);
- }
- var expression = parsePrimaryExpression();
- var typeArguments;
- while (true) {
- expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ false);
- typeArguments = tryParse(parseTypeArgumentsInExpression);
- if (isTemplateStartOfTaggedTemplate()) {
- ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
- expression = parseTaggedTemplateRest(expression, /*optionalChain*/ undefined, typeArguments);
- typeArguments = undefined;
- }
- break;
- }
- var node = createNode(197 /* NewExpression */, fullStart);
- node.expression = expression;
- node.typeArguments = typeArguments;
- if (token() === 20 /* OpenParenToken */) {
- node.arguments = parseArgumentList();
- }
- else if (node.typeArguments) {
- parseErrorAt(fullStart, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
- }
- return finishNode(node);
- }
- // STATEMENTS
- function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
- var node = createNode(223 /* Block */);
- var openBracePosition = scanner.getTokenPos();
- if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
- if (scanner.hasPrecedingLineBreak()) {
- node.multiLine = true;
- }
- node.statements = parseList(1 /* BlockStatements */, parseStatement);
- if (!parseExpected(19 /* CloseBraceToken */)) {
- var lastError = ts.lastOrUndefined(parseDiagnostics);
- if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
- ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
- }
- }
- }
- else {
- node.statements = createMissingList();
- }
- return finishNode(node);
- }
- function parseFunctionBlock(flags, diagnosticMessage) {
- var savedYieldContext = inYieldContext();
- setYieldContext(!!(flags & 1 /* Yield */));
- var savedAwaitContext = inAwaitContext();
- setAwaitContext(!!(flags & 2 /* Await */));
- // We may be in a [Decorator] context when parsing a function expression or
- // arrow function. The body of the function is not in [Decorator] context.
- var saveDecoratorContext = inDecoratorContext();
- if (saveDecoratorContext) {
- setDecoratorContext(/*val*/ false);
- }
- var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
- if (saveDecoratorContext) {
- setDecoratorContext(/*val*/ true);
- }
- setYieldContext(savedYieldContext);
- setAwaitContext(savedAwaitContext);
- return block;
- }
- function parseEmptyStatement() {
- var node = createNode(224 /* EmptyStatement */);
- parseExpected(26 /* SemicolonToken */);
- return finishNode(node);
- }
- function parseIfStatement() {
- var node = createNode(227 /* IfStatement */);
- parseExpected(95 /* IfKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- node.thenStatement = parseStatement();
- node.elseStatement = parseOptional(87 /* ElseKeyword */) ? parseStatement() : undefined;
- return finishNode(node);
- }
- function parseDoStatement() {
- var node = createNode(228 /* DoStatement */);
- parseExpected(86 /* DoKeyword */);
- node.statement = parseStatement();
- parseExpected(111 /* WhileKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
- // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
- // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
- // do;while(0)x will have a semicolon inserted before x.
- parseOptional(26 /* SemicolonToken */);
- return finishNode(node);
- }
- function parseWhileStatement() {
- var node = createNode(229 /* WhileStatement */);
- parseExpected(111 /* WhileKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- node.statement = parseStatement();
- return finishNode(node);
- }
- function parseForOrForInOrForOfStatement() {
- var pos = getNodePos();
- parseExpected(93 /* ForKeyword */);
- var awaitToken = parseOptionalToken(127 /* AwaitKeyword */);
- parseExpected(20 /* OpenParenToken */);
- var initializer;
- if (token() !== 26 /* SemicolonToken */) {
- if (token() === 109 /* VarKeyword */ || token() === 115 /* LetKeyword */ || token() === 81 /* ConstKeyword */) {
- initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
- }
- else {
- initializer = disallowInAnd(parseExpression);
- }
- }
- var forOrForInOrForOfStatement;
- if (awaitToken ? parseExpected(152 /* OfKeyword */) : parseOptional(152 /* OfKeyword */)) {
- var forOfStatement = createNode(232 /* ForOfStatement */, pos);
- forOfStatement.awaitModifier = awaitToken;
- forOfStatement.initializer = initializer;
- forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
- parseExpected(21 /* CloseParenToken */);
- forOrForInOrForOfStatement = forOfStatement;
- }
- else if (parseOptional(97 /* InKeyword */)) {
- var forInStatement = createNode(231 /* ForInStatement */, pos);
- forInStatement.initializer = initializer;
- forInStatement.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- forOrForInOrForOfStatement = forInStatement;
- }
- else {
- var forStatement = createNode(230 /* ForStatement */, pos);
- forStatement.initializer = initializer;
- parseExpected(26 /* SemicolonToken */);
- if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) {
- forStatement.condition = allowInAnd(parseExpression);
- }
- parseExpected(26 /* SemicolonToken */);
- if (token() !== 21 /* CloseParenToken */) {
- forStatement.incrementor = allowInAnd(parseExpression);
- }
- parseExpected(21 /* CloseParenToken */);
- forOrForInOrForOfStatement = forStatement;
- }
- forOrForInOrForOfStatement.statement = parseStatement();
- return finishNode(forOrForInOrForOfStatement);
- }
- function parseBreakOrContinueStatement(kind) {
- var node = createNode(kind);
- parseExpected(kind === 234 /* BreakStatement */ ? 77 /* BreakKeyword */ : 82 /* ContinueKeyword */);
- if (!canParseSemicolon()) {
- node.label = parseIdentifier();
- }
- parseSemicolon();
- return finishNode(node);
- }
- function parseReturnStatement() {
- var node = createNode(235 /* ReturnStatement */);
- parseExpected(101 /* ReturnKeyword */);
- if (!canParseSemicolon()) {
- node.expression = allowInAnd(parseExpression);
- }
- parseSemicolon();
- return finishNode(node);
- }
- function parseWithStatement() {
- var node = createNode(236 /* WithStatement */);
- parseExpected(112 /* WithKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- node.statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
- return finishNode(node);
- }
- function parseCaseClause() {
- var node = createNode(277 /* CaseClause */);
- parseExpected(78 /* CaseKeyword */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(58 /* ColonToken */);
- node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
- return finishNode(node);
- }
- function parseDefaultClause() {
- var node = createNode(278 /* DefaultClause */);
- parseExpected(84 /* DefaultKeyword */);
- parseExpected(58 /* ColonToken */);
- node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
- return finishNode(node);
- }
- function parseCaseOrDefaultClause() {
- return token() === 78 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
- }
- function parseSwitchStatement() {
- var node = createNode(237 /* SwitchStatement */);
- parseExpected(103 /* SwitchKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = allowInAnd(parseExpression);
- parseExpected(21 /* CloseParenToken */);
- var caseBlock = createNode(251 /* CaseBlock */);
- parseExpected(18 /* OpenBraceToken */);
- caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
- parseExpected(19 /* CloseBraceToken */);
- node.caseBlock = finishNode(caseBlock);
- return finishNode(node);
- }
- function parseThrowStatement() {
- // ThrowStatement[Yield] :
- // throw [no LineTerminator here]Expression[In, ?Yield];
- // Because of automatic semicolon insertion, we need to report error if this
- // throw could be terminated with a semicolon. Note: we can't call 'parseExpression'
- // 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(239 /* ThrowStatement */);
- parseExpected(105 /* ThrowKeyword */);
- node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
- parseSemicolon();
- return finishNode(node);
- }
- // TODO: Review for error recovery
- function parseTryStatement() {
- var node = createNode(240 /* TryStatement */);
- parseExpected(107 /* TryKeyword */);
- node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
- node.catchClause = token() === 79 /* CatchKeyword */ ? parseCatchClause() : undefined;
- // If we don't have a catch clause, then we must have a finally clause. Try to parse
- // one out no matter what.
- if (!node.catchClause || token() === 92 /* FinallyKeyword */) {
- parseExpected(92 /* FinallyKeyword */);
- node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
- }
- return finishNode(node);
- }
- function parseCatchClause() {
- var result = createNode(280 /* CatchClause */);
- parseExpected(79 /* CatchKeyword */);
- if (parseOptional(20 /* OpenParenToken */)) {
- result.variableDeclaration = parseVariableDeclaration();
- parseExpected(21 /* CloseParenToken */);
- }
- else {
- // Keep shape of node to avoid degrading performance.
- result.variableDeclaration = undefined;
- }
- result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
- return finishNode(result);
- }
- function parseDebuggerStatement() {
- var node = createNode(241 /* DebuggerStatement */);
- parseExpected(83 /* DebuggerKeyword */);
- parseSemicolon();
- return finishNode(node);
- }
- function parseExpressionOrLabeledStatement() {
- // Avoiding having to do the lookahead for a labeled statement by just trying to parse
- // out an expression, seeing if it is identifier and then seeing if it is followed by
- // a colon.
- var node = createNodeWithJSDoc(token() === 75 /* Identifier */ ? 0 /* Unknown */ : 226 /* ExpressionStatement */);
- var expression = allowInAnd(parseExpression);
- if (expression.kind === 75 /* Identifier */ && parseOptional(58 /* ColonToken */)) {
- node.kind = 238 /* LabeledStatement */;
- node.label = expression;
- node.statement = parseStatement();
- }
- else {
- node.kind = 226 /* ExpressionStatement */;
- node.expression = expression;
- parseSemicolon();
- }
- return finishNode(node);
- }
- function nextTokenIsIdentifierOrKeywordOnSameLine() {
- nextToken();
- return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
- }
- function nextTokenIsClassKeywordOnSameLine() {
- nextToken();
- return token() === 80 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
- }
- function nextTokenIsFunctionKeywordOnSameLine() {
- nextToken();
- return token() === 94 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
- }
- function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
- nextToken();
- return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
- }
- function isDeclaration() {
- while (true) {
- switch (token()) {
- case 109 /* VarKeyword */:
- case 115 /* LetKeyword */:
- case 81 /* ConstKeyword */:
- case 94 /* FunctionKeyword */:
- case 80 /* ClassKeyword */:
- case 88 /* EnumKeyword */:
- return true;
- // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
- // however, an identifier cannot be followed by another identifier on the same line. This is what we
- // count on to parse out the respective declarations. For instance, we exploit this to say that
- //
- // namespace n
- //
- // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
- //
- // namespace
- // n
- //
- // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
- // We need to look one token ahead to see if it permissible to try parsing a declaration.
- //
- // *Note*: 'interface' is actually a strict mode reserved word. So while
- //
- // "use strict"
- // interface
- // I {}
- //
- // could be legal, it would add complexity for very little gain.
- case 114 /* InterfaceKeyword */:
- case 145 /* TypeKeyword */:
- return nextTokenIsIdentifierOnSameLine();
- case 135 /* ModuleKeyword */:
- case 136 /* NamespaceKeyword */:
- return nextTokenIsIdentifierOrStringLiteralOnSameLine();
- case 122 /* AbstractKeyword */:
- case 126 /* AsyncKeyword */:
- case 130 /* DeclareKeyword */:
- case 117 /* PrivateKeyword */:
- case 118 /* ProtectedKeyword */:
- case 119 /* PublicKeyword */:
- case 138 /* ReadonlyKeyword */:
- nextToken();
- // ASI takes effect for this modifier.
- if (scanner.hasPrecedingLineBreak()) {
- return false;
- }
- continue;
- case 150 /* GlobalKeyword */:
- nextToken();
- return token() === 18 /* OpenBraceToken */ || token() === 75 /* Identifier */ || token() === 89 /* ExportKeyword */;
- case 96 /* ImportKeyword */:
- nextToken();
- return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
- token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
- case 89 /* ExportKeyword */:
- var currentToken_1 = nextToken();
- if (currentToken_1 === 145 /* TypeKeyword */) {
- currentToken_1 = lookAhead(nextToken);
- }
- if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
- currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 84 /* DefaultKeyword */ ||
- currentToken_1 === 123 /* AsKeyword */) {
- return true;
- }
- continue;
- case 120 /* StaticKeyword */:
- nextToken();
- continue;
- default:
- return false;
- }
- }
- }
- function isStartOfDeclaration() {
- return lookAhead(isDeclaration);
- }
- function isStartOfStatement() {
- switch (token()) {
- case 59 /* AtToken */:
- case 26 /* SemicolonToken */:
- case 18 /* OpenBraceToken */:
- case 109 /* VarKeyword */:
- case 115 /* LetKeyword */:
- case 94 /* FunctionKeyword */:
- case 80 /* ClassKeyword */:
- case 88 /* EnumKeyword */:
- case 95 /* IfKeyword */:
- case 86 /* DoKeyword */:
- case 111 /* WhileKeyword */:
- case 93 /* ForKeyword */:
- case 82 /* ContinueKeyword */:
- case 77 /* BreakKeyword */:
- case 101 /* ReturnKeyword */:
- case 112 /* WithKeyword */:
- case 103 /* SwitchKeyword */:
- case 105 /* ThrowKeyword */:
- case 107 /* TryKeyword */:
- case 83 /* DebuggerKeyword */:
- // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
- // however, we say they are here so that we may gracefully parse them and error later.
- // falls through
- case 79 /* CatchKeyword */:
- case 92 /* FinallyKeyword */:
- return true;
- case 96 /* ImportKeyword */:
- return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
- case 81 /* ConstKeyword */:
- case 89 /* ExportKeyword */:
- return isStartOfDeclaration();
- case 126 /* AsyncKeyword */:
- case 130 /* DeclareKeyword */:
- case 114 /* InterfaceKeyword */:
- case 135 /* ModuleKeyword */:
- case 136 /* NamespaceKeyword */:
- case 145 /* TypeKeyword */:
- case 150 /* GlobalKeyword */:
- // When these don't start a declaration, they're an identifier in an expression statement
- return true;
- case 119 /* PublicKeyword */:
- case 117 /* PrivateKeyword */:
- case 118 /* ProtectedKeyword */:
- case 120 /* StaticKeyword */:
- case 138 /* ReadonlyKeyword */:
- // When these don't start a declaration, they may be the start of a class member if an identifier
- // immediately follows. Otherwise they're an identifier in an expression statement.
- return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
- default:
- return isStartOfExpression();
- }
- }
- function nextTokenIsIdentifierOrStartOfDestructuring() {
- nextToken();
- return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
- }
- function isLetDeclaration() {
- // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
- // or [.
- return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
- }
- function parseStatement() {
- switch (token()) {
- case 26 /* SemicolonToken */:
- return parseEmptyStatement();
- case 18 /* OpenBraceToken */:
- return parseBlock(/*ignoreMissingOpenBrace*/ false);
- case 109 /* VarKeyword */:
- return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
- case 115 /* LetKeyword */:
- if (isLetDeclaration()) {
- return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
- }
- break;
- case 94 /* FunctionKeyword */:
- return parseFunctionDeclaration(createNodeWithJSDoc(244 /* FunctionDeclaration */));
- case 80 /* ClassKeyword */:
- return parseClassDeclaration(createNodeWithJSDoc(245 /* ClassDeclaration */));
- case 95 /* IfKeyword */:
- return parseIfStatement();
- case 86 /* DoKeyword */:
- return parseDoStatement();
- case 111 /* WhileKeyword */:
- return parseWhileStatement();
- case 93 /* ForKeyword */:
- return parseForOrForInOrForOfStatement();
- case 82 /* ContinueKeyword */:
- return parseBreakOrContinueStatement(233 /* ContinueStatement */);
- case 77 /* BreakKeyword */:
- return parseBreakOrContinueStatement(234 /* BreakStatement */);
- case 101 /* ReturnKeyword */:
- return parseReturnStatement();
- case 112 /* WithKeyword */:
- return parseWithStatement();
- case 103 /* SwitchKeyword */:
- return parseSwitchStatement();
- case 105 /* ThrowKeyword */:
- return parseThrowStatement();
- case 107 /* TryKeyword */:
- // Include 'catch' and 'finally' for error recovery.
- // falls through
- case 79 /* CatchKeyword */:
- case 92 /* FinallyKeyword */:
- return parseTryStatement();
- case 83 /* DebuggerKeyword */:
- return parseDebuggerStatement();
- case 59 /* AtToken */:
- return parseDeclaration();
- case 126 /* AsyncKeyword */:
- case 114 /* InterfaceKeyword */:
- case 145 /* TypeKeyword */:
- case 135 /* ModuleKeyword */:
- case 136 /* NamespaceKeyword */:
- case 130 /* DeclareKeyword */:
- case 81 /* ConstKeyword */:
- case 88 /* EnumKeyword */:
- case 89 /* ExportKeyword */:
- case 96 /* ImportKeyword */:
- case 117 /* PrivateKeyword */:
- case 118 /* ProtectedKeyword */:
- case 119 /* PublicKeyword */:
- case 122 /* AbstractKeyword */:
- case 120 /* StaticKeyword */:
- case 138 /* ReadonlyKeyword */:
- case 150 /* GlobalKeyword */:
- if (isStartOfDeclaration()) {
- return parseDeclaration();
- }
- break;
- }
- return parseExpressionOrLabeledStatement();
- }
- function isDeclareModifier(modifier) {
- return modifier.kind === 130 /* DeclareKeyword */;
- }
- function parseDeclaration() {
- var modifiers = lookAhead(function () { return (parseDecorators(), parseModifiers()); });
- // `parseListElement` attempted to get the reused node at this position,
- // but the ambient context flag was not yet set, so the node appeared
- // not reusable in that context.
- var isAmbient = ts.some(modifiers, isDeclareModifier);
- if (isAmbient) {
- var node_3 = tryReuseAmbientDeclaration();
- if (node_3) {
- return node_3;
- }
- }
- var node = createNodeWithJSDoc(0 /* Unknown */);
- node.decorators = parseDecorators();
- node.modifiers = parseModifiers();
- if (isAmbient) {
- for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
- var m = _a[_i];
- m.flags |= 8388608 /* Ambient */;
- }
- return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(node); });
- }
- else {
- return parseDeclarationWorker(node);
- }
- }
- function tryReuseAmbientDeclaration() {
- return doInsideOfContext(8388608 /* Ambient */, function () {
- var node = currentNode(parsingContext);
- if (node) {
- return consumeNode(node);
- }
- });
- }
- function parseDeclarationWorker(node) {
- switch (token()) {
- case 109 /* VarKeyword */:
- case 115 /* LetKeyword */:
- case 81 /* ConstKeyword */:
- return parseVariableStatement(node);
- case 94 /* FunctionKeyword */:
- return parseFunctionDeclaration(node);
- case 80 /* ClassKeyword */:
- return parseClassDeclaration(node);
- case 114 /* InterfaceKeyword */:
- return parseInterfaceDeclaration(node);
- case 145 /* TypeKeyword */:
- return parseTypeAliasDeclaration(node);
- case 88 /* EnumKeyword */:
- return parseEnumDeclaration(node);
- case 150 /* GlobalKeyword */:
- case 135 /* ModuleKeyword */:
- case 136 /* NamespaceKeyword */:
- return parseModuleDeclaration(node);
- case 96 /* ImportKeyword */:
- return parseImportDeclarationOrImportEqualsDeclaration(node);
- case 89 /* ExportKeyword */:
- nextToken();
- switch (token()) {
- case 84 /* DefaultKeyword */:
- case 62 /* EqualsToken */:
- return parseExportAssignment(node);
- case 123 /* AsKeyword */:
- return parseNamespaceExportDeclaration(node);
- default:
- return parseExportDeclaration(node);
- }
- default:
- if (node.decorators || node.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 missing = createMissingNode(264 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
- missing.pos = node.pos;
- missing.decorators = node.decorators;
- missing.modifiers = node.modifiers;
- return finishNode(missing);
- }
- return undefined; // TODO: GH#18217
- }
- }
- function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
- nextToken();
- return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
- }
- function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
- if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
- parseSemicolon();
- return;
- }
- return parseFunctionBlock(flags, diagnosticMessage);
- }
- // DECLARATIONS
- function parseArrayBindingElement() {
- if (token() === 27 /* CommaToken */) {
- return createNode(215 /* OmittedExpression */);
- }
- var node = createNode(191 /* BindingElement */);
- node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
- node.name = parseIdentifierOrPattern();
- node.initializer = parseInitializer();
- return finishNode(node);
- }
- function parseObjectBindingElement() {
- var node = createNode(191 /* BindingElement */);
- node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
- var tokenIsIdentifier = isIdentifier();
- var propertyName = parsePropertyName();
- if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
- node.name = propertyName;
- }
- else {
- parseExpected(58 /* ColonToken */);
- node.propertyName = propertyName;
- node.name = parseIdentifierOrPattern();
- }
- node.initializer = parseInitializer();
- return finishNode(node);
- }
- function parseObjectBindingPattern() {
- var node = createNode(189 /* ObjectBindingPattern */);
- parseExpected(18 /* OpenBraceToken */);
- node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
- parseExpected(19 /* CloseBraceToken */);
- return finishNode(node);
- }
- function parseArrayBindingPattern() {
- var node = createNode(190 /* ArrayBindingPattern */);
- parseExpected(22 /* OpenBracketToken */);
- node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
- parseExpected(23 /* CloseBracketToken */);
- return finishNode(node);
- }
- function isIdentifierOrPrivateIdentifierOrPattern() {
- return token() === 18 /* OpenBraceToken */
- || token() === 22 /* OpenBracketToken */
- || token() === 76 /* PrivateIdentifier */
- || isIdentifier();
- }
- function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
- if (token() === 22 /* OpenBracketToken */) {
- return parseArrayBindingPattern();
- }
- if (token() === 18 /* OpenBraceToken */) {
- return parseObjectBindingPattern();
- }
- return parseIdentifier(/*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
- }
- function parseVariableDeclarationAllowExclamation() {
- return parseVariableDeclaration(/*allowExclamation*/ true);
- }
- function parseVariableDeclaration(allowExclamation) {
- var node = createNode(242 /* VariableDeclaration */);
- node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
- if (allowExclamation && node.name.kind === 75 /* Identifier */ &&
- token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
- node.exclamationToken = parseTokenNode();
- }
- node.type = parseTypeAnnotation();
- if (!isInOrOfKeyword(token())) {
- node.initializer = parseInitializer();
- }
- return finishNode(node);
- }
- function parseVariableDeclarationList(inForStatementInitializer) {
- var node = createNode(243 /* VariableDeclarationList */);
- switch (token()) {
- case 109 /* VarKeyword */:
- break;
- case 115 /* LetKeyword */:
- node.flags |= 1 /* Let */;
- break;
- case 81 /* ConstKeyword */:
- node.flags |= 2 /* Const */;
- break;
- default:
- ts.Debug.fail();
- }
- nextToken();
- // The user may have written the following:
- //
- // for (let of X) { }
- //
- // In this case, we want to parse an empty declaration list, and then parse 'of'
- // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
- // 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() === 152 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
- node.declarations = createMissingList();
- }
- else {
- var savedDisallowIn = inDisallowInContext();
- setDisallowInContext(inForStatementInitializer);
- node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
- setDisallowInContext(savedDisallowIn);
- }
- return finishNode(node);
- }
- function canFollowContextualOfKeyword() {
- return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
- }
- function parseVariableStatement(node) {
- node.kind = 225 /* VariableStatement */;
- node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
- parseSemicolon();
- return finishNode(node);
- }
- function parseFunctionDeclaration(node) {
- node.kind = 244 /* FunctionDeclaration */;
- parseExpected(94 /* FunctionKeyword */);
- node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
- node.name = hasModifierOfKind(node, 84 /* DefaultKeyword */) ? parseOptionalIdentifier() : parseIdentifier();
- var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
- var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
- fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
- node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
- return finishNode(node);
- }
- function parseConstructorName() {
- if (token() === 129 /* ConstructorKeyword */) {
- return parseExpected(129 /* ConstructorKeyword */);
- }
- if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
- return tryParse(function () {
- var literalNode = parseLiteralNode();
- return literalNode.text === "constructor" ? literalNode : undefined;
- });
- }
- }
- function tryParseConstructorDeclaration(node) {
- return tryParse(function () {
- if (parseConstructorName()) {
- node.kind = 162 /* Constructor */;
- fillSignature(58 /* ColonToken */, 0 /* None */, node);
- node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
- return finishNode(node);
- }
- });
- }
- function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
- node.kind = 161 /* MethodDeclaration */;
- node.asteriskToken = asteriskToken;
- var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
- var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
- fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
- node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
- return finishNode(node);
- }
- function parsePropertyDeclaration(node) {
- node.kind = 159 /* PropertyDeclaration */;
- if (!node.questionToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
- node.exclamationToken = parseTokenNode();
- }
- node.type = parseTypeAnnotation();
- node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
- parseSemicolon();
- return finishNode(node);
- }
- function parsePropertyOrMethodDeclaration(node) {
- var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
- node.name = parsePropertyName();
- // Note: this is not legal as per the grammar. But we allow it in the parser and
- // report an error in the grammar checker.
- node.questionToken = parseOptionalToken(57 /* QuestionToken */);
- if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
- return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
- }
- return parsePropertyDeclaration(node);
- }
- function parseAccessorDeclaration(node, kind) {
- node.kind = kind;
- node.name = parsePropertyName();
- fillSignature(58 /* ColonToken */, 0 /* None */, node);
- node.body = parseFunctionBlockOrSemicolon(0 /* None */);
- return finishNode(node);
- }
- function isClassMemberStart() {
- var idToken;
- if (token() === 59 /* AtToken */) {
- return true;
- }
- // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
- while (ts.isModifierKind(token())) {
- idToken = token();
- // If the idToken is a class modifier (protected, private, public, and static), it is
- // certain that we are starting to parse class member. This allows better error recovery
- // Example:
- // public foo() ... // true
- // public @dec blah ... // true; we will then report an error later
- // export public ... // true; we will then report an error later
- if (ts.isClassMemberModifier(idToken)) {
- return true;
- }
- nextToken();
- }
- if (token() === 41 /* AsteriskToken */) {
- return true;
- }
- // Try to get the first property-like token following all modifiers.
- // This can either be an identifier or the 'get' or 'set' keywords.
- if (isLiteralPropertyName()) {
- idToken = token();
- nextToken();
- }
- // Index signatures and computed properties are class members; we can parse.
- if (token() === 22 /* OpenBracketToken */) {
- return true;
- }
- // 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 === 142 /* SetKeyword */ || idToken === 131 /* GetKeyword */) {
- return true;
- }
- // If it *is* a keyword, but not an accessor, check a little farther along
- // to see if it should actually be parsed as a class member.
- switch (token()) {
- case 20 /* OpenParenToken */: // Method declaration
- case 29 /* LessThanToken */: // Generic Method declaration
- case 53 /* ExclamationToken */: // Non-null assertion on property name
- case 58 /* ColonToken */: // Type Annotation for declaration
- case 62 /* EqualsToken */: // Initializer for declaration
- case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
- return true;
- default:
- // Covers
- // - Semicolons (declaration termination)
- // - Closing braces (end-of-class, must be declaration)
- // - End-of-files (not valid, but permitted so that it gets caught later on)
- // - Line-breaks (enabling *automatic semicolon insertion*)
- return canParseSemicolon();
- }
- }
- return false;
- }
- function parseDecorators() {
- var list;
- var listPos = getNodePos();
- while (true) {
- var decoratorStart = getNodePos();
- if (!parseOptional(59 /* AtToken */)) {
- break;
- }
- var decorator = createNode(157 /* Decorator */, decoratorStart);
- decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
- finishNode(decorator);
- (list || (list = [])).push(decorator);
- }
- return list && createNodeArray(list, listPos);
- }
- /*
- * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
- * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
- * and turns it into a standalone declaration), then it is better to parse it and report an error later.
- *
- * In such situations, 'permitInvalidConstAsModifier' should be set to true.
- */
- function parseModifiers(permitInvalidConstAsModifier) {
- var list;
- var listPos = getNodePos();
- while (true) {
- var modifierStart = scanner.getStartPos();
- var modifierKind = token();
- if (token() === 81 /* ConstKeyword */ && permitInvalidConstAsModifier) {
- // We need to ensure that any subsequent modifiers appear on the same line
- // so that when 'const' is a standalone declaration, we don't issue an error.
- if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
- break;
- }
- }
- else {
- if (!parseAnyContextualModifier()) {
- break;
- }
- }
- var modifier = finishNode(createNode(modifierKind, modifierStart));
- (list || (list = [])).push(modifier);
- }
- return list && createNodeArray(list, listPos);
- }
- function parseModifiersForArrowFunction() {
- var modifiers;
- if (token() === 126 /* AsyncKeyword */) {
- var modifierStart = scanner.getStartPos();
- var modifierKind = token();
- nextToken();
- var modifier = finishNode(createNode(modifierKind, modifierStart));
- modifiers = createNodeArray([modifier], modifierStart);
- }
- return modifiers;
- }
- function parseClassElement() {
- if (token() === 26 /* SemicolonToken */) {
- var result = createNode(222 /* SemicolonClassElement */);
- nextToken();
- return finishNode(result);
- }
- var node = createNodeWithJSDoc(0 /* Unknown */);
- node.decorators = parseDecorators();
- node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
- if (parseContextualModifier(131 /* GetKeyword */)) {
- return parseAccessorDeclaration(node, 163 /* GetAccessor */);
- }
- if (parseContextualModifier(142 /* SetKeyword */)) {
- return parseAccessorDeclaration(node, 164 /* SetAccessor */);
- }
- if (token() === 129 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
- var constructorDeclaration = tryParseConstructorDeclaration(node);
- if (constructorDeclaration) {
- return constructorDeclaration;
- }
- }
- if (isIndexSignature()) {
- return parseIndexSignatureDeclaration(node);
- }
- // It is very important that we check this *after* checking indexers because
- // the [ token can start an index signature or a computed property name
- if (ts.tokenIsIdentifierOrKeyword(token()) ||
- token() === 10 /* StringLiteral */ ||
- token() === 8 /* NumericLiteral */ ||
- token() === 41 /* AsteriskToken */ ||
- token() === 22 /* OpenBracketToken */) {
- var isAmbient = node.modifiers && ts.some(node.modifiers, isDeclareModifier);
- if (isAmbient) {
- for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
- var m = _a[_i];
- m.flags |= 8388608 /* Ambient */;
- }
- return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(node); });
- }
- else {
- return parsePropertyOrMethodDeclaration(node);
- }
- }
- if (node.decorators || node.modifiers) {
- // treat this as a property declaration with a missing name.
- node.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
- return parsePropertyDeclaration(node);
- }
- // 'isClassMemberStart' should have hinted not to attempt parsing.
- return ts.Debug.fail("Should not have attempted to parse class member declaration.");
- }
- function parseClassExpression() {
- return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 214 /* ClassExpression */);
- }
- function parseClassDeclaration(node) {
- return parseClassDeclarationOrExpression(node, 245 /* ClassDeclaration */);
- }
- function parseClassDeclarationOrExpression(node, kind) {
- node.kind = kind;
- parseExpected(80 /* ClassKeyword */);
- node.name = parseNameOfClassDeclarationOrExpression();
- node.typeParameters = parseTypeParameters();
- node.heritageClauses = parseHeritageClauses();
- if (parseExpected(18 /* OpenBraceToken */)) {
- // ClassTail[Yield,Await] : (Modified) See 14.5
- // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
- node.members = parseClassMembers();
- parseExpected(19 /* CloseBraceToken */);
- }
- else {
- node.members = createMissingList();
- }
- return finishNode(node);
- }
- function parseNameOfClassDeclarationOrExpression() {
- // implements is a future reserved word so
- // 'class implements' might mean either
- // - class expression with omitted name, 'implements' starts heritage clause
- // - class with name 'implements'
- // 'isImplementsClause' helps to disambiguate between these two cases
- return isIdentifier() && !isImplementsClause()
- ? parseIdentifier()
- : undefined;
- }
- function isImplementsClause() {
- return token() === 113 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
- }
- function parseHeritageClauses() {
- // ClassTail[Yield,Await] : (Modified) See 14.5
- // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
- if (isHeritageClause()) {
- return parseList(22 /* HeritageClauses */, parseHeritageClause);
- }
- return undefined;
- }
- function parseHeritageClause() {
- var tok = token();
- ts.Debug.assert(tok === 90 /* ExtendsKeyword */ || tok === 113 /* ImplementsKeyword */); // isListElement() should ensure this.
- var node = createNode(279 /* HeritageClause */);
- node.token = tok;
- nextToken();
- node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
- return finishNode(node);
- }
- function parseExpressionWithTypeArguments() {
- var node = createNode(216 /* ExpressionWithTypeArguments */);
- node.expression = parseLeftHandSideExpressionOrHigher();
- node.typeArguments = tryParseTypeArguments();
- return finishNode(node);
- }
- function tryParseTypeArguments() {
- return token() === 29 /* LessThanToken */ ?
- parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
- }
- function isHeritageClause() {
- return token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
- }
- function parseClassMembers() {
- return parseList(5 /* ClassMembers */, parseClassElement);
- }
- function parseInterfaceDeclaration(node) {
- node.kind = 246 /* InterfaceDeclaration */;
- parseExpected(114 /* InterfaceKeyword */);
- node.name = parseIdentifier();
- node.typeParameters = parseTypeParameters();
- node.heritageClauses = parseHeritageClauses();
- node.members = parseObjectTypeMembers();
- return finishNode(node);
- }
- function parseTypeAliasDeclaration(node) {
- node.kind = 247 /* TypeAliasDeclaration */;
- parseExpected(145 /* TypeKeyword */);
- node.name = parseIdentifier();
- node.typeParameters = parseTypeParameters();
- parseExpected(62 /* EqualsToken */);
- node.type = parseType();
- parseSemicolon();
- return finishNode(node);
- }
- // In an ambient declaration, the grammar only allows integer literals as initializers.
- // In a non-ambient declaration, the grammar allows uninitialized members only in a
- // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
- // or any time an integer literal initializer is encountered.
- function parseEnumMember() {
- var node = createNodeWithJSDoc(284 /* EnumMember */);
- node.name = parsePropertyName();
- node.initializer = allowInAnd(parseInitializer);
- return finishNode(node);
- }
- function parseEnumDeclaration(node) {
- node.kind = 248 /* EnumDeclaration */;
- parseExpected(88 /* EnumKeyword */);
- node.name = parseIdentifier();
- if (parseExpected(18 /* OpenBraceToken */)) {
- node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
- parseExpected(19 /* CloseBraceToken */);
- }
- else {
- node.members = createMissingList();
- }
- return finishNode(node);
- }
- function parseModuleBlock() {
- var node = createNode(250 /* ModuleBlock */);
- if (parseExpected(18 /* OpenBraceToken */)) {
- node.statements = parseList(1 /* BlockStatements */, parseStatement);
- parseExpected(19 /* CloseBraceToken */);
- }
- else {
- node.statements = createMissingList();
- }
- return finishNode(node);
- }
- function parseModuleOrNamespaceDeclaration(node, flags) {
- node.kind = 249 /* ModuleDeclaration */;
- // 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 */;
- node.flags |= flags;
- node.name = parseIdentifier();
- node.body = parseOptional(24 /* DotToken */)
- ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
- : parseModuleBlock();
- return finishNode(node);
- }
- function parseAmbientExternalModuleDeclaration(node) {
- node.kind = 249 /* ModuleDeclaration */;
- if (token() === 150 /* GlobalKeyword */) {
- // parse 'global' as name of global scope augmentation
- node.name = parseIdentifier();
- node.flags |= 1024 /* GlobalAugmentation */;
- }
- else {
- node.name = parseLiteralNode();
- node.name.text = internIdentifier(node.name.text);
- }
- if (token() === 18 /* OpenBraceToken */) {
- node.body = parseModuleBlock();
- }
- else {
- parseSemicolon();
- }
- return finishNode(node);
- }
- function parseModuleDeclaration(node) {
- var flags = 0;
- if (token() === 150 /* GlobalKeyword */) {
- // global augmentation
- return parseAmbientExternalModuleDeclaration(node);
- }
- else if (parseOptional(136 /* NamespaceKeyword */)) {
- flags |= 16 /* Namespace */;
- }
- else {
- parseExpected(135 /* ModuleKeyword */);
- if (token() === 10 /* StringLiteral */) {
- return parseAmbientExternalModuleDeclaration(node);
- }
- }
- return parseModuleOrNamespaceDeclaration(node, flags);
- }
- function isExternalModuleReference() {
- return token() === 139 /* RequireKeyword */ &&
- lookAhead(nextTokenIsOpenParen);
- }
- function nextTokenIsOpenParen() {
- return nextToken() === 20 /* OpenParenToken */;
- }
- function nextTokenIsSlash() {
- return nextToken() === 43 /* SlashToken */;
- }
- function parseNamespaceExportDeclaration(node) {
- node.kind = 252 /* NamespaceExportDeclaration */;
- parseExpected(123 /* AsKeyword */);
- parseExpected(136 /* NamespaceKeyword */);
- node.name = parseIdentifier();
- parseSemicolon();
- return finishNode(node);
- }
- function parseImportDeclarationOrImportEqualsDeclaration(node) {
- parseExpected(96 /* ImportKeyword */);
- var afterImportPos = scanner.getStartPos();
- var identifier;
- if (isIdentifier()) {
- identifier = parseIdentifier();
- }
- var isTypeOnly = false;
- if (token() !== 149 /* FromKeyword */ &&
- (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
- (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
- isTypeOnly = true;
- identifier = isIdentifier() ? parseIdentifier() : undefined;
- }
- if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
- return parseImportEqualsDeclaration(node, identifier, isTypeOnly);
- }
- // Import statement
- node.kind = 254 /* ImportDeclaration */;
- // ImportDeclaration:
- // import ImportClause from ModuleSpecifier ;
- // import ModuleSpecifier;
- if (identifier || // import id
- token() === 41 /* AsteriskToken */ || // import *
- token() === 18 /* OpenBraceToken */ // import {
- ) {
- node.importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
- parseExpected(149 /* FromKeyword */);
- }
- node.moduleSpecifier = parseModuleSpecifier();
- parseSemicolon();
- return finishNode(node);
- }
- function tokenAfterImportDefinitelyProducesImportDeclaration() {
- return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
- }
- function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
- // In `import id ___`, the current token decides whether to produce
- // an ImportDeclaration or ImportEqualsDeclaration.
- return token() === 27 /* CommaToken */ || token() === 149 /* FromKeyword */;
- }
- function parseImportEqualsDeclaration(node, identifier, isTypeOnly) {
- node.kind = 253 /* ImportEqualsDeclaration */;
- node.name = identifier;
- parseExpected(62 /* EqualsToken */);
- node.moduleReference = parseModuleReference();
- parseSemicolon();
- var finished = finishNode(node);
- if (isTypeOnly) {
- parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
- }
- return finished;
- }
- function parseImportClause(identifier, fullStart, isTypeOnly) {
- // ImportClause:
- // ImportedDefaultBinding
- // NameSpaceImport
- // NamedImports
- // ImportedDefaultBinding, NameSpaceImport
- // ImportedDefaultBinding, NamedImports
- var importClause = createNode(255 /* ImportClause */, fullStart);
- importClause.isTypeOnly = isTypeOnly;
- if (identifier) {
- // ImportedDefaultBinding:
- // ImportedBinding
- importClause.name = identifier;
- }
- // If there was no default import or if there is comma token after default import
- // parse namespace or named imports
- if (!importClause.name ||
- parseOptional(27 /* CommaToken */)) {
- importClause.namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(257 /* NamedImports */);
- }
- return finishNode(importClause);
- }
- function parseModuleReference() {
- return isExternalModuleReference()
- ? parseExternalModuleReference()
- : parseEntityName(/*allowReservedWords*/ false);
- }
- function parseExternalModuleReference() {
- var node = createNode(265 /* ExternalModuleReference */);
- parseExpected(139 /* RequireKeyword */);
- parseExpected(20 /* OpenParenToken */);
- node.expression = parseModuleSpecifier();
- parseExpected(21 /* CloseParenToken */);
- return finishNode(node);
- }
- function parseModuleSpecifier() {
- if (token() === 10 /* StringLiteral */) {
- var result = parseLiteralNode();
- result.text = internIdentifier(result.text);
- return result;
- }
- else {
- // We allow arbitrary expressions here, even though the grammar only allows string
- // literals. We check to ensure that it is only a string literal later in the grammar
- // check pass.
- return parseExpression();
- }
- }
- function parseNamespaceImport() {
- // NameSpaceImport:
- // * as ImportedBinding
- var namespaceImport = createNode(256 /* NamespaceImport */);
- parseExpected(41 /* AsteriskToken */);
- parseExpected(123 /* AsKeyword */);
- namespaceImport.name = parseIdentifier();
- return finishNode(namespaceImport);
- }
- function parseNamedImportsOrExports(kind) {
- var node = createNode(kind);
- // NamedImports:
- // { }
- // { ImportsList }
- // { ImportsList, }
- // ImportsList:
- // ImportSpecifier
- // ImportsList, ImportSpecifier
- node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 257 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */);
- return finishNode(node);
- }
- function parseExportSpecifier() {
- return parseImportOrExportSpecifier(263 /* ExportSpecifier */);
- }
- function parseImportSpecifier() {
- return parseImportOrExportSpecifier(258 /* ImportSpecifier */);
- }
- function parseImportOrExportSpecifier(kind) {
- var node = createNode(kind);
- // ImportSpecifier:
- // BindingIdentifier
- // IdentifierName as BindingIdentifier
- // ExportSpecifier:
- // IdentifierName
- // IdentifierName as IdentifierName
- var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
- var checkIdentifierStart = scanner.getTokenPos();
- var checkIdentifierEnd = scanner.getTextPos();
- var identifierName = parseIdentifierName();
- if (token() === 123 /* AsKeyword */) {
- node.propertyName = identifierName;
- parseExpected(123 /* AsKeyword */);
- checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
- checkIdentifierStart = scanner.getTokenPos();
- checkIdentifierEnd = scanner.getTextPos();
- node.name = parseIdentifierName();
- }
- else {
- node.name = identifierName;
- }
- if (kind === 258 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
- parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
- }
- return finishNode(node);
- }
- function parseNamespaceExport(pos) {
- var node = createNode(262 /* NamespaceExport */, pos);
- node.name = parseIdentifier();
- return finishNode(node);
- }
- function parseExportDeclaration(node) {
- node.kind = 260 /* ExportDeclaration */;
- node.isTypeOnly = parseOptional(145 /* TypeKeyword */);
- var namespaceExportPos = scanner.getStartPos();
- if (parseOptional(41 /* AsteriskToken */)) {
- if (parseOptional(123 /* AsKeyword */)) {
- node.exportClause = parseNamespaceExport(namespaceExportPos);
- }
- parseExpected(149 /* FromKeyword */);
- node.moduleSpecifier = parseModuleSpecifier();
- }
- else {
- node.exportClause = parseNamedImportsOrExports(261 /* 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() === 149 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
- parseExpected(149 /* FromKeyword */);
- node.moduleSpecifier = parseModuleSpecifier();
- }
- }
- parseSemicolon();
- return finishNode(node);
- }
- function parseExportAssignment(node) {
- node.kind = 259 /* ExportAssignment */;
- if (parseOptional(62 /* EqualsToken */)) {
- node.isExportEquals = true;
- }
- else {
- parseExpected(84 /* DefaultKeyword */);
- }
- node.expression = parseAssignmentExpressionOrHigher();
- parseSemicolon();
- return finishNode(node);
- }
- function setExternalModuleIndicator(sourceFile) {
- // Try to use the first top-level import/export when available, then
- // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
- sourceFile.externalModuleIndicator =
- ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
- getImportMetaIfNecessary(sourceFile);
- }
- function isAnExternalModuleIndicatorNode(node) {
- return hasModifierOfKind(node, 89 /* ExportKeyword */)
- || node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */
- || node.kind === 254 /* ImportDeclaration */
- || node.kind === 259 /* ExportAssignment */
- || node.kind === 260 /* ExportDeclaration */ ? node : undefined;
- }
- function getImportMetaIfNecessary(sourceFile) {
- return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
- walkTreeForExternalModuleIndicators(sourceFile) :
- undefined;
- }
- function walkTreeForExternalModuleIndicators(node) {
- return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
- }
- /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
- function hasModifierOfKind(node, kind) {
- return ts.some(node.modifiers, function (m) { return m.kind === kind; });
- }
- function isImportMeta(node) {
- return ts.isMetaProperty(node) && node.keywordToken === 96 /* ImportKeyword */ && node.name.escapedText === "meta";
- }
- var ParsingContext;
- (function (ParsingContext) {
- ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
- ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
- ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
- ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
- ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
- ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
- ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
- ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
- ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
- ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
- ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
- ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
- ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
- ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
- ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
- ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
- ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
- ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
- ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
- ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
- ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
- ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
- ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
- ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
- ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
- })(ParsingContext || (ParsingContext = {}));
- var Tristate;
- (function (Tristate) {
- Tristate[Tristate["False"] = 0] = "False";
- Tristate[Tristate["True"] = 1] = "True";
- Tristate[Tristate["Unknown"] = 2] = "Unknown";
- })(Tristate || (Tristate = {}));
- var JSDocParser;
- (function (JSDocParser) {
- function parseJSDocTypeExpressionForTests(content, start, length) {
- initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
- sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
- scanner.setText(content, start, length);
- currentToken = scanner.scan();
- var jsDocTypeExpression = parseJSDocTypeExpression();
- var diagnostics = parseDiagnostics;
- clearState();
- return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
- }
- JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
- // Parses out a JSDoc type expression.
- function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(294 /* JSDocTypeExpression */);
- var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
- result.type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
- if (!mayOmitBraces || hasBrace) {
- parseExpectedJSDoc(19 /* CloseBraceToken */);
- }
- fixupParentReferences(result);
- return finishNode(result);
- }
- JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
- function parseIsolatedJSDocComment(content, start, length) {
- initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
- sourceFile = { languageVariant: 0 /* Standard */, text: content };
- var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
- var diagnostics = parseDiagnostics;
- clearState();
- return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
- }
- JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
- function parseJSDocComment(parent, start, length) {
- var _a;
- var saveToken = currentToken;
- var saveParseDiagnosticsLength = parseDiagnostics.length;
- var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
- var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
- if (comment) {
- comment.parent = parent;
- }
- if (contextFlags & 131072 /* JavaScriptFile */) {
- if (!sourceFile.jsDocDiagnostics) {
- sourceFile.jsDocDiagnostics = [];
- }
- (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
- }
- currentToken = saveToken;
- parseDiagnostics.length = saveParseDiagnosticsLength;
- parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
- return comment;
- }
- JSDocParser.parseJSDocComment = parseJSDocComment;
- var JSDocState;
- (function (JSDocState) {
- JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
- JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
- JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
- JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
- })(JSDocState || (JSDocState = {}));
- var PropertyLikeParse;
- (function (PropertyLikeParse) {
- PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
- PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
- PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
- })(PropertyLikeParse || (PropertyLikeParse = {}));
- function parseJSDocCommentWorker(start, length) {
- if (start === void 0) { start = 0; }
- var content = sourceText;
- var end = length === undefined ? content.length : start + length;
- length = end - start;
- ts.Debug.assert(start >= 0);
- ts.Debug.assert(start <= end);
- ts.Debug.assert(end <= content.length);
- // Check for /** (JSDoc opening part)
- if (!isJSDocLikeText(content, start)) {
- return undefined;
- }
- var tags;
- var tagsPos;
- var tagsEnd;
- var comments = [];
- // + 3 for leading /**, - 5 in total for /** */
- return scanner.scanRange(start + 3, length - 5, function () {
- // Initially we can parse out a tag. We also have seen a starting asterisk.
- // This is so that /** * @type */ doesn't parse.
- var state = 1 /* SawAsterisk */;
- var margin;
- // + 4 for leading '/** '
- var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
- function pushComment(text) {
- if (!margin) {
- margin = indent;
- }
- comments.push(text);
- indent += text.length;
- }
- nextTokenJSDoc();
- while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
- ;
- if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
- state = 0 /* BeginningOfLine */;
- indent = 0;
- }
- loop: while (true) {
- switch (token()) {
- case 59 /* AtToken */:
- if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
- removeTrailingWhitespace(comments);
- addTag(parseTag(indent));
- // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
- // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
- // for malformed examples like `/** @param {string} x @returns {number} the length */`
- state = 0 /* BeginningOfLine */;
- margin = undefined;
- }
- else {
- pushComment(scanner.getTokenText());
- }
- break;
- case 4 /* NewLineTrivia */:
- comments.push(scanner.getTokenText());
- state = 0 /* BeginningOfLine */;
- indent = 0;
- break;
- case 41 /* AsteriskToken */:
- var asterisk = scanner.getTokenText();
- 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);
- }
- else {
- // Ignore the first asterisk on a line
- state = 1 /* SawAsterisk */;
- indent += asterisk.length;
- }
- break;
- 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 */) {
- comments.push(whitespace);
- }
- else if (margin !== undefined && indent + whitespace.length > margin) {
- comments.push(whitespace.slice(margin - indent - 1));
- }
- indent += whitespace.length;
- break;
- case 1 /* EndOfFileToken */:
- break loop;
- default:
- // Anything else is doc comment text. We just save it. Because it
- // wasn't a tag, we can no longer parse a tag on this line until we hit the next
- // line break.
- state = 2 /* SavingComments */;
- pushComment(scanner.getTokenText());
- break;
- }
- nextTokenJSDoc();
- }
- removeLeadingNewlines(comments);
- removeTrailingWhitespace(comments);
- return createJSDocComment();
- });
- function removeLeadingNewlines(comments) {
- while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
- comments.shift();
- }
- }
- function removeTrailingWhitespace(comments) {
- while (comments.length && comments[comments.length - 1].trim() === "") {
- comments.pop();
- }
- }
- function createJSDocComment() {
- var result = createNode(303 /* JSDocComment */, start);
- result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
- result.comment = comments.length ? comments.join("") : undefined;
- return finishNode(result, end);
- }
- function isNextNonwhitespaceTokenEndOfFile() {
- // We must use infinite lookahead, as there could be any number of newlines :(
- while (true) {
- nextTokenJSDoc();
- if (token() === 1 /* EndOfFileToken */) {
- return true;
- }
- if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
- return false;
- }
- }
- }
- function skipWhitespace() {
- if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
- if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
- return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
- }
- }
- while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
- nextTokenJSDoc();
- }
- }
- function skipWhitespaceOrAsterisk() {
- if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
- if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
- return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
- }
- }
- var precedingLineBreak = scanner.hasPrecedingLineBreak();
- var seenLineBreak = false;
- var indentText = "";
- while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
- indentText += scanner.getTokenText();
- if (token() === 4 /* NewLineTrivia */) {
- precedingLineBreak = true;
- seenLineBreak = true;
- indentText = "";
- }
- else if (token() === 41 /* AsteriskToken */) {
- precedingLineBreak = false;
- }
- nextTokenJSDoc();
- }
- return seenLineBreak ? indentText : "";
- }
- function parseTag(margin) {
- ts.Debug.assert(token() === 59 /* AtToken */);
- var start = scanner.getTokenPos();
- nextTokenJSDoc();
- var tagName = parseJSDocIdentifierName(/*message*/ undefined);
- var indentText = skipWhitespaceOrAsterisk();
- var tag;
- switch (tagName.escapedText) {
- case "author":
- tag = parseAuthorTag(start, tagName, margin);
- break;
- case "implements":
- tag = parseImplementsTag(start, tagName);
- break;
- case "augments":
- case "extends":
- tag = parseAugmentsTag(start, tagName);
- break;
- case "class":
- case "constructor":
- tag = parseSimpleTag(start, 310 /* JSDocClassTag */, tagName);
- break;
- case "public":
- tag = parseSimpleTag(start, 311 /* JSDocPublicTag */, tagName);
- break;
- case "private":
- tag = parseSimpleTag(start, 312 /* JSDocPrivateTag */, tagName);
- break;
- case "protected":
- tag = parseSimpleTag(start, 313 /* JSDocProtectedTag */, tagName);
- break;
- case "readonly":
- tag = parseSimpleTag(start, 314 /* JSDocReadonlyTag */, tagName);
- break;
- case "this":
- tag = parseThisTag(start, tagName);
- break;
- case "enum":
- tag = parseEnumTag(start, tagName);
- break;
- case "arg":
- case "argument":
- case "param":
- return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
- case "return":
- case "returns":
- tag = parseReturnTag(start, tagName);
- break;
- case "template":
- tag = parseTemplateTag(start, tagName);
- break;
- case "type":
- tag = parseTypeTag(start, tagName);
- break;
- case "typedef":
- tag = parseTypedefTag(start, tagName, margin);
- break;
- case "callback":
- tag = parseCallbackTag(start, tagName, margin);
- break;
- default:
- tag = parseUnknownTag(start, tagName);
- break;
- }
- if (!tag.comment) {
- // some tags, like typedef and callback, have already parsed their comments earlier
- if (!indentText) {
- margin += tag.end - tag.pos;
- }
- tag.comment = parseTagComments(margin, indentText.slice(margin));
- }
- return tag;
- }
- function parseTagComments(indent, initialMargin) {
- var comments = [];
- var state = 0 /* BeginningOfLine */;
- var margin;
- function pushComment(text) {
- if (!margin) {
- margin = indent;
- }
- comments.push(text);
- indent += text.length;
- }
- if (initialMargin !== undefined) {
- // jump straight to saving comments if there is some initial indentation
- if (initialMargin !== "") {
- pushComment(initialMargin);
- }
- state = 1 /* SawAsterisk */;
- }
- var tok = token();
- loop: while (true) {
- switch (tok) {
- case 4 /* NewLineTrivia */:
- if (state >= 1 /* SawAsterisk */) {
- state = 0 /* BeginningOfLine */;
- // don't use pushComment here because we want to keep the margin unchanged
- comments.push(scanner.getTokenText());
- }
- indent = 0;
- break;
- case 59 /* AtToken */:
- if (state === 3 /* SavingBackticks */) {
- comments.push(scanner.getTokenText());
- break;
- }
- scanner.setTextPos(scanner.getTextPos() - 1);
- // falls through
- case 1 /* EndOfFileToken */:
- // Done
- break loop;
- case 5 /* WhitespaceTrivia */:
- if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
- pushComment(scanner.getTokenText());
- }
- else {
- var whitespace = scanner.getTokenText();
- // if the whitespace crosses the margin, take only the whitespace that passes the margin
- if (margin !== undefined && indent + whitespace.length > margin) {
- comments.push(whitespace.slice(margin - indent));
- }
- indent += whitespace.length;
- }
- break;
- case 18 /* OpenBraceToken */:
- state = 2 /* SavingComments */;
- if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
- pushComment(scanner.getTokenText());
- nextTokenJSDoc();
- pushComment(scanner.getTokenText());
- nextTokenJSDoc();
- }
- pushComment(scanner.getTokenText());
- break;
- case 61 /* BacktickToken */:
- if (state === 3 /* SavingBackticks */) {
- state = 2 /* SavingComments */;
- }
- else {
- state = 3 /* SavingBackticks */;
- }
- pushComment(scanner.getTokenText());
- break;
- case 41 /* AsteriskToken */:
- if (state === 0 /* BeginningOfLine */) {
- // leading asterisks start recording on the *next* (non-whitespace) token
- state = 1 /* SawAsterisk */;
- indent += 1;
- break;
- }
- // record the * as a comment
- // falls through
- default:
- if (state !== 3 /* SavingBackticks */) {
- state = 2 /* SavingComments */; // leading identifiers start recording as well
- }
- pushComment(scanner.getTokenText());
- break;
- }
- tok = nextTokenJSDoc();
- }
- removeLeadingNewlines(comments);
- removeTrailingWhitespace(comments);
- return comments.length === 0 ? undefined : comments.join("");
- }
- function parseUnknownTag(start, tagName) {
- var result = createNode(306 /* JSDocTag */, start);
- result.tagName = tagName;
- return finishNode(result);
- }
- function addTag(tag) {
- if (!tag) {
- return;
- }
- if (!tags) {
- tags = [tag];
- tagsPos = tag.pos;
- }
- else {
- tags.push(tag);
- }
- tagsEnd = tag.end;
- }
- function tryParseTypeExpression() {
- skipWhitespaceOrAsterisk();
- return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
- }
- function parseBracketNameInPropertyAndParamTag() {
- // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
- var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
- if (isBracketed) {
- skipWhitespace();
- }
- // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
- var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
- var name = parseJSDocEntityName();
- if (isBackquoted) {
- parseExpectedTokenJSDoc(61 /* BacktickToken */);
- }
- if (isBracketed) {
- skipWhitespace();
- // May have an optional default, e.g. '[foo = 42]'
- if (parseOptionalToken(62 /* EqualsToken */)) {
- parseExpression();
- }
- parseExpected(23 /* CloseBracketToken */);
- }
- return { name: name, isBracketed: isBracketed };
- }
- function isObjectOrObjectArrayTypeReference(node) {
- switch (node.kind) {
- case 141 /* ObjectKeyword */:
- return true;
- case 174 /* ArrayType */:
- return isObjectOrObjectArrayTypeReference(node.elementType);
- default:
- return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
- }
- }
- function parseParameterOrPropertyTag(start, tagName, target, indent) {
- var typeExpression = tryParseTypeExpression();
- var isNameFirst = !typeExpression;
- skipWhitespaceOrAsterisk();
- var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
- skipWhitespace();
- if (isNameFirst) {
- typeExpression = tryParseTypeExpression();
- }
- var result = target === 1 /* Property */ ?
- createNode(323 /* JSDocPropertyTag */, start) :
- createNode(317 /* JSDocParameterTag */, start);
- var comment = parseTagComments(indent + scanner.getStartPos() - start);
- var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
- if (nestedTypeLiteral) {
- typeExpression = nestedTypeLiteral;
- isNameFirst = true;
- }
- result.tagName = tagName;
- result.typeExpression = typeExpression;
- result.name = name;
- result.isNameFirst = isNameFirst;
- result.isBracketed = isBracketed;
- result.comment = comment;
- return finishNode(result);
- }
- function parseNestedTypeLiteral(typeExpression, name, target, indent) {
- if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(294 /* JSDocTypeExpression */, scanner.getTokenPos());
- var child = void 0;
- var jsdocTypeLiteral = void 0;
- var start_3 = scanner.getStartPos();
- var children = void 0;
- while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
- if (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) {
- children = ts.append(children, child);
- }
- }
- if (children) {
- jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start_3);
- jsdocTypeLiteral.jsDocPropertyTags = children;
- if (typeExpression.type.kind === 174 /* ArrayType */) {
- jsdocTypeLiteral.isArrayType = true;
- }
- typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
- return finishNode(typeLiteralExpression);
- }
- }
- }
- function parseReturnTag(start, tagName) {
- if (ts.some(tags, ts.isJSDocReturnTag)) {
- parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
- }
- var result = createNode(318 /* JSDocReturnTag */, start);
- result.tagName = tagName;
- result.typeExpression = tryParseTypeExpression();
- return finishNode(result);
- }
- function parseTypeTag(start, tagName) {
- if (ts.some(tags, ts.isJSDocTypeTag)) {
- parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
- }
- var result = createNode(320 /* JSDocTypeTag */, start);
- result.tagName = tagName;
- result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
- return finishNode(result);
- }
- function parseAuthorTag(start, tagName, indent) {
- var result = createNode(309 /* JSDocAuthorTag */, start);
- result.tagName = tagName;
- var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
- if (!authorInfoWithEmail) {
- return finishNode(result);
- }
- result.comment = authorInfoWithEmail;
- if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
- var comment = parseTagComments(indent);
- if (comment) {
- result.comment += comment;
- }
- }
- return finishNode(result);
- }
- function tryParseAuthorNameAndEmail() {
- var comments = [];
- var seenLessThan = false;
- var seenGreaterThan = false;
- var token = scanner.getToken();
- loop: while (true) {
- switch (token) {
- case 75 /* Identifier */:
- case 5 /* WhitespaceTrivia */:
- case 24 /* DotToken */:
- case 59 /* AtToken */:
- comments.push(scanner.getTokenText());
- break;
- case 29 /* LessThanToken */:
- if (seenLessThan || seenGreaterThan) {
- return;
- }
- seenLessThan = true;
- comments.push(scanner.getTokenText());
- break;
- case 31 /* GreaterThanToken */:
- if (!seenLessThan || seenGreaterThan) {
- return;
- }
- seenGreaterThan = true;
- comments.push(scanner.getTokenText());
- scanner.setTextPos(scanner.getTokenPos() + 1);
- break loop;
- case 4 /* NewLineTrivia */:
- case 1 /* EndOfFileToken */:
- break loop;
- }
- token = nextTokenJSDoc();
- }
- if (seenLessThan && seenGreaterThan) {
- return comments.length === 0 ? undefined : comments.join("");
- }
- }
- function parseImplementsTag(start, tagName) {
- var result = createNode(308 /* JSDocImplementsTag */, start);
- result.tagName = tagName;
- result.class = parseExpressionWithTypeArgumentsForAugments();
- return finishNode(result);
- }
- function parseAugmentsTag(start, tagName) {
- var result = createNode(307 /* JSDocAugmentsTag */, start);
- result.tagName = tagName;
- result.class = parseExpressionWithTypeArgumentsForAugments();
- return finishNode(result);
- }
- function parseExpressionWithTypeArgumentsForAugments() {
- var usedBrace = parseOptional(18 /* OpenBraceToken */);
- var node = createNode(216 /* ExpressionWithTypeArguments */);
- node.expression = parsePropertyAccessEntityNameExpression();
- node.typeArguments = tryParseTypeArguments();
- var res = finishNode(node);
- if (usedBrace) {
- parseExpected(19 /* CloseBraceToken */);
- }
- return res;
- }
- function parsePropertyAccessEntityNameExpression() {
- var node = parseJSDocIdentifierName();
- while (parseOptional(24 /* DotToken */)) {
- var prop = createNode(194 /* PropertyAccessExpression */, node.pos);
- prop.expression = node;
- prop.name = parseJSDocIdentifierName();
- node = finishNode(prop);
- }
- return node;
- }
- function parseSimpleTag(start, kind, tagName) {
- var tag = createNode(kind, start);
- tag.tagName = tagName;
- return finishNode(tag);
- }
- function parseThisTag(start, tagName) {
- var tag = createNode(319 /* JSDocThisTag */, start);
- tag.tagName = tagName;
- tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
- skipWhitespace();
- return finishNode(tag);
- }
- function parseEnumTag(start, tagName) {
- var tag = createNode(316 /* JSDocEnumTag */, start);
- tag.tagName = tagName;
- tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
- skipWhitespace();
- return finishNode(tag);
- }
- function parseTypedefTag(start, tagName, indent) {
- var typeExpression = tryParseTypeExpression();
- skipWhitespaceOrAsterisk();
- var typedefTag = createNode(322 /* JSDocTypedefTag */, start);
- typedefTag.tagName = tagName;
- typedefTag.fullName = parseJSDocTypeNameWithNamespace();
- typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
- skipWhitespace();
- typedefTag.comment = parseTagComments(indent);
- typedefTag.typeExpression = typeExpression;
- var end;
- if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var child = void 0;
- var jsdocTypeLiteral = void 0;
- var childTypeTag = void 0;
- while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
- if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start);
- }
- if (child.kind === 320 /* JSDocTypeTag */) {
- if (childTypeTag) {
- break;
- }
- else {
- childTypeTag = child;
- }
- }
- else {
- jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
- }
- }
- if (jsdocTypeLiteral) {
- if (typeExpression && typeExpression.type.kind === 174 /* ArrayType */) {
- jsdocTypeLiteral.isArrayType = true;
- }
- typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
- childTypeTag.typeExpression :
- finishNode(jsdocTypeLiteral);
- end = typedefTag.typeExpression.end;
- }
- }
- // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
- return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
- }
- function parseJSDocTypeNameWithNamespace(nested) {
- var pos = scanner.getTokenPos();
- if (!ts.tokenIsIdentifierOrKeyword(token())) {
- return undefined;
- }
- var typeNameOrNamespaceName = parseJSDocIdentifierName();
- if (parseOptional(24 /* DotToken */)) {
- var jsDocNamespaceNode = createNode(249 /* ModuleDeclaration */, pos);
- if (nested) {
- jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
- }
- jsDocNamespaceNode.name = typeNameOrNamespaceName;
- jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
- return finishNode(jsDocNamespaceNode);
- }
- if (nested) {
- typeNameOrNamespaceName.isInJSDocNamespace = true;
- }
- return typeNameOrNamespaceName;
- }
- function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(315 /* JSDocCallbackTag */, start);
- callbackTag.tagName = tagName;
- callbackTag.fullName = parseJSDocTypeNameWithNamespace();
- callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
- skipWhitespace();
- callbackTag.comment = parseTagComments(indent);
- var child;
- var jsdocSignature = createNode(305 /* JSDocSignature */, start);
- jsdocSignature.parameters = [];
- while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
- jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
- }
- var returnTag = tryParse(function () {
- if (parseOptionalJsdoc(59 /* AtToken */)) {
- var tag = parseTag(indent);
- if (tag && tag.kind === 318 /* JSDocReturnTag */) {
- return tag;
- }
- }
- });
- if (returnTag) {
- jsdocSignature.type = returnTag;
- }
- callbackTag.typeExpression = finishNode(jsdocSignature);
- return finishNode(callbackTag);
- }
- function getJSDocTypeAliasName(fullName) {
- if (fullName) {
- var rightNode = fullName;
- while (true) {
- if (ts.isIdentifier(rightNode) || !rightNode.body) {
- return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
- }
- rightNode = rightNode.body;
- }
- }
- }
- function escapedTextsEqual(a, b) {
- while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
- if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
- a = a.left;
- b = b.left;
- }
- else {
- return false;
- }
- }
- return a.escapedText === b.escapedText;
- }
- function parseChildPropertyTag(indent) {
- return parseChildParameterOrPropertyTag(1 /* Property */, indent);
- }
- function parseChildParameterOrPropertyTag(target, indent, name) {
- var canParseTag = true;
- var seenAsterisk = false;
- while (true) {
- switch (nextTokenJSDoc()) {
- case 59 /* AtToken */:
- if (canParseTag) {
- var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) &&
- target !== 4 /* CallbackParameter */ &&
- name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
- return false;
- }
- return child;
- }
- seenAsterisk = false;
- break;
- case 4 /* NewLineTrivia */:
- canParseTag = true;
- seenAsterisk = false;
- break;
- case 41 /* AsteriskToken */:
- if (seenAsterisk) {
- canParseTag = false;
- }
- seenAsterisk = true;
- break;
- case 75 /* Identifier */:
- canParseTag = false;
- break;
- case 1 /* EndOfFileToken */:
- return false;
- }
- }
- }
- function tryParseChildTag(target, indent) {
- ts.Debug.assert(token() === 59 /* AtToken */);
- var start = scanner.getStartPos();
- nextTokenJSDoc();
- var tagName = parseJSDocIdentifierName();
- skipWhitespace();
- var t;
- switch (tagName.escapedText) {
- case "type":
- return target === 1 /* Property */ && parseTypeTag(start, tagName);
- case "prop":
- case "property":
- t = 1 /* Property */;
- break;
- case "arg":
- case "argument":
- case "param":
- t = 2 /* Parameter */ | 4 /* CallbackParameter */;
- break;
- default:
- return false;
- }
- if (!(target & t)) {
- return false;
- }
- return parseParameterOrPropertyTag(start, tagName, target, indent);
- }
- function parseTemplateTag(start, tagName) {
- // the template tag looks like '@template {Constraint} T,U,V'
- var constraint;
- if (token() === 18 /* OpenBraceToken */) {
- constraint = parseJSDocTypeExpression();
- }
- var typeParameters = [];
- var typeParametersPos = getNodePos();
- do {
- skipWhitespace();
- var typeParameter = createNode(155 /* TypeParameter */);
- typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
- finishNode(typeParameter);
- skipWhitespaceOrAsterisk();
- typeParameters.push(typeParameter);
- } while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(321 /* JSDocTemplateTag */, start);
- result.tagName = tagName;
- result.constraint = constraint;
- result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
- finishNode(result);
- return result;
- }
- function parseOptionalJsdoc(t) {
- if (token() === t) {
- nextTokenJSDoc();
- return true;
- }
- return false;
- }
- function parseJSDocEntityName() {
- var entity = parseJSDocIdentifierName();
- if (parseOptional(22 /* OpenBracketToken */)) {
- parseExpected(23 /* CloseBracketToken */);
- // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
- // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
- // but it's not worth it to enforce that restriction.
- }
- while (parseOptional(24 /* DotToken */)) {
- var name = parseJSDocIdentifierName();
- if (parseOptional(22 /* OpenBracketToken */)) {
- parseExpected(23 /* CloseBracketToken */);
- }
- entity = createQualifiedName(entity, name);
- }
- return entity;
- }
- function parseJSDocIdentifierName(message) {
- if (!ts.tokenIsIdentifierOrKeyword(token())) {
- return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
- }
- identifierCount++;
- var pos = scanner.getTokenPos();
- var end = scanner.getTextPos();
- var result = createNode(75 /* Identifier */, pos);
- if (token() !== 75 /* Identifier */) {
- result.originalKeywordKind = token();
- }
- result.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
- finishNode(result, end);
- nextTokenJSDoc();
- return result;
- }
- }
- })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
- })(Parser || (Parser = {}));
- var IncrementalParser;
- (function (IncrementalParser) {
- function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
- aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
- checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
- if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
- // if the text didn't change, then we can just return our current source file as-is.
- return sourceFile;
- }
- if (sourceFile.statements.length === 0) {
- // If we don't have any statements in the current source file, then there's no real
- // way to incrementally parse. So just do a full parse instead.
- return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
- }
- // Make sure we're not trying to incrementally update a source file more than once. Once
- // we do an update the original source file is considered unusable from that point onwards.
- //
- // This is because we do incremental parsing in-place. i.e. we take nodes from the old
- // tree and give them new positions and parents. From that point on, trusting the old
- // tree at all is not possible as far too much of it may violate invariants.
- var incrementalSourceFile = sourceFile;
- ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
- incrementalSourceFile.hasBeenIncrementallyParsed = true;
- var oldText = sourceFile.text;
- var syntaxCursor = createSyntaxCursor(sourceFile);
- // Make the actual change larger so that we know to reparse anything whose lookahead
- // might have intersected the change.
- var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
- checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
- // Ensure that extending the affected range only moved the start of the change range
- // earlier in the file.
- ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
- ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
- ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
- // The is the amount the nodes after the edit range need to be adjusted. It can be
- // positive (if the edit added characters), negative (if the edit deleted characters)
- // or zero (if this was a pure overwrite with nothing added/removed).
- var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
- // If we added or removed characters during the edit, then we need to go and adjust all
- // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they
- // may move backward (if we deleted chars).
- //
- // Doing this helps us out in two ways. First, it means that any nodes/tokens we want
- // to reuse are already at the appropriate position in the new text. That way when we
- // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes
- // it very easy to determine if we can reuse a node. If the node's position is at where
- // we are in the text, then we can reuse it. Otherwise we can't. If the node's position
- // is ahead of us, then we'll need to rescan tokens. If the node's position is behind
- // us, then we'll need to skip it or crumble it as appropriate
- //
- // We will also adjust the positions of nodes that intersect the change range as well.
- // By doing this, we ensure that all the positions in the old tree are consistent, not
- // just the positions of nodes entirely before/after the change range. By being
- // consistent, we can then easily map from positions to nodes in the old tree easily.
- //
- // Also, mark any syntax elements that intersect the changed span. We know, up front,
- // that we cannot reuse these elements.
- updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
- // Now that we've set up our internal incremental state just proceed and parse the
- // source file in the normal fashion. When possible the parser will retrieve and
- // reuse nodes from the old tree.
- //
- // Note: passing in 'true' for setNodeParents is very important. When incrementally
- // parsing, we will be reusing nodes from the old tree, and placing it into new
- // parents. If we don't set the parents now, we'll end up with an observably
- // inconsistent tree. Setting the parents on the new tree should be very fast. We
- // will immediately bail out of walking any subtrees when we can see that their parents
- // are already correct.
- var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
- result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
- return result;
- }
- IncrementalParser.updateSourceFile = updateSourceFile;
- function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
- if (!oldDirectives)
- return newDirectives;
- var commentDirectives;
- var addedNewlyScannedDirectives = false;
- for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
- var directive = oldDirectives_1[_i];
- var range = directive.range, type = directive.type;
- // Range before the change
- if (range.end < changeStart) {
- commentDirectives = ts.append(commentDirectives, directive);
- }
- else if (range.pos > changeRangeOldEnd) {
- addNewlyScannedDirectives();
- // Node is entirely past the change range. We need to move both its pos and
- // end, forward or backward appropriately.
- var updatedDirective = {
- range: { pos: range.pos + delta, end: range.end + delta },
- type: type
- };
- commentDirectives = ts.append(commentDirectives, updatedDirective);
- if (aggressiveChecks) {
- ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
- }
- }
- // Ignore ranges that fall in change range
- }
- addNewlyScannedDirectives();
- return commentDirectives;
- function addNewlyScannedDirectives() {
- if (addedNewlyScannedDirectives)
- return;
- addedNewlyScannedDirectives = true;
- if (!commentDirectives) {
- commentDirectives = newDirectives;
- }
- else if (newDirectives) {
- commentDirectives.push.apply(commentDirectives, newDirectives);
- }
- }
- }
- function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
- if (isArray) {
- visitArray(element);
- }
- else {
- visitNode(element);
- }
- return;
- function visitNode(node) {
- var text = "";
- if (aggressiveChecks && shouldCheckNode(node)) {
- text = oldText.substring(node.pos, node.end);
- }
- // Ditch any existing LS children we may have created. This way we can avoid
- // moving them forward.
- if (node._children) {
- node._children = undefined;
- }
- node.pos += delta;
- node.end += delta;
- if (aggressiveChecks && shouldCheckNode(node)) {
- ts.Debug.assert(text === newText.substring(node.pos, node.end));
- }
- forEachChild(node, visitNode, visitArray);
- if (ts.hasJSDocNodes(node)) {
- for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
- var jsDocComment = _a[_i];
- visitNode(jsDocComment);
- }
- }
- checkNodePositions(node, aggressiveChecks);
- }
- function visitArray(array) {
- array._children = undefined;
- array.pos += delta;
- array.end += delta;
- for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
- var node = array_8[_i];
- visitNode(node);
- }
- }
- }
- function shouldCheckNode(node) {
- switch (node.kind) {
- case 10 /* StringLiteral */:
- case 8 /* NumericLiteral */:
- case 75 /* Identifier */:
- return true;
- }
- return false;
- }
- function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
- ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
- ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
- ts.Debug.assert(element.pos <= element.end);
- // We have an element that intersects the change range in some way. It may have its
- // start, or its end (or both) in the changed range. We want to adjust any part
- // that intersects such that the final tree is in a consistent state. i.e. all
- // children have spans within the span of their parent, and all siblings are ordered
- // properly.
- // We may need to update both the 'pos' and the 'end' of the element.
- // If the 'pos' is before the start of the change, then we don't need to touch it.
- // If it isn't, then the 'pos' must be inside the change. How we update it will
- // depend if delta is positive or negative. If delta is positive then we have
- // something like:
- //
- // -------------------AAA-----------------
- // -------------------BBBCCCCCCC-----------------
- //
- // In this case, we consider any node that started in the change range to still be
- // starting at the same position.
- //
- // however, if the delta is negative, then we instead have something like this:
- //
- // -------------------XXXYYYYYYY-----------------
- // -------------------ZZZ-----------------
- //
- // In this case, any element that started in the 'X' range will keep its position.
- // However any element that started after that will have their pos adjusted to be
- // at the end of the new range. i.e. any node that started in the 'Y' range will
- // be adjusted to have their start at the end of the 'Z' range.
- //
- // The element will keep its position if possible. Or Move backward to the new-end
- // if it's in the 'Y' range.
- element.pos = Math.min(element.pos, changeRangeNewEnd);
- // If the 'end' is after the change range, then we always adjust it by the delta
- // amount. However, if the end is in the change range, then how we adjust it
- // will depend on if delta is positive or negative. If delta is positive then we
- // have something like:
- //
- // -------------------AAA-----------------
- // -------------------BBBCCCCCCC-----------------
- //
- // In this case, we consider any node that ended inside the change range to keep its
- // end position.
- //
- // however, if the delta is negative, then we instead have something like this:
- //
- // -------------------XXXYYYYYYY-----------------
- // -------------------ZZZ-----------------
- //
- // In this case, any element that ended in the 'X' range will keep its position.
- // However any element that ended after that will have their pos adjusted to be
- // at the end of the new range. i.e. any node that ended in the 'Y' range will
- // be adjusted to have their end at the end of the 'Z' range.
- if (element.end >= changeRangeOldEnd) {
- // Element ends after the change range. Always adjust the end pos.
- element.end += delta;
- }
- else {
- // Element ends in the change range. The element will keep its position if
- // possible. Or Move backward to the new-end if it's in the 'Y' range.
- element.end = Math.min(element.end, changeRangeNewEnd);
- }
- ts.Debug.assert(element.pos <= element.end);
- if (element.parent) {
- ts.Debug.assert(element.pos >= element.parent.pos);
- ts.Debug.assert(element.end <= element.parent.end);
- }
- }
- function checkNodePositions(node, aggressiveChecks) {
- if (aggressiveChecks) {
- var pos_2 = node.pos;
- var visitNode_1 = function (child) {
- ts.Debug.assert(child.pos >= pos_2);
- pos_2 = child.end;
- };
- if (ts.hasJSDocNodes(node)) {
- for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
- var jsDocComment = _a[_i];
- visitNode_1(jsDocComment);
- }
- }
- forEachChild(node, visitNode_1);
- ts.Debug.assert(pos_2 <= node.end);
- }
- }
- function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
- visitNode(sourceFile);
- return;
- function visitNode(child) {
- ts.Debug.assert(child.pos <= child.end);
- if (child.pos > changeRangeOldEnd) {
- // Node is entirely past the change range. We need to move both its pos and
- // end, forward or backward appropriately.
- moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
- return;
- }
- // Check if the element intersects the change range. If it does, then it is not
- // reusable. Also, we'll need to recurse to see what constituent portions we may
- // be able to use.
- var fullEnd = child.end;
- if (fullEnd >= changeStart) {
- child.intersectsChange = true;
- child._children = undefined;
- // Adjust the pos or end (or both) of the intersecting element accordingly.
- adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
- forEachChild(child, visitNode, visitArray);
- if (ts.hasJSDocNodes(child)) {
- for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
- var jsDocComment = _a[_i];
- visitNode(jsDocComment);
- }
- }
- checkNodePositions(child, aggressiveChecks);
- return;
- }
- // Otherwise, the node is entirely before the change range. No need to do anything with it.
- ts.Debug.assert(fullEnd < changeStart);
- }
- function visitArray(array) {
- ts.Debug.assert(array.pos <= array.end);
- if (array.pos > changeRangeOldEnd) {
- // Array is entirely after the change range. We need to move it, and move any of
- // its children.
- moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
- return;
- }
- // Check if the element intersects the change range. If it does, then it is not
- // reusable. Also, we'll need to recurse to see what constituent portions we may
- // be able to use.
- var fullEnd = array.end;
- if (fullEnd >= changeStart) {
- array.intersectsChange = true;
- array._children = undefined;
- // Adjust the pos or end (or both) of the intersecting array accordingly.
- adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
- for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
- var node = array_9[_i];
- visitNode(node);
- }
- return;
- }
- // Otherwise, the array is entirely before the change range. No need to do anything with it.
- ts.Debug.assert(fullEnd < changeStart);
- }
- }
- function extendToAffectedRange(sourceFile, changeRange) {
- // Consider the following code:
- // void foo() { /; }
- //
- // If the text changes with an insertion of / just before the semicolon then we end up with:
- // void foo() { //; }
- //
- // If we were to just use the changeRange a is, then we would not rescan the { token
- // (as it does not intersect the actual original change range). Because an edit may
- // change the token touching it, we actually need to look back *at least* one token so
- // that the prior token sees that change.
- var maxLookahead = 1;
- var start = changeRange.span.start;
- // the first iteration aligns us with the change start. subsequent iteration move us to
- // the left by maxLookahead tokens. We only need to do this as long as we're not at the
- // start of the tree.
- for (var i = 0; start > 0 && i <= maxLookahead; i++) {
- var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
- ts.Debug.assert(nearestNode.pos <= start);
- var position = nearestNode.pos;
- start = Math.max(0, position - 1);
- }
- var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
- var finalLength = changeRange.newLength + (changeRange.span.start - start);
- return ts.createTextChangeRange(finalSpan, finalLength);
- }
- function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
- var bestResult = sourceFile;
- var lastNodeEntirelyBeforePosition;
- forEachChild(sourceFile, visit);
- if (lastNodeEntirelyBeforePosition) {
- var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
- if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
- bestResult = lastChildOfLastEntireNodeBeforePosition;
- }
- }
- return bestResult;
- function getLastDescendant(node) {
- while (true) {
- var lastChild = ts.getLastChild(node);
- if (lastChild) {
- node = lastChild;
- }
- else {
- return node;
- }
- }
- }
- function visit(child) {
- if (ts.nodeIsMissing(child)) {
- // Missing nodes are effectively invisible to us. We never even consider them
- // When trying to find the nearest node before us.
- return;
- }
- // If the child intersects this position, then this node is currently the nearest
- // node that starts before the position.
- if (child.pos <= position) {
- if (child.pos >= bestResult.pos) {
- // This node starts before the position, and is closer to the position than
- // the previous best node we found. It is now the new best node.
- bestResult = child;
- }
- // Now, the node may overlap the position, or it may end entirely before the
- // position. If it overlaps with the position, then either it, or one of its
- // children must be the nearest node before the position. So we can just
- // recurse into this child to see if we can find something better.
- if (position < child.end) {
- // The nearest node is either this child, or one of the children inside
- // of it. We've already marked this child as the best so far. Recurse
- // in case one of the children is better.
- forEachChild(child, visit);
- // Once we look at the children of this node, then there's no need to
- // continue any further.
- return true;
- }
- else {
- ts.Debug.assert(child.end <= position);
- // The child ends entirely before this position. Say you have the following
- // (where $ is the position)
- //
- // <complex expr 1> ? <complex expr 2> $ : <...> <...>
- //
- // We would want to find the nearest preceding node in "complex expr 2".
- // To support that, we keep track of this node, and once we're done searching
- // for a best node, we recurse down this node to see if we can find a good
- // result in it.
- //
- // This approach allows us to quickly skip over nodes that are entirely
- // before the position, while still allowing us to find any nodes in the
- // last one that might be what we want.
- lastNodeEntirelyBeforePosition = child;
- }
- }
- else {
- ts.Debug.assert(child.pos > position);
- // We're now at a node that is entirely past the position we're searching for.
- // This node (and all following nodes) could never contribute to the result,
- // so just skip them by returning 'true' here.
- return true;
- }
- }
- }
- function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
- var oldText = sourceFile.text;
- if (textChangeRange) {
- ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
- if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
- var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
- var newTextPrefix = newText.substr(0, textChangeRange.span.start);
- ts.Debug.assert(oldTextPrefix === newTextPrefix);
- var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
- var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
- ts.Debug.assert(oldTextSuffix === newTextSuffix);
- }
- }
- }
- function createSyntaxCursor(sourceFile) {
- var currentArray = sourceFile.statements;
- var currentArrayIndex = 0;
- ts.Debug.assert(currentArrayIndex < currentArray.length);
- var current = currentArray[currentArrayIndex];
- var lastQueriedPosition = -1 /* Value */;
- return {
- currentNode: function (position) {
- // Only compute the current node if the position is different than the last time
- // we were asked. The parser commonly asks for the node at the same position
- // twice. Once to know if can read an appropriate list element at a certain point,
- // and then to actually read and consume the node.
- if (position !== lastQueriedPosition) {
- // Much of the time the parser will need the very next node in the array that
- // we just returned a node from.So just simply check for that case and move
- // forward in the array instead of searching for the node again.
- if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
- currentArrayIndex++;
- current = currentArray[currentArrayIndex];
- }
- // If we don't have a node, or the node we have isn't in the right position,
- // then try to find a viable node at the position requested.
- if (!current || current.pos !== position) {
- findHighestListElementThatStartsAtPosition(position);
- }
- }
- // Cache this query so that we don't do any extra work if the parser calls back
- // into us. Note: this is very common as the parser will make pairs of calls like
- // 'isListElement -> parseListElement'. If we were unable to find a node when
- // called with 'isListElement', we don't want to redo the work when parseListElement
- // is called immediately after.
- lastQueriedPosition = position;
- // Either we don'd have a node, or we have a node at the position being asked for.
- ts.Debug.assert(!current || current.pos === position);
- return current;
- }
- };
- // Finds the highest element in the tree we can find that starts at the provided position.
- // The element must be a direct child of some node list in the tree. This way after we
- // return it, we can easily return its next sibling in the list.
- function findHighestListElementThatStartsAtPosition(position) {
- // Clear out any cached state about the last node we found.
- currentArray = undefined;
- currentArrayIndex = -1 /* Value */;
- current = undefined;
- // Recurse into the source file to find the highest node at this position.
- forEachChild(sourceFile, visitNode, visitArray);
- return;
- function visitNode(node) {
- if (position >= node.pos && position < node.end) {
- // Position was within this node. Keep searching deeper to find the node.
- forEachChild(node, visitNode, visitArray);
- // don't proceed any further in the search.
- return true;
- }
- // position wasn't in this node, have to keep searching.
- return false;
- }
- function visitArray(array) {
- 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; i < array.length; i++) {
- var child = array[i];
- if (child) {
- if (child.pos === position) {
- // Found the right node. We're done.
- currentArray = array;
- currentArrayIndex = i;
- current = child;
- return true;
- }
- else {
- if (child.pos < position && position < child.end) {
- // Position in somewhere within this child. Search in it and
- // stop searching in this array.
- forEachChild(child, visitNode, visitArray);
- return true;
- }
- }
- }
- }
- }
- // position wasn't in this array, have to keep searching.
- return false;
- }
- }
- }
- var InvalidPosition;
- (function (InvalidPosition) {
- InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
- })(InvalidPosition || (InvalidPosition = {}));
- })(IncrementalParser || (IncrementalParser = {}));
- /** @internal */
- function isDeclarationFileName(fileName) {
- return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
- }
- ts.isDeclarationFileName = isDeclarationFileName;
- /*@internal*/
- function processCommentPragmas(context, sourceText) {
- var pragmas = [];
- for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
- var range = _a[_i];
- var comment = sourceText.substring(range.pos, range.end);
- extractPragmas(pragmas, range, comment);
- }
- context.pragmas = ts.createMap();
- for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
- var pragma = pragmas_1[_b];
- if (context.pragmas.has(pragma.name)) {
- var currentValue = context.pragmas.get(pragma.name);
- if (currentValue instanceof Array) {
- currentValue.push(pragma.args);
- }
- else {
- context.pragmas.set(pragma.name, [currentValue, pragma.args]);
- }
- continue;
- }
- context.pragmas.set(pragma.name, pragma.args);
- }
- }
- ts.processCommentPragmas = processCommentPragmas;
- /*@internal*/
- function processPragmasIntoFields(context, reportDiagnostic) {
- context.checkJsDirective = undefined;
- context.referencedFiles = [];
- context.typeReferenceDirectives = [];
- context.libReferenceDirectives = [];
- context.amdDependencies = [];
- context.hasNoDefaultLib = false;
- context.pragmas.forEach(function (entryOrList, key) {
- // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
- // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
- switch (key) {
- case "reference": {
- var referencedFiles_1 = context.referencedFiles;
- var typeReferenceDirectives_1 = context.typeReferenceDirectives;
- var libReferenceDirectives_1 = context.libReferenceDirectives;
- ts.forEach(ts.toArray(entryOrList), function (arg) {
- var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
- if (arg.arguments["no-default-lib"]) {
- context.hasNoDefaultLib = true;
- }
- else if (types) {
- typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
- }
- else if (lib) {
- libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
- }
- else if (path) {
- referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
- }
- else {
- reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
- }
- });
- break;
- }
- case "amd-dependency": {
- context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
- break;
- }
- case "amd-module": {
- if (entryOrList instanceof Array) {
- for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
- var entry = entryOrList_1[_i];
- if (context.moduleName) {
- // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
- reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
- }
- context.moduleName = entry.arguments.name;
- }
- }
- else {
- context.moduleName = entryOrList.arguments.name;
- }
- break;
- }
- case "ts-nocheck":
- case "ts-check": {
- // _last_ of either nocheck or check in a file is the "winner"
- ts.forEach(ts.toArray(entryOrList), function (entry) {
- if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
- context.checkJsDirective = {
- enabled: key === "ts-check",
- end: entry.range.end,
- pos: entry.range.pos
- };
- }
- });
- break;
- }
- case "jsx": return; // Accessed directly
- default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
- }
- });
- }
- ts.processPragmasIntoFields = processPragmasIntoFields;
- var namedArgRegExCache = ts.createMap();
- function getNamedArgRegEx(name) {
- if (namedArgRegExCache.has(name)) {
- return namedArgRegExCache.get(name);
- }
- var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
- namedArgRegExCache.set(name, result);
- return result;
- }
- var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
- var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
- function extractPragmas(pragmas, range, text) {
- var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
- if (tripleSlash) {
- var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
- var pragma = ts.commentPragmas[name];
- if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
- return;
- }
- if (pragma.args) {
- var argument = {};
- for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
- var arg = _a[_i];
- var matcher = getNamedArgRegEx(arg.name);
- var matchResult = matcher.exec(text);
- if (!matchResult && !arg.optional) {
- return; // Missing required argument, don't parse
- }
- else if (matchResult) {
- if (arg.captureSpan) {
- var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
- argument[arg.name] = {
- value: matchResult[3],
- pos: startPos,
- end: startPos + matchResult[3].length
- };
- }
- else {
- argument[arg.name] = matchResult[3];
- }
- }
- }
- pragmas.push({ name: name, args: { arguments: argument, range: range } });
- }
- else {
- pragmas.push({ name: name, args: { arguments: {}, range: range } });
- }
- return;
- }
- var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
- if (singleLine) {
- return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
- }
- if (range.kind === 3 /* MultiLineCommentTrivia */) {
- var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
- var multiLineMatch = void 0;
- while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
- addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
- }
- }
- }
- function addPragmaForMatch(pragmas, range, kind, match) {
- if (!match)
- return;
- var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
- var pragma = ts.commentPragmas[name];
- if (!pragma || !(pragma.kind & kind)) {
- return;
- }
- var args = match[2]; // Split on spaces and match up positionally with definition
- var argument = getNamedPragmaArguments(pragma, args);
- if (argument === "fail")
- return; // Missing required argument, fail to parse it
- pragmas.push({ name: name, args: { arguments: argument, range: range } });
- return;
- }
- function getNamedPragmaArguments(pragma, text) {
- if (!text)
- return {};
- if (!pragma.args)
- return {};
- var args = text.split(/\s+/);
- var argMap = {};
- for (var i = 0; i < pragma.args.length; i++) {
- var argument = pragma.args[i];
- if (!args[i] && !argument.optional) {
- return "fail";
- }
- if (argument.captureSpan) {
- return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
- }
- argMap[argument.name] = args[i];
- }
- return argMap;
- }
- /** @internal */
- function tagNamesAreEquivalent(lhs, rhs) {
- if (lhs.kind !== rhs.kind) {
- return false;
- }
- if (lhs.kind === 75 /* Identifier */) {
- return lhs.escapedText === rhs.escapedText;
- }
- if (lhs.kind === 104 /* ThisKeyword */) {
- return true;
- }
- // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
- // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
- // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
- return lhs.name.escapedText === rhs.name.escapedText &&
- tagNamesAreEquivalent(lhs.expression, rhs.expression);
- }
- ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
-})(ts || (ts = {}));
-var ts;
-(function (ts) {
- /* @internal */
- ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
- // NOTE: The order here is important to default lib ordering as entries will have the same
- // order in the generated program (see `getDefaultLibPriority` in program.ts). This
- // order also affects overload resolution when a type declared in one lib is
- // augmented in another lib.
- var libEntries = [
- // 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"],
- ["es2018", "lib.es2018.d.ts"],
- ["es2019", "lib.es2019.d.ts"],
- ["es2020", "lib.es2020.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"],
- ["webworker.importscripts", "lib.webworker.importscripts.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"],
- ["es2017.intl", "lib.es2017.intl.d.ts"],
- ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
- ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
- ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
- ["es2018.intl", "lib.es2018.intl.d.ts"],
- ["es2018.promise", "lib.es2018.promise.d.ts"],
- ["es2018.regexp", "lib.es2018.regexp.d.ts"],
- ["es2019.array", "lib.es2019.array.d.ts"],
- ["es2019.object", "lib.es2019.object.d.ts"],
- ["es2019.string", "lib.es2019.string.d.ts"],
- ["es2019.symbol", "lib.es2019.symbol.d.ts"],
- ["es2020.bigint", "lib.es2020.bigint.d.ts"],
- ["es2020.promise", "lib.es2020.promise.d.ts"],
- ["es2020.string", "lib.es2020.string.d.ts"],
- ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
- ["esnext.array", "lib.es2019.array.d.ts"],
- ["esnext.symbol", "lib.es2019.symbol.d.ts"],
- ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
- ["esnext.intl", "lib.esnext.intl.d.ts"],
- ["esnext.bigint", "lib.es2020.bigint.d.ts"],
- ["esnext.string", "lib.esnext.string.d.ts"],
- ["esnext.promise", "lib.esnext.promise.d.ts"]
- ];
- /**
- * An array of supported "lib" reference file names used to determine the order for inclusion
- * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
- * overload resolution when a type declared in one lib is extended by another.
- */
- /* @internal */
- ts.libs = libEntries.map(function (entry) { return entry[0]; });
- /**
- * A map of lib names to lib files. This map is used both for parsing the "lib" command line
- * option as well as for resolving lib reference directives.
- */
- /* @internal */
- ts.libMap = ts.createMapFromEntries(libEntries);
- // Watch related options
- /* @internal */
- ts.optionsForWatch = [
- {
- name: "watchFile",
- type: ts.createMapFromTemplate({
- fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
- prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
- dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
- usefsevents: ts.WatchFileKind.UseFsEvents,
- usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
- }),
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
- },
- {
- name: "watchDirectory",
- type: ts.createMapFromTemplate({
- usefsevents: ts.WatchDirectoryKind.UseFsEvents,
- fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
- dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
- }),
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
- },
- {
- name: "fallbackPolling",
- type: ts.createMapFromTemplate({
- fixedinterval: ts.PollingWatchKind.FixedInterval,
- priorityinterval: ts.PollingWatchKind.PriorityInterval,
- dynamicpriority: ts.PollingWatchKind.DynamicPriority,
- }),
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
- },
- {
- name: "synchronousWatchDirectory",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
- },
- ];
- /* @internal */
- ts.commonOptionsWithBuild = [
- {
- name: "help",
- shortName: "h",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Print_this_message,
- },
- {
- name: "help",
- shortName: "?",
- type: "boolean"
- },
- {
- name: "watch",
- shortName: "w",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Watch_input_files,
- },
- {
- name: "preserveWatchOutput",
- type: "boolean",
- showInSimplifiedHelpView: false,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
- },
- {
- name: "listFiles",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
- },
- {
- name: "listEmittedFiles",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
- },
- {
- 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: "traceResolution",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
- },
- {
- 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: "generateCpuProfile",
- type: "string",
- isFilePath: true,
- paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Generates_a_CPU_profile
- },
- {
- name: "incremental",
- shortName: "i",
- type: "boolean",
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Enable_incremental_compilation,
- transpileOptionValue: undefined
- },
- {
- name: "assumeChangesOnlyAffectDirectDependencies",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
- },
- {
- 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
- },
- ];
- /* @internal */
- ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
- {
- name: "all",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Show_all_compiler_options,
- },
- {
- name: "version",
- shortName: "v",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Print_the_compiler_s_version,
- },
- {
- 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: "project",
- shortName: "p",
- type: "string",
- 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: "build",
- type: "boolean",
- shortName: "b",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Command_line_Options,
- description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
- },
- {
- name: "showConfig",
- type: "boolean",
- category: ts.Diagnostics.Command_line_Options,
- isCommandLineOnly: true,
- description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
- },
- {
- name: "listFilesOnly",
- type: "boolean",
- category: ts.Diagnostics.Command_line_Options,
- affectsSemanticDiagnostics: true,
- affectsEmit: true,
- isCommandLineOnly: true,
- description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
- },
- // Basic
- {
- 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 */,
- es2018: 5 /* ES2018 */,
- es2019: 6 /* ES2019 */,
- es2020: 7 /* ES2020 */,
- esnext: 99 /* ESNext */,
- }),
- affectsSourceFile: true,
- affectsModuleResolution: true,
- affectsEmit: true,
- 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_ES2018_ES2019_ES2020_or_ESNEXT,
- },
- {
- name: "module",
- shortName: "m",
- type: ts.createMapFromTemplate({
- none: ts.ModuleKind.None,
- commonjs: ts.ModuleKind.CommonJS,
- amd: ts.ModuleKind.AMD,
- system: ts.ModuleKind.System,
- umd: ts.ModuleKind.UMD,
- es6: ts.ModuleKind.ES2015,
- es2015: ts.ModuleKind.ES2015,
- es2020: ts.ModuleKind.ES2020,
- esnext: ts.ModuleKind.ESNext
- }),
- affectsModuleResolution: true,
- affectsEmit: true,
- paramType: ts.Diagnostics.KIND,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
- },
- {
- name: "lib",
- type: "list",
- element: {
- name: "lib",
- type: ts.libMap
- },
- affectsModuleResolution: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
- transpileOptionValue: undefined
- },
- {
- name: "allowJs",
- type: "boolean",
- affectsModuleResolution: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
- },
- {
- name: "checkJs",
- type: "boolean",
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Report_errors_in_js_files
- },
- {
- name: "jsx",
- type: ts.createMapFromTemplate({
- "preserve": 1 /* Preserve */,
- "react-native": 3 /* ReactNative */,
- "react": 2 /* React */
- }),
- affectsSourceFile: true,
- 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: "declaration",
- shortName: "d",
- type: "boolean",
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Generates_corresponding_d_ts_file,
- transpileOptionValue: undefined
- },
- {
- name: "declarationMap",
- type: "boolean",
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
- transpileOptionValue: undefined
- },
- {
- name: "emitDeclarationOnly",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
- transpileOptionValue: undefined
- },
- {
- name: "sourceMap",
- type: "boolean",
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Generates_corresponding_map_file,
- },
- {
- name: "outFile",
- type: "string",
- affectsEmit: true,
- isFilePath: true,
- paramType: ts.Diagnostics.FILE,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
- transpileOptionValue: undefined
- },
- {
- name: "outDir",
- type: "string",
- affectsEmit: true,
- isFilePath: true,
- paramType: ts.Diagnostics.DIRECTORY,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
- },
- {
- name: "rootDir",
- type: "string",
- affectsEmit: true,
- 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: "composite",
- type: "boolean",
- affectsEmit: true,
- isTSConfigOnly: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Enable_project_compilation,
- transpileOptionValue: undefined
- },
- {
- name: "tsBuildInfoFile",
- type: "string",
- affectsEmit: true,
- isFilePath: true,
- paramType: ts.Diagnostics.FILE,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
- transpileOptionValue: undefined
- },
- {
- name: "removeComments",
- type: "boolean",
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Do_not_emit_comments_to_output,
- },
- {
- name: "noEmit",
- type: "boolean",
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Do_not_emit_outputs,
- transpileOptionValue: undefined
- },
- {
- name: "importHelpers",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Import_emit_helpers_from_tslib
- },
- {
- name: "importsNotUsedAsValues",
- type: ts.createMapFromTemplate({
- remove: 0 /* Remove */,
- preserve: 1 /* Preserve */,
- error: 2 /* Error */
- }),
- affectsEmit: true,
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
- },
- {
- name: "downlevelIteration",
- type: "boolean",
- affectsEmit: true,
- 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: "isolatedModules",
- type: "boolean",
- category: ts.Diagnostics.Basic_Options,
- description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
- transpileOptionValue: true
- },
- // Strict Type Checks
- {
- name: "strict",
- type: "boolean",
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Enable_all_strict_type_checking_options
- },
- {
- name: "noImplicitAny",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
- },
- {
- name: "strictNullChecks",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Enable_strict_null_checks
- },
- {
- name: "strictFunctionTypes",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Enable_strict_checking_of_function_types
- },
- {
- name: "strictBindCallApply",
- type: "boolean",
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
- },
- {
- name: "strictPropertyInitialization",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
- },
- {
- name: "noImplicitThis",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- strictFlag: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Strict_Type_Checking_Options,
- description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
- },
- {
- name: "alwaysStrict",
- type: "boolean",
- affectsSourceFile: true,
- strictFlag: true,
- 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: "noUnusedLocals",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Additional_Checks,
- description: ts.Diagnostics.Report_errors_on_unused_locals,
- },
- {
- name: "noUnusedParameters",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Additional_Checks,
- description: ts.Diagnostics.Report_errors_on_unused_parameters,
- },
- {
- name: "noImplicitReturns",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- 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",
- affectsBindDiagnostics: true,
- affectsSemanticDiagnostics: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Additional_Checks,
- description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
- },
- // Module Resolution
- {
- name: "moduleResolution",
- type: ts.createMapFromTemplate({
- node: ts.ModuleResolutionKind.NodeJs,
- classic: ts.ModuleResolutionKind.Classic,
- }),
- affectsModuleResolution: true,
- 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",
- affectsModuleResolution: true,
- isFilePath: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
- },
- {
- // this option can only be specified in tsconfig.json
- // use type = object to copy the value as-is
- name: "paths",
- type: "object",
- affectsModuleResolution: 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,
- transpileOptionValue: undefined
- },
- {
- // this option can only be specified in tsconfig.json
- // use type = object to copy the value as-is
- name: "rootDirs",
- type: "list",
- isTSConfigOnly: true,
- element: {
- name: "rootDirs",
- type: "string",
- isFilePath: true
- },
- affectsModuleResolution: 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,
- transpileOptionValue: undefined
- },
- {
- name: "typeRoots",
- type: "list",
- element: {
- name: "typeRoots",
- type: "string",
- isFilePath: true
- },
- affectsModuleResolution: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
- },
- {
- name: "types",
- type: "list",
- element: {
- name: "types",
- type: "string"
- },
- affectsModuleResolution: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
- transpileOptionValue: undefined
- },
- {
- name: "allowSyntheticDefaultImports",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- 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
- },
- {
- name: "esModuleInterop",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- affectsEmit: true,
- showInSimplifiedHelpView: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
- },
- {
- name: "preserveSymlinks",
- type: "boolean",
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
- },
- {
- name: "allowUmdGlobalAccess",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Module_Resolution_Options,
- description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
- },
- // Source Maps
- {
- name: "sourceRoot",
- type: "string",
- affectsEmit: 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",
- affectsEmit: 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",
- affectsEmit: true,
- 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",
- affectsEmit: true,
- 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",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Experimental_Options,
- description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
- },
- {
- name: "emitDecoratorMetadata",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- affectsEmit: true,
- 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: "resolveJsonModule",
- type: "boolean",
- affectsModuleResolution: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Include_modules_imported_with_json_extension
- },
- {
- name: "out",
- type: "string",
- affectsEmit: true,
- 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,
- transpileOptionValue: undefined
- },
- {
- name: "reactNamespace",
- type: "string",
- affectsEmit: true,
- 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",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
- },
- {
- name: "newLine",
- type: ts.createMapFromTemplate({
- crlf: 0 /* CarriageReturnLineFeed */,
- lf: 1 /* LineFeed */
- }),
- affectsEmit: true,
- 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",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_truncate_error_messages
- },
- {
- name: "noLib",
- type: "boolean",
- affectsModuleResolution: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
- // We are not returning a sourceFile for lib file when asked by the program,
- // so pass --noLib to avoid reporting a file not found error.
- transpileOptionValue: true
- },
- {
- name: "noResolve",
- type: "boolean",
- affectsModuleResolution: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
- // We are not doing a full typecheck, we are not resolving the whole context,
- // so pass --noResolve to avoid reporting missing file errors.
- transpileOptionValue: true
- },
- {
- name: "stripInternal",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
- },
- {
- name: "disableSizeLimit",
- type: "boolean",
- affectsSourceFile: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
- },
- {
- name: "disableSourceOfProjectReferenceRedirect",
- type: "boolean",
- isTSConfigOnly: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
- },
- {
- name: "disableSolutionSearching",
- type: "boolean",
- isTSConfigOnly: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Disable_solution_searching_for_this_project
- },
- {
- name: "noImplicitUseStrict",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
- },
- {
- name: "noEmitHelpers",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
- },
- {
- name: "noEmitOnError",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
- transpileOptionValue: undefined
- },
- {
- name: "preserveConstEnums",
- type: "boolean",
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
- },
- {
- name: "declarationDir",
- type: "string",
- affectsEmit: true,
- isFilePath: true,
- paramType: ts.Diagnostics.DIRECTORY,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
- transpileOptionValue: undefined
- },
- {
- name: "skipLibCheck",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
- },
- {
- name: "allowUnusedLabels",
- type: "boolean",
- affectsBindDiagnostics: true,
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
- },
- {
- name: "allowUnreachableCode",
- type: "boolean",
- affectsBindDiagnostics: true,
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
- },
- {
- name: "suppressExcessPropertyErrors",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
- },
- {
- name: "suppressImplicitAnyIndexErrors",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
- },
- {
- name: "forceConsistentCasingInFileNames",
- type: "boolean",
- affectsModuleResolution: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
- },
- {
- name: "maxNodeModuleJsDepth",
- type: "number",
- affectsModuleResolution: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
- },
- {
- name: "noStrictGenericChecks",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
- },
- {
- name: "useDefineForClassFields",
- type: "boolean",
- affectsSemanticDiagnostics: true,
- affectsEmit: true,
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
- },
- {
- name: "keyofStringsOnly",
- type: "boolean",
- category: ts.Diagnostics.Advanced_Options,
- description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
- },
- {
- // 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
- },
- ]);
+ };
+ }
+ ts.helperString = helperString;
+ // TypeScript Helpers
+ ts.decorateHelper = {
+ name: "typescript:decorate",
+ importName: "__decorate",
+ 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 };"
+ };
+ ts.metadataHelper = {
+ name: "typescript:metadata",
+ importName: "__metadata",
+ scoped: false,
+ 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 };"
+ };
+ ts.paramHelper = {
+ name: "typescript:param",
+ importName: "__param",
+ scoped: false,
+ priority: 4,
+ text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };"
+ };
+ // ES2018 Helpers
+ ts.assignHelper = {
+ name: "typescript:assign",
+ importName: "__assign",
+ scoped: false,
+ priority: 1,
+ text: "\n var __assign = (this && this.__assign) || function () {\n __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 };\n return __assign.apply(this, arguments);\n };"
+ };
+ ts.awaitHelper = {
+ name: "typescript:await",
+ importName: "__await",
+ scoped: false,
+ text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
+ };
+ ts.asyncGeneratorHelper = {
+ name: "typescript:asyncGenerator",
+ importName: "__asyncGenerator",
+ scoped: false,
+ dependencies: [ts.awaitHelper],
+ 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 || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
+ };
+ ts.asyncDelegator = {
+ name: "typescript:asyncDelegator",
+ importName: "__asyncDelegator",
+ scoped: false,
+ dependencies: [ts.awaitHelper],
+ text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
+ };
+ ts.asyncValues = {
+ name: "typescript:asyncValues",
+ importName: "__asyncValues",
+ scoped: false,
+ text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
+ };
+ // ES2018 Destructuring Helpers
+ ts.restHelper = {
+ name: "typescript:rest",
+ importName: "__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 (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n };"
+ };
+ // ES2017 Helpers
+ ts.awaiterHelper = {
+ name: "typescript:awaiter",
+ importName: "__awaiter",
+ scoped: false,
+ priority: 5,
+ text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\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) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
+ };
+ // ES2015 Helpers
+ ts.extendsHelper = {
+ name: "typescript:extends",
+ importName: "__extends",
+ scoped: false,
+ priority: 0,
+ text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\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.templateObjectHelper = {
+ name: "typescript:makeTemplateObject",
+ importName: "__makeTemplateObject",
+ scoped: false,
+ priority: 0,
+ text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };"
+ };
+ ts.readHelper = {
+ name: "typescript:read",
+ importName: "__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 };"
+ };
+ ts.spreadHelper = {
+ name: "typescript:spread",
+ importName: "__spread",
+ scoped: false,
+ dependencies: [ts.readHelper],
+ 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 };"
+ };
+ ts.spreadArraysHelper = {
+ name: "typescript:spreadArrays",
+ importName: "__spreadArrays",
+ scoped: false,
+ text: "\n var __spreadArrays = (this && this.__spreadArrays) || function () {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n };"
+ };
+ // ES2015 Destructuring Helpers
+ ts.valuesHelper = {
+ name: "typescript:values",
+ importName: "__values",
+ scoped: false,
+ text: "\n var __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n };"
+ };
+ // ES2015 Generator Helpers
+ // The __generator helper is used by down-level transformations to emulate the runtime
+ // semantics of an ES2015 generator function. When called, this helper returns an
+ // object that implements the Iterator protocol, in that it has `next`, `return`, and
+ // `throw` methods that step through the generator when invoked.
+ //
+ // parameters:
+ // @param thisArg The value to use as the `this` binding for the transformed generator body.
+ // @param body A function that acts as the transformed generator body.
+ //
+ // variables:
+ // _ Persistent state for the generator that is shared between the helper and the
+ // generator body. The state object has the following members:
+ // sent() - A method that returns or throws the current completion value.
+ // label - The next point at which to resume evaluation of the generator body.
+ // trys - A stack of protected regions (try/catch/finally blocks).
+ // ops - A stack of pending instructions when inside of a finally block.
+ // f A value indicating whether the generator is executing.
+ // y An iterator to delegate for a yield*.
+ // t A temporary variable that holds one of the following values (note that these
+ // cases do not overlap):
+ // - The completion value when resuming from a `yield` or `yield*`.
+ // - The error value for a catch block.
+ // - The current protected region (array of try/catch/finally/end labels).
+ // - The verb (`next`, `throw`, or `return` method) to delegate to the expression
+ // of a `yield*`.
+ // - The result of evaluating the verb delegated to the expression of a `yield*`.
+ //
+ // functions:
+ // verb(n) Creates a bound callback to the `step` function for opcode `n`.
+ // step(op) Evaluates opcodes in a generator body until execution is suspended or
+ // completed.
+ //
+ // The __generator helper understands a limited set of instructions:
+ // 0: next(value?) - Start or resume the generator with the specified value.
+ // 1: throw(error) - Resume the generator with an exception. If the generator is
+ // suspended inside of one or more protected regions, evaluates
+ // any intervening finally blocks between the current label and
+ // the nearest catch block or function boundary. If uncaught, the
+ // exception is thrown to the caller.
+ // 2: return(value?) - Resume the generator as if with a return. If the generator is
+ // suspended inside of one or more protected regions, evaluates any
+ // intervening finally blocks.
+ // 3: break(label) - Jump to the specified label. If the label is outside of the
+ // current protected region, evaluates any intervening finally
+ // blocks.
+ // 4: yield(value?) - Yield execution to the caller with an optional value. When
+ // resumed, the generator will continue at the next label.
+ // 5: yield*(value) - Delegates evaluation to the supplied iterator. When
+ // delegation completes, the generator will continue at the next
+ // label.
+ // 6: catch(error) - Handles an exception thrown from within the generator body. If
+ // the current label is inside of one or more protected regions,
+ // evaluates any intervening finally blocks between the current
+ // label and the nearest catch block or function boundary. If
+ // uncaught, the exception is thrown to the caller.
+ // 7: endfinally - Ends a finally block, resuming the last instruction prior to
+ // entering a finally block.
+ //
+ // For examples of how these are used, see the comments in ./transformers/generators.ts
+ ts.generatorHelper = {
+ name: "typescript:generator",
+ importName: "__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, 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 = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, 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 };"
+ };
+ // ES Module Helpers
+ ts.createBindingHelper = {
+ name: "typescript:commonjscreatebinding",
+ importName: "__createBinding",
+ scoped: false,
+ priority: 1,
+ text: "\n var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n }) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n }));"
+ };
+ ts.setModuleDefaultHelper = {
+ name: "typescript:commonjscreatevalue",
+ importName: "__setModuleDefault",
+ scoped: false,
+ priority: 1,
+ text: "\n var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n }) : function(o, v) {\n o[\"default\"] = v;\n });"
+ };
+ // emit helper for `import * as Name from "foo"`
+ ts.importStarHelper = {
+ name: "typescript:commonjsimportstar",
+ importName: "__importStar",
+ scoped: false,
+ dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
+ priority: 2,
+ text: "\n var __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n };"
+ };
+ // emit helper for `import Name from "foo"`
+ ts.importDefaultHelper = {
+ name: "typescript:commonjsimportdefault",
+ importName: "__importDefault",
+ scoped: false,
+ text: "\n var __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n };"
+ };
+ // emit output for the __export helper function
+ ts.exportStarHelper = {
+ name: "typescript:export-star",
+ importName: "__exportStar",
+ scoped: false,
+ dependencies: [ts.createBindingHelper],
+ priority: 2,
+ text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n };"
+ };
+ // Class fields helpers
+ ts.classPrivateFieldGetHelper = {
+ name: "typescript:classPrivateFieldGet",
+ importName: "__classPrivateFieldGet",
+ scoped: false,
+ text: "\n var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return privateMap.get(receiver);\n };"
+ };
+ ts.classPrivateFieldSetHelper = {
+ name: "typescript:classPrivateFieldSet",
+ importName: "__classPrivateFieldSet",
+ scoped: false,
+ text: "\n var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n privateMap.set(receiver, value);\n return value;\n };"
+ };
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.restHelper,
+ ts.awaiterHelper,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.spreadHelper,
+ ts.spreadArraysHelper,
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper,
+ ts.exportStarHelper,
+ ts.classPrivateFieldGetHelper,
+ ts.classPrivateFieldSetHelper,
+ ts.createBindingHelper,
+ ts.setModuleDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ ts.getAllUnscopedEmitHelpers = getAllUnscopedEmitHelpers;
+ ts.asyncSuperHelper = {
+ name: "typescript:async-super",
+ scoped: true,
+ text: helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex")
+ };
+ ts.advancedAsyncSuperHelper = {
+ name: "typescript:advanced-async-super",
+ scoped: true,
+ text: helperString(__makeTemplateObject(["\n const ", " = (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 const ", " = (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);"]), "_superIndex")
+ };
+})(ts || (ts = {}));
+var ts;
+(function (ts) {
+ // Literals
+ function isNumericLiteral(node) {
+ return node.kind === 8 /* NumericLiteral */;
+ }
+ ts.isNumericLiteral = isNumericLiteral;
+ function isBigIntLiteral(node) {
+ return node.kind === 9 /* BigIntLiteral */;
+ }
+ ts.isBigIntLiteral = isBigIntLiteral;
+ function isStringLiteral(node) {
+ return node.kind === 10 /* StringLiteral */;
+ }
+ ts.isStringLiteral = isStringLiteral;
+ function isJsxText(node) {
+ return node.kind === 11 /* JsxText */;
+ }
+ ts.isJsxText = isJsxText;
+ function isRegularExpressionLiteral(node) {
+ return node.kind === 13 /* RegularExpressionLiteral */;
+ }
+ ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
+ function isNoSubstitutionTemplateLiteral(node) {
+ return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
+ }
+ ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
+ // Pseudo-literals
+ function isTemplateHead(node) {
+ return node.kind === 15 /* TemplateHead */;
+ }
+ ts.isTemplateHead = isTemplateHead;
+ function isTemplateMiddle(node) {
+ return node.kind === 16 /* TemplateMiddle */;
+ }
+ ts.isTemplateMiddle = isTemplateMiddle;
+ function isTemplateTail(node) {
+ return node.kind === 17 /* TemplateTail */;
+ }
+ ts.isTemplateTail = isTemplateTail;
+ // Identifiers
+ function isIdentifier(node) {
+ return node.kind === 78 /* Identifier */;
+ }
+ ts.isIdentifier = isIdentifier;
+ // Names
+ function isQualifiedName(node) {
+ return node.kind === 157 /* QualifiedName */;
+ }
+ ts.isQualifiedName = isQualifiedName;
+ function isComputedPropertyName(node) {
+ return node.kind === 158 /* ComputedPropertyName */;
+ }
+ ts.isComputedPropertyName = isComputedPropertyName;
+ function isPrivateIdentifier(node) {
+ return node.kind === 79 /* PrivateIdentifier */;
+ }
+ ts.isPrivateIdentifier = isPrivateIdentifier;
+ // Tokens
+ /*@internal*/
+ function isSuperKeyword(node) {
+ return node.kind === 105 /* SuperKeyword */;
+ }
+ ts.isSuperKeyword = isSuperKeyword;
+ /*@internal*/
+ function isImportKeyword(node) {
+ return node.kind === 99 /* ImportKeyword */;
+ }
+ ts.isImportKeyword = isImportKeyword;
+ /*@internal*/
+ function isCommaToken(node) {
+ return node.kind === 27 /* CommaToken */;
+ }
+ ts.isCommaToken = isCommaToken;
+ /*@internal*/
+ function isQuestionToken(node) {
+ return node.kind === 57 /* QuestionToken */;
+ }
+ ts.isQuestionToken = isQuestionToken;
+ /*@internal*/
+ function isExclamationToken(node) {
+ return node.kind === 53 /* ExclamationToken */;
+ }
+ ts.isExclamationToken = isExclamationToken;
+ // Signature elements
+ function isTypeParameterDeclaration(node) {
+ return node.kind === 159 /* TypeParameter */;
+ }
+ ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
+ // TODO(rbuckton): Rename to 'isParameterDeclaration'
+ function isParameter(node) {
+ return node.kind === 160 /* Parameter */;
+ }
+ ts.isParameter = isParameter;
+ function isDecorator(node) {
+ return node.kind === 161 /* Decorator */;
+ }
+ ts.isDecorator = isDecorator;
+ // TypeMember
+ function isPropertySignature(node) {
+ return node.kind === 162 /* PropertySignature */;
+ }
+ ts.isPropertySignature = isPropertySignature;
+ function isPropertyDeclaration(node) {
+ return node.kind === 163 /* PropertyDeclaration */;
+ }
+ ts.isPropertyDeclaration = isPropertyDeclaration;
+ function isMethodSignature(node) {
+ return node.kind === 164 /* MethodSignature */;
+ }
+ ts.isMethodSignature = isMethodSignature;
+ function isMethodDeclaration(node) {
+ return node.kind === 165 /* MethodDeclaration */;
+ }
+ ts.isMethodDeclaration = isMethodDeclaration;
+ function isConstructorDeclaration(node) {
+ return node.kind === 166 /* Constructor */;
+ }
+ ts.isConstructorDeclaration = isConstructorDeclaration;
+ function isGetAccessorDeclaration(node) {
+ return node.kind === 167 /* GetAccessor */;
+ }
+ ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
+ function isSetAccessorDeclaration(node) {
+ return node.kind === 168 /* SetAccessor */;
+ }
+ ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
+ function isCallSignatureDeclaration(node) {
+ return node.kind === 169 /* CallSignature */;
+ }
+ ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
+ function isConstructSignatureDeclaration(node) {
+ return node.kind === 170 /* ConstructSignature */;
+ }
+ ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
+ function isIndexSignatureDeclaration(node) {
+ return node.kind === 171 /* IndexSignature */;
+ }
+ ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
+ // Type
+ function isTypePredicateNode(node) {
+ return node.kind === 172 /* TypePredicate */;
+ }
+ ts.isTypePredicateNode = isTypePredicateNode;
+ function isTypeReferenceNode(node) {
+ return node.kind === 173 /* TypeReference */;
+ }
+ ts.isTypeReferenceNode = isTypeReferenceNode;
+ function isFunctionTypeNode(node) {
+ return node.kind === 174 /* FunctionType */;
+ }
+ ts.isFunctionTypeNode = isFunctionTypeNode;
+ function isConstructorTypeNode(node) {
+ return node.kind === 175 /* ConstructorType */;
+ }
+ ts.isConstructorTypeNode = isConstructorTypeNode;
+ function isTypeQueryNode(node) {
+ return node.kind === 176 /* TypeQuery */;
+ }
+ ts.isTypeQueryNode = isTypeQueryNode;
+ function isTypeLiteralNode(node) {
+ return node.kind === 177 /* TypeLiteral */;
+ }
+ ts.isTypeLiteralNode = isTypeLiteralNode;
+ function isArrayTypeNode(node) {
+ return node.kind === 178 /* ArrayType */;
+ }
+ ts.isArrayTypeNode = isArrayTypeNode;
+ function isTupleTypeNode(node) {
+ return node.kind === 179 /* TupleType */;
+ }
+ ts.isTupleTypeNode = isTupleTypeNode;
+ function isNamedTupleMember(node) {
+ return node.kind === 192 /* NamedTupleMember */;
+ }
+ ts.isNamedTupleMember = isNamedTupleMember;
+ function isOptionalTypeNode(node) {
+ return node.kind === 180 /* OptionalType */;
+ }
+ ts.isOptionalTypeNode = isOptionalTypeNode;
+ function isRestTypeNode(node) {
+ return node.kind === 181 /* RestType */;
+ }
+ ts.isRestTypeNode = isRestTypeNode;
+ function isUnionTypeNode(node) {
+ return node.kind === 182 /* UnionType */;
+ }
+ ts.isUnionTypeNode = isUnionTypeNode;
+ function isIntersectionTypeNode(node) {
+ return node.kind === 183 /* IntersectionType */;
+ }
+ ts.isIntersectionTypeNode = isIntersectionTypeNode;
+ function isConditionalTypeNode(node) {
+ return node.kind === 184 /* ConditionalType */;
+ }
+ ts.isConditionalTypeNode = isConditionalTypeNode;
+ function isInferTypeNode(node) {
+ return node.kind === 185 /* InferType */;
+ }
+ ts.isInferTypeNode = isInferTypeNode;
+ function isParenthesizedTypeNode(node) {
+ return node.kind === 186 /* ParenthesizedType */;
+ }
+ ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
+ function isThisTypeNode(node) {
+ return node.kind === 187 /* ThisType */;
+ }
+ ts.isThisTypeNode = isThisTypeNode;
+ function isTypeOperatorNode(node) {
+ return node.kind === 188 /* TypeOperator */;
+ }
+ ts.isTypeOperatorNode = isTypeOperatorNode;
+ function isIndexedAccessTypeNode(node) {
+ return node.kind === 189 /* IndexedAccessType */;
+ }
+ ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
+ function isMappedTypeNode(node) {
+ return node.kind === 190 /* MappedType */;
+ }
+ ts.isMappedTypeNode = isMappedTypeNode;
+ function isLiteralTypeNode(node) {
+ return node.kind === 191 /* LiteralType */;
+ }
+ ts.isLiteralTypeNode = isLiteralTypeNode;
+ function isImportTypeNode(node) {
+ return node.kind === 195 /* ImportType */;
+ }
+ ts.isImportTypeNode = isImportTypeNode;
+ function isTemplateLiteralTypeSpan(node) {
+ return node.kind === 194 /* TemplateLiteralTypeSpan */;
+ }
+ ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan;
+ function isTemplateLiteralTypeNode(node) {
+ return node.kind === 193 /* TemplateLiteralType */;
+ }
+ ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode;
+ // Binding patterns
+ function isObjectBindingPattern(node) {
+ return node.kind === 196 /* ObjectBindingPattern */;
+ }
+ ts.isObjectBindingPattern = isObjectBindingPattern;
+ function isArrayBindingPattern(node) {
+ return node.kind === 197 /* ArrayBindingPattern */;
+ }
+ ts.isArrayBindingPattern = isArrayBindingPattern;
+ function isBindingElement(node) {
+ return node.kind === 198 /* BindingElement */;
+ }
+ ts.isBindingElement = isBindingElement;
+ // Expression
+ function isArrayLiteralExpression(node) {
+ return node.kind === 199 /* ArrayLiteralExpression */;
+ }
+ ts.isArrayLiteralExpression = isArrayLiteralExpression;
+ function isObjectLiteralExpression(node) {
+ return node.kind === 200 /* ObjectLiteralExpression */;
+ }
+ ts.isObjectLiteralExpression = isObjectLiteralExpression;
+ function isPropertyAccessExpression(node) {
+ return node.kind === 201 /* PropertyAccessExpression */;
+ }
+ ts.isPropertyAccessExpression = isPropertyAccessExpression;
+ function isElementAccessExpression(node) {
+ return node.kind === 202 /* ElementAccessExpression */;
+ }
+ ts.isElementAccessExpression = isElementAccessExpression;
+ function isCallExpression(node) {
+ return node.kind === 203 /* CallExpression */;
+ }
+ ts.isCallExpression = isCallExpression;
+ function isNewExpression(node) {
+ return node.kind === 204 /* NewExpression */;
+ }
+ ts.isNewExpression = isNewExpression;
+ function isTaggedTemplateExpression(node) {
+ return node.kind === 205 /* TaggedTemplateExpression */;
+ }
+ ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
+ function isTypeAssertionExpression(node) {
+ return node.kind === 206 /* TypeAssertionExpression */;
+ }
+ ts.isTypeAssertionExpression = isTypeAssertionExpression;
+ function isParenthesizedExpression(node) {
+ return node.kind === 207 /* ParenthesizedExpression */;
+ }
+ ts.isParenthesizedExpression = isParenthesizedExpression;
+ function isFunctionExpression(node) {
+ return node.kind === 208 /* FunctionExpression */;
+ }
+ ts.isFunctionExpression = isFunctionExpression;
+ function isArrowFunction(node) {
+ return node.kind === 209 /* ArrowFunction */;
+ }
+ ts.isArrowFunction = isArrowFunction;
+ function isDeleteExpression(node) {
+ return node.kind === 210 /* DeleteExpression */;
+ }
+ ts.isDeleteExpression = isDeleteExpression;
+ function isTypeOfExpression(node) {
+ return node.kind === 211 /* TypeOfExpression */;
+ }
+ ts.isTypeOfExpression = isTypeOfExpression;
+ function isVoidExpression(node) {
+ return node.kind === 212 /* VoidExpression */;
+ }
+ ts.isVoidExpression = isVoidExpression;
+ function isAwaitExpression(node) {
+ return node.kind === 213 /* AwaitExpression */;
+ }
+ ts.isAwaitExpression = isAwaitExpression;
+ function isPrefixUnaryExpression(node) {
+ return node.kind === 214 /* PrefixUnaryExpression */;
+ }
+ ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
+ function isPostfixUnaryExpression(node) {
+ return node.kind === 215 /* PostfixUnaryExpression */;
+ }
+ ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
+ function isBinaryExpression(node) {
+ return node.kind === 216 /* BinaryExpression */;
+ }
+ ts.isBinaryExpression = isBinaryExpression;
+ function isConditionalExpression(node) {
+ return node.kind === 217 /* ConditionalExpression */;
+ }
+ ts.isConditionalExpression = isConditionalExpression;
+ function isTemplateExpression(node) {
+ return node.kind === 218 /* TemplateExpression */;
+ }
+ ts.isTemplateExpression = isTemplateExpression;
+ function isYieldExpression(node) {
+ return node.kind === 219 /* YieldExpression */;
+ }
+ ts.isYieldExpression = isYieldExpression;
+ function isSpreadElement(node) {
+ return node.kind === 220 /* SpreadElement */;
+ }
+ ts.isSpreadElement = isSpreadElement;
+ function isClassExpression(node) {
+ return node.kind === 221 /* ClassExpression */;
+ }
+ ts.isClassExpression = isClassExpression;
+ function isOmittedExpression(node) {
+ return node.kind === 222 /* OmittedExpression */;
+ }
+ ts.isOmittedExpression = isOmittedExpression;
+ function isExpressionWithTypeArguments(node) {
+ return node.kind === 223 /* ExpressionWithTypeArguments */;
+ }
+ ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
+ function isAsExpression(node) {
+ return node.kind === 224 /* AsExpression */;
+ }
+ ts.isAsExpression = isAsExpression;
+ function isNonNullExpression(node) {
+ return node.kind === 225 /* NonNullExpression */;
+ }
+ ts.isNonNullExpression = isNonNullExpression;
+ function isMetaProperty(node) {
+ return node.kind === 226 /* MetaProperty */;
+ }
+ ts.isMetaProperty = isMetaProperty;
+ function isSyntheticExpression(node) {
+ return node.kind === 227 /* SyntheticExpression */;
+ }
+ ts.isSyntheticExpression = isSyntheticExpression;
+ function isPartiallyEmittedExpression(node) {
+ return node.kind === 336 /* PartiallyEmittedExpression */;
+ }
+ ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
+ function isCommaListExpression(node) {
+ return node.kind === 337 /* CommaListExpression */;
+ }
+ ts.isCommaListExpression = isCommaListExpression;
+ // Misc
+ function isTemplateSpan(node) {
+ return node.kind === 228 /* TemplateSpan */;
+ }
+ ts.isTemplateSpan = isTemplateSpan;
+ function isSemicolonClassElement(node) {
+ return node.kind === 229 /* SemicolonClassElement */;
+ }
+ ts.isSemicolonClassElement = isSemicolonClassElement;
+ // Elements
+ function isBlock(node) {
+ return node.kind === 230 /* Block */;
+ }
+ ts.isBlock = isBlock;
+ function isVariableStatement(node) {
+ return node.kind === 232 /* VariableStatement */;
+ }
+ ts.isVariableStatement = isVariableStatement;
+ function isEmptyStatement(node) {
+ return node.kind === 231 /* EmptyStatement */;
+ }
+ ts.isEmptyStatement = isEmptyStatement;
+ function isExpressionStatement(node) {
+ return node.kind === 233 /* ExpressionStatement */;
+ }
+ ts.isExpressionStatement = isExpressionStatement;
+ function isIfStatement(node) {
+ return node.kind === 234 /* IfStatement */;
+ }
+ ts.isIfStatement = isIfStatement;
+ function isDoStatement(node) {
+ return node.kind === 235 /* DoStatement */;
+ }
+ ts.isDoStatement = isDoStatement;
+ function isWhileStatement(node) {
+ return node.kind === 236 /* WhileStatement */;
+ }
+ ts.isWhileStatement = isWhileStatement;
+ function isForStatement(node) {
+ return node.kind === 237 /* ForStatement */;
+ }
+ ts.isForStatement = isForStatement;
+ function isForInStatement(node) {
+ return node.kind === 238 /* ForInStatement */;
+ }
+ ts.isForInStatement = isForInStatement;
+ function isForOfStatement(node) {
+ return node.kind === 239 /* ForOfStatement */;
+ }
+ ts.isForOfStatement = isForOfStatement;
+ function isContinueStatement(node) {
+ return node.kind === 240 /* ContinueStatement */;
+ }
+ ts.isContinueStatement = isContinueStatement;
+ function isBreakStatement(node) {
+ return node.kind === 241 /* BreakStatement */;
+ }
+ ts.isBreakStatement = isBreakStatement;
+ function isReturnStatement(node) {
+ return node.kind === 242 /* ReturnStatement */;
+ }
+ ts.isReturnStatement = isReturnStatement;
+ function isWithStatement(node) {
+ return node.kind === 243 /* WithStatement */;
+ }
+ ts.isWithStatement = isWithStatement;
+ function isSwitchStatement(node) {
+ return node.kind === 244 /* SwitchStatement */;
+ }
+ ts.isSwitchStatement = isSwitchStatement;
+ function isLabeledStatement(node) {
+ return node.kind === 245 /* LabeledStatement */;
+ }
+ ts.isLabeledStatement = isLabeledStatement;
+ function isThrowStatement(node) {
+ return node.kind === 246 /* ThrowStatement */;
+ }
+ ts.isThrowStatement = isThrowStatement;
+ function isTryStatement(node) {
+ return node.kind === 247 /* TryStatement */;
+ }
+ ts.isTryStatement = isTryStatement;
+ function isDebuggerStatement(node) {
+ return node.kind === 248 /* DebuggerStatement */;
+ }
+ ts.isDebuggerStatement = isDebuggerStatement;
+ function isVariableDeclaration(node) {
+ return node.kind === 249 /* VariableDeclaration */;
+ }
+ ts.isVariableDeclaration = isVariableDeclaration;
+ function isVariableDeclarationList(node) {
+ return node.kind === 250 /* VariableDeclarationList */;
+ }
+ ts.isVariableDeclarationList = isVariableDeclarationList;
+ function isFunctionDeclaration(node) {
+ return node.kind === 251 /* FunctionDeclaration */;
+ }
+ ts.isFunctionDeclaration = isFunctionDeclaration;
+ function isClassDeclaration(node) {
+ return node.kind === 252 /* ClassDeclaration */;
+ }
+ ts.isClassDeclaration = isClassDeclaration;
+ function isInterfaceDeclaration(node) {
+ return node.kind === 253 /* InterfaceDeclaration */;
+ }
+ ts.isInterfaceDeclaration = isInterfaceDeclaration;
+ function isTypeAliasDeclaration(node) {
+ return node.kind === 254 /* TypeAliasDeclaration */;
+ }
+ ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
+ function isEnumDeclaration(node) {
+ return node.kind === 255 /* EnumDeclaration */;
+ }
+ ts.isEnumDeclaration = isEnumDeclaration;
+ function isModuleDeclaration(node) {
+ return node.kind === 256 /* ModuleDeclaration */;
+ }
+ ts.isModuleDeclaration = isModuleDeclaration;
+ function isModuleBlock(node) {
+ return node.kind === 257 /* ModuleBlock */;
+ }
+ ts.isModuleBlock = isModuleBlock;
+ function isCaseBlock(node) {
+ return node.kind === 258 /* CaseBlock */;
+ }
+ ts.isCaseBlock = isCaseBlock;
+ function isNamespaceExportDeclaration(node) {
+ return node.kind === 259 /* NamespaceExportDeclaration */;
+ }
+ ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
+ function isImportEqualsDeclaration(node) {
+ return node.kind === 260 /* ImportEqualsDeclaration */;
+ }
+ ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
+ function isImportDeclaration(node) {
+ return node.kind === 261 /* ImportDeclaration */;
+ }
+ ts.isImportDeclaration = isImportDeclaration;
+ function isImportClause(node) {
+ return node.kind === 262 /* ImportClause */;
+ }
+ ts.isImportClause = isImportClause;
+ function isNamespaceImport(node) {
+ return node.kind === 263 /* NamespaceImport */;
+ }
+ ts.isNamespaceImport = isNamespaceImport;
+ function isNamespaceExport(node) {
+ return node.kind === 269 /* NamespaceExport */;
+ }
+ ts.isNamespaceExport = isNamespaceExport;
+ function isNamedImports(node) {
+ return node.kind === 264 /* NamedImports */;
+ }
+ ts.isNamedImports = isNamedImports;
+ function isImportSpecifier(node) {
+ return node.kind === 265 /* ImportSpecifier */;
+ }
+ ts.isImportSpecifier = isImportSpecifier;
+ function isExportAssignment(node) {
+ return node.kind === 266 /* ExportAssignment */;
+ }
+ ts.isExportAssignment = isExportAssignment;
+ function isExportDeclaration(node) {
+ return node.kind === 267 /* ExportDeclaration */;
+ }
+ ts.isExportDeclaration = isExportDeclaration;
+ function isNamedExports(node) {
+ return node.kind === 268 /* NamedExports */;
+ }
+ ts.isNamedExports = isNamedExports;
+ function isExportSpecifier(node) {
+ return node.kind === 270 /* ExportSpecifier */;
+ }
+ ts.isExportSpecifier = isExportSpecifier;
+ function isMissingDeclaration(node) {
+ return node.kind === 271 /* MissingDeclaration */;
+ }
+ ts.isMissingDeclaration = isMissingDeclaration;
+ function isNotEmittedStatement(node) {
+ return node.kind === 335 /* NotEmittedStatement */;
+ }
+ ts.isNotEmittedStatement = isNotEmittedStatement;
+ /* @internal */
+ function isSyntheticReference(node) {
+ return node.kind === 340 /* SyntheticReferenceExpression */;
+ }
+ ts.isSyntheticReference = isSyntheticReference;
+ /* @internal */
+ function isMergeDeclarationMarker(node) {
+ return node.kind === 338 /* MergeDeclarationMarker */;
+ }
+ ts.isMergeDeclarationMarker = isMergeDeclarationMarker;
+ /* @internal */
+ function isEndOfDeclarationMarker(node) {
+ return node.kind === 339 /* EndOfDeclarationMarker */;
+ }
+ ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker;
+ // Module References
+ function isExternalModuleReference(node) {
+ return node.kind === 272 /* ExternalModuleReference */;
+ }
+ ts.isExternalModuleReference = isExternalModuleReference;
+ // JSX
+ function isJsxElement(node) {
+ return node.kind === 273 /* JsxElement */;
+ }
+ ts.isJsxElement = isJsxElement;
+ function isJsxSelfClosingElement(node) {
+ return node.kind === 274 /* JsxSelfClosingElement */;
+ }
+ ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
+ function isJsxOpeningElement(node) {
+ return node.kind === 275 /* JsxOpeningElement */;
+ }
+ ts.isJsxOpeningElement = isJsxOpeningElement;
+ function isJsxClosingElement(node) {
+ return node.kind === 276 /* JsxClosingElement */;
+ }
+ ts.isJsxClosingElement = isJsxClosingElement;
+ function isJsxFragment(node) {
+ return node.kind === 277 /* JsxFragment */;
+ }
+ ts.isJsxFragment = isJsxFragment;
+ function isJsxOpeningFragment(node) {
+ return node.kind === 278 /* JsxOpeningFragment */;
+ }
+ ts.isJsxOpeningFragment = isJsxOpeningFragment;
+ function isJsxClosingFragment(node) {
+ return node.kind === 279 /* JsxClosingFragment */;
+ }
+ ts.isJsxClosingFragment = isJsxClosingFragment;
+ function isJsxAttribute(node) {
+ return node.kind === 280 /* JsxAttribute */;
+ }
+ ts.isJsxAttribute = isJsxAttribute;
+ function isJsxAttributes(node) {
+ return node.kind === 281 /* JsxAttributes */;
+ }
+ ts.isJsxAttributes = isJsxAttributes;
+ function isJsxSpreadAttribute(node) {
+ return node.kind === 282 /* JsxSpreadAttribute */;
+ }
+ ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
+ function isJsxExpression(node) {
+ return node.kind === 283 /* JsxExpression */;
+ }
+ ts.isJsxExpression = isJsxExpression;
+ // Clauses
+ function isCaseClause(node) {
+ return node.kind === 284 /* CaseClause */;
+ }
+ ts.isCaseClause = isCaseClause;
+ function isDefaultClause(node) {
+ return node.kind === 285 /* DefaultClause */;
+ }
+ ts.isDefaultClause = isDefaultClause;
+ function isHeritageClause(node) {
+ return node.kind === 286 /* HeritageClause */;
+ }
+ ts.isHeritageClause = isHeritageClause;
+ function isCatchClause(node) {
+ return node.kind === 287 /* CatchClause */;
+ }
+ ts.isCatchClause = isCatchClause;
+ // Property assignments
+ function isPropertyAssignment(node) {
+ return node.kind === 288 /* PropertyAssignment */;
+ }
+ ts.isPropertyAssignment = isPropertyAssignment;
+ function isShorthandPropertyAssignment(node) {
+ return node.kind === 289 /* ShorthandPropertyAssignment */;
+ }
+ ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
+ function isSpreadAssignment(node) {
+ return node.kind === 290 /* SpreadAssignment */;
+ }
+ ts.isSpreadAssignment = isSpreadAssignment;
+ // Enum
+ function isEnumMember(node) {
+ return node.kind === 291 /* EnumMember */;
+ }
+ ts.isEnumMember = isEnumMember;
+ // Unparsed
+ // TODO(rbuckton): isUnparsedPrologue
+ function isUnparsedPrepend(node) {
+ return node.kind === 293 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ // TODO(rbuckton): isUnparsedText
+ // TODO(rbuckton): isUnparsedInternalText
+ // TODO(rbuckton): isUnparsedSyntheticReference
+ // Top-level nodes
+ function isSourceFile(node) {
+ return node.kind === 297 /* SourceFile */;
+ }
+ ts.isSourceFile = isSourceFile;
+ function isBundle(node) {
+ return node.kind === 298 /* Bundle */;
+ }
+ ts.isBundle = isBundle;
+ function isUnparsedSource(node) {
+ return node.kind === 299 /* UnparsedSource */;
+ }
+ ts.isUnparsedSource = isUnparsedSource;
+ // TODO(rbuckton): isInputFiles
+ // JSDoc Elements
+ function isJSDocTypeExpression(node) {
+ return node.kind === 301 /* JSDocTypeExpression */;
+ }
+ ts.isJSDocTypeExpression = isJSDocTypeExpression;
+ function isJSDocNameReference(node) {
+ return node.kind === 302 /* JSDocNameReference */;
+ }
+ ts.isJSDocNameReference = isJSDocNameReference;
+ function isJSDocAllType(node) {
+ return node.kind === 303 /* JSDocAllType */;
+ }
+ ts.isJSDocAllType = isJSDocAllType;
+ function isJSDocUnknownType(node) {
+ return node.kind === 304 /* JSDocUnknownType */;
+ }
+ ts.isJSDocUnknownType = isJSDocUnknownType;
+ function isJSDocNullableType(node) {
+ return node.kind === 305 /* JSDocNullableType */;
+ }
+ ts.isJSDocNullableType = isJSDocNullableType;
+ function isJSDocNonNullableType(node) {
+ return node.kind === 306 /* JSDocNonNullableType */;
+ }
+ ts.isJSDocNonNullableType = isJSDocNonNullableType;
+ function isJSDocOptionalType(node) {
+ return node.kind === 307 /* JSDocOptionalType */;
+ }
+ ts.isJSDocOptionalType = isJSDocOptionalType;
+ function isJSDocFunctionType(node) {
+ return node.kind === 308 /* JSDocFunctionType */;
+ }
+ ts.isJSDocFunctionType = isJSDocFunctionType;
+ function isJSDocVariadicType(node) {
+ return node.kind === 309 /* JSDocVariadicType */;
+ }
+ ts.isJSDocVariadicType = isJSDocVariadicType;
+ function isJSDocNamepathType(node) {
+ return node.kind === 310 /* JSDocNamepathType */;
+ }
+ ts.isJSDocNamepathType = isJSDocNamepathType;
+ function isJSDoc(node) {
+ return node.kind === 311 /* JSDocComment */;
+ }
+ ts.isJSDoc = isJSDoc;
+ function isJSDocTypeLiteral(node) {
+ return node.kind === 312 /* JSDocTypeLiteral */;
+ }
+ ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
+ function isJSDocSignature(node) {
+ return node.kind === 313 /* JSDocSignature */;
+ }
+ ts.isJSDocSignature = isJSDocSignature;
+ // JSDoc Tags
+ function isJSDocAugmentsTag(node) {
+ return node.kind === 315 /* JSDocAugmentsTag */;
+ }
+ ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
+ function isJSDocAuthorTag(node) {
+ return node.kind === 317 /* JSDocAuthorTag */;
+ }
+ ts.isJSDocAuthorTag = isJSDocAuthorTag;
+ function isJSDocClassTag(node) {
+ return node.kind === 319 /* JSDocClassTag */;
+ }
+ ts.isJSDocClassTag = isJSDocClassTag;
+ function isJSDocCallbackTag(node) {
+ return node.kind === 324 /* JSDocCallbackTag */;
+ }
+ ts.isJSDocCallbackTag = isJSDocCallbackTag;
+ function isJSDocPublicTag(node) {
+ return node.kind === 320 /* JSDocPublicTag */;
+ }
+ ts.isJSDocPublicTag = isJSDocPublicTag;
+ function isJSDocPrivateTag(node) {
+ return node.kind === 321 /* JSDocPrivateTag */;
+ }
+ ts.isJSDocPrivateTag = isJSDocPrivateTag;
+ function isJSDocProtectedTag(node) {
+ return node.kind === 322 /* JSDocProtectedTag */;
+ }
+ ts.isJSDocProtectedTag = isJSDocProtectedTag;
+ function isJSDocReadonlyTag(node) {
+ return node.kind === 323 /* JSDocReadonlyTag */;
+ }
+ ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
+ function isJSDocDeprecatedTag(node) {
+ return node.kind === 318 /* JSDocDeprecatedTag */;
+ }
+ ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag;
+ function isJSDocEnumTag(node) {
+ return node.kind === 325 /* JSDocEnumTag */;
+ }
+ ts.isJSDocEnumTag = isJSDocEnumTag;
+ function isJSDocParameterTag(node) {
+ return node.kind === 326 /* JSDocParameterTag */;
+ }
+ ts.isJSDocParameterTag = isJSDocParameterTag;
+ function isJSDocReturnTag(node) {
+ return node.kind === 327 /* JSDocReturnTag */;
+ }
+ ts.isJSDocReturnTag = isJSDocReturnTag;
+ function isJSDocThisTag(node) {
+ return node.kind === 328 /* JSDocThisTag */;
+ }
+ ts.isJSDocThisTag = isJSDocThisTag;
+ function isJSDocTypeTag(node) {
+ return node.kind === 329 /* JSDocTypeTag */;
+ }
+ ts.isJSDocTypeTag = isJSDocTypeTag;
+ function isJSDocTemplateTag(node) {
+ return node.kind === 330 /* JSDocTemplateTag */;
+ }
+ ts.isJSDocTemplateTag = isJSDocTemplateTag;
+ function isJSDocTypedefTag(node) {
+ return node.kind === 331 /* JSDocTypedefTag */;
+ }
+ ts.isJSDocTypedefTag = isJSDocTypedefTag;
+ function isJSDocUnknownTag(node) {
+ return node.kind === 314 /* JSDocTag */;
+ }
+ ts.isJSDocUnknownTag = isJSDocUnknownTag;
+ function isJSDocPropertyTag(node) {
+ return node.kind === 333 /* JSDocPropertyTag */;
+ }
+ ts.isJSDocPropertyTag = isJSDocPropertyTag;
+ function isJSDocImplementsTag(node) {
+ return node.kind === 316 /* JSDocImplementsTag */;
+ }
+ ts.isJSDocImplementsTag = isJSDocImplementsTag;
+ // Synthesized list
+ /* @internal */
+ function isSyntaxList(n) {
+ return n.kind === 334 /* SyntaxList */;
+ }
+ ts.isSyntaxList = isSyntaxList;
+})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ // Compound nodes
+ function createEmptyExports(factory) {
+ return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined);
+ }
+ ts.createEmptyExports = createEmptyExports;
+ function createMemberAccessForPropertyName(factory, target, memberName, location) {
+ if (ts.isComputedPropertyName(memberName)) {
+ return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location);
+ }
+ else {
+ var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName)
+ ? factory.createPropertyAccessExpression(target, memberName)
+ : factory.createElementAccessExpression(target, memberName), memberName);
+ ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
+ return expression;
+ }
+ }
+ ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
+ 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 = ts.parseNodeFactory.createIdentifier(reactNamespace || "React");
+ // Set the parent that is in parse tree
+ // this makes sure that parent chain is intact for checker to traverse complete scope tree
+ ts.setParent(react, ts.getParseTreeNode(parent));
+ return react;
+ }
+ function createJsxFactoryExpressionFromEntityName(factory, jsxFactory, parent) {
+ if (ts.isQualifiedName(jsxFactory)) {
+ var left = createJsxFactoryExpressionFromEntityName(factory, jsxFactory.left, parent);
+ var right = factory.createIdentifier(ts.idText(jsxFactory.right));
+ right.escapedText = jsxFactory.right.escapedText;
+ return factory.createPropertyAccessExpression(left, right);
+ }
+ else {
+ return createReactNamespace(ts.idText(jsxFactory), parent);
+ }
+ }
+ function createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parent) {
+ return jsxFactoryEntity ?
+ createJsxFactoryExpressionFromEntityName(factory, jsxFactoryEntity, parent) :
+ factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "createElement");
+ }
+ ts.createJsxFactoryExpression = createJsxFactoryExpression;
+ function createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parent) {
+ return jsxFragmentFactoryEntity ?
+ createJsxFactoryExpressionFromEntityName(factory, jsxFragmentFactoryEntity, parent) :
+ factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "Fragment");
+ }
+ function createExpressionForJsxElement(factory, callee, tagName, props, children, location) {
+ var argumentsList = [tagName];
+ if (props) {
+ argumentsList.push(props);
+ }
+ if (children && children.length > 0) {
+ if (!props) {
+ argumentsList.push(factory.createNull());
+ }
+ if (children.length > 1) {
+ for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
+ var child = children_3[_i];
+ startOnNewLine(child);
+ argumentsList.push(child);
+ }
+ }
+ else {
+ argumentsList.push(children[0]);
+ }
+ }
+ return ts.setTextRange(factory.createCallExpression(callee,
+ /*typeArguments*/ undefined, argumentsList), location);
+ }
+ ts.createExpressionForJsxElement = createExpressionForJsxElement;
+ function createExpressionForJsxFragment(factory, jsxFactoryEntity, jsxFragmentFactoryEntity, reactNamespace, children, parentElement, location) {
+ var tagName = createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parentElement);
+ var argumentsList = [tagName, factory.createNull()];
+ if (children && children.length > 0) {
+ if (children.length > 1) {
+ for (var _i = 0, children_4 = children; _i < children_4.length; _i++) {
+ var child = children_4[_i];
+ startOnNewLine(child);
+ argumentsList.push(child);
+ }
+ }
+ else {
+ argumentsList.push(children[0]);
+ }
+ }
+ return ts.setTextRange(factory.createCallExpression(createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parentElement),
+ /*typeArguments*/ undefined, argumentsList), location);
+ }
+ ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
+ // Utilities
+ function createForOfBindingStatement(factory, node, boundValue) {
+ if (ts.isVariableDeclarationList(node)) {
+ var firstDeclaration = ts.first(node.declarations);
+ var updatedDeclaration = factory.updateVariableDeclaration(firstDeclaration, firstDeclaration.name,
+ /*exclamationToken*/ undefined,
+ /*type*/ undefined, boundValue);
+ return ts.setTextRange(factory.createVariableStatement(
+ /*modifiers*/ undefined, factory.updateVariableDeclarationList(node, [updatedDeclaration])),
+ /*location*/ node);
+ }
+ else {
+ var updatedExpression = ts.setTextRange(factory.createAssignment(node, boundValue), /*location*/ node);
+ return ts.setTextRange(factory.createExpressionStatement(updatedExpression), /*location*/ node);
+ }
+ }
+ ts.createForOfBindingStatement = createForOfBindingStatement;
+ function insertLeadingStatement(factory, dest, source) {
+ if (ts.isBlock(dest)) {
+ return factory.updateBlock(dest, ts.setTextRange(factory.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
+ }
+ else {
+ return factory.createBlock(factory.createNodeArray([dest, source]), /*multiLine*/ true);
+ }
+ }
+ ts.insertLeadingStatement = insertLeadingStatement;
+ function createExpressionFromEntityName(factory, node) {
+ if (ts.isQualifiedName(node)) {
+ var left = createExpressionFromEntityName(factory, node.left);
+ // TODO(rbuckton): Does this need to be parented?
+ var right = ts.setParent(ts.setTextRange(factory.cloneNode(node.right), node.right), node.right.parent);
+ return ts.setTextRange(factory.createPropertyAccessExpression(left, right), node);
+ }
+ else {
+ // TODO(rbuckton): Does this need to be parented?
+ return ts.setParent(ts.setTextRange(factory.cloneNode(node), node), node.parent);
+ }
+ }
+ ts.createExpressionFromEntityName = createExpressionFromEntityName;
+ function createExpressionForPropertyName(factory, memberName) {
+ if (ts.isIdentifier(memberName)) {
+ return factory.createStringLiteralFromNode(memberName);
+ }
+ else if (ts.isComputedPropertyName(memberName)) {
+ // TODO(rbuckton): Does this need to be parented?
+ return ts.setParent(ts.setTextRange(factory.cloneNode(memberName.expression), memberName.expression), memberName.expression.parent);
+ }
+ else {
+ // TODO(rbuckton): Does this need to be parented?
+ return ts.setParent(ts.setTextRange(factory.cloneNode(memberName), memberName), memberName.parent);
+ }
+ }
+ ts.createExpressionForPropertyName = createExpressionForPropertyName;
+ function createExpressionForAccessorDeclaration(factory, properties, property, receiver, multiLine) {
+ var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
+ if (property === firstAccessor) {
+ return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({
+ enumerable: factory.createFalse(),
+ configurable: true,
+ get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers,
+ /*asteriskToken*/ undefined,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, getAccessor.parameters,
+ /*type*/ undefined, getAccessor.body // TODO: GH#18217
+ ), getAccessor), getAccessor),
+ set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers,
+ /*asteriskToken*/ undefined,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, setAccessor.parameters,
+ /*type*/ undefined, setAccessor.body // TODO: GH#18217
+ ), setAccessor), setAccessor)
+ }, !multiLine)), firstAccessor);
+ }
+ return undefined;
+ }
+ function createExpressionForPropertyAssignment(factory, property, receiver) {
+ return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), property.initializer), property), property);
+ }
+ function createExpressionForShorthandPropertyAssignment(factory, property, receiver) {
+ return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), factory.cloneNode(property.name)),
+ /*location*/ property),
+ /*original*/ property);
+ }
+ function createExpressionForMethodDeclaration(factory, method, receiver) {
+ return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken,
+ /*name*/ undefined,
+ /*typeParameters*/ undefined, method.parameters,
+ /*type*/ undefined, method.body // TODO: GH#18217
+ ),
+ /*location*/ method),
+ /*original*/ method)),
+ /*location*/ method),
+ /*original*/ method);
+ }
+ function createExpressionForObjectLiteralElementLike(factory, node, property, receiver) {
+ if (property.name && ts.isPrivateIdentifier(property.name)) {
+ ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
+ }
+ switch (property.kind) {
+ case 167 /* GetAccessor */:
+ case 168 /* SetAccessor */:
+ return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine);
+ case 288 /* PropertyAssignment */:
+ return createExpressionForPropertyAssignment(factory, property, receiver);
+ case 289 /* ShorthandPropertyAssignment */:
+ return createExpressionForShorthandPropertyAssignment(factory, property, receiver);
+ case 165 /* MethodDeclaration */:
+ return createExpressionForMethodDeclaration(factory, property, receiver);
+ }
+ }
+ ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
+ /**
+ * Gets whether an identifier should only be referred to by its internal name.
+ */
+ function isInternalName(node) {
+ return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
+ }
+ ts.isInternalName = isInternalName;
+ /**
+ * Gets whether an identifier should only be referred to by its local name.
+ */
+ function isLocalName(node) {
+ return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
+ }
+ ts.isLocalName = isLocalName;
+ /**
+ * Gets whether an identifier should only be referred to by its export representation if the
+ * name points to an exported symbol.
+ */
+ function isExportName(node) {
+ return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
+ }
+ ts.isExportName = isExportName;
+ function isUseStrictPrologue(node) {
+ return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
+ }
+ function findUseStrictPrologue(statements) {
+ for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
+ var statement = statements_1[_i];
+ if (ts.isPrologueDirective(statement)) {
+ if (isUseStrictPrologue(statement)) {
+ return statement;
+ }
+ }
+ else {
+ break;
+ }
+ }
+ return undefined;
+ }
+ ts.findUseStrictPrologue = findUseStrictPrologue;
+ function startsWithUseStrict(statements) {
+ var firstStatement = ts.firstOrUndefined(statements);
+ return firstStatement !== undefined
+ && ts.isPrologueDirective(firstStatement)
+ && isUseStrictPrologue(firstStatement);
+ }
+ ts.startsWithUseStrict = startsWithUseStrict;
+ function isCommaSequence(node) {
+ return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
+ node.kind === 337 /* CommaListExpression */;
+ }
+ ts.isCommaSequence = isCommaSequence;
+ function isOuterExpression(node, kinds) {
+ if (kinds === void 0) { kinds = 15 /* All */; }
+ switch (node.kind) {
+ case 207 /* ParenthesizedExpression */:
+ return (kinds & 1 /* Parentheses */) !== 0;
+ case 206 /* TypeAssertionExpression */:
+ case 224 /* AsExpression */:
+ return (kinds & 2 /* TypeAssertions */) !== 0;
+ case 225 /* NonNullExpression */:
+ return (kinds & 4 /* NonNullAssertions */) !== 0;
+ case 336 /* PartiallyEmittedExpression */:
+ return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
+ }
+ return false;
+ }
+ ts.isOuterExpression = isOuterExpression;
+ function skipOuterExpressions(node, kinds) {
+ if (kinds === void 0) { kinds = 15 /* All */; }
+ while (isOuterExpression(node, kinds)) {
+ node = node.expression;
+ }
+ return node;
+ }
+ ts.skipOuterExpressions = skipOuterExpressions;
+ function skipAssertions(node) {
+ return skipOuterExpressions(node, 6 /* Assertions */);
+ }
+ ts.skipAssertions = skipAssertions;
+ function startOnNewLine(node) {
+ return ts.setStartsOnNewLine(node, /*newLine*/ true);
+ }
+ ts.startOnNewLine = startOnNewLine;
+ function getExternalHelpersModuleName(node) {
+ var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
+ var emitNode = parseNode && parseNode.emitNode;
+ return emitNode && emitNode.externalHelpersModuleName;
+ }
+ ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
+ function hasRecordedExternalHelpers(sourceFile) {
+ var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
+ var emitNode = parseNode && parseNode.emitNode;
+ return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
+ }
+ ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
+ function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
+ if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
+ var namedBindings = void 0;
+ var moduleKind = ts.getEmitModuleKind(compilerOptions);
+ if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
+ // use named imports
+ var helpers = ts.getEmitHelpers(sourceFile);
+ if (helpers) {
+ var helperNames = [];
+ for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
+ var helper = helpers_3[_i];
+ if (!helper.scoped) {
+ var importName = helper.importName;
+ if (importName) {
+ ts.pushIfUnique(helperNames, importName);
+ }
+ }
+ }
+ if (ts.some(helperNames)) {
+ helperNames.sort(ts.compareStringsCaseSensitive);
+ // Alias the imports if the names are used somewhere in the file.
+ // NOTE: We don't need to care about global import collisions as this is a module.
+ namedBindings = nodeFactory.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
+ ? nodeFactory.createImportSpecifier(/*propertyName*/ undefined, nodeFactory.createIdentifier(name))
+ : nodeFactory.createImportSpecifier(nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name)); }));
+ var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
+ var emitNode = ts.getOrCreateEmitNode(parseNode);
+ emitNode.externalHelpers = true;
+ }
+ }
+ }
+ else {
+ // use a namespace import
+ var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
+ if (externalHelpersModuleName) {
+ namedBindings = nodeFactory.createNamespaceImport(externalHelpersModuleName);
+ }
+ }
+ if (namedBindings) {
+ var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText));
+ ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
+ return externalHelpersImportDeclaration;
+ }
+ }
+ }
+ ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
+ function getOrCreateExternalHelpersModuleNameIfNeeded(factory, node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
+ if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
+ var externalHelpersModuleName = getExternalHelpersModuleName(node);
+ if (externalHelpersModuleName) {
+ return externalHelpersModuleName;
+ }
+ var moduleKind = ts.getEmitModuleKind(compilerOptions);
+ var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
+ && moduleKind !== ts.ModuleKind.System
+ && moduleKind < ts.ModuleKind.ES2015;
+ if (!create) {
+ var helpers = ts.getEmitHelpers(node);
+ if (helpers) {
+ for (var _i = 0, helpers_4 = helpers; _i < helpers_4.length; _i++) {
+ var helper = helpers_4[_i];
+ if (!helper.scoped) {
+ create = true;
+ break;
+ }
+ }
+ }
+ }
+ if (create) {
+ var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
+ var emitNode = ts.getOrCreateEmitNode(parseNode);
+ return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory.createUniqueName(ts.externalHelpersModuleNameText));
+ }
+ }
+ }
+ ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
+ /**
+ * Get the name of that target module from an import or export declaration
+ */
+ function getLocalNameForExternalImport(factory, node, sourceFile) {
+ var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
+ if (namespaceDeclaration && !ts.isDefaultImport(node) && !ts.isExportNamespaceAsDefaultDeclaration(node)) {
+ var name = namespaceDeclaration.name;
+ return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
+ }
+ if (node.kind === 261 /* ImportDeclaration */ && node.importClause) {
+ return factory.getGeneratedNameForNode(node);
+ }
+ if (node.kind === 267 /* ExportDeclaration */ && node.moduleSpecifier) {
+ return factory.getGeneratedNameForNode(node);
+ }
+ return undefined;
+ }
+ ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
+ /**
+ * Get the name of a target module from an import/export declaration as should be written in the emitted output.
+ * The emitted output name can be different from the input if:
+ * 1. The module has a /// <amd-module name="<new name>" />
+ * 2. --out or --outFile is used, making the name relative to the rootDir
+ * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
+ * Otherwise, a new StringLiteral node representing the module name will be returned.
+ */
+ function getExternalModuleNameLiteral(factory, importNode, sourceFile, host, resolver, compilerOptions) {
+ var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
+ if (moduleName.kind === 10 /* StringLiteral */) {
+ return tryGetModuleNameFromDeclaration(importNode, host, factory, resolver, compilerOptions)
+ || tryRenameExternalModule(factory, moduleName, sourceFile)
+ || factory.cloneNode(moduleName);
+ }
+ return undefined;
+ }
+ ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
+ /**
+ * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
+ * Here we check if alternative name was provided for a given moduleName and return it if possible.
+ */
+ function tryRenameExternalModule(factory, moduleName, sourceFile) {
+ var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
+ return rename && factory.createStringLiteral(rename);
+ }
+ /**
+ * Get the name of a module as should be written in the emitted output.
+ * The emitted output name can be different from the input if:
+ * 1. The module has a /// <amd-module name="<new name>" />
+ * 2. --out or --outFile is used, making the name relative to the rootDir
+ * Otherwise, a new StringLiteral node representing the module name will be returned.
+ */
+ function tryGetModuleNameFromFile(factory, file, host, options) {
+ if (!file) {
+ return undefined;
+ }
+ if (file.moduleName) {
+ return factory.createStringLiteral(file.moduleName);
+ }
+ if (!file.isDeclarationFile && ts.outFile(options)) {
+ return factory.createStringLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
+ }
+ return undefined;
+ }
+ ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
+ function tryGetModuleNameFromDeclaration(declaration, host, factory, resolver, compilerOptions) {
+ return tryGetModuleNameFromFile(factory, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
+ }
+ /**
+ * Gets the initializer of an BindingOrAssignmentElement.
+ */
+ function getInitializerOfBindingOrAssignmentElement(bindingElement) {
+ if (ts.isDeclarationBindingElement(bindingElement)) {
+ // `1` in `let { a = 1 } = ...`
+ // `1` in `let { a: b = 1 } = ...`
+ // `1` in `let { a: {b} = 1 } = ...`
+ // `1` in `let { a: [b] = 1 } = ...`
+ // `1` in `let [a = 1] = ...`
+ // `1` in `let [{a} = 1] = ...`
+ // `1` in `let [[a] = 1] = ...`
+ return bindingElement.initializer;
+ }
+ if (ts.isPropertyAssignment(bindingElement)) {
+ // `1` in `({ a: b = 1 } = ...)`
+ // `1` in `({ a: {b} = 1 } = ...)`
+ // `1` in `({ a: [b] = 1 } = ...)`
+ var initializer = bindingElement.initializer;
+ return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
+ ? initializer.right
+ : undefined;
+ }
+ if (ts.isShorthandPropertyAssignment(bindingElement)) {
+ // `1` in `({ a = 1 } = ...)`
+ return bindingElement.objectAssignmentInitializer;
+ }
+ if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
+ // `1` in `[a = 1] = ...`
+ // `1` in `[{a} = 1] = ...`
+ // `1` in `[[a] = 1] = ...`
+ return bindingElement.right;
+ }
+ if (ts.isSpreadElement(bindingElement)) {
+ // Recovery consistent with existing emit.
+ return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
+ }
+ }
+ ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
+ /**
+ * Gets the name of an BindingOrAssignmentElement.
+ */
+ function getTargetOfBindingOrAssignmentElement(bindingElement) {
+ if (ts.isDeclarationBindingElement(bindingElement)) {
+ // `a` in `let { a } = ...`
+ // `a` in `let { a = 1 } = ...`
+ // `b` in `let { a: b } = ...`
+ // `b` in `let { a: b = 1 } = ...`
+ // `a` in `let { ...a } = ...`
+ // `{b}` in `let { a: {b} } = ...`
+ // `{b}` in `let { a: {b} = 1 } = ...`
+ // `[b]` in `let { a: [b] } = ...`
+ // `[b]` in `let { a: [b] = 1 } = ...`
+ // `a` in `let [a] = ...`
+ // `a` in `let [a = 1] = ...`
+ // `a` in `let [...a] = ...`
+ // `{a}` in `let [{a}] = ...`
+ // `{a}` in `let [{a} = 1] = ...`
+ // `[a]` in `let [[a]] = ...`
+ // `[a]` in `let [[a] = 1] = ...`
+ return bindingElement.name;
+ }
+ if (ts.isObjectLiteralElementLike(bindingElement)) {
+ switch (bindingElement.kind) {
+ case 288 /* PropertyAssignment */:
+ // `b` in `({ a: b } = ...)`
+ // `b` in `({ a: b = 1 } = ...)`
+ // `{b}` in `({ a: {b} } = ...)`
+ // `{b}` in `({ a: {b} = 1 } = ...)`
+ // `[b]` in `({ a: [b] } = ...)`
+ // `[b]` in `({ a: [b] = 1 } = ...)`
+ // `b.c` in `({ a: b.c } = ...)`
+ // `b.c` in `({ a: b.c = 1 } = ...)`
+ // `b[0]` in `({ a: b[0] } = ...)`
+ // `b[0]` in `({ a: b[0] = 1 } = ...)`
+ return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
+ case 289 /* ShorthandPropertyAssignment */:
+ // `a` in `({ a } = ...)`
+ // `a` in `({ a = 1 } = ...)`
+ return bindingElement.name;
+ case 290 /* SpreadAssignment */:
+ // `a` in `({ ...a } = ...)`
+ return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
+ }
+ // no target
+ return undefined;
+ }
+ if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
+ // `a` in `[a = 1] = ...`
+ // `{a}` in `[{a} = 1] = ...`
+ // `[a]` in `[[a] = 1] = ...`
+ // `a.b` in `[a.b = 1] = ...`
+ // `a[0]` in `[a[0] = 1] = ...`
+ return getTargetOfBindingOrAssignmentElement(bindingElement.left);
+ }
+ if (ts.isSpreadElement(bindingElement)) {
+ // `a` in `[...a] = ...`
+ return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
+ }
+ // `a` in `[a] = ...`
+ // `{a}` in `[{a}] = ...`
+ // `[a]` in `[[a]] = ...`
+ // `a.b` in `[a.b] = ...`
+ // `a[0]` in `[a[0]] = ...`
+ return bindingElement;
+ }
+ ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
+ /**
+ * Determines whether an BindingOrAssignmentElement is a rest element.
+ */
+ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
+ switch (bindingElement.kind) {
+ case 160 /* Parameter */:
+ case 198 /* BindingElement */:
+ // `...` in `let [...a] = ...`
+ return bindingElement.dotDotDotToken;
+ case 220 /* SpreadElement */:
+ case 290 /* SpreadAssignment */:
+ // `...` in `[...a] = ...`
+ return bindingElement;
+ }
+ return undefined;
+ }
+ ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
+ /**
+ * Gets the property name of a BindingOrAssignmentElement
+ */
+ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
+ var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
+ ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
+ return propertyName;
+ }
+ ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
+ function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
+ switch (bindingElement.kind) {
+ case 198 /* BindingElement */:
+ // `a` in `let { a: b } = ...`
+ // `[a]` in `let { [a]: b } = ...`
+ // `"a"` in `let { "a": b } = ...`
+ // `1` in `let { 1: b } = ...`
+ if (bindingElement.propertyName) {
+ var propertyName = bindingElement.propertyName;
+ if (ts.isPrivateIdentifier(propertyName)) {
+ return ts.Debug.failBadSyntaxKind(propertyName);
+ }
+ return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
+ ? propertyName.expression
+ : propertyName;
+ }
+ break;
+ case 288 /* PropertyAssignment */:
+ // `a` in `({ a: b } = ...)`
+ // `[a]` in `({ [a]: b } = ...)`
+ // `"a"` in `({ "a": b } = ...)`
+ // `1` in `({ 1: b } = ...)`
+ if (bindingElement.name) {
+ var propertyName = bindingElement.name;
+ if (ts.isPrivateIdentifier(propertyName)) {
+ return ts.Debug.failBadSyntaxKind(propertyName);
+ }
+ return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
+ ? propertyName.expression
+ : propertyName;
+ }
+ break;
+ case 290 /* SpreadAssignment */:
+ // `a` in `({ ...a } = ...)`
+ if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
+ return ts.Debug.failBadSyntaxKind(bindingElement.name);
+ }
+ return bindingElement.name;
+ }
+ var target = getTargetOfBindingOrAssignmentElement(bindingElement);
+ if (target && ts.isPropertyName(target)) {
+ return target;
+ }
+ }
+ ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
+ function isStringOrNumericLiteral(node) {
+ var kind = node.kind;
+ return kind === 10 /* StringLiteral */
+ || kind === 8 /* NumericLiteral */;
+ }
+ /**
+ * Gets the elements of a BindingOrAssignmentPattern
+ */
+ function getElementsOfBindingOrAssignmentPattern(name) {
+ switch (name.kind) {
+ case 196 /* ObjectBindingPattern */:
+ case 197 /* ArrayBindingPattern */:
+ case 199 /* ArrayLiteralExpression */:
+ // `a` in `{a}`
+ // `a` in `[a]`
+ return name.elements;
+ case 200 /* ObjectLiteralExpression */:
+ // `a` in `{a}`
+ return name.properties;
+ }
+ }
+ ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;