///
///
///
module ts {
var nodeConstructors = new Array Node>(SyntaxKind.Count);
export function getFullWidth(node: Node) {
return node.end - node.pos;
}
function hasFlag(val: number, flag: number): boolean {
return (val & flag) !== 0;
}
// Returns true if this node contains a parse error anywhere underneath it.
export function containsParseError(node: Node): boolean {
if (!hasFlag(node.parserContextFlags, ParserContextFlags.HasPropagatedChildContainsErrorFlag)) {
// A node is considered to contain a parse error if:
// a) the parser explicitly marked that it had an error
// b) any of it's children reported that it had an error.
var val = hasFlag(node.parserContextFlags, ParserContextFlags.ContainsError) ||
forEachChild(node, containsParseError);
// If so, mark ourselves accordingly.
if (val) {
node.parserContextFlags |= ParserContextFlags.ContainsError;
}
// Also mark that we've propogated the child information to this node. This way we can
// always consult the bit directly on this node without needing to check its children
// again.
node.parserContextFlags |= ParserContextFlags.HasPropagatedChildContainsErrorFlag;
}
return hasFlag(node.parserContextFlags, ParserContextFlags.ContainsError);
}
export function getNodeConstructor(kind: SyntaxKind): new () => Node {
return nodeConstructors[kind] || (nodeConstructors[kind] = objectAllocator.getNodeConstructor(kind));
}
function createRootNode(kind: SyntaxKind, pos: number, end: number, flags: NodeFlags): Node {
var node = new (getNodeConstructor(kind))();
node.pos = pos;
node.end = end;
node.flags = flags;
return node;
}
interface ReferenceComments {
referencedFiles: FileReference[];
amdDependencies: string[];
amdModuleName: string;
}
export function getSourceFileOfNode(node: Node): SourceFile {
while (node && node.kind !== SyntaxKind.SourceFile) node = node.parent;
return node;
}
// This is a useful function for debugging purposes.
export function nodePosToString(node: Node): string {
var file = getSourceFileOfNode(node);
var loc = file.getLineAndCharacterFromPosition(node.pos);
return file.filename + "(" + loc.line + "," + loc.character + ")";
}
export function getStartPosOfNode(node: Node): number {
return node.pos;
}
export function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number {
// With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
// want to skip trivia because this will launch us forward to the next token.
if (node.pos === node.end) {
return node.pos;
}
return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
}
export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string {
var text = sourceFile.text;
return text.substring(skipTrivia(text, node.pos), node.end);
}
export function getTextOfNodeFromSourceText(sourceText: string, node: Node): string {
return sourceText.substring(skipTrivia(sourceText, node.pos), node.end);
}
export function getTextOfNode(node: Node): string {
return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node);
}
// Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__'
export function escapeIdentifier(identifier: string): string {
return identifier.length >= 2 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ ? "_" + identifier : identifier;
}
// Remove extra underscore from escaped identifier
export function unescapeIdentifier(identifier: string): string {
return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier;
}
// Return display name of an identifier
// Computed property names will just be emitted as "[]", where is the source
// text of the expression in the computed property.
export function declarationNameToString(name: DeclarationName) {
return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
}
export function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic {
node = getErrorSpanForNode(node);
var file = getSourceFileOfNode(node);
var start = getFullWidth(node) === 0 ? node.pos : skipTrivia(file.text, node.pos);
var length = node.end - start;
return createFileDiagnostic(file, start, length, message, arg0, arg1, arg2);
}
export function createDiagnosticForNodeFromMessageChain(node: Node, messageChain: DiagnosticMessageChain, newLine: string): Diagnostic {
node = getErrorSpanForNode(node);
var file = getSourceFileOfNode(node);
var start = skipTrivia(file.text, node.pos);
var length = node.end - start;
return flattenDiagnosticChain(file, start, length, messageChain, newLine);
}
export function getErrorSpanForNode(node: Node): Node {
var errorSpan: Node;
switch (node.kind) {
// This list is a work in progress. Add missing node kinds to improve their error
// spans.
case SyntaxKind.VariableDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMember:
errorSpan = (node).name;
break;
}
// We now have the ideal error span, but it may be a node that is optional and absent
// (e.g. the name of a function expression), in which case errorSpan will be undefined.
// Alternatively, it might be required and missing (e.g. the name of a module), in which
// case its pos will equal its end (length 0). In either of these cases, we should fall
// back to the original node that the error was issued on.
return errorSpan && errorSpan.pos < errorSpan.end ? errorSpan : node;
}
export function isExternalModule(file: SourceFile): boolean {
return file.externalModuleIndicator !== undefined;
}
export function isDeclarationFile(file: SourceFile): boolean {
return (file.flags & NodeFlags.DeclarationFile) !== 0;
}
export function isConstEnumDeclaration(node: Node): boolean {
return node.kind === SyntaxKind.EnumDeclaration && isConst(node);
}
export function isConst(node: Node): boolean {
return !!(node.flags & NodeFlags.Const);
}
export function isLet(node: Node): boolean {
return !!(node.flags & NodeFlags.Let);
}
export function isPrologueDirective(node: Node): boolean {
return node.kind === SyntaxKind.ExpressionStatement && (node).expression.kind === SyntaxKind.StringLiteral;
}
function isEvalOrArgumentsIdentifier(node: Node): boolean {
return node.kind === SyntaxKind.Identifier &&
(node).text &&
((node).text === "eval" || (node).text === "arguments");
}
/// Should be called only on prologue directives (isPrologueDirective(node) should be true)
function isUseStrictPrologueDirective(node: Node): boolean {
Debug.assert(isPrologueDirective(node));
return ((node).expression).text === "use strict";
}
export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode?: SourceFile) {
sourceFileOfNode = sourceFileOfNode || getSourceFileOfNode(node);
// If parameter/type parameter, the prev token trailing comments are part of this node too
if (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) {
// e.g. (/** blah */ a, /** blah */ b);
return concatenate(getTrailingCommentRanges(sourceFileOfNode.text, node.pos),
// e.g.: (
// /** blah */ a,
// /** blah */ b);
getLeadingCommentRanges(sourceFileOfNode.text, node.pos));
}
else {
return getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}
}
export function getJsDocComments(node: Node, sourceFileOfNode: SourceFile) {
return filter(getLeadingCommentRangesOfNode(node, sourceFileOfNode), isJsDocComment);
function isJsDocComment(comment: CommentRange) {
// True if the comment starts with '/**' but not if it is '/**/'
return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk &&
sourceFileOfNode.text.charCodeAt(comment.pos + 2) === CharacterCodes.asterisk &&
sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== CharacterCodes.slash;
}
}
export var fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/
// Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
// stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
// embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
// a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
export function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodes?: (nodes: Node[]) => T): T {
function child(node: Node): T {
if (node) return cbNode(node);
}
function children(nodes: Node[]) {
if (nodes) {
if (cbNodes) return cbNodes(nodes);
var result: T;
for (var i = 0, len = nodes.length; i < len; i++) {
if (result = cbNode(nodes[i])) break;
}
return result;
}
}
if (!node) return;
switch (node.kind) {
case SyntaxKind.QualifiedName:
return child((node).left) ||
child((node).right);
case SyntaxKind.TypeParameter:
return child((node).name) ||
child((node).constraint);
case SyntaxKind.Parameter:
return children(node.modifiers) ||
child((node).dotDotDotToken) ||
child((node).name) ||
child((node).questionToken) ||
child((node).type) ||
child((node).initializer);
case SyntaxKind.Property:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
return children(node.modifiers) ||
child((node).name) ||
child((node).questionToken) ||
child((node).type) ||
child((node).initializer);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
return children(node.modifiers) ||
children((node).typeParameters) ||
children((node).parameters) ||
child((node).type);
case SyntaxKind.Method:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
return children(node.modifiers) ||
child((node).name) ||
child((node).questionToken) ||
children((node).typeParameters) ||
children((node).parameters) ||
child((node).type) ||
child((node).body);
case SyntaxKind.TypeReference:
return child((node).typeName) ||
children((node).typeArguments);
case SyntaxKind.TypeQuery:
return child((node).exprName);
case SyntaxKind.TypeLiteral:
return children((node).members);
case SyntaxKind.ArrayType:
return child((node).elementType);
case SyntaxKind.TupleType:
return children((node).elementTypes);
case SyntaxKind.UnionType:
return children((node).types);
case SyntaxKind.ParenthesizedType:
return child((node).type);
case SyntaxKind.ArrayLiteralExpression:
return children((node).elements);
case SyntaxKind.ObjectLiteralExpression:
return children((node).properties);
case SyntaxKind.PropertyAccessExpression:
return child((node).expression) ||
child((node).name);
case SyntaxKind.ElementAccessExpression:
return child((node).expression) ||
child((node).argumentExpression);
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
return child((node).expression) ||
children((node).typeArguments) ||
children((node).arguments);
case SyntaxKind.TaggedTemplateExpression:
return child((node).tag) ||
child((node).template);
case SyntaxKind.TypeAssertionExpression:
return child((node).type) ||
child((node).expression);
case SyntaxKind.ParenthesizedExpression:
return child((node).expression);
case SyntaxKind.DeleteExpression:
return child((node).expression);
case SyntaxKind.TypeOfExpression:
return child((node).expression);
case SyntaxKind.VoidExpression:
return child((node).expression);
case SyntaxKind.PrefixUnaryExpression:
return child((node).operand);
case SyntaxKind.PostfixUnaryExpression:
return child((node).operand);
case SyntaxKind.BinaryExpression:
return child((node).left) ||
child((node).right);
case SyntaxKind.ConditionalExpression:
return child((node).condition) ||
child((node).whenTrue) ||
child((node).whenFalse);
case SyntaxKind.Block:
case SyntaxKind.TryBlock:
case SyntaxKind.FinallyBlock:
case SyntaxKind.ModuleBlock:
return children((node).statements);
case SyntaxKind.SourceFile:
return children((node).statements) ||
child((node).endOfFileToken);
case SyntaxKind.VariableStatement:
return children(node.modifiers) ||
children((node).declarations);
case SyntaxKind.ExpressionStatement:
return child((node).expression);
case SyntaxKind.IfStatement:
return child((node).expression) ||
child((node).thenStatement) ||
child((node).elseStatement);
case SyntaxKind.DoStatement:
return child((node).statement) ||
child((node).expression);
case SyntaxKind.WhileStatement:
return child((node).expression) ||
child((node).statement);
case SyntaxKind.ForStatement:
return children((node).declarations) ||
child((node).initializer) ||
child((node).condition) ||
child((node).iterator) ||
child((node).statement);
case SyntaxKind.ForInStatement:
return children((node).declarations) ||
child((node).variable) ||
child((node).expression) ||
child((node).statement);
case SyntaxKind.ContinueStatement:
case SyntaxKind.BreakStatement:
return child((node).label);
case SyntaxKind.ReturnStatement:
return child((node).expression);
case SyntaxKind.WithStatement:
return child((node).expression) ||
child((node).statement);
case SyntaxKind.SwitchStatement:
return child((node).expression) ||
children((node).clauses);
case SyntaxKind.CaseClause:
return child((node).expression) ||
children((node).statements);
case SyntaxKind.DefaultClause:
return children((node).statements);
case SyntaxKind.LabeledStatement:
return child((node).label) ||
child((node).statement);
case SyntaxKind.ThrowStatement:
return child((node).expression);
case SyntaxKind.TryStatement:
return child((node).tryBlock) ||
child((node).catchClause) ||
child((node).finallyBlock);
case SyntaxKind.CatchClause:
return child((node).name) ||
child((node).type) ||
child((node).block);
case SyntaxKind.VariableDeclaration:
return children(node.modifiers) ||
child((node).name) ||
child((node).type) ||
child((node).initializer);
case SyntaxKind.ClassDeclaration:
return children(node.modifiers) ||
child((node).name) ||
children((node).typeParameters) ||
children((node).heritageClauses) ||
children((node).members);
case SyntaxKind.InterfaceDeclaration:
return children(node.modifiers) ||
child((node).name) ||
children((node).typeParameters) ||
children((node).heritageClauses) ||
children((node).members);
case SyntaxKind.TypeAliasDeclaration:
return children(node.modifiers) ||
child((node).name) ||
child((node).type);
case SyntaxKind.EnumDeclaration:
return children(node.modifiers) ||
child((node).name) ||
children((node).members);
case SyntaxKind.EnumMember:
return child((node).name) ||
child((node).initializer);
case SyntaxKind.ModuleDeclaration:
return children(node.modifiers) ||
child((node).name) ||
child((node).body);
case SyntaxKind.ImportDeclaration:
return children(node.modifiers) ||
child((node).name) ||
child((node).moduleReference);
case SyntaxKind.ExportAssignment:
return children(node.modifiers) ||
child((node).exportName);
case SyntaxKind.TemplateExpression:
return child((node).head) || children((node).templateSpans);
case SyntaxKind.TemplateSpan:
return child((node).expression) || child((node).literal);
case SyntaxKind.ComputedPropertyName:
return child((node).expression);
case SyntaxKind.HeritageClause:
return children((node).types);
case SyntaxKind.ExternalModuleReference:
return child((node).expression);
}
}
// Warning: This has the same semantics as the forEach family of functions,
// in that traversal terminates in the event that 'visitor' supplies a truthy value.
export function forEachReturnStatement(body: Block, visitor: (stmt: ReturnStatement) => T): T {
return traverse(body);
function traverse(node: Node): T {
switch (node.kind) {
case SyntaxKind.ReturnStatement:
return visitor(node);
case SyntaxKind.Block:
case SyntaxKind.IfStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.WithStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
case SyntaxKind.LabeledStatement:
case SyntaxKind.TryStatement:
case SyntaxKind.TryBlock:
case SyntaxKind.CatchClause:
case SyntaxKind.FinallyBlock:
return forEachChild(node, traverse);
}
}
}
export function isAnyFunction(node: Node): boolean {
if (node) {
switch (node.kind) {
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
case SyntaxKind.Method:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.Constructor:
return true;
}
}
return false;
}
export function isFunctionBlock(node: Node) {
return node !== undefined && node.kind === SyntaxKind.Block && isAnyFunction(node.parent);
}
export function isObjectLiteralMethod(node: Node) {
return node !== undefined && node.kind === SyntaxKind.Method && node.parent.kind === SyntaxKind.ObjectLiteralExpression;
}
export function getContainingFunction(node: Node): FunctionLikeDeclaration {
while (true) {
node = node.parent;
if (!node || isAnyFunction(node)) {
return node;
}
}
}
export function getThisContainer(node: Node, includeArrowFunctions: boolean): Node {
while (true) {
node = node.parent;
if (!node) {
return undefined;
}
switch (node.kind) {
case SyntaxKind.ArrowFunction:
if (!includeArrowFunctions) {
continue;
}
// Fall through
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.Property:
case SyntaxKind.Method:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.SourceFile:
return node;
}
}
}
export function getSuperContainer(node: Node): Node {
while (true) {
node = node.parent;
if (!node) {
return undefined;
}
switch (node.kind) {
case SyntaxKind.Property:
case SyntaxKind.Method:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return node;
}
}
}
export function getInvokedExpression(node: CallLikeExpression): Expression {
if (node.kind === SyntaxKind.TaggedTemplateExpression) {
return (node).tag;
}
// Will either be a CallExpression or NewExpression.
return (node).expression;
}
export function isExpression(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.ThisKeyword:
case SyntaxKind.SuperKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.RegularExpressionLiteral:
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.VoidExpression:
case SyntaxKind.DeleteExpression:
case SyntaxKind.TypeOfExpression:
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
case SyntaxKind.BinaryExpression:
case SyntaxKind.ConditionalExpression:
case SyntaxKind.TemplateExpression:
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.OmittedExpression:
return true;
case SyntaxKind.QualifiedName:
while (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
}
return node.parent.kind === SyntaxKind.TypeQuery;
case SyntaxKind.Identifier:
if (node.parent.kind === SyntaxKind.TypeQuery) {
return true;
}
// fall through
case SyntaxKind.NumericLiteral:
case SyntaxKind.StringLiteral:
var parent = node.parent;
switch (parent.kind) {
case SyntaxKind.VariableDeclaration:
case SyntaxKind.Parameter:
case SyntaxKind.Property:
case SyntaxKind.EnumMember:
case SyntaxKind.PropertyAssignment:
return (parent).initializer === node;
case SyntaxKind.ExpressionStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.WithStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.CaseClause:
case SyntaxKind.ThrowStatement:
case SyntaxKind.SwitchStatement:
return (parent).expression === node;
case SyntaxKind.ForStatement:
return (parent).initializer === node ||
(parent).condition === node ||
(parent).iterator === node;
case SyntaxKind.ForInStatement:
return (parent).variable === node ||
(parent).expression === node;
case SyntaxKind.TypeAssertionExpression:
return node === (parent).expression;
case SyntaxKind.TemplateSpan:
return node === (parent).expression;
default:
if (isExpression(parent)) {
return true;
}
}
}
return false;
}
export function isExternalModuleImportDeclaration(node: Node) {
return node.kind === SyntaxKind.ImportDeclaration && (node).moduleReference.kind === SyntaxKind.ExternalModuleReference;
}
export function getExternalModuleImportDeclarationExpression(node: Node) {
Debug.assert(isExternalModuleImportDeclaration(node));
return ((node).moduleReference).expression;
}
export function isInternalModuleImportDeclaration(node: Node) {
return node.kind === SyntaxKind.ImportDeclaration && (node).moduleReference.kind !== SyntaxKind.ExternalModuleReference;
}
export function hasDotDotDotToken(node: Node) {
return node && node.kind === SyntaxKind.Parameter && (node).dotDotDotToken !== undefined;
}
export function hasQuestionToken(node: Node) {
if (node) {
switch (node.kind) {
case SyntaxKind.Parameter:
return (node).questionToken !== undefined;
case SyntaxKind.Method:
return (node).questionToken !== undefined;
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.Property:
return (node).questionToken !== undefined;
}
}
return false;
}
export function hasRestParameters(s: SignatureDeclaration): boolean {
return s.parameters.length > 0 && s.parameters[s.parameters.length - 1].dotDotDotToken !== undefined;
}
export function isLiteralKind(kind: SyntaxKind): boolean {
return SyntaxKind.FirstLiteralToken <= kind && kind <= SyntaxKind.LastLiteralToken;
}
export function isTextualLiteralKind(kind: SyntaxKind): boolean {
return kind === SyntaxKind.StringLiteral || kind === SyntaxKind.NoSubstitutionTemplateLiteral;
}
export function isTemplateLiteralKind(kind: SyntaxKind): boolean {
return SyntaxKind.FirstTemplateToken <= kind && kind <= SyntaxKind.LastTemplateToken;
}
export function isInAmbientContext(node: Node): boolean {
while (node) {
if (node.flags & (NodeFlags.Ambient | NodeFlags.DeclarationFile)) return true;
node = node.parent;
}
return false;
}
export function isDeclaration(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.TypeParameter:
case SyntaxKind.Parameter:
case SyntaxKind.VariableDeclaration:
case SyntaxKind.Property:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.EnumMember:
case SyntaxKind.Method:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.Constructor:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ImportDeclaration:
return true;
}
return false;
}
export function isStatement(n: Node): boolean {
switch(n.kind) {
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
case SyntaxKind.DebuggerStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.ExpressionStatement:
case SyntaxKind.EmptyStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.LabeledStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.ThrowKeyword:
case SyntaxKind.TryStatement:
case SyntaxKind.VariableStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.WithStatement:
case SyntaxKind.ExportAssignment:
return true;
default:
return false;
}
}
// True if the given identifier, string literal, or number literal is the name of a declaration node
export function isDeclarationOrFunctionExpressionOrCatchVariableName(name: Node): boolean {
if (name.kind !== SyntaxKind.Identifier && name.kind !== SyntaxKind.StringLiteral && name.kind !== SyntaxKind.NumericLiteral) {
return false;
}
var parent = name.parent;
if (isDeclaration(parent) || parent.kind === SyntaxKind.FunctionExpression) {
return (parent).name === name;
}
if (parent.kind === SyntaxKind.CatchClause) {
return (parent).name === name;
}
return false;
}
export function getClassBaseTypeNode(node: ClassDeclaration) {
var heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword);
return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
}
export function getClassImplementedTypeNodes(node: ClassDeclaration) {
var heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ImplementsKeyword);
return heritageClause ? heritageClause.types : undefined;
}
export function getInterfaceBaseTypeNodes(node: InterfaceDeclaration) {
var heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword);
return heritageClause ? heritageClause.types : undefined;
}
export function getHeritageClause(clauses: NodeArray, kind: SyntaxKind) {
if (clauses) {
for (var i = 0, n = clauses.length; i < n; i++) {
if (clauses[i].token === kind) {
return clauses[i];
}
}
}
return undefined;
}
export function tryResolveScriptReference(program: Program, sourceFile: SourceFile, reference: FileReference) {
if (!program.getCompilerOptions().noResolve) {
var referenceFileName = isRootedDiskPath(reference.filename) ? reference.filename : combinePaths(getDirectoryPath(sourceFile.filename), reference.filename);
referenceFileName = getNormalizedAbsolutePath(referenceFileName, program.getCompilerHost().getCurrentDirectory());
return program.getSourceFile(referenceFileName);
}
}
export function getAncestor(node: Node, kind: SyntaxKind): Node {
switch (kind) {
// special-cases that can be come first
case SyntaxKind.ClassDeclaration:
while (node) {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
return node;
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ImportDeclaration:
// early exit cases - declarations cannot be nested in classes
return undefined;
default:
node = node.parent;
continue;
}
}
break;
default:
while (node) {
if (node.kind === kind) {
return node;
}
node = node.parent;
}
break;
}
return undefined;
}
const enum ParsingContext {
SourceElements, // Elements in source file
ModuleElements, // Elements in module declaration
BlockStatements, // Statements in block
SwitchClauses, // Clauses in switch statement
SwitchClauseStatements, // Statements in switch clause
TypeMembers, // Members in interface or type literal
ClassMembers, // Members in class declaration
EnumMembers, // Members in enum declaration
TypeReferences, // Type references in extends or implements clause
VariableDeclarations, // Variable declarations in variable statement
ArgumentExpressions, // Expressions in argument list
ObjectLiteralMembers, // Members in object literal
ArrayLiteralMembers, // Members in array literal
Parameters, // Parameters in parameter list
TypeParameters, // Type parameters in type parameter list
TypeArguments, // Type arguments in type argument list
TupleElementTypes, // Element types in tuple element type list
HeritageClauses, // Heritage clauses for a class or interface declaration.
Count // Number of parsing contexts
}
const enum Tristate {
False,
True,
Unknown
}
function parsingContextErrors(context: ParsingContext): DiagnosticMessage {
switch (context) {
case ParsingContext.SourceElements: return Diagnostics.Declaration_or_statement_expected;
case ParsingContext.ModuleElements: return Diagnostics.Declaration_or_statement_expected;
case ParsingContext.BlockStatements: return Diagnostics.Statement_expected;
case ParsingContext.SwitchClauses: return Diagnostics.case_or_default_expected;
case ParsingContext.SwitchClauseStatements: return Diagnostics.Statement_expected;
case ParsingContext.TypeMembers: return Diagnostics.Property_or_signature_expected;
case ParsingContext.ClassMembers: return Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
case ParsingContext.EnumMembers: return Diagnostics.Enum_member_expected;
case ParsingContext.TypeReferences: return Diagnostics.Type_reference_expected;
case ParsingContext.VariableDeclarations: return Diagnostics.Variable_declaration_expected;
case ParsingContext.ArgumentExpressions: return Diagnostics.Argument_expression_expected;
case ParsingContext.ObjectLiteralMembers: return Diagnostics.Property_assignment_expected;
case ParsingContext.ArrayLiteralMembers: return Diagnostics.Expression_or_comma_expected;
case ParsingContext.Parameters: return Diagnostics.Parameter_declaration_expected;
case ParsingContext.TypeParameters: return Diagnostics.Type_parameter_declaration_expected;
case ParsingContext.TypeArguments: return Diagnostics.Type_argument_expected;
case ParsingContext.TupleElementTypes: return Diagnostics.Type_expected;
case ParsingContext.HeritageClauses: return Diagnostics.Unexpected_token_expected;
}
};
export interface ReferencePathMatchResult {
fileReference?: FileReference
diagnosticMessage?: DiagnosticMessage
isNoDefaultLib?: boolean
}
export function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult {
var simpleReferenceRegEx = /^\/\/\/\s*/gim;
if (simpleReferenceRegEx.exec(comment)) {
if (isNoDefaultLibRegEx.exec(comment)) {
return {
isNoDefaultLib: true
}
}
else {
var matchResult = fullTripleSlashReferencePathRegEx.exec(comment);
if (matchResult) {
var start = commentRange.pos;
var end = commentRange.end;
return {
fileReference: {
pos: start,
end: end,
filename: matchResult[3]
},
isNoDefaultLib: false
};
}
else {
return {
diagnosticMessage: Diagnostics.Invalid_reference_directive_syntax,
isNoDefaultLib: false
};
}
}
}
return undefined;
}
export function isKeyword(token: SyntaxKind): boolean {
return SyntaxKind.FirstKeyword <= token && token <= SyntaxKind.LastKeyword;
}
export function isTrivia(token: SyntaxKind) {
return SyntaxKind.FirstTriviaToken <= token && token <= SyntaxKind.LastTriviaToken;
}
export function isModifier(token: SyntaxKind): boolean {
switch (token) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.StaticKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.ConstKeyword:
return true;
}
return false;
}
function modifierToFlag(token: SyntaxKind): NodeFlags {
switch (token) {
case SyntaxKind.StaticKeyword: return NodeFlags.Static;
case SyntaxKind.PublicKeyword: return NodeFlags.Public;
case SyntaxKind.ProtectedKeyword: return NodeFlags.Protected;
case SyntaxKind.PrivateKeyword: return NodeFlags.Private;
case SyntaxKind.ExportKeyword: return NodeFlags.Export;
case SyntaxKind.DeclareKeyword: return NodeFlags.Ambient;
case SyntaxKind.ConstKeyword: return NodeFlags.Const;
}
return 0;
}
export function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget, version: string, isOpen: boolean = false): SourceFile {
var token: SyntaxKind;
var parsingContext: ParsingContext;
var identifiers: Map = {};
var identifierCount = 0;
var nodeCount = 0;
var lineStarts: number[];
// Flags that dictate what parsing context we're in. For example:
// Whether or not we are in strict parsing mode. All that changes in strict parsing mode is
// that some tokens that would be considered identifiers may be considered keywords. When
// rewinding, we need to store and restore this as the mode may have changed.
//
// When adding more parser context flags, consider which is the more common case that the
// flag will be in. This should be hte 'false' state for that flag. The reason for this is
// that we don't store data in our nodes unless the value is in the *non-default* state. So,
// for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for
// 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost
// all nodes would need extra state on them to store this info.
//
// Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
// grammar specification.
//
// An important thing about these context concepts. By default they are effectively inherited
// while parsing through every grammar production. i.e. if you don't change them, then when
// you parse a sub-production, it will have the same context values as hte parent production.
// This is great most of the time. After all, consider all the 'expression' grammar productions
// and how nearly all of them pass along the 'in' and 'yield' context values:
//
// EqualityExpression[In, Yield] :
// RelationalExpression[?In, ?Yield]
// EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
// EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
// EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
// EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
//
// Where you have to be careful is then understanding what the points are in the grammar
// where the values are *not* passed along. For example:
//
// SingleNameBinding[Yield,GeneratorParameter]
// [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
// [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
//
// Here this is saying that if the GeneratorParameter context flag is set, that we should
// explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
// and we should explicitly unset the 'yield' context flag before calling into the Initializer.
// production. Conversely, if the GeneratorParameter context flag is not set, then we
// should leave the 'yield' context flag alone.
//
// Getting this all correct is tricky and requires careful reading of the grammar to
// understand when these values should be changed versus when they should be inherited.
//
// Note: it should not be necessary to save/restore these flags during speculative/lookahead
// parsing. These context flags are naturally stored and restored through normal recursive
// descent parsing and unwinding.
var contextFlags: ParserContextFlags = 0;
// Whether or not we've had a parse error since creating the last AST node. If we have
// encountered an error, it will be stored on the next AST node we create. Parse errors
// can be broken down into three categories:
//
// 1) An error that occurred during scanning. For example, an unterminated literal, or a
// character that was completely not understood.
//
// 2) A token was expected, but was not present. This type of error is commonly produced
// by the 'parseExpected' function.
//
// 3) A token was present that no parsing function was able to consume. This type of error
// only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
// decides to skip the token.
//
// In all of these cases, we want to mark the next node as having had an error before it.
// With this mark, we can know in incremental settings if this node can be reused, or if
// we have to reparse it. If we don't keep this information around, we may just reuse the
// node. in that event we would then not produce the same errors as we did before, causing
// significant confusion problems.
//
// Note: it is necessary that this value be saved/restored during speculative/lookahead
// parsing. During lookahead parsing, we will often create a node. That node will have
// this value attached, and then this value will be set back to 'false'. If we decide to
// rewind, we must get back to the same value we had prior to the lookahead.
//
// Note: any errors at the end of the file that do not precede a regular node, should get
// attached to the EOF token.
var parseErrorBeforeNextFinishedNode = false;
function setContextFlag(val: Boolean, flag: ParserContextFlags) {
if (val) {
contextFlags |= flag;
}
else {
contextFlags &= ~flag;
}
}
function setStrictModeContext(val: boolean) {
setContextFlag(val, ParserContextFlags.StrictMode);
}
function setDisallowInContext(val: boolean) {
setContextFlag(val, ParserContextFlags.DisallowIn);
}
function setYieldContext(val: boolean) {
setContextFlag(val, ParserContextFlags.Yield);
}
function setGeneratorParameterContext(val: boolean) {
setContextFlag(val, ParserContextFlags.GeneratorParameter);
}
function allowInAnd(func: () => T): T {
if (contextFlags & ParserContextFlags.DisallowIn) {
setDisallowInContext(false);
var result = func();
setDisallowInContext(true);
return result;
}
// no need to do anything special if 'in' is already allowed.
return func();
}
function disallowInAnd(func: () => T): T {
if (contextFlags & ParserContextFlags.DisallowIn) {
// no need to do anything special if 'in' is already disallowed.
return func();
}
setDisallowInContext(true);
var result = func();
setDisallowInContext(false);
return result;
}
function doInYieldContext(func: () => T): T {
if (contextFlags & ParserContextFlags.Yield) {
// no need to do anything special if we're already in the [Yield] context.
return func();
}
setYieldContext(true);
var result = func();
setYieldContext(false);
return result;
}
function doOutsideOfYieldContext(func: () => T): T {
if (contextFlags & ParserContextFlags.Yield) {
setYieldContext(false);
var result = func();
setYieldContext(true);
return result;
}
// no need to do anything special if we're not in the [Yield] context.
return func();
}
function inYieldContext() {
return (contextFlags & ParserContextFlags.Yield) !== 0;
}
function inStrictModeContext() {
return (contextFlags & ParserContextFlags.StrictMode) !== 0;
}
function inGeneratorParameterContext() {
return (contextFlags & ParserContextFlags.GeneratorParameter) !== 0;
}
function inDisallowInContext() {
return (contextFlags & ParserContextFlags.DisallowIn) !== 0;
}
function getLineStarts(): number[] {
return lineStarts || (lineStarts = computeLineStarts(sourceText));
}
function getLineAndCharacterFromSourcePosition(position: number) {
return getLineAndCharacterOfPosition(getLineStarts(), position);
}
function getPositionFromSourceLineAndCharacter(line: number, character: number): number {
return getPositionFromLineAndCharacter(getLineStarts(), line, character);
}
function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: any): void {
var start = scanner.getTokenPos();
var length = scanner.getTextPos() - start;
parseErrorAtPosition(start, length, message, arg0);
}
function parseErrorAtPosition(start: number, length: number, message: DiagnosticMessage, arg0?: any): void {
// Don't report another error if it would just be at the same position as the last error.
var lastError = lastOrUndefined(sourceFile.parseDiagnostics);
if (!lastError || start !== lastError.start) {
sourceFile.parseDiagnostics.push(createFileDiagnostic(sourceFile, start, length, message, arg0));
}
// Mark that we've encountered an error. We'll set an appropriate bit on the next
// node we finish so that it can't be reused incrementally.
parseErrorBeforeNextFinishedNode = true;
}
function scanError(message: DiagnosticMessage) {
var pos = scanner.getTextPos();
parseErrorAtPosition(pos, 0, message);
}
function getNodePos(): number {
return scanner.getStartPos();
}
function getNodeEnd(): number {
return scanner.getStartPos();
}
function nextToken(): SyntaxKind {
return token = scanner.scan();
}
function getTokenPos(pos: number): number {
return skipTrivia(sourceText, pos);
}
function reScanGreaterToken(): SyntaxKind {
return token = scanner.reScanGreaterToken();
}
function reScanSlashToken(): SyntaxKind {
return token = scanner.reScanSlashToken();
}
function reScanTemplateToken(): SyntaxKind {
return token = scanner.reScanTemplateToken();
}
function speculationHelper(callback: () => T, isLookAhead: boolean): T {
// Keep track of the state we'll need to rollback to if lookahead fails (or if the
// caller asked us to always reset our state).
var saveToken = token;
var saveParseDiagnosticsLength = sourceFile.parseDiagnostics.length;
var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
// Note: it is not actually necessary to save/restore the context flags here. That's
// because the saving/restorating of these flags happens naturally through the recursive
// descent nature of our parser. However, we still store this here just so we can
// assert that that invariant holds.
var saveContextFlags = contextFlags;
// If we're only looking ahead, then tell the scanner to only lookahead as well.
// Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
// same.
var result = isLookAhead
? scanner.lookAhead(callback)
: scanner.tryScan(callback);
Debug.assert(saveContextFlags === contextFlags);
// If our callback returned something 'falsy' or we're just looking ahead,
// then unconditionally restore us to where we were.
if (!result || isLookAhead) {
token = saveToken;
sourceFile.parseDiagnostics.length = saveParseDiagnosticsLength;
parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
}
return result;
}
// Invokes the provided callback then unconditionally restores the parser to the state it
// was in immediately prior to invoking the callback. The result of invoking the callback
// is returned from this function.
function lookAhead(callback: () => T): T {
return speculationHelper(callback, /*isLookAhead:*/ true);
}
// Invokes the provided callback. If the callback returns something falsy, then it restores
// the parser to the state it was in immediately prior to invoking the callback. If the
// callback returns something truthy, then the parser state is not rolled back. The result
// of invoking the callback is returned from this function.
function tryParse(callback: () => T): T {
return speculationHelper(callback, /*isLookAhead:*/ false);
}
function isIdentifier(): boolean {
if (token === SyntaxKind.Identifier) {
return true;
}
// If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
// considered a keyword and is not an identifier.
if (token === SyntaxKind.YieldKeyword && inYieldContext()) {
return false;
}
return inStrictModeContext() ? token > SyntaxKind.LastFutureReservedWord : token > SyntaxKind.LastReservedWord;
}
function parseExpected(kind: SyntaxKind, diagnosticMessage?: DiagnosticMessage, arg0?: any): boolean {
if (token === kind) {
nextToken();
return true;
}
// Report specific message if provided with one. Otherwise, report generic fallback message.
if (diagnosticMessage) {
parseErrorAtCurrentToken(diagnosticMessage, arg0);
}
else {
parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(kind));
}
return false;
}
function parseOptional(t: SyntaxKind): boolean {
if (token === t) {
nextToken();
return true;
}
return false;
}
function parseOptionalToken(t: SyntaxKind): Node {
if (token === t) {
var node = createNode(t);
nextToken();
return finishNode(node);
}
return undefined;
}
function canParseSemicolon() {
// If there's a real semicolon, then we can always parse it out.
if (token === SyntaxKind.SemicolonToken) {
return true;
}
// We can parse out an optional semicolon in ASI cases in the following cases.
return token === SyntaxKind.CloseBraceToken || token === SyntaxKind.EndOfFileToken || scanner.hasPrecedingLineBreak();
}
function parseSemicolon(diagnosticMessage?: DiagnosticMessage): void {
if (canParseSemicolon()) {
if (token === SyntaxKind.SemicolonToken) {
// consume the semicolon if it was explicitly provided.
nextToken();
}
}
else {
parseExpected(SyntaxKind.SemicolonToken, diagnosticMessage);
}
}
function createNode(kind: SyntaxKind, pos?: number): Node {
nodeCount++;
var node = new (nodeConstructors[kind] || (nodeConstructors[kind] = objectAllocator.getNodeConstructor(kind)))();
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
node.pos = pos;
node.end = pos;
return node;
}
function finishNode(node: T): T {
node.end = scanner.getStartPos();
if (contextFlags) {
node.parserContextFlags = contextFlags;
}
// Keep track on the node if we encountered an error while parsing it. If we did, then
// we cannot reuse the node incrementally. Once we've marked this node, clear out the
// flag so that we don't mark any subsequent nodes.
if (parseErrorBeforeNextFinishedNode) {
parseErrorBeforeNextFinishedNode = false;
node.parserContextFlags |= ParserContextFlags.ContainsError;
}
return node;
}
function createMissingNode(kind: SyntaxKind, reportAtCurrentPosition: boolean, diagnosticMessage: DiagnosticMessage, arg0?: any): Node {
if (reportAtCurrentPosition) {
parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
}
else {
parseErrorAtCurrentToken(diagnosticMessage, arg0);
}
var result = createNode(kind, scanner.getStartPos());
(result).text = "";
return finishNode(result);
}
function internIdentifier(text: string): string {
text = escapeIdentifier(text);
return hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text);
}
// An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
// with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
// each identifier in order to reduce memory consumption.
function createIdentifier(isIdentifier: boolean, diagnosticMessage?: DiagnosticMessage): Identifier {
identifierCount++;
if (isIdentifier) {
var node = createNode(SyntaxKind.Identifier);
node.text = internIdentifier(scanner.getTokenValue());
nextToken();
return finishNode(node);
}
return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition:*/ false, diagnosticMessage || Diagnostics.Identifier_expected);
}
function parseIdentifier(diagnosticMessage?: DiagnosticMessage): Identifier {
return createIdentifier(isIdentifier(), diagnosticMessage);
}
function parseIdentifierName(): Identifier {
return createIdentifier(isIdentifierOrKeyword());
}
function isLiteralPropertyName(): boolean {
return isIdentifierOrKeyword() ||
token === SyntaxKind.StringLiteral ||
token === SyntaxKind.NumericLiteral;
}
function parsePropertyName(): DeclarationName {
if (token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral) {
return parseLiteralNode(/*internName:*/ true);
}
if (token === SyntaxKind.OpenBracketToken) {
return parseComputedPropertyName();
}
return parseIdentifierName();
}
function parseComputedPropertyName(): ComputedPropertyName {
// PropertyName[Yield,GeneratorParameter] :
// LiteralPropertyName
// [+GeneratorParameter] ComputedPropertyName
// [~GeneratorParameter] ComputedPropertyName[?Yield]
//
// ComputedPropertyName[Yield] :
// [ AssignmentExpression[In, ?Yield] ]
//
var node = createNode(SyntaxKind.ComputedPropertyName);
parseExpected(SyntaxKind.OpenBracketToken);
// We parse any expression (including a comma expression). But the grammar
// says that only an assignment expression is allowed, so the grammar checker
// will error if it sees a comma expression.
var yieldContext = inYieldContext();
if (inGeneratorParameterContext()) {
setYieldContext(false);
}
node.expression = allowInAnd(parseExpression);
if (inGeneratorParameterContext()) {
setYieldContext(yieldContext);
}
parseExpected(SyntaxKind.CloseBracketToken);
return finishNode(node);
}
function parseContextualModifier(t: SyntaxKind): boolean {
return token === t && tryParse(nextTokenCanFollowModifier);
}
function nextTokenCanFollowModifier() {
nextToken();
return canFollowModifier();
}
function parseAnyContextualModifier(): boolean {
return isModifier(token) && tryParse(nextTokenCanFollowContextualModifier);
}
function nextTokenCanFollowContextualModifier() {
if (token === SyntaxKind.ConstKeyword) {
// 'const' is only a modifier if followed by 'enum'.
return nextToken() === SyntaxKind.EnumKeyword;
}
nextToken();
return canFollowModifier();
}
function canFollowModifier(): boolean {
return token === SyntaxKind.OpenBracketToken || token === SyntaxKind.AsteriskToken || isLiteralPropertyName();
}
// True if positioned at the start of a list element
function isListElement(kind: ParsingContext, inErrorRecovery: boolean): boolean {
switch (kind) {
case ParsingContext.SourceElements:
case ParsingContext.ModuleElements:
return isSourceElement(inErrorRecovery);
case ParsingContext.BlockStatements:
case ParsingContext.SwitchClauseStatements:
return isStatement(inErrorRecovery);
case ParsingContext.SwitchClauses:
return token === SyntaxKind.CaseKeyword || token === SyntaxKind.DefaultKeyword;
case ParsingContext.TypeMembers:
return isStartOfTypeMember();
case ParsingContext.ClassMembers:
return lookAhead(isClassMemberStart);
case ParsingContext.EnumMembers:
// Include open bracket computed properties. This technically also lets in indexers,
// which would be a candidate for improved error reporting.
return token === SyntaxKind.OpenBracketToken || isLiteralPropertyName();
case ParsingContext.ObjectLiteralMembers:
return token === SyntaxKind.OpenBracketToken || token === SyntaxKind.AsteriskToken || isLiteralPropertyName();
case ParsingContext.TypeReferences:
// We want to make sure that the "extends" in "extends foo" or the "implements" in
// "implements foo" is not considered a type name.
return isIdentifier() && !isNotHeritageClauseTypeName();
case ParsingContext.VariableDeclarations:
case ParsingContext.TypeParameters:
return isIdentifier();
case ParsingContext.ArgumentExpressions:
return token === SyntaxKind.CommaToken || isStartOfExpression();
case ParsingContext.ArrayLiteralMembers:
return token === SyntaxKind.CommaToken || isStartOfExpression();
case ParsingContext.Parameters:
return isStartOfParameter();
case ParsingContext.TypeArguments:
case ParsingContext.TupleElementTypes:
return token === SyntaxKind.CommaToken || isStartOfType();
case ParsingContext.HeritageClauses:
return isHeritageClause();
}
Debug.fail("Non-exhaustive case in 'isListElement'.");
}
function nextTokenIsIdentifier() {
nextToken();
return isIdentifier();
}
function isNotHeritageClauseTypeName(): boolean {
if (token === SyntaxKind.ImplementsKeyword ||
token === SyntaxKind.ExtendsKeyword) {
return lookAhead(nextTokenIsIdentifier);
}
return false;
}
// True if positioned at a list terminator
function isListTerminator(kind: ParsingContext): boolean {
if (token === SyntaxKind.EndOfFileToken) {
// Being at the end of the file ends all lists.
return true;
}
switch (kind) {
case ParsingContext.ModuleElements:
case ParsingContext.BlockStatements:
case ParsingContext.SwitchClauses:
case ParsingContext.TypeMembers:
case ParsingContext.ClassMembers:
case ParsingContext.EnumMembers:
case ParsingContext.ObjectLiteralMembers:
return token === SyntaxKind.CloseBraceToken;
case ParsingContext.SwitchClauseStatements:
return token === SyntaxKind.CloseBraceToken || token === SyntaxKind.CaseKeyword || token === SyntaxKind.DefaultKeyword;
case ParsingContext.TypeReferences:
return token === SyntaxKind.OpenBraceToken || token === SyntaxKind.ExtendsKeyword || token === SyntaxKind.ImplementsKeyword;
case ParsingContext.VariableDeclarations:
return isVariableDeclaratorListTerminator();
case ParsingContext.TypeParameters:
// Tokens other than '>' are here for better error recovery
return token === SyntaxKind.GreaterThanToken || token === SyntaxKind.OpenParenToken || token === SyntaxKind.OpenBraceToken || token === SyntaxKind.ExtendsKeyword || token === SyntaxKind.ImplementsKeyword;
case ParsingContext.ArgumentExpressions:
// Tokens other than ')' are here for better error recovery
return token === SyntaxKind.CloseParenToken || token === SyntaxKind.SemicolonToken;
case ParsingContext.ArrayLiteralMembers:
case ParsingContext.TupleElementTypes:
return token === SyntaxKind.CloseBracketToken;
case ParsingContext.Parameters:
// Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
return token === SyntaxKind.CloseParenToken || token === SyntaxKind.CloseBracketToken || token === SyntaxKind.OpenBraceToken;
case ParsingContext.TypeArguments:
// Tokens other than '>' are here for better error recovery
return token === SyntaxKind.GreaterThanToken || token === SyntaxKind.OpenParenToken;
case ParsingContext.HeritageClauses:
return token === SyntaxKind.OpenBraceToken || token === SyntaxKind.CloseBraceToken;
}
}
function isVariableDeclaratorListTerminator(): boolean {
// If we can consume a semicolon (either explicitly, or with ASI), then consider us done
// with parsing the list of variable declarators.
if (canParseSemicolon()) {
return true;
}
// in the case where we're parsing the variable declarator of a 'for-in' statement, we
// are done if we see an 'in' keyword in front of us.
if (token === SyntaxKind.InKeyword) {
return true;
}
// ERROR RECOVERY TWEAK:
// For better error recovery, if we see an '=>' then we just stop immediately. We've got an
// arrow function here and it's going to be very unlikely that we'll resynchronize and get
// another variable declaration.
if (token === SyntaxKind.EqualsGreaterThanToken) {
return true;
}
// Keep trying to parse out variable declarators.
return false;
}
// True if positioned at element or terminator of the current list or any enclosing list
function isInSomeParsingContext(): boolean {
for (var kind = 0; kind < ParsingContext.Count; kind++) {
if (parsingContext & (1 << kind)) {
if (isListElement(kind, /* inErrorRecovery */ true) || isListTerminator(kind)) {
return true;
}
}
}
return false;
}
// Parses a list of elements
function parseList(kind: ParsingContext, checkForStrictMode: boolean, parseElement: () => T): NodeArray {
var saveParsingContext = parsingContext;
parsingContext |= 1 << kind;
var result = >[];
result.pos = getNodePos();
var savedStrictModeContext = inStrictModeContext();
while (!isListTerminator(kind)) {
if (isListElement(kind, /* inErrorRecovery */ false)) {
var element = parseElement();
result.push(element);
// test elements only if we are not already in strict mode
if (checkForStrictMode && !inStrictModeContext()) {
if (isPrologueDirective(element)) {
if (isUseStrictPrologueDirective(element)) {
setStrictModeContext(true);
checkForStrictMode = false;
}
}
else {
checkForStrictMode = false;
}
}
continue;
}
if (abortParsingListOrMoveToNextToken(kind)) {
break;
}
}
setStrictModeContext(savedStrictModeContext);
result.end = getNodeEnd();
parsingContext = saveParsingContext;
return result;
}
// Returns true if we should abort parsing.
function abortParsingListOrMoveToNextToken(kind: ParsingContext) {
parseErrorAtCurrentToken(parsingContextErrors(kind));
if (isInSomeParsingContext()) {
return true;
}
nextToken();
return false;
}
// Parses a comma-delimited list of elements
function parseDelimitedList(kind: ParsingContext, parseElement: () => T): NodeArray {
var saveParsingContext = parsingContext;
parsingContext |= 1 << kind;
var result = >[];
result.pos = getNodePos();
var commaStart = -1; // Meaning the previous token was not a comma
while (true) {
if (isListElement(kind, /* inErrorRecovery */ false)) {
result.push(parseElement());
commaStart = scanner.getTokenPos();
if (parseOptional(SyntaxKind.CommaToken)) {
continue;
}
commaStart = -1; // Back to the state where the last token was not a comma
if (isListTerminator(kind)) {
break;
}
parseExpected(SyntaxKind.CommaToken);
continue;
}
if (isListTerminator(kind)) {
break;
}
if (abortParsingListOrMoveToNextToken(kind)) {
break;
}
}
// Recording the trailing comma is deliberately done after the previous
// loop, and not just if we see a list terminator. This is because the list
// may have ended incorrectly, but it is still important to know if there
// was a trailing comma.
// Check if the last token was a comma.
if (commaStart >= 0) {
// Always preserve a trailing comma by marking it on the NodeArray
result.hasTrailingComma = true;
}
result.end = getNodeEnd();
parsingContext = saveParsingContext;
return result;
}
function createMissingList(): NodeArray {
var pos = getNodePos();
var result = >[];
result.pos = pos;
result.end = pos;
return result;
}
function parseBracketedList(kind: ParsingContext, parseElement: () => T, open: SyntaxKind, close: SyntaxKind): NodeArray {
if (parseExpected(open)) {
var result = parseDelimitedList(kind, parseElement);
parseExpected(close);
return result;
}
return createMissingList();
}
// The allowReservedWords parameter controls whether reserved words are permitted after the first dot
function parseEntityName(allowReservedWords: boolean, diagnosticMessage?: DiagnosticMessage): EntityName {
var entity: EntityName = parseIdentifier(diagnosticMessage);
while (parseOptional(SyntaxKind.DotToken)) {
var node = createNode(SyntaxKind.QualifiedName, entity.pos);
node.left = entity;
node.right = parseRightSideOfDot(allowReservedWords);
entity = finishNode(node);
}
return entity;
}
function parseRightSideOfDot(allowIdentifierNames: boolean): Identifier {
// Technically a keyword is valid here as all keywords are identifier names.
// However, often we'll encounter this in error situations when the keyword
// is actually starting another valid construct.
//
// So, we check for the following specific case:
//
// name.
// keyword identifierNameOrKeyword
//
// Note: the newlines are important here. For example, if that above code
// were rewritten into:
//
// name.keyword
// identifierNameOrKeyword
//
// Then we would consider it valid. That's because ASI would take effect and
// the code would be implicitly: "name.keyword; identifierNameOrKeyword".
// In the first case though, ASI will not take effect because there is not a
// line terminator after the keyword.
if (scanner.hasPrecedingLineBreak() && scanner.isReservedWord()) {
var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
if (matchesPattern) {
// Report that we need an identifier. However, report it right after the dot,
// and not on the next token. This is because the next token might actually
// be an identifier and the error woudl be quite confusing.
return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentToken:*/ true, Diagnostics.Identifier_expected);
}
}
return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
}
function parseTokenNode(): T {
var node = createNode(token);
nextToken();
return finishNode(node);
}
function parseTemplateExpression(): TemplateExpression {
var template = createNode(SyntaxKind.TemplateExpression);
template.head = parseLiteralNode();
Debug.assert(template.head.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind");
var templateSpans = >[];
templateSpans.pos = getNodePos();
do {
templateSpans.push(parseTemplateSpan());
}
while (templateSpans[templateSpans.length - 1].literal.kind === SyntaxKind.TemplateMiddle)
templateSpans.end = getNodeEnd();
template.templateSpans = templateSpans;
return finishNode(template);
}
function parseTemplateSpan(): TemplateSpan {
var span = createNode(SyntaxKind.TemplateSpan);
span.expression = allowInAnd(parseExpression);
var literal: LiteralExpression;
if (token === SyntaxKind.CloseBraceToken) {
reScanTemplateToken()
literal = parseLiteralNode();
}
else {
literal = createMissingNode(
SyntaxKind.TemplateTail, /*reportAtCurrentPosition:*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken));
}
span.literal = literal;
return finishNode(span);
}
function parseLiteralNode(internName?: boolean): LiteralExpression {
var node = createNode(token);
var text = scanner.getTokenValue();
node.text = internName ? internIdentifier(text) : text;
if (scanner.isUnterminated()) {
node.isUnterminated = true;
}
var tokenPos = scanner.getTokenPos();
nextToken();
finishNode(node);
// Octal literals are not allowed in strict mode or ES5
// Note that theoretically the following condition would hold true literals like 009,
// which is not octal.But because of how the scanner separates the tokens, we would
// never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
// We also do not need to check for negatives because any prefix operator would be part of a
// parent unary expression.
if (node.kind === SyntaxKind.NumericLiteral
&& sourceText.charCodeAt(tokenPos) === CharacterCodes._0
&& isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) {
node.flags |= NodeFlags.OctalLiteral;
}
return node;
}
// TYPES
function parseTypeReference(): TypeReferenceNode {
var node = createNode(SyntaxKind.TypeReference);
node.typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected);
if (!scanner.hasPrecedingLineBreak() && token === SyntaxKind.LessThanToken) {
node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken);
}
return finishNode(node);
}
function parseTypeQuery(): TypeQueryNode {
var node = createNode(SyntaxKind.TypeQuery);
parseExpected(SyntaxKind.TypeOfKeyword);
node.exprName = parseEntityName(/*allowReservedWords*/ true);
return finishNode(node);
}
function parseTypeParameter(): TypeParameterDeclaration {
var node = createNode(SyntaxKind.TypeParameter);
node.name = parseIdentifier();
if (parseOptional(SyntaxKind.ExtendsKeyword)) {
// It's not uncommon for people to write improper constraints to a generic. If the
// user writes a constraint that is an expression and not an actual type, then parse
// it out as an expression (so we can recover well), but report that a type is needed
// instead.
if (isStartOfType() || !isStartOfExpression()) {
node.constraint = parseType();
}
else {
// It was not a type, and it looked like an expression. Parse out an expression
// here so we recover well. Note: it is important that we call parseUnaryExpression
// and not parseExpression here. If the user has:
//
//
//
// We do *not* want to consume the > as we're consuming the expression for "".
node.expression = parseUnaryExpressionOrHigher();
}
}
return finishNode(node);
}
function parseTypeParameters(): NodeArray {
if (token === SyntaxKind.LessThanToken) {
return parseBracketedList(ParsingContext.TypeParameters, parseTypeParameter, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken);
}
}
function parseParameterType(): TypeNode | StringLiteralExpression {
if (parseOptional(SyntaxKind.ColonToken)) {
return token === SyntaxKind.StringLiteral
? parseLiteralNode(/*internName:*/ true)
: parseType();
}
return undefined;
}
function isStartOfParameter(): boolean {
return token === SyntaxKind.DotDotDotToken || isIdentifier() || isModifier(token);
}
function setModifiers(node: Node, modifiers: ModifiersArray) {
if (modifiers) {
node.flags |= modifiers.flags;
node.modifiers = modifiers;
}
}
function parseParameter(): ParameterDeclaration {
var node = createNode(SyntaxKind.Parameter);
setModifiers(node, parseModifiers());
node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
// SingleNameBinding[Yield,GeneratorParameter] : See 13.2.3
// [+GeneratorParameter]BindingIdentifier[Yield]Initializer[In]opt
// [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
node.name = inGeneratorParameterContext()
? doInYieldContext(parseIdentifier)
: parseIdentifier();
if (getFullWidth(node.name) === 0 && node.flags === 0 && isModifier(token)) {
// in cases like
// 'use strict'
// function foo(static)
// isParameter('static') === true, because of isModifier('static')
// however 'static' is not a legal identifier in a strict mode.
// so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
// and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
// to avoid this we'll advance cursor to the next token.
nextToken();
}
node.questionToken = parseOptionalToken(SyntaxKind.QuestionToken);
node.type = parseParameterType();
node.initializer = inGeneratorParameterContext()
? doOutsideOfYieldContext(parseParameterInitializer)
: parseParameterInitializer();
// Do not check for initializers in an ambient context for parameters. This is not
// a grammar error because the grammar allows arbitrary call signatures in
// an ambient context.
// It is actually not necessary for this to be an error at all. The reason is that
// function/constructor implementations are syntactically disallowed in ambient
// contexts. In addition, parameter initializers are semantically disallowed in
// overload signatures. So parameter initializers are transitively disallowed in
// ambient contexts.
return finishNode(node);
}
function parseParameterInitializer() {
return parseInitializer(/*inParameter*/ true);
}
function fillSignature(
returnToken: SyntaxKind,
yieldAndGeneratorParameterContext: boolean,
requireCompleteParameterList: boolean,
signature: SignatureDeclaration): void {
var returnTokenRequired = returnToken === SyntaxKind.EqualsGreaterThanToken;
signature.typeParameters = parseTypeParameters();
signature.parameters = parseParameterList(yieldAndGeneratorParameterContext, requireCompleteParameterList);
if (returnTokenRequired) {
parseExpected(returnToken);
signature.type = parseType();
}
else if (parseOptional(returnToken)) {
signature.type = parseType();
}
}
// Note: after careful analysis of the grammar, it does not appear to be possible to
// have 'Yield' And 'GeneratorParameter' not in sync. i.e. any production calling
// this FormalParameters production either always sets both to true, or always sets
// both to false. As such we only have a single parameter to represent both.
function parseParameterList(yieldAndGeneratorParameterContext: boolean, requireCompleteParameterList: boolean) {
// FormalParameters[Yield,GeneratorParameter] :
// ...
//
// FormalParameter[Yield,GeneratorParameter] :
// BindingElement[?Yield, ?GeneratorParameter]
//
// BindingElement[Yield, GeneratorParameter ] : See 13.2.3
// SingleNameBinding[?Yield, ?GeneratorParameter]
// [+GeneratorParameter]BindingPattern[?Yield, GeneratorParameter]Initializer[In]opt
// [~GeneratorParameter]BindingPattern[?Yield]Initializer[In, ?Yield]opt
//
// SingleNameBinding[Yield, GeneratorParameter] : See 13.2.3
// [+GeneratorParameter]BindingIdentifier[Yield]Initializer[In]opt
// [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
if (parseExpected(SyntaxKind.OpenParenToken)) {
var savedYieldContext = inYieldContext();
var savedGeneratorParameterContext = inGeneratorParameterContext();
setYieldContext(yieldAndGeneratorParameterContext);
setGeneratorParameterContext(yieldAndGeneratorParameterContext);
var result = parseDelimitedList(ParsingContext.Parameters, parseParameter);
setYieldContext(savedYieldContext);
setGeneratorParameterContext(savedGeneratorParameterContext);
if (!parseExpected(SyntaxKind.CloseParenToken) && requireCompleteParameterList) {
// Caller insisted that we had to end with a ) We didn't. So just return
// undefined here.
return undefined;
}
return result;
}
// We didn't even have an open paren. If the caller requires a complete parameter list,
// we definitely can't provide that. However, if they're ok with an incomplete one,
// then just return an empty set of parameters.
return requireCompleteParameterList ? undefined : createMissingList();
}
function parseSignatureMember(kind: SyntaxKind): SignatureDeclaration {
var node = createNode(kind);
if (kind === SyntaxKind.ConstructSignature) {
parseExpected(SyntaxKind.NewKeyword);
}
fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, node);
parseSemicolon();
return finishNode(node);
}
function isIndexSignature(): boolean {
if (token !== SyntaxKind.OpenBracketToken) {
return false;
}
return lookAhead(isUnambiguouslyIndexSignature);
}
function isUnambiguouslyIndexSignature() {
// The only allowed sequence is:
//
// [id:
//
// However, for error recovery, we also check the following cases:
//
// [...
// [id,
// [id?,
// [id?:
// [id?]
// [public id
// [private id
// [protected id
// []
//
nextToken();
if (token === SyntaxKind.DotDotDotToken || token === SyntaxKind.CloseBracketToken) {
return true;
}
if (isModifier(token)) {
nextToken();
if (isIdentifier()) {
return true;
}
}
else if (!isIdentifier()) {
return false;
}
else {
// Skip the identifier
nextToken();
}
// A colon signifies a well formed indexer
// A comma should be a badly formed indexer because comma expressions are not allowed
// in computed properties.
if (token === SyntaxKind.ColonToken || token === SyntaxKind.CommaToken) {
return true;
}
// Question mark could be an indexer with an optional property,
// or it could be a conditional expression in a computed property.
if (token !== SyntaxKind.QuestionToken) {
return false;
}
// If any of the following tokens are after the question mark, it cannot
// be a conditional expression, so treat it as an indexer.
nextToken();
return token === SyntaxKind.ColonToken || token === SyntaxKind.CommaToken || token === SyntaxKind.CloseBracketToken;
}
function parseIndexSignatureDeclaration(fullStart: number, modifiers: ModifiersArray): IndexSignatureDeclaration {
var node = createNode(SyntaxKind.IndexSignature, fullStart);
setModifiers(node, modifiers);
node.parameters = parseBracketedList(ParsingContext.Parameters, parseParameter, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken);
node.type = parseTypeAnnotation();
parseSemicolon();
return finishNode(node)
}
function parsePropertyOrMethod(): Declaration {
var fullStart = scanner.getStartPos();
var name = parsePropertyName();
var questionToken = parseOptionalToken(SyntaxKind.QuestionToken);
if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) {
var method = createNode(SyntaxKind.Method, fullStart);
method.name = name;
method.questionToken = questionToken;
// Method signatues don't exist in expression contexts. So they have neither
// [Yield] nor [GeneratorParameter]
fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, method);
parseSemicolon();
return finishNode(method);
}
else {
var property = createNode(SyntaxKind.Property, fullStart);
property.name = name;
property.questionToken = questionToken;
property.type = parseTypeAnnotation();
parseSemicolon();
return finishNode(property);
}
}
function isStartOfTypeMember(): boolean {
switch (token) {
case SyntaxKind.OpenParenToken:
case SyntaxKind.LessThanToken:
case SyntaxKind.OpenBracketToken: // Both for indexers and computed properties
return true;
default:
return isLiteralPropertyName() && lookAhead(isTypeMemberWithLiteralPropertyName);
}
}
function isTypeMemberWithLiteralPropertyName() {
nextToken();
return token === SyntaxKind.OpenParenToken ||
token === SyntaxKind.LessThanToken ||
token === SyntaxKind.QuestionToken ||
token === SyntaxKind.ColonToken ||
canParseSemicolon();
}
function parseTypeMember(): Declaration {
switch (token) {
case SyntaxKind.OpenParenToken:
case SyntaxKind.LessThanToken:
return parseSignatureMember(SyntaxKind.CallSignature);
case SyntaxKind.OpenBracketToken:
// Indexer or computed property
return isIndexSignature() ? parseIndexSignatureDeclaration(scanner.getStartPos(), /*modifiers:*/ undefined) : parsePropertyOrMethod();
case SyntaxKind.NewKeyword:
if (lookAhead(isStartOfConstructSignature)) {
return parseSignatureMember(SyntaxKind.ConstructSignature);
}
// fall through.
case SyntaxKind.StringLiteral:
case SyntaxKind.NumericLiteral:
return parsePropertyOrMethod();
default:
if (isIdentifierOrKeyword()) {
return parsePropertyOrMethod();
}
}
}
function isStartOfConstructSignature() {
nextToken();
return token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken;
}
function parseTypeLiteral(): TypeLiteralNode {
var node = createNode(SyntaxKind.TypeLiteral);
node.members = parseObjectTypeMembers();
return finishNode(node);
}
function parseObjectTypeMembers(): NodeArray {
var members: NodeArray;
if (parseExpected(SyntaxKind.OpenBraceToken)) {
members = parseList(ParsingContext.TypeMembers, /*checkForStrictMode*/ false, parseTypeMember);
parseExpected(SyntaxKind.CloseBraceToken);
}
else {
members = createMissingList();
}
return members;
}
function parseTupleType(): TupleTypeNode {
var node = createNode(SyntaxKind.TupleType);
node.elementTypes = parseBracketedList(ParsingContext.TupleElementTypes, parseType, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken);
return finishNode(node);
}
function parseParenthesizedType(): ParenthesizedTypeNode {
var node = createNode(SyntaxKind.ParenthesizedType);
parseExpected(SyntaxKind.OpenParenToken);
node.type = parseType();
parseExpected(SyntaxKind.CloseParenToken);
return finishNode(node);
}
function parseFunctionOrConstructorType(kind: SyntaxKind): FunctionOrConstructorTypeNode {
var node = createNode(kind);
if (kind === SyntaxKind.ConstructorType) {
parseExpected(SyntaxKind.NewKeyword);
}
fillSignature(SyntaxKind.EqualsGreaterThanToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, node);
return finishNode(node);
}
function parseKeywordAndNoDot(): TypeNode {
var node = parseTokenNode();
return token === SyntaxKind.DotToken ? undefined : node;
}
function parseNonArrayType(): TypeNode {
switch (token) {
case SyntaxKind.AnyKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.BooleanKeyword:
// If these are followed by a dot, then parse these out as a dotted type reference instead.
var node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReference();
case SyntaxKind.VoidKeyword:
return parseTokenNode();
case SyntaxKind.TypeOfKeyword:
return parseTypeQuery();
case SyntaxKind.OpenBraceToken:
return parseTypeLiteral();
case SyntaxKind.OpenBracketToken:
return parseTupleType();
case SyntaxKind.OpenParenToken:
return parseParenthesizedType();
default:
return parseTypeReference();
}
}
function isStartOfType(): boolean {
switch (token) {
case SyntaxKind.AnyKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.TypeOfKeyword:
case SyntaxKind.OpenBraceToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.LessThanToken:
case SyntaxKind.NewKeyword:
return true;
case SyntaxKind.OpenParenToken:
// Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
// or something that starts a type. We don't want to consider things like '(1)' a type.
return lookAhead(isStartOfParenthesizedOrFunctionType);
default:
return isIdentifier();
}
}
function isStartOfParenthesizedOrFunctionType() {
nextToken();
return token === SyntaxKind.CloseParenToken || isStartOfParameter() || isStartOfType();
}
function parseArrayTypeOrHigher(): TypeNode {
var type = parseNonArrayType();
while (!scanner.hasPrecedingLineBreak() && parseOptional(SyntaxKind.OpenBracketToken)) {
parseExpected(SyntaxKind.CloseBracketToken);
var node = createNode(SyntaxKind.ArrayType, type.pos);
node.elementType = type;
type = finishNode(node);
}
return type;
}
function parseUnionTypeOrHigher(): TypeNode {
var type = parseArrayTypeOrHigher();
if (token === SyntaxKind.BarToken) {
var types = >[type];
types.pos = type.pos;
while (parseOptional(SyntaxKind.BarToken)) {
types.push(parseArrayTypeOrHigher());
}
types.end = getNodeEnd();
var node = createNode(SyntaxKind.UnionType, type.pos);
node.types = types;
type = finishNode(node);
}
return type;
}
function isStartOfFunctionType(): boolean {
if (token === SyntaxKind.LessThanToken) {
return true;
}
return token === SyntaxKind.OpenParenToken && lookAhead(isUnambiguouslyStartOfFunctionType);
}
function isUnambiguouslyStartOfFunctionType() {
nextToken();
if (token === SyntaxKind.CloseParenToken || token === SyntaxKind.DotDotDotToken) {
// ( )
// ( ...
return true;
}
if (isIdentifier() || isModifier(token)) {
nextToken();
if (token === SyntaxKind.ColonToken || token === SyntaxKind.CommaToken ||
token === SyntaxKind.QuestionToken || token === SyntaxKind.EqualsToken ||
isIdentifier() || isModifier(token)) {
// ( id :
// ( id ,
// ( id ?
// ( id =
// ( modifier id
return true;
}
if (token === SyntaxKind.CloseParenToken) {
nextToken();
if (token === SyntaxKind.EqualsGreaterThanToken) {
// ( id ) =>
return true;
}
}
}
return false;
}
function parseType(): TypeNode {
// The rules about 'yield' only apply to actual code/expression contexts. They don't
// apply to 'type' contexts. So we disable these parameters here before moving on.
var savedYieldContext = inYieldContext();
var savedGeneratorParameterContext = inGeneratorParameterContext();
setYieldContext(false);
setGeneratorParameterContext(false);
var result = parseTypeWorker();
setYieldContext(savedYieldContext);
setGeneratorParameterContext(savedGeneratorParameterContext);
return result;
}
function parseTypeWorker(): TypeNode {
if (isStartOfFunctionType()) {
return parseFunctionOrConstructorType(SyntaxKind.FunctionType);
}
if (token === SyntaxKind.NewKeyword) {
return parseFunctionOrConstructorType(SyntaxKind.ConstructorType);
}
return parseUnionTypeOrHigher();
}
function parseTypeAnnotation(): TypeNode {
return parseOptional(SyntaxKind.ColonToken) ? parseType() : undefined;
}
// EXPRESSIONS
function isStartOfExpression(): boolean {
switch (token) {
case SyntaxKind.ThisKeyword:
case SyntaxKind.SuperKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.NumericLiteral:
case SyntaxKind.StringLiteral:
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.TemplateHead:
case SyntaxKind.OpenParenToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.OpenBraceToken:
case SyntaxKind.FunctionKeyword:
case SyntaxKind.NewKeyword:
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
case SyntaxKind.TildeToken:
case SyntaxKind.ExclamationToken:
case SyntaxKind.DeleteKeyword:
case SyntaxKind.TypeOfKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.PlusPlusToken:
case SyntaxKind.MinusMinusToken:
case SyntaxKind.LessThanToken:
case SyntaxKind.Identifier:
case SyntaxKind.YieldKeyword:
// Yield always starts an expression. Either it is an identifier (in which case
// it is definitely an expression). Or it's a keyword (either because we're in
// a generator, or in strict mode (or both)) and it started a yield expression.
return true;
default:
return isIdentifier();
}
}
function isStartOfExpressionStatement(): boolean {
// As per the grammar, neither '{' nor 'function' can start an expression statement.
return token !== SyntaxKind.OpenBraceToken && token !== SyntaxKind.FunctionKeyword && isStartOfExpression();
}
function parseExpression(): Expression {
// Expression[in]:
// AssignmentExpression[in]
// Expression[in] , AssignmentExpression[in]
var expr = parseAssignmentExpressionOrHigher();
while (parseOptional(SyntaxKind.CommaToken)) {
expr = makeBinaryExpression(expr, SyntaxKind.CommaToken, parseAssignmentExpressionOrHigher());
}
return expr;
}
function parseInitializer(inParameter: boolean): Expression {
if (token !== SyntaxKind.EqualsToken) {
// It's not uncommon during typing for the user to miss writing the '=' token. Check if
// there is no newline after the last token and if we're on an expression. If so, parse
// this as an equals-value clause with a missing equals.
// NOTE: There are two places where we allow equals-value clauses. The first is in a
// variable declarator. The second is with a parameter. For variable declarators
// it's more likely that a { would be a allowed (as an object literal). While this
// is also allowed for parameters, the risk is that we consume the { as an object
// literal when it really will be for the block following the parameter.
if (scanner.hasPrecedingLineBreak() || (inParameter && token === SyntaxKind.OpenBraceToken) || !isStartOfExpression()) {
// preceding line break, open brace in a parameter (likely a function body) or current token is not an expression -
// do not try to parse initializer
return undefined;
}
}
// Initializer[In, Yield] :
// = AssignmentExpression[?In, ?Yield]
parseExpected(SyntaxKind.EqualsToken);
return parseAssignmentExpressionOrHigher();
}
function parseAssignmentExpressionOrHigher(): Expression {
// AssignmentExpression[in,yield]:
// 1) ConditionalExpression[?in,?yield]
// 2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
// 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
// 4) ArrowFunctionExpression[?in,?yield]
// 5) [+Yield] YieldExpression[?In]
//
// Note: for ease of implementation we treat productions '2' and '3' as the same thing.
// (i.e. they're both BinaryExpressions with an assignment operator in it).
// First, do the simple check if we have a YieldExpression (production '5').
if (isYieldExpression()) {
return parseYieldExpression();
}
// Then, check if we have an arrow function (production '4') that starts with a parenthesized
// parameter list. If we do, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
// not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done
// with AssignmentExpression if we see one.
var arrowExpression = tryParseParenthesizedArrowFunctionExpression();
if (arrowExpression) {
return arrowExpression;
}
// Now try to see if we're in production '1', '2' or '3'. A conditional expression can
// start with a LogicalOrExpression, while the assignment productions can only start with
// LeftHandSideExpressions.
//
// So, first, we try to just parse out a BinaryExpression. If we get something that is a
// LeftHandSide or higher, then we can try to parse out the assignment expression part.
// Otherwise, we try to parse out the conditional expression bit. We want to allow any
// binary expression here, so we pass in the 'lowest' precedence here so that it matches
// and consumes anything.
var expr = parseBinaryExpressionOrHigher(/*precedence:*/ 0);
// To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
// parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
// identifier and the current token is an arrow.
if (expr.kind === SyntaxKind.Identifier && token === SyntaxKind.EqualsGreaterThanToken) {
return parseSimpleArrowFunctionExpression(expr);
}
// Now see if we might be in cases '2' or '3'.
// If the expression was a LHS expression, and we have an assignment operator, then
// we're in '2' or '3'. Consume the assignment and return.
//
// Note: we call reScanGreaterToken so that we get an appropriately merged token
// for cases like > > = becoming >>=
if (isLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) {
var operator = token;
nextToken();
return makeBinaryExpression(expr, operator, parseAssignmentExpressionOrHigher());
}
// It wasn't an assignment or a lambda. This is a conditional expression:
return parseConditionalExpressionRest(expr);
}
function isYieldExpression(): boolean {
if (token === SyntaxKind.YieldKeyword) {
// If we have a 'yield' keyword, and htis is a context where yield expressions are
// allowed, then definitely parse out a yield expression.
if (inYieldContext()) {
return true;
}
if (inStrictModeContext()) {
// If we're in strict mode, then 'yield' is a keyword, could only ever start
// a yield expression.
return true;
}
// We're in a context where 'yield expr' is not allowed. However, if we can
// definitely tell that the user was trying to parse a 'yield expr' and not
// just a normal expr that start with a 'yield' identifier, then parse out
// a 'yield expr'. We can then report an error later that they are only
// allowed in generator expressions.
//
// for example, if we see 'yield(foo)', then we'll have to treat that as an
// invocation expression of something called 'yield'. However, if we have
// 'yield foo' then that is not legal as a normal expression, so we can
// definitely recognize this as a yield expression.
//
// for now we just check if the next token is an identifier. More heuristics
// can be added here later as necessary. We just need to make sure that we
// don't accidently consume something legal.
return lookAhead(nextTokenIsIdentifierOnSameLine);
}
return false;
}
function nextTokenIsIdentifierOnSameLine() {
nextToken();
return !scanner.hasPrecedingLineBreak() && isIdentifier()
}
function parseYieldExpression(): YieldExpression {
var node = createNode(SyntaxKind.YieldExpression);
// YieldExpression[In] :
// yield
// yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
// yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
nextToken();
if (!scanner.hasPrecedingLineBreak() &&
(token === SyntaxKind.AsteriskToken || isStartOfExpression())) {
node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
node.expression = parseAssignmentExpressionOrHigher();
return finishNode(node);
}
else {
// if the next token is not on the same line as yield. or we don't have an '*' or
// the start of an expressin, then this is just a simple "yield" expression.
return finishNode(node);
}
}
function parseSimpleArrowFunctionExpression(identifier: Identifier): Expression {
Debug.assert(token === SyntaxKind.EqualsGreaterThanToken, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
var node = createNode(SyntaxKind.ArrowFunction, identifier.pos);
var parameter = createNode(SyntaxKind.Parameter, identifier.pos);
parameter.name = identifier;
finishNode(parameter);
node.parameters = >[parameter];
node.parameters.pos = parameter.pos;
node.parameters.end = parameter.end;
parseExpected(SyntaxKind.EqualsGreaterThanToken);
node.body = parseArrowFunctionExpressionBody();
return finishNode(node);
}
function tryParseParenthesizedArrowFunctionExpression(): Expression {
var triState = isParenthesizedArrowFunctionExpression();
if (triState === Tristate.False) {
// It's definitely not a parenthesized arrow function expression.
return undefined;
}
// If we definitely have an arrow function, then we can just parse one, not requiring a
// following => or { token. Otherwise, we *might* have an arrow function. Try to parse
// it out, but don't allow any ambiguity, and return 'undefined' if this could be an
// expression instead.
var arrowFunction = triState === Tristate.True
? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity:*/ true)
: tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
if (!arrowFunction) {
// Didn't appear to actually be a parenthesized arrow function. Just bail out.
return undefined;
}
// If we have an arrow, then try to parse the body. Even if not, try to parse if we
// have an opening brace, just in case we're in an error state.
if (parseExpected(SyntaxKind.EqualsGreaterThanToken) || token === SyntaxKind.OpenBraceToken) {
arrowFunction.body = parseArrowFunctionExpressionBody();
}
else {
// If not, we're probably better off bailing out and returning a bogus function expression.
arrowFunction.body = parseIdentifier();
}
return finishNode(arrowFunction);
}
// True -> We definitely expect a parenthesized arrow function here.
// False -> There *cannot* be a parenthesized arrow function here.
// Unknown -> There *might* be a parenthesized arrow function here.
// Speculatively look ahead to be sure, and rollback if not.
function isParenthesizedArrowFunctionExpression(): Tristate {
if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) {
return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
}
if (token === SyntaxKind.EqualsGreaterThanToken) {
// ERROR RECOVERY TWEAK:
// If we see a standalone => try to parse it as an arrow function expression as that's
// likely what the user intended to write.
return Tristate.True;
}
// Definitely not a parenthesized arrow function.
return Tristate.False;
}
function isParenthesizedArrowFunctionExpressionWorker() {
var first = token;
var second = nextToken();
if (first === SyntaxKind.OpenParenToken) {
if (second === SyntaxKind.CloseParenToken) {
// Simple cases: "() =>", "(): ", and "() {".
// This is an arrow function with no parameters.
// The last one is not actually an arrow function,
// but this is probably what the user intended.
var third = nextToken();
switch (third) {
case SyntaxKind.EqualsGreaterThanToken:
case SyntaxKind.ColonToken:
case SyntaxKind.OpenBraceToken:
return Tristate.True;
default:
return Tristate.False;
}
}
// Simple case: "(..."
// This is an arrow function with a rest parameter.
if (second === SyntaxKind.DotDotDotToken) {
return Tristate.True;
}
// If we had "(" followed by something that's not an identifier,
// then this definitely doesn't look like a lambda.
// Note: we could be a little more lenient and allow
// "(public" or "(private". These would not ever actually be allowed,
// but we could provide a good error message instead of bailing out.
if (!isIdentifier()) {
return Tristate.False;
}
// If we have something like "(a:", then we must have a
// type-annotated parameter in an arrow function expression.
if (nextToken() === SyntaxKind.ColonToken) {
return Tristate.True;
}
// This *could* be a parenthesized arrow function.
// Return Unknown to let the caller know.
return Tristate.Unknown;
}
else {
Debug.assert(first === SyntaxKind.LessThanToken);
// If we have "<" not followed by an identifier,
// then this definitely is not an arrow function.
if (!isIdentifier()) {
return Tristate.False;
}
// This *could* be a parenthesized arrow function.
return Tristate.Unknown;
}
}
function parsePossibleParenthesizedArrowFunctionExpressionHead() {
return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity:*/ false);
}
function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity: boolean): FunctionExpression {
var node = createNode(SyntaxKind.ArrowFunction);
// Arrow functions are never generators.
//
// If we're speculatively parsing a signature for a parenthesized arrow function, then
// we have to have a complete parameter list. Otherwise we might see something like
// a => (b => c)
// And think that "(b =>" was actually a parenthesized arrow function with a missing
// close paren.
fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ !allowAmbiguity, node);
// If we couldn't get parameters, we definitely could not parse out an arrow function.
if (!node.parameters) {
return undefined;
}
// Parsing a signature isn't enough.
// Parenthesized arrow signatures often look like other valid expressions.
// For instance:
// - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
// - "(x,y)" is a comma expression parsed as a signature with two parameters.
// - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
//
// So we need just a bit of lookahead to ensure that it can only be a signature.
if (!allowAmbiguity && token !== SyntaxKind.EqualsGreaterThanToken && token !== SyntaxKind.OpenBraceToken) {
// Returning undefined here will cause our caller to rewind to where we started from.
return undefined;
}
return node;
}
function parseArrowFunctionExpressionBody(): Block | Expression {
if (token === SyntaxKind.OpenBraceToken) {
return parseFunctionBlock(/*allowYield:*/ false, /* ignoreMissingOpenBrace */ false);
}
if (isStatement(/* inErrorRecovery */ true) && !isStartOfExpressionStatement() && token !== SyntaxKind.FunctionKeyword) {
// Check if we got a plain statement (i.e. no expression-statements, no functions expressions/declarations)
//
// Here we try to recover from a potential error situation in the case where the
// user meant to supply a block. For example, if the user wrote:
//
// a =>
// var v = 0;
// }
//
// they may be missing an open brace. Check to see if that's the case so we can
// try to recover better. If we don't do this, then the next close curly we see may end
// up preemptively closing the containing construct.
//
// Note: even when 'ignoreMissingOpenBrace' is passed as true, parseBody will still error.
return parseFunctionBlock(/*allowYield:*/ false, /* ignoreMissingOpenBrace */ true);
}
return parseAssignmentExpressionOrHigher();
}
function parseConditionalExpressionRest(leftOperand: Expression): Expression {
// Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
if (!parseOptional(SyntaxKind.QuestionToken)) {
return leftOperand;
}
// Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
// we do not that for the 'whenFalse' part.
var node = createNode(SyntaxKind.ConditionalExpression, leftOperand.pos);
node.condition = leftOperand;
node.whenTrue = allowInAnd(parseAssignmentExpressionOrHigher);
parseExpected(SyntaxKind.ColonToken);
node.whenFalse = parseAssignmentExpressionOrHigher();
return finishNode(node);
}
function parseBinaryExpressionOrHigher(precedence: number): Expression {
var leftOperand = parseUnaryExpressionOrHigher();
return parseBinaryExpressionRest(precedence, leftOperand);
}
function parseBinaryExpressionRest(precedence: number, leftOperand: Expression): Expression {
while (true) {
// We either have a binary operator here, or we're finished. We call
// reScanGreaterToken so that we merge token sequences like > and = into >=
reScanGreaterToken();
var newPrecedence = getOperatorPrecedence();
// Check the precedence to see if we should "take" this operator
if (newPrecedence <= precedence) {
break;
}
if (token === SyntaxKind.InKeyword && inDisallowInContext()) {
break;
}
var operator = token;
nextToken();
leftOperand = makeBinaryExpression(leftOperand, operator, parseBinaryExpressionOrHigher(newPrecedence));
}
return leftOperand;
}
function getOperatorPrecedence(): number {
switch (token) {
case SyntaxKind.BarBarToken:
return 1;
case SyntaxKind.AmpersandAmpersandToken:
return 2;
case SyntaxKind.BarToken:
return 3;
case SyntaxKind.CaretToken:
return 4;
case SyntaxKind.AmpersandToken:
return 5;
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsEqualsToken:
return 6;
case SyntaxKind.LessThanToken:
case SyntaxKind.GreaterThanToken:
case SyntaxKind.LessThanEqualsToken:
case SyntaxKind.GreaterThanEqualsToken:
case SyntaxKind.InstanceOfKeyword:
case SyntaxKind.InKeyword:
return 7;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
return 8;
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
return 9;
case SyntaxKind.AsteriskToken:
case SyntaxKind.SlashToken:
case SyntaxKind.PercentToken:
return 10;
}
// -1 is lower than all other precedences. Returning it will cause binary expression
// parsing to stop.
return -1;
}
function makeBinaryExpression(left: Expression, operator: SyntaxKind, right: Expression): BinaryExpression {
var node = createNode(SyntaxKind.BinaryExpression, left.pos);
node.left = left;
node.operator = operator;
node.right = right;
return finishNode(node);
}
function parsePrefixUnaryExpression() {
var node = createNode(SyntaxKind.PrefixUnaryExpression);
node.operator = token;
nextToken();
node.operand = parseUnaryExpressionOrHigher();
return finishNode(node);
}
function parseDeleteExpression() {
var node = createNode(SyntaxKind.DeleteExpression);
nextToken();
node.expression = parseUnaryExpressionOrHigher();
return finishNode(node);
}
function parseTypeOfExpression() {
var node = createNode(SyntaxKind.TypeOfExpression);
nextToken();
node.expression = parseUnaryExpressionOrHigher();
return finishNode(node);
}
function parseVoidExpression() {
var node = createNode(SyntaxKind.VoidExpression);
nextToken();
node.expression = parseUnaryExpressionOrHigher();
return finishNode(node);
}
function parseUnaryExpressionOrHigher(): UnaryExpression {
switch (token) {
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
case SyntaxKind.TildeToken:
case SyntaxKind.ExclamationToken:
case SyntaxKind.PlusPlusToken:
case SyntaxKind.MinusMinusToken:
return parsePrefixUnaryExpression();
case SyntaxKind.DeleteKeyword:
return parseDeleteExpression();
case SyntaxKind.TypeOfKeyword:
return parseTypeOfExpression();
case SyntaxKind.VoidKeyword:
return parseVoidExpression();
case SyntaxKind.LessThanToken:
return parseTypeAssertion();
default:
return parsePostfixExpressionOrHigher();
}
}
function parsePostfixExpressionOrHigher(): PostfixExpression {
var expression = parseLeftHandSideExpressionOrHigher();
Debug.assert(isLeftHandSideExpression(expression));
if ((token === SyntaxKind.PlusPlusToken || token === SyntaxKind.MinusMinusToken) && !scanner.hasPrecedingLineBreak()) {
var node = createNode(SyntaxKind.PostfixUnaryExpression, expression.pos);
node.operand = expression;
node.operator = token;
nextToken();
return finishNode(node);
}
return expression;
}
function parseLeftHandSideExpressionOrHigher(): LeftHandSideExpression {
// Original Ecma:
// LeftHandSideExpression: See 11.2
// NewExpression
// CallExpression
//
// Our simplification:
//
// LeftHandSideExpression: See 11.2
// MemberExpression
// CallExpression
//
// See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
// MemberExpression to make our lives easier.
//
// to best understand the below code, it's important to see how CallExpression expands
// out into its own productions:
//
// CallExpression:
// MemberExpression Arguments
// CallExpression Arguments
// CallExpression[Expression]
// CallExpression.IdentifierName
// super ( ArgumentListopt )
// super.IdentifierName
//
// Because of the recursion in these calls, we need to bottom out first. There are two
// bottom out states we can run into. Either we see 'super' which must start either of
// the last two CallExpression productions. Or we have a MemberExpression which either
// completes the LeftHandSideExpression, or starts the beginning of the first four
// CallExpression productions.
var expression = token === SyntaxKind.SuperKeyword
? parseSuperExpression()
: parseMemberExpressionOrHigher();
// Now, we *may* be complete. However, we might have consumed the start of a
// CallExpression. As such, we need to consume the rest of it here to be complete.
return parseCallExpressionRest(expression);
}
function parseMemberExpressionOrHigher(): MemberExpression {
// Note: to make our lives simpler, we decompose the the NewExpression productions and
// place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
// like so:
//
// PrimaryExpression : See 11.1
// this
// Identifier
// Literal
// ArrayLiteral
// ObjectLiteral
// (Expression)
// FunctionExpression
// new MemberExpression Arguments?
//
// MemberExpression : See 11.2
// PrimaryExpression
// MemberExpression[Expression]
// MemberExpression.IdentifierName
//
// CallExpression : See 11.2
// MemberExpression
// CallExpression Arguments
// CallExpression[Expression]
// CallExpression.IdentifierName
//
// Technically this is ambiguous. i.e. CallExpression defines:
//
// CallExpression:
// CallExpression Arguments
//
// If you see: "new Foo()"
//
// Then that could be treated as a single ObjectCreationExpression, or it could be
// treated as the invocation of "new Foo". We disambiguate that in code (to match
// the original grammar) by making sure that if we see an ObjectCreationExpression
// we always consume arguments if they are there. So we treat "new Foo()" as an
// object creation only, and not at all as an invocation) Another way to think
// about this is that for every "new" that we see, we will consume an argument list if
// it is there as part of the *associated* object creation node. Any additional
// argument lists we see, will become invocation expressions.
//
// Because there are no other places in the grammar now that refer to FunctionExpression
// or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
// production.
//
// Because CallExpression and MemberExpression are left recursive, we need to bottom out
// of the recursion immediately. So we parse out a primary expression to start with.
var expression = parsePrimaryExpression();
return parseMemberExpressionRest(expression);
}
function parseSuperExpression(): MemberExpression {
var expression = parseTokenNode();
if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.DotToken) {
return expression;
}
// If we have seen "super" it must be followed by '(' or '.'.
// If it wasn't then just try to parse out a '.' and report an error.
var node = createNode(SyntaxKind.PropertyAccessExpression, expression.pos);
node.expression = expression;
parseExpected(SyntaxKind.DotToken, Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
node.name = parseRightSideOfDot(/*allowIdentifierNames:*/ true);
return finishNode(node);
}
function parseTypeAssertion(): TypeAssertion {
var node = createNode(SyntaxKind.TypeAssertionExpression);
parseExpected(SyntaxKind.LessThanToken);
node.type = parseType();
parseExpected(SyntaxKind.GreaterThanToken);
node.expression = parseUnaryExpressionOrHigher();
return finishNode(node);
}
function parseMemberExpressionRest(expression: LeftHandSideExpression): MemberExpression {
while (true) {
var dotOrBracketStart = scanner.getTokenPos();
if (parseOptional(SyntaxKind.DotToken)) {
var propertyAccess = createNode(SyntaxKind.PropertyAccessExpression, expression.pos);
propertyAccess.expression = expression;
propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames:*/ true);
expression = finishNode(propertyAccess);
continue;
}
if (parseOptional(SyntaxKind.OpenBracketToken)) {
var indexedAccess = createNode(SyntaxKind.ElementAccessExpression, expression.pos);
indexedAccess.expression = expression;
// It's not uncommon for a user to write: "new Type[]".
// Check for that common pattern and report a better error message.
if (token !== SyntaxKind.CloseBracketToken) {
indexedAccess.argumentExpression = allowInAnd(parseExpression);
if (indexedAccess.argumentExpression.kind === SyntaxKind.StringLiteral || indexedAccess.argumentExpression.kind === SyntaxKind.NumericLiteral) {
var literal = indexedAccess.argumentExpression;
literal.text = internIdentifier(literal.text);
}
}
parseExpected(SyntaxKind.CloseBracketToken);
expression = finishNode(indexedAccess);
continue;
}
if (token === SyntaxKind.NoSubstitutionTemplateLiteral || token === SyntaxKind.TemplateHead) {
var tagExpression = createNode(SyntaxKind.TaggedTemplateExpression, expression.pos);
tagExpression.tag = expression;
tagExpression.template = token === SyntaxKind.NoSubstitutionTemplateLiteral
? parseLiteralNode()
: parseTemplateExpression();
expression = finishNode(tagExpression);
continue;
}
return expression;
}
}
function parseCallExpressionRest(expression: LeftHandSideExpression): LeftHandSideExpression {
while (true) {
expression = parseMemberExpressionRest(expression);
if (token === SyntaxKind.LessThanToken) {
// 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) {
return expression;
}
var callExpr = createNode(SyntaxKind.CallExpression, expression.pos);
callExpr.expression = expression;
callExpr.typeArguments = typeArguments;
callExpr.arguments = parseArgumentList();
expression = finishNode(callExpr);
continue;
}
else if (token === SyntaxKind.OpenParenToken) {
var callExpr = createNode(SyntaxKind.CallExpression, expression.pos);
callExpr.expression = expression;
callExpr.arguments = parseArgumentList();
expression = finishNode(callExpr);
continue;
}
return expression;
}
}
function parseArgumentList() {
parseExpected(SyntaxKind.OpenParenToken);
var result = parseDelimitedList(ParsingContext.ArgumentExpressions, parseArgumentExpression);
parseExpected(SyntaxKind.CloseParenToken);
return result;
}
function parseTypeArgumentsInExpression() {
if (!parseOptional(SyntaxKind.LessThanToken)) {
return undefined;
}
var typeArguments = parseDelimitedList(ParsingContext.TypeArguments, parseType);
if (!parseExpected(SyntaxKind.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 arugment 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(): boolean {
switch (token) {
case SyntaxKind.OpenParenToken: // foo(
// this case are the only case where this token can legally follow a type argument
// list. So we definitely want to treat this as a type arg list.
case SyntaxKind.DotToken: // foo.
case SyntaxKind.CloseParenToken: // foo)
case SyntaxKind.CloseBracketToken: // foo]
case SyntaxKind.ColonToken: // foo:
case SyntaxKind.SemicolonToken: // foo;
case SyntaxKind.CommaToken: // foo,
case SyntaxKind.QuestionToken: // foo?
case SyntaxKind.EqualsEqualsToken: // foo ==
case SyntaxKind.EqualsEqualsEqualsToken: // foo ===
case SyntaxKind.ExclamationEqualsToken: // foo !=
case SyntaxKind.ExclamationEqualsEqualsToken: // foo !==
case SyntaxKind.AmpersandAmpersandToken: // foo