TypeScript/src/compiler/visitorPublic.ts

1079 lines
63 KiB
TypeScript
Raw Normal View History

namespace ts {
const isTypeNodeOrTypeParameterDeclaration = or(isTypeNode, isTypeParameterDeclaration);
/**
* Visits a Node using the supplied visitor, possibly returning a new Node in its place.
*
* @param node The Node to visit.
* @param visitor The callback used to visit the Node.
* @param test A callback to execute to verify the Node is valid.
* @param lift An optional callback to execute to lift a NodeArray into a valid Node.
*/
export function visitNode<T extends Node>(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray<Node>) => T): T;
/**
* Visits a Node using the supplied visitor, possibly returning a new Node in its place.
*
* @param node The Node to visit.
* @param visitor The callback used to visit the Node.
* @param test A callback to execute to verify the Node is valid.
* @param lift An optional callback to execute to lift a NodeArray into a valid Node.
*/
export function visitNode<T extends Node>(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray<Node>) => T): T | undefined;
export function visitNode<T extends Node>(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray<Node>) => T): T | undefined {
if (node === undefined || visitor === undefined) {
return node;
}
aggregateTransformFlags(node);
const visited = visitor(node);
if (visited === node) {
return node;
}
let visitedNode: Node | undefined;
if (visited === undefined) {
return undefined;
}
else if (isArray(visited)) {
visitedNode = (lift || extractSingleNode)(visited);
}
else {
visitedNode = visited;
}
Debug.assertNode(visitedNode, test);
aggregateTransformFlags(visitedNode!);
return <T>visitedNode;
}
/**
* Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
*
* @param nodes The NodeArray to visit.
* @param visitor The callback used to visit a Node.
* @param test A node test to execute for each node.
* @param start An optional value indicating the starting offset at which to start visiting.
* @param count An optional value indicating the maximum number of nodes to visit.
*/
export function visitNodes<T extends Node>(nodes: NodeArray<T> | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray<T>;
/**
* Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
*
* @param nodes The NodeArray to visit.
* @param visitor The callback used to visit a Node.
* @param test A node test to execute for each node.
* @param start An optional value indicating the starting offset at which to start visiting.
* @param count An optional value indicating the maximum number of nodes to visit.
*/
export function visitNodes<T extends Node>(nodes: NodeArray<T> | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray<T> | undefined;
/**
* Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
*
* @param nodes The NodeArray to visit.
* @param visitor The callback used to visit a Node.
* @param test A node test to execute for each node.
* @param start An optional value indicating the starting offset at which to start visiting.
* @param count An optional value indicating the maximum number of nodes to visit.
*/
export function visitNodes<T extends Node>(nodes: NodeArray<T> | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray<T> | undefined {
if (nodes === undefined || visitor === undefined) {
return nodes;
}
let updated: MutableNodeArray<T> | undefined;
// Ensure start and count have valid values
const length = nodes.length;
if (start === undefined || start < 0) {
start = 0;
}
if (count === undefined || count > length - start) {
count = length - start;
}
if (start > 0 || count < length) {
// If we are not visiting all of the original nodes, we must always create a new array.
// Since this is a fragment of a node array, we do not copy over the previous location
// and will only copy over `hasTrailingComma` if we are including the last element.
updated = createNodeArray<T>([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
}
// Visit each original node.
for (let i = 0; i < count; i++) {
const node: T = nodes[i + start];
aggregateTransformFlags(node);
const visited = node !== undefined ? visitor(node) : undefined;
if (updated !== undefined || visited === undefined || visited !== node) {
if (updated === undefined) {
// Ensure we have a copy of `nodes`, up to the current index.
updated = createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
setTextRange(updated, nodes);
}
if (visited) {
if (isArray(visited)) {
for (const visitedNode of visited) {
Debug.assertNode(visitedNode, test);
aggregateTransformFlags(visitedNode);
updated.push(<T>visitedNode);
}
}
else {
Debug.assertNode(visited, test);
aggregateTransformFlags(visited);
updated.push(<T>visited);
}
}
}
}
return updated || nodes;
}
/**
* Starts a new lexical environment and visits a statement list, ending the lexical environment
* and merging hoisted declarations upon completion.
*/
export function visitLexicalEnvironment(statements: NodeArray<Statement>, visitor: Visitor, context: TransformationContext, start?: number, ensureUseStrict?: boolean) {
context.startLexicalEnvironment();
statements = visitNodes(statements, visitor, isStatement, start);
if (ensureUseStrict) statements = ts.ensureUseStrict(statements); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier
return mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
}
/**
* Starts a new lexical environment and visits a parameter list, suspending the lexical
* environment upon completion.
*/
export function visitParameterList(nodes: NodeArray<ParameterDeclaration>, visitor: Visitor, context: TransformationContext, nodesVisitor?: <T extends Node>(nodes: NodeArray<T>, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number) => NodeArray<T>): NodeArray<ParameterDeclaration>;
export function visitParameterList(nodes: NodeArray<ParameterDeclaration> | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: <T extends Node>(nodes: NodeArray<T> | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number) => NodeArray<T> | undefined): NodeArray<ParameterDeclaration> | undefined;
export function visitParameterList(nodes: NodeArray<ParameterDeclaration> | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor = visitNodes) {
let updated: NodeArray<ParameterDeclaration> | undefined;
context.startLexicalEnvironment();
if (nodes) {
context.setLexicalEnvironmentFlags(LexicalEnvironmentFlags.InParameters, true);
updated = nodesVisitor(nodes, visitor, isParameterDeclaration);
// As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
// initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
// that we might transform that introduces a temporary variable would fail as the temporary variable
// exists in a different lexical scope. To address this, we move any binding patterns and initializers
// in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
// when the emit target is greater than ES2015.
if (context.getLexicalEnvironmentFlags() & LexicalEnvironmentFlags.VariablesHoistedInParameters &&
getEmitScriptTarget(context.getCompilerOptions()) >= ScriptTarget.ES2015) {
updated = addDefaultValueAssignmentsIfNeeded(updated, context);
}
context.setLexicalEnvironmentFlags(LexicalEnvironmentFlags.InParameters, false);
}
context.suspendLexicalEnvironment();
return updated;
}
function addDefaultValueAssignmentsIfNeeded(parameters: NodeArray<ParameterDeclaration>, context: TransformationContext) {
let result: ParameterDeclaration[] | undefined;
for (let i = 0; i < parameters.length; i++) {
const parameter = parameters[i];
const updated = addDefaultValueAssignmentIfNeeded(parameter, context);
if (result || updated !== parameter) {
if (!result) result = parameters.slice(0, i);
result[i] = updated;
}
}
if (result) {
return setTextRange(createNodeArray(result, parameters.hasTrailingComma), parameters);
}
return parameters;
}
function addDefaultValueAssignmentIfNeeded(parameter: ParameterDeclaration, context: TransformationContext) {
// A rest parameter cannot have a binding pattern or an initializer,
// so let's just ignore it.
return parameter.dotDotDotToken ? parameter :
isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
parameter;
}
function addDefaultValueAssignmentForBindingPattern(parameter: ParameterDeclaration, context: TransformationContext) {
context.addInitializationStatement(
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
parameter.name,
parameter.type,
parameter.initializer ?
createConditional(
createStrictEquality(
getGeneratedNameForNode(parameter),
createVoidZero()
),
parameter.initializer,
getGeneratedNameForNode(parameter)
) :
getGeneratedNameForNode(parameter)
),
])
)
);
return updateParameter(parameter,
parameter.decorators,
parameter.modifiers,
parameter.dotDotDotToken,
getGeneratedNameForNode(parameter),
parameter.questionToken,
parameter.type,
/*initializer*/ undefined);
}
function addDefaultValueAssignmentForInitializer(parameter: ParameterDeclaration, name: Identifier, initializer: Expression, context: TransformationContext) {
context.addInitializationStatement(
createIf(
createTypeCheck(getSynthesizedClone(name), "undefined"),
setEmitFlags(
setTextRange(
createBlock([
createExpressionStatement(
setEmitFlags(
setTextRange(
createAssignment(
setEmitFlags(getMutableClone(name), EmitFlags.NoSourceMap),
setEmitFlags(initializer, EmitFlags.NoSourceMap | getEmitFlags(initializer) | EmitFlags.NoComments)
),
parameter
),
EmitFlags.NoComments
)
)
]),
parameter
),
EmitFlags.SingleLine | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTokenSourceMaps | EmitFlags.NoComments
)
)
);
return updateParameter(parameter,
parameter.decorators,
parameter.modifiers,
parameter.dotDotDotToken,
parameter.name,
parameter.questionToken,
parameter.type,
/*initializer*/ undefined);
}
/**
* Resumes a suspended lexical environment and visits a function body, ending the lexical
* environment and merging hoisted declarations upon completion.
*/
export function visitFunctionBody(node: FunctionBody, visitor: Visitor, context: TransformationContext): FunctionBody;
/**
* Resumes a suspended lexical environment and visits a function body, ending the lexical
* environment and merging hoisted declarations upon completion.
*/
export function visitFunctionBody(node: FunctionBody | undefined, visitor: Visitor, context: TransformationContext): FunctionBody | undefined;
/**
* Resumes a suspended lexical environment and visits a concise body, ending the lexical
* environment and merging hoisted declarations upon completion.
*/
export function visitFunctionBody(node: ConciseBody, visitor: Visitor, context: TransformationContext): ConciseBody;
export function visitFunctionBody(node: ConciseBody | undefined, visitor: Visitor, context: TransformationContext): ConciseBody | undefined {
context.resumeLexicalEnvironment();
const updated = visitNode(node, visitor, isConciseBody);
const declarations = context.endLexicalEnvironment();
if (some(declarations)) {
const block = convertToFunctionBody(updated);
const statements = mergeLexicalEnvironment(block.statements, declarations);
return updateBlock(block, statements);
}
return updated;
}
/**
* Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place.
*
* @param node The Node whose children will be visited.
* @param visitor The callback used to visit each child.
* @param context A lexical environment context for the visitor.
*/
export function visitEachChild<T extends Node>(node: T, visitor: Visitor, context: TransformationContext): T;
/**
* Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place.
*
* @param node The Node whose children will be visited.
* @param visitor The callback used to visit each child.
* @param context A lexical environment context for the visitor.
*/
export function visitEachChild<T extends Node>(node: T | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes, tokenVisitor?: Visitor): T | undefined;
export function visitEachChild(node: Node | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor = visitNodes, tokenVisitor?: Visitor): Node | undefined {
if (node === undefined) {
return undefined;
}
const kind = node.kind;
// No need to visit nodes with no children.
if ((kind > SyntaxKind.FirstToken && kind <= SyntaxKind.LastToken) || kind === SyntaxKind.ThisType) {
return node;
}
switch (kind) {
// Names
case SyntaxKind.Identifier:
return updateIdentifier(<Identifier>node, nodesVisitor((<Identifier>node).typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
case SyntaxKind.QualifiedName:
return updateQualifiedName(<QualifiedName>node,
visitNode((<QualifiedName>node).left, visitor, isEntityName),
visitNode((<QualifiedName>node).right, visitor, isIdentifier));
case SyntaxKind.ComputedPropertyName:
return updateComputedPropertyName(<ComputedPropertyName>node,
visitNode((<ComputedPropertyName>node).expression, visitor, isExpression));
// Signature elements
case SyntaxKind.TypeParameter:
return updateTypeParameterDeclaration(<TypeParameterDeclaration>node,
visitNode((<TypeParameterDeclaration>node).name, visitor, isIdentifier),
visitNode((<TypeParameterDeclaration>node).constraint, visitor, isTypeNode),
visitNode((<TypeParameterDeclaration>node).default, visitor, isTypeNode));
case SyntaxKind.Parameter:
return updateParameter(<ParameterDeclaration>node,
nodesVisitor((<ParameterDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<ParameterDeclaration>node).modifiers, visitor, isModifier),
visitNode((<ParameterDeclaration>node).dotDotDotToken, tokenVisitor, isToken),
visitNode((<ParameterDeclaration>node).name, visitor, isBindingName),
visitNode((<ParameterDeclaration>node).questionToken, tokenVisitor, isToken),
visitNode((<ParameterDeclaration>node).type, visitor, isTypeNode),
visitNode((<ParameterDeclaration>node).initializer, visitor, isExpression));
case SyntaxKind.Decorator:
return updateDecorator(<Decorator>node,
visitNode((<Decorator>node).expression, visitor, isExpression));
// Type elements
case SyntaxKind.PropertySignature:
return updatePropertySignature((<PropertySignature>node),
nodesVisitor((<PropertySignature>node).modifiers, visitor, isToken),
visitNode((<PropertySignature>node).name, visitor, isPropertyName),
visitNode((<PropertySignature>node).questionToken, tokenVisitor, isToken),
visitNode((<PropertySignature>node).type, visitor, isTypeNode),
visitNode((<PropertySignature>node).initializer, visitor, isExpression));
case SyntaxKind.PropertyDeclaration:
return updateProperty(<PropertyDeclaration>node,
nodesVisitor((<PropertyDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<PropertyDeclaration>node).modifiers, visitor, isModifier),
visitNode((<PropertyDeclaration>node).name, visitor, isPropertyName),
// QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
visitNode((<PropertyDeclaration>node).questionToken || (<PropertyDeclaration>node).exclamationToken, tokenVisitor, isToken),
visitNode((<PropertyDeclaration>node).type, visitor, isTypeNode),
visitNode((<PropertyDeclaration>node).initializer, visitor, isExpression));
case SyntaxKind.MethodSignature:
return updateMethodSignature(<MethodSignature>node,
nodesVisitor((<MethodSignature>node).typeParameters, visitor, isTypeParameterDeclaration),
nodesVisitor((<MethodSignature>node).parameters, visitor, isParameterDeclaration),
visitNode((<MethodSignature>node).type, visitor, isTypeNode),
visitNode((<MethodSignature>node).name, visitor, isPropertyName),
visitNode((<MethodSignature>node).questionToken, tokenVisitor, isToken));
case SyntaxKind.MethodDeclaration:
return updateMethod(<MethodDeclaration>node,
nodesVisitor((<MethodDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<MethodDeclaration>node).modifiers, visitor, isModifier),
visitNode((<MethodDeclaration>node).asteriskToken, tokenVisitor, isToken),
visitNode((<MethodDeclaration>node).name, visitor, isPropertyName),
visitNode((<MethodDeclaration>node).questionToken, tokenVisitor, isToken),
nodesVisitor((<MethodDeclaration>node).typeParameters, visitor, isTypeParameterDeclaration),
visitParameterList((<MethodDeclaration>node).parameters, visitor, context, nodesVisitor),
visitNode((<MethodDeclaration>node).type, visitor, isTypeNode),
visitFunctionBody((<MethodDeclaration>node).body!, visitor, context));
case SyntaxKind.Constructor:
return updateConstructor(<ConstructorDeclaration>node,
nodesVisitor((<ConstructorDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<ConstructorDeclaration>node).modifiers, visitor, isModifier),
visitParameterList((<ConstructorDeclaration>node).parameters, visitor, context, nodesVisitor),
visitFunctionBody((<ConstructorDeclaration>node).body!, visitor, context));
case SyntaxKind.GetAccessor:
return updateGetAccessor(<GetAccessorDeclaration>node,
nodesVisitor((<GetAccessorDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<GetAccessorDeclaration>node).modifiers, visitor, isModifier),
visitNode((<GetAccessorDeclaration>node).name, visitor, isPropertyName),
visitParameterList((<GetAccessorDeclaration>node).parameters, visitor, context, nodesVisitor),
visitNode((<GetAccessorDeclaration>node).type, visitor, isTypeNode),
visitFunctionBody((<GetAccessorDeclaration>node).body!, visitor, context));
case SyntaxKind.SetAccessor:
return updateSetAccessor(<SetAccessorDeclaration>node,
nodesVisitor((<SetAccessorDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<SetAccessorDeclaration>node).modifiers, visitor, isModifier),
visitNode((<SetAccessorDeclaration>node).name, visitor, isPropertyName),
visitParameterList((<SetAccessorDeclaration>node).parameters, visitor, context, nodesVisitor),
visitFunctionBody((<SetAccessorDeclaration>node).body!, visitor, context));
case SyntaxKind.CallSignature:
return updateCallSignature(<CallSignatureDeclaration>node,
nodesVisitor((<CallSignatureDeclaration>node).typeParameters, visitor, isTypeParameterDeclaration),
nodesVisitor((<CallSignatureDeclaration>node).parameters, visitor, isParameterDeclaration),
visitNode((<CallSignatureDeclaration>node).type, visitor, isTypeNode));
case SyntaxKind.ConstructSignature:
return updateConstructSignature(<ConstructSignatureDeclaration>node,
nodesVisitor((<ConstructSignatureDeclaration>node).typeParameters, visitor, isTypeParameterDeclaration),
nodesVisitor((<ConstructSignatureDeclaration>node).parameters, visitor, isParameterDeclaration),
visitNode((<ConstructSignatureDeclaration>node).type, visitor, isTypeNode));
case SyntaxKind.IndexSignature:
return updateIndexSignature(<IndexSignatureDeclaration>node,
nodesVisitor((<IndexSignatureDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<IndexSignatureDeclaration>node).modifiers, visitor, isModifier),
nodesVisitor((<IndexSignatureDeclaration>node).parameters, visitor, isParameterDeclaration),
visitNode((<IndexSignatureDeclaration>node).type, visitor, isTypeNode));
// Types
case SyntaxKind.TypePredicate:
return updateTypePredicateNodeWithModifier(<TypePredicateNode>node,
visitNode((<TypePredicateNode>node).assertsModifier, visitor),
visitNode((<TypePredicateNode>node).parameterName, visitor),
visitNode((<TypePredicateNode>node).type, visitor, isTypeNode));
case SyntaxKind.TypeReference:
return updateTypeReferenceNode(<TypeReferenceNode>node,
visitNode((<TypeReferenceNode>node).typeName, visitor, isEntityName),
nodesVisitor((<TypeReferenceNode>node).typeArguments, visitor, isTypeNode));
case SyntaxKind.FunctionType:
return updateFunctionTypeNode(<FunctionTypeNode>node,
nodesVisitor((<FunctionTypeNode>node).typeParameters, visitor, isTypeParameterDeclaration),
nodesVisitor((<FunctionTypeNode>node).parameters, visitor, isParameterDeclaration),
visitNode((<FunctionTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.ConstructorType:
return updateConstructorTypeNode(<ConstructorTypeNode>node,
nodesVisitor((<ConstructorTypeNode>node).typeParameters, visitor, isTypeParameterDeclaration),
nodesVisitor((<ConstructorTypeNode>node).parameters, visitor, isParameterDeclaration),
visitNode((<ConstructorTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.TypeQuery:
return updateTypeQueryNode((<TypeQueryNode>node),
visitNode((<TypeQueryNode>node).exprName, visitor, isEntityName));
case SyntaxKind.TypeLiteral:
return updateTypeLiteralNode((<TypeLiteralNode>node),
nodesVisitor((<TypeLiteralNode>node).members, visitor, isTypeElement));
case SyntaxKind.ArrayType:
return updateArrayTypeNode(<ArrayTypeNode>node,
visitNode((<ArrayTypeNode>node).elementType, visitor, isTypeNode));
case SyntaxKind.TupleType:
return updateTupleTypeNode((<TupleTypeNode>node),
nodesVisitor((<TupleTypeNode>node).elements, visitor, isTypeNode));
case SyntaxKind.OptionalType:
return updateOptionalTypeNode((<OptionalTypeNode>node),
visitNode((<OptionalTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.RestType:
return updateRestTypeNode((<RestTypeNode>node),
visitNode((<RestTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.UnionType:
return updateUnionTypeNode(<UnionTypeNode>node,
nodesVisitor((<UnionTypeNode>node).types, visitor, isTypeNode));
case SyntaxKind.IntersectionType:
return updateIntersectionTypeNode(<IntersectionTypeNode>node,
nodesVisitor((<IntersectionTypeNode>node).types, visitor, isTypeNode));
case SyntaxKind.ConditionalType:
return updateConditionalTypeNode(<ConditionalTypeNode>node,
visitNode((<ConditionalTypeNode>node).checkType, visitor, isTypeNode),
visitNode((<ConditionalTypeNode>node).extendsType, visitor, isTypeNode),
visitNode((<ConditionalTypeNode>node).trueType, visitor, isTypeNode),
visitNode((<ConditionalTypeNode>node).falseType, visitor, isTypeNode));
case SyntaxKind.InferType:
return updateInferTypeNode(<InferTypeNode>node,
visitNode((<InferTypeNode>node).typeParameter, visitor, isTypeParameterDeclaration));
case SyntaxKind.ImportType:
return updateImportTypeNode(<ImportTypeNode>node,
visitNode((<ImportTypeNode>node).argument, visitor, isTypeNode),
visitNode((<ImportTypeNode>node).qualifier, visitor, isEntityName),
visitNodes((<ImportTypeNode>node).typeArguments, visitor, isTypeNode),
(<ImportTypeNode>node).isTypeOf
);
case SyntaxKind.NamedTupleMember:
return updateNamedTupleMember(<NamedTupleMember>node,
visitNode((<NamedTupleMember>node).dotDotDotToken, visitor, isToken),
visitNode((<NamedTupleMember>node).name, visitor, isIdentifier),
visitNode((<NamedTupleMember>node).questionToken, visitor, isToken),
visitNode((<NamedTupleMember>node).type, visitor, isTypeNode),
);
case SyntaxKind.ParenthesizedType:
return updateParenthesizedType(<ParenthesizedTypeNode>node,
visitNode((<ParenthesizedTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.TypeOperator:
return updateTypeOperatorNode(<TypeOperatorNode>node,
visitNode((<TypeOperatorNode>node).type, visitor, isTypeNode));
case SyntaxKind.IndexedAccessType:
return updateIndexedAccessTypeNode((<IndexedAccessTypeNode>node),
visitNode((<IndexedAccessTypeNode>node).objectType, visitor, isTypeNode),
visitNode((<IndexedAccessTypeNode>node).indexType, visitor, isTypeNode));
case SyntaxKind.MappedType:
return updateMappedTypeNode((<MappedTypeNode>node),
visitNode((<MappedTypeNode>node).readonlyToken, tokenVisitor, isToken),
visitNode((<MappedTypeNode>node).typeParameter, visitor, isTypeParameterDeclaration),
visitNode((<MappedTypeNode>node).questionToken, tokenVisitor, isToken),
visitNode((<MappedTypeNode>node).type, visitor, isTypeNode));
case SyntaxKind.LiteralType:
return updateLiteralTypeNode(<LiteralTypeNode>node,
visitNode((<LiteralTypeNode>node).literal, visitor, isExpression));
// Binding patterns
case SyntaxKind.ObjectBindingPattern:
return updateObjectBindingPattern(<ObjectBindingPattern>node,
nodesVisitor((<ObjectBindingPattern>node).elements, visitor, isBindingElement));
case SyntaxKind.ArrayBindingPattern:
return updateArrayBindingPattern(<ArrayBindingPattern>node,
nodesVisitor((<ArrayBindingPattern>node).elements, visitor, isArrayBindingElement));
case SyntaxKind.BindingElement:
return updateBindingElement(<BindingElement>node,
visitNode((<BindingElement>node).dotDotDotToken, tokenVisitor, isToken),
visitNode((<BindingElement>node).propertyName, visitor, isPropertyName),
visitNode((<BindingElement>node).name, visitor, isBindingName),
visitNode((<BindingElement>node).initializer, visitor, isExpression));
// Expression
case SyntaxKind.ArrayLiteralExpression:
return updateArrayLiteral(<ArrayLiteralExpression>node,
nodesVisitor((<ArrayLiteralExpression>node).elements, visitor, isExpression));
case SyntaxKind.ObjectLiteralExpression:
return updateObjectLiteral(<ObjectLiteralExpression>node,
nodesVisitor((<ObjectLiteralExpression>node).properties, visitor, isObjectLiteralElementLike));
case SyntaxKind.PropertyAccessExpression:
if (node.flags & NodeFlags.OptionalChain) {
return updatePropertyAccessChain(<PropertyAccessChain>node,
visitNode((<PropertyAccessChain>node).expression, visitor, isExpression),
visitNode((<PropertyAccessChain>node).questionDotToken, tokenVisitor, isToken),
visitNode((<PropertyAccessChain>node).name, visitor, isIdentifier));
}
return updatePropertyAccess(<PropertyAccessExpression>node,
visitNode((<PropertyAccessExpression>node).expression, visitor, isExpression),
Private named instance fields (#30829) * Fix display of private names in language server Signed-off-by: Joseph Watts <jwatts43@bloomberg.net> Signed-off-by: Max Heiber <max.heiber@gmail.com> * Parse private names Signed-off-by: Max Heiber <max.heiber@gmail.com> * update parser error recovery tests to use ¬ not # The intent of the tests seemed to be to regiment the behavior of the parser when a weird symbol is encountered. The `#` is now taken by private identifiers, so `¬` seems like a good new choice for keeping the diff small, since it also fits in 16 bits (wide emojis would be treated as multiple characters, since the scanner uses ++). Signed-off-by: Max Heiber <max.heiber@gmail.com> * Private Name Support in the Checker (#5) - [x] treat private names as unique: - case 1: cannot say that a variable is of a class type unless the variable points to an instance of the class - see [test](https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNamesUnique.ts) - case 2: private names in class hierarchies do not conflict - see [test](https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNamesNoConflictWhenInheriting.ts) - [x] `#constructor` is reserved - see [test](https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNameConstructorReserved.ts) - check in `bindWorker`, where every node is visited - [x] Accessibility modifiers can't be used with private names - see [test](https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNamesNoAccessibilityModifiers.ts) - implemented in `checkAccessibilityModifiers`, using `ModifierFlags.AccessibilityModifier` - [x] `delete #foo` not allowed - [x] Private name accesses not allowed outside of the defining class - see test: https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNameNotAccessibleOutsideDefiningClass.ts - see [test](https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNamesNoDelete.ts) - implemented in `checkDeleteExpression` - [x] Do [the right thing](https://gist.github.com/mheiber/b6fc7adb426c2e1cdaceb5d7786fc630) for nested classes mv private name tests together more checker tests for private names update naming and cleanup for check private names for private name support in the checker: - make names more consistent - remove unnecessary checks - add utility function to public API - other small cleanup Move getPropertyNameForUniqueESSymbol to utility for consistency with other calculation of special property names (starting with __), move the calculation of property names for unique es symbols to `utilities.ts`. private name tests strict+es6 Update private name tests to use 'strict' type checking and to target es6 instead of default. Makes the js output easier to read and tests more surface area with other checker features. error message for private names in obj literals Disallow decorating private-named properties because the spec is still in flux. Signed-off-by: Max Heiber <max.heiber@gmail.com> * Add private instance field transformation, pr feedback Implements private instance fields on top of the class properties refactor. This commit also includes incorporation of PR feedback on the checker, parser, and transformer in order to make the rebase manageable. Co-Authored-By: Max Heiber <max.heiber@gmail.com> Co-Authored-By: Ron Buckton <ron.buckton@microsoft.com> Signed-off-by: Joey Watts <jwatts43@bloomberg.net> Signed-off-by: Max Heiber <max.heiber@gmail.com> Incorporate PR feedback Fix checker crash with new block scoped bindings Add classExpressionInLoop test Update baselines for private name errors Apply suggestions from code review Fix privateNameFieldCallExpression test Remove unnecessary comment Fix PropertyAccessEntityNameExpression type Remove PrivateName from PropertyNameLiteral Add createPrivateName Remove PrivateName type from textSourceNode Add Debug asserts for invalid syntax kinds Don't output private name syntax when undeclared Make PrivateName extend Node Update baselines for public API Fix completions in language server Fix fourslash test crash intern private name descriptions undo expensive node.name.parent assignment Back the way things were on `master`: only assign node.name.parent when we need to Add tests for private names and JSDoc Patch hoverOverPrivateName fourslash test Fix goToDefinition for private-named fields remove Debug.fail for private name outside class Remove Debug.fail in binder.ts::`getDeclarationName`. It turns out this code path *does* get hit (intentionally). For best error messages, return `undefined` and rely on the parser generating a good error message "Private names are not allowed outside class bodies" Add rbuckton test cases for private names These test cases specifically exercise where we needed to use name-mangling. They are cases where private names have the same description. - private names no conflict when inheriting - private names distinct even when the two classes have the same name check dup instance+static private identifiers class A { #foo; static #foo; } not allowed because static and private names share the same lexical scope https://tc39.es/proposal-class-fields/#prod-ClassBody refactor getPropertyForPrivateName, rel spans refactor getPropertyForPrivateName so it is easier to read (use findAncestor instead of loop). Fix bugs in getPropertyForPrivateName: - make it work with deeply-nested classes with and without shadowing - make it catch shadowing when the conflict is between static and instance private name descriptions (these can actually clash) And add related spans to diagnostics for getPropertyForPrivateName catch conflicts between static and instance private identifiers: - cannot have an instance and static private identifier with the same spelling, as there is only one namespace for private names rename 'PrivateName' to 'PrivateIdentifier' to match the change of wording in the spec prposal: https://tc39.es/proposal-class-fields/#sec-syntax The rename in the spec was to avoid confusion between the AST Node PrivateIdentifier and the internal spec type PrivateName. So one uses the [[Description]] of a PrivateIdentifier to look up the PrivateName for a given scope. This corresponds closely to our implementation in the binder and checker: - we mangle PrivateIdentifier.escapedText to get a `key` which we use to get the symbol for a property f getLiteralTypeFromProperty-check privateIdentifier rename and simplify privateNameAndAny test case make it clearer that all this test is showing is that we allow accessing arbitrary private identifiers on `any`. Note: we could have something more sound here by checking that there is a private-named field declaration in a class scope above the property access. Discussion: https://github.com/microsoft/TypeScript/pull/30829/files#r302760015 Fix typo in checker s/identifer/identifier remove accidental change patch fourslash test broken by isPrivateIdentifier just needed to add a check to see if the symbol .name is defined extract reportUnmatchedProperty per @nsandersn feedback propertiesRelatedTo was getting to long pull out the unmatchedProperty reporting into a seprate function fix typo in private names test Fix type soundness with private names Remove PrivateIdentifier from emit with Expr hint Fixup helpers and set function name for privates remove accidentally-committed baselines These baselines somehow ended up in this pr, though they have nothing to do with the changes Revert "getLiteralTypeFromProperty-check privateIdentifier" This reverts commit bd1155c300bc3517a0543580f4790268f86e473f. reason: the check for isIdentifier in getLiteralTypeFromProperty is superfluous because we do this check in getLiteralTypeFromPropertyName Update comment in private name uniqueness test 3 I think the comments were not accurate and that we export the error on `this.#x = child.#x` because: - private names are lexically scoped: the code in question is not in a lexical scope under the definition of Child's #x. - private names are private to their containing class: never inherited This expected behavior matches that of Chrome Canary and my understanding of the spec test private names use before def, circular ref test private names use before def, circular ref update diagnosticMessages s/delete/'delete' per @DanielRosenwasser and @sandersn guidance, use this style in diagnostic messages: "operand of a 'delete' operator" (single quotes) rather than old style: "operand of a delete operator" (single quotes) This is for consistency, as we use the new style in the privateIdentifiers error messages and it is consistent with our messages about other operators incorporate private names early exit feedback and code style change to use a ternary instead of if so we can 'const' require private-named fields to be declared in JS All fields must be declared in TS files. In JS files, we typically do not have this requirement. So special-case private fields, which must always be declared (even in JS files, per spec) update debug failure for es2015 private identifier Co-Authored-By: Ron Buckton <ron.buckton@microsoft.com> fix checker handling of private name in subclasse update checker and tests to account for the following ts features: - private names do not participate in the prototype chain, but *are* assigned in the parent class' constructor. So parent can access its *own* private fields on instances of the subclass Add more tests for private-named fields in JS add test to hit symbolToExpression w private names symbolToExpression knows about private names add a test to exercise this code path ban private-named static methods (not supported yet) ban private-named methods (not supported yet) ban private-named accessors (not supported yet) fix privateIdentifier fourslash test change assertion throw to return Co-Authored-By: Ron Buckton <ron.buckton@microsoft.com> Update comment in checker.ts re reserved members Remove case for privateIdentifier in EntityNameExpr Remove case for privateIdentifier in EntityNameExpr. That code path is never hit, and privateIdnetifiers cannot be entity names. remove unnecessary parentheses Ban private identifier in enum As the new test, 'privateNameEnumNoEmit', shows, the checker now correctly makes a diagnostic for private identifiers in enums. However, when noEmit is false we hit this assertion in the transformer. This assertion will have to be removed so that we have a diagnostic here instead of an assertion error. When the assertion is removed, the 'privateNameEnum' baseline will have to be updated Fix destructuring assignment, use createCallBinding, remove unneeded helper Add class private field helpers to external helpers Remove private identifier enum assertion, use missing identifiers Fix hash map inefficiency by only using get Update baselines with empty identifier change Add privateNameEnum test baselines Fix private identifier destructuring (array assignment defaults, unique names) Use createPrivateIdentifierAssignment in destructuring transform Fix lint error Separate destructuring target visitor from regular visitor Fix destructuring assignment with this bindings Fix destructuring assignment with this bindings Fix syntax error with destructuring assignment output Disallow private identifiers in property signatures remove duplicate test baselines Add tests for undeclarated private identifiers remove unnecessary cast Nicer error message for mis-placed hashbang Workaround v8 bug with destructured assignments Optimize private identifier stack lookup Avoid the cost of performing an array lookup to look at the top of the private identifier environment stack. Change function name to be more specific Changes "getOperatorForCompoundAssignment" to "getNonAssignmentOperatorForCompoundAssignment" now that this function is accessible to the entire compiler. Improve test case for private name assignment Adds a compound assignment test case for a class with private names being declared on the left-hand-side of the assignment expression. Remove extra non-private-field test Remove isPrivateIdentifierAssignmentExpression helper Don't transform private names in ESNext target Preserve private fields initialized to functions Move function expressions to outer scope for efficiency Add WeakMap collision check Modify potential WeakMap collision condition Fix this property assignment binding with private names Add correct error message for WeakMap collision Add error for statements before super with private identifiers Refactor getPropertyForPrivateIdentifier Add test for private identifier fields initialized to class exprs Fix shebang errors Fix private errors on index signatures Add codefix for missing private property Update error messages for unsupported private features Fix inheritance-related errors Fixes inheritance-related errors with private identifiers by resolving properties from base classes. Private identifiers do not show up as properties on a union type, so those do not type-check. Add test for interface extending class with private access Remove debugging log Remove name assignment from private named functions Rename to getPrivateIdentifierPropertyOfType Fix index signature test comment Fix test target syntax error Change error messages patch private identifiers outside class bodies Add test for private identifier with ooo super Add test for a class with a private identifier with a non-preambly (for example, not a comment) statement before 'super': should error, saying 'super' must come first Fix nits incorporate PR feedback Incorporate checker feedback - reorganize if statements in checkFunctionOrConstructorSymbol - remove overload for getPrivateIdentifierPropertyOfType reorganize if statements in checkFunctionOrConstructorSymbol test for private names with JSX use getPropertyOftype in getPropertyForPrivateIdentifier getPrivateIdentifierPropertyOfType error on synthetic make getPrivateIdentifierPropertyOfType error if given a node that is not from the parse tree Simplify checkPrivateIdentifierPropertyAccess use getPropertiesOfType instead of rehashing that logic test for private identifiers w decl merging fix test target for privateNameDeclarationMerging update baselines Fix private identifier ++/-- numeric coercion Remove 'downleveled' from super error Fix bad comments in helper call emit Error on private identifiers in JSX tag names Add more private identifier tests Add es2015 target for private name destructured binding test Add privateNameConstructorSignature test Add test for navigation bar w private identifier Remove spurious line from test // in js file class A { exports.#foo = 3; // should error } The above line failed to produce an error when run using the test harness. When using tsc or the language server, we got the expected error message. Removing the troublesome line, as it seems to say more about the test runner than about the code it is testing. Fix inefficient constructor generation dts: don't emit type for private-identified field Do not emit types for private-identified fields when generating declaration files. // example.ts export class A { #foo: number; } // example.d.ts export declare class A { #foo; } **This is not ideal!** The following would be better: // example.d.ts export declare unique class A { #foo; } See discussion: https://github.com/microsoft/TypeScript/pull/33038#issuecomment-530321165 notice when private-identified field unused Notice when private-identified fields are unused, and implement the same behavior as for unused private-modified fields. This is used in the language server to make things grayed out. This case generates an error when --noUnusedLocals flag is passed to tsc: - "<name> is declared but never used" accept baselines Revert "dts: don't emit type for private-identified field" This reverts commit e50305df5fb88121486291abad14478f5339a455. Instead of just excluding the type from private identifier emit, only emit a single private identifier per class. This accomplishes nominality while hiding implementation detail that is irrelevant to .d.ts consumers only emit a single private identifier in dts In dts emit, emit at most one private identifier, and rename it to `#private`. refactor getPrivateIdentifierPropertyOfType - safer check for wehther is parse tree node - return undefined when not found (instead of a Debug.fail) Incorporate PR feedback Don't rely on parent pointers in transform Passes context about whether the postfix unary expression value is discarded down the tree into the visitPostfixUnaryExpression function. Remove orphaned test baseline files remove unreachable if Check `any`-typed private identified fields Update private identifier incompatible modifier checks - disallow 'abstract' with private identifiers - s/private-named-property/private identifier Add additional call expression test cases Fix disallow 'abstract' with private identifier Static private identifiers not inherited Including this in the PR for private instance fields even though static private identifiers are banned. Reason: this change improves quality of error messages, see test case. Thanks Ron! Simplifiy private identifier 'any' type handling Error on private identifier declarations for ES5/ES3 Bind `this` for private identifier property tagged template literals Fix target for jsdocPrivateName1 test Update getPrivateIdentifierPropertyOfType API Make it easier to use by accepting a string and location, rather than a PrivateIdentifier. Thanks Ron! remove orphaned tests rename test remove duplicate tests Remove unrelated error from test update diagnostic message 'private identifier' The nodes for hash private fields are now called 'private identifier'. Update one last diagnostic message to use the new terminology. refine solution for static private identifier fields - use `continue` instead of `filter` for perf - better naming - make it clear the current solution will need to be altered when we lift the ban on static private identifier fields, including a test case that should change in the future Fix display of private identifiers in lang server Fix bug where private identifiers in completion tooltips in the playground were showing up as the symbol table entries (with underscores and such). https://github.com/microsoft/TypeScript/pull/30829#issuecomment-534157560 Signed-off-by: Max Heiber <max.heiber@gmail.com> * fix privateIdentifier w !useDefineForClassFields Signed-off-by: Max Heiber <max.heiber@gmail.com> * Disallow PrivateIdentifier in Optional Chains Signed-off-by: Max Heiber <max.heiber@gmail.com> * restrict privateIdentifier completions correctly Don't autocomplete privateIdentifiers in places where they are not allowed. Signed-off-by: Max Heiber <max.heiber@gmail.com> * make PrivateIdentifier not a PropertyNameLiteral Signed-off-by: Max Heiber <max.heiber@gmail.com> * Added test. * Accepted baselines. * Update symbol serializer to understand private fields in JS `.d.ts` emit. * Accepted baselines. * fix for private field no initializer esnext Signed-off-by: Max Heiber <max.heiber@gmail.com> * fix private fields .d.ts emit for JS w expando fix bug where the following in a JS file would lead to a `#private` in the .d.ts: ```js class C { constructor () { this.a = 3 } } ``` Co-authored-by: Joey Watts <joey.watts.96@gmail.com> Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2019-12-27 22:07:35 +01:00
visitNode((<PropertyAccessExpression>node).name, visitor, isIdentifierOrPrivateIdentifier));
case SyntaxKind.ElementAccessExpression:
if (node.flags & NodeFlags.OptionalChain) {
return updateElementAccessChain(<ElementAccessChain>node,
visitNode((<ElementAccessChain>node).expression, visitor, isExpression),
visitNode((<ElementAccessChain>node).questionDotToken, tokenVisitor, isToken),
visitNode((<ElementAccessChain>node).argumentExpression, visitor, isExpression));
}
return updateElementAccess(<ElementAccessExpression>node,
visitNode((<ElementAccessExpression>node).expression, visitor, isExpression),
visitNode((<ElementAccessExpression>node).argumentExpression, visitor, isExpression));
case SyntaxKind.CallExpression:
if (node.flags & NodeFlags.OptionalChain) {
return updateCallChain(<CallChain>node,
visitNode((<CallChain>node).expression, visitor, isExpression),
visitNode((<CallChain>node).questionDotToken, tokenVisitor, isToken),
nodesVisitor((<CallChain>node).typeArguments, visitor, isTypeNode),
nodesVisitor((<CallChain>node).arguments, visitor, isExpression));
}
return updateCall(<CallExpression>node,
visitNode((<CallExpression>node).expression, visitor, isExpression),
nodesVisitor((<CallExpression>node).typeArguments, visitor, isTypeNode),
nodesVisitor((<CallExpression>node).arguments, visitor, isExpression));
case SyntaxKind.NewExpression:
return updateNew(<NewExpression>node,
visitNode((<NewExpression>node).expression, visitor, isExpression),
nodesVisitor((<NewExpression>node).typeArguments, visitor, isTypeNode),
nodesVisitor((<NewExpression>node).arguments, visitor, isExpression));
case SyntaxKind.TaggedTemplateExpression:
return updateTaggedTemplate(<TaggedTemplateExpression>node,
visitNode((<TaggedTemplateExpression>node).tag, visitor, isExpression),
visitNodes((<TaggedTemplateExpression>node).typeArguments, visitor, isExpression),
visitNode((<TaggedTemplateExpression>node).template, visitor, isTemplateLiteral));
case SyntaxKind.TypeAssertionExpression:
return updateTypeAssertion(<TypeAssertion>node,
visitNode((<TypeAssertion>node).type, visitor, isTypeNode),
visitNode((<TypeAssertion>node).expression, visitor, isExpression));
case SyntaxKind.ParenthesizedExpression:
return updateParen(<ParenthesizedExpression>node,
visitNode((<ParenthesizedExpression>node).expression, visitor, isExpression));
case SyntaxKind.FunctionExpression:
return updateFunctionExpression(<FunctionExpression>node,
nodesVisitor((<FunctionExpression>node).modifiers, visitor, isModifier),
visitNode((<FunctionExpression>node).asteriskToken, tokenVisitor, isToken),
visitNode((<FunctionExpression>node).name, visitor, isIdentifier),
nodesVisitor((<FunctionExpression>node).typeParameters, visitor, isTypeParameterDeclaration),
visitParameterList((<FunctionExpression>node).parameters, visitor, context, nodesVisitor),
visitNode((<FunctionExpression>node).type, visitor, isTypeNode),
visitFunctionBody((<FunctionExpression>node).body, visitor, context));
case SyntaxKind.ArrowFunction:
return updateArrowFunction(<ArrowFunction>node,
nodesVisitor((<ArrowFunction>node).modifiers, visitor, isModifier),
nodesVisitor((<ArrowFunction>node).typeParameters, visitor, isTypeParameterDeclaration),
visitParameterList((<ArrowFunction>node).parameters, visitor, context, nodesVisitor),
visitNode((<ArrowFunction>node).type, visitor, isTypeNode),
visitNode((<ArrowFunction>node).equalsGreaterThanToken, tokenVisitor, isToken),
visitFunctionBody((<ArrowFunction>node).body, visitor, context));
case SyntaxKind.DeleteExpression:
return updateDelete(<DeleteExpression>node,
visitNode((<DeleteExpression>node).expression, visitor, isExpression));
case SyntaxKind.TypeOfExpression:
return updateTypeOf(<TypeOfExpression>node,
visitNode((<TypeOfExpression>node).expression, visitor, isExpression));
case SyntaxKind.VoidExpression:
return updateVoid(<VoidExpression>node,
visitNode((<VoidExpression>node).expression, visitor, isExpression));
case SyntaxKind.AwaitExpression:
return updateAwait(<AwaitExpression>node,
visitNode((<AwaitExpression>node).expression, visitor, isExpression));
case SyntaxKind.PrefixUnaryExpression:
return updatePrefix(<PrefixUnaryExpression>node,
visitNode((<PrefixUnaryExpression>node).operand, visitor, isExpression));
case SyntaxKind.PostfixUnaryExpression:
return updatePostfix(<PostfixUnaryExpression>node,
visitNode((<PostfixUnaryExpression>node).operand, visitor, isExpression));
case SyntaxKind.BinaryExpression:
return updateBinary(<BinaryExpression>node,
visitNode((<BinaryExpression>node).left, visitor, isExpression),
visitNode((<BinaryExpression>node).right, visitor, isExpression),
visitNode((<BinaryExpression>node).operatorToken, tokenVisitor, isToken));
case SyntaxKind.ConditionalExpression:
return updateConditional(<ConditionalExpression>node,
visitNode((<ConditionalExpression>node).condition, visitor, isExpression),
visitNode((<ConditionalExpression>node).questionToken, tokenVisitor, isToken),
visitNode((<ConditionalExpression>node).whenTrue, visitor, isExpression),
visitNode((<ConditionalExpression>node).colonToken, tokenVisitor, isToken),
visitNode((<ConditionalExpression>node).whenFalse, visitor, isExpression));
case SyntaxKind.TemplateExpression:
return updateTemplateExpression(<TemplateExpression>node,
visitNode((<TemplateExpression>node).head, visitor, isTemplateHead),
nodesVisitor((<TemplateExpression>node).templateSpans, visitor, isTemplateSpan));
case SyntaxKind.YieldExpression:
return updateYield(<YieldExpression>node,
visitNode((<YieldExpression>node).asteriskToken, tokenVisitor, isToken),
visitNode((<YieldExpression>node).expression, visitor, isExpression));
case SyntaxKind.SpreadElement:
return updateSpread(<SpreadElement>node,
visitNode((<SpreadElement>node).expression, visitor, isExpression));
case SyntaxKind.ClassExpression:
return updateClassExpression(<ClassExpression>node,
nodesVisitor((<ClassExpression>node).modifiers, visitor, isModifier),
visitNode((<ClassExpression>node).name, visitor, isIdentifier),
nodesVisitor((<ClassExpression>node).typeParameters, visitor, isTypeParameterDeclaration),
nodesVisitor((<ClassExpression>node).heritageClauses, visitor, isHeritageClause),
nodesVisitor((<ClassExpression>node).members, visitor, isClassElement));
case SyntaxKind.ExpressionWithTypeArguments:
return updateExpressionWithTypeArguments(<ExpressionWithTypeArguments>node,
nodesVisitor((<ExpressionWithTypeArguments>node).typeArguments, visitor, isTypeNode),
visitNode((<ExpressionWithTypeArguments>node).expression, visitor, isExpression));
case SyntaxKind.AsExpression:
return updateAsExpression(<AsExpression>node,
visitNode((<AsExpression>node).expression, visitor, isExpression),
visitNode((<AsExpression>node).type, visitor, isTypeNode));
case SyntaxKind.NonNullExpression:
return updateNonNullExpression(<NonNullExpression>node,
visitNode((<NonNullExpression>node).expression, visitor, isExpression));
case SyntaxKind.MetaProperty:
return updateMetaProperty(<MetaProperty>node,
visitNode((<MetaProperty>node).name, visitor, isIdentifier));
// Misc
case SyntaxKind.TemplateSpan:
return updateTemplateSpan(<TemplateSpan>node,
visitNode((<TemplateSpan>node).expression, visitor, isExpression),
visitNode((<TemplateSpan>node).literal, visitor, isTemplateMiddleOrTemplateTail));
// Element
case SyntaxKind.Block:
return updateBlock(<Block>node,
nodesVisitor((<Block>node).statements, visitor, isStatement));
case SyntaxKind.VariableStatement:
return updateVariableStatement(<VariableStatement>node,
nodesVisitor((<VariableStatement>node).modifiers, visitor, isModifier),
visitNode((<VariableStatement>node).declarationList, visitor, isVariableDeclarationList));
case SyntaxKind.ExpressionStatement:
return updateExpressionStatement(<ExpressionStatement>node,
visitNode((<ExpressionStatement>node).expression, visitor, isExpression));
case SyntaxKind.IfStatement:
return updateIf(<IfStatement>node,
visitNode((<IfStatement>node).expression, visitor, isExpression),
visitNode((<IfStatement>node).thenStatement, visitor, isStatement, liftToBlock),
visitNode((<IfStatement>node).elseStatement, visitor, isStatement, liftToBlock));
case SyntaxKind.DoStatement:
return updateDo(<DoStatement>node,
visitNode((<DoStatement>node).statement, visitor, isStatement, liftToBlock),
visitNode((<DoStatement>node).expression, visitor, isExpression));
case SyntaxKind.WhileStatement:
return updateWhile(<WhileStatement>node,
visitNode((<WhileStatement>node).expression, visitor, isExpression),
visitNode((<WhileStatement>node).statement, visitor, isStatement, liftToBlock));
case SyntaxKind.ForStatement:
return updateFor(<ForStatement>node,
visitNode((<ForStatement>node).initializer, visitor, isForInitializer),
visitNode((<ForStatement>node).condition, visitor, isExpression),
visitNode((<ForStatement>node).incrementor, visitor, isExpression),
visitNode((<ForStatement>node).statement, visitor, isStatement, liftToBlock));
case SyntaxKind.ForInStatement:
return updateForIn(<ForInStatement>node,
visitNode((<ForInStatement>node).initializer, visitor, isForInitializer),
visitNode((<ForInStatement>node).expression, visitor, isExpression),
visitNode((<ForInStatement>node).statement, visitor, isStatement, liftToBlock));
case SyntaxKind.ForOfStatement:
return updateForOf(<ForOfStatement>node,
visitNode((<ForOfStatement>node).awaitModifier, tokenVisitor, isToken),
visitNode((<ForOfStatement>node).initializer, visitor, isForInitializer),
visitNode((<ForOfStatement>node).expression, visitor, isExpression),
visitNode((<ForOfStatement>node).statement, visitor, isStatement, liftToBlock));
case SyntaxKind.ContinueStatement:
return updateContinue(<ContinueStatement>node,
visitNode((<ContinueStatement>node).label, visitor, isIdentifier));
case SyntaxKind.BreakStatement:
return updateBreak(<BreakStatement>node,
visitNode((<BreakStatement>node).label, visitor, isIdentifier));
case SyntaxKind.ReturnStatement:
return updateReturn(<ReturnStatement>node,
visitNode((<ReturnStatement>node).expression, visitor, isExpression));
case SyntaxKind.WithStatement:
return updateWith(<WithStatement>node,
visitNode((<WithStatement>node).expression, visitor, isExpression),
visitNode((<WithStatement>node).statement, visitor, isStatement, liftToBlock));
case SyntaxKind.SwitchStatement:
return updateSwitch(<SwitchStatement>node,
visitNode((<SwitchStatement>node).expression, visitor, isExpression),
visitNode((<SwitchStatement>node).caseBlock, visitor, isCaseBlock));
case SyntaxKind.LabeledStatement:
return updateLabel(<LabeledStatement>node,
visitNode((<LabeledStatement>node).label, visitor, isIdentifier),
visitNode((<LabeledStatement>node).statement, visitor, isStatement, liftToBlock));
case SyntaxKind.ThrowStatement:
return updateThrow(<ThrowStatement>node,
visitNode((<ThrowStatement>node).expression, visitor, isExpression));
case SyntaxKind.TryStatement:
return updateTry(<TryStatement>node,
visitNode((<TryStatement>node).tryBlock, visitor, isBlock),
visitNode((<TryStatement>node).catchClause, visitor, isCatchClause),
visitNode((<TryStatement>node).finallyBlock, visitor, isBlock));
case SyntaxKind.VariableDeclaration:
return updateTypeScriptVariableDeclaration(<VariableDeclaration>node,
visitNode((<VariableDeclaration>node).name, visitor, isBindingName),
visitNode((<VariableDeclaration>node).exclamationToken, tokenVisitor, isToken),
visitNode((<VariableDeclaration>node).type, visitor, isTypeNode),
visitNode((<VariableDeclaration>node).initializer, visitor, isExpression));
case SyntaxKind.VariableDeclarationList:
return updateVariableDeclarationList(<VariableDeclarationList>node,
nodesVisitor((<VariableDeclarationList>node).declarations, visitor, isVariableDeclaration));
case SyntaxKind.FunctionDeclaration:
return updateFunctionDeclaration(<FunctionDeclaration>node,
nodesVisitor((<FunctionDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<FunctionDeclaration>node).modifiers, visitor, isModifier),
visitNode((<FunctionDeclaration>node).asteriskToken, tokenVisitor, isToken),
visitNode((<FunctionDeclaration>node).name, visitor, isIdentifier),
nodesVisitor((<FunctionDeclaration>node).typeParameters, visitor, isTypeParameterDeclaration),
visitParameterList((<FunctionDeclaration>node).parameters, visitor, context, nodesVisitor),
visitNode((<FunctionDeclaration>node).type, visitor, isTypeNode),
visitFunctionBody((<FunctionExpression>node).body, visitor, context));
case SyntaxKind.ClassDeclaration:
return updateClassDeclaration(<ClassDeclaration>node,
nodesVisitor((<ClassDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<ClassDeclaration>node).modifiers, visitor, isModifier),
visitNode((<ClassDeclaration>node).name, visitor, isIdentifier),
nodesVisitor((<ClassDeclaration>node).typeParameters, visitor, isTypeParameterDeclaration),
nodesVisitor((<ClassDeclaration>node).heritageClauses, visitor, isHeritageClause),
nodesVisitor((<ClassDeclaration>node).members, visitor, isClassElement));
case SyntaxKind.InterfaceDeclaration:
return updateInterfaceDeclaration(<InterfaceDeclaration>node,
nodesVisitor((<InterfaceDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<InterfaceDeclaration>node).modifiers, visitor, isModifier),
visitNode((<InterfaceDeclaration>node).name, visitor, isIdentifier),
nodesVisitor((<InterfaceDeclaration>node).typeParameters, visitor, isTypeParameterDeclaration),
nodesVisitor((<InterfaceDeclaration>node).heritageClauses, visitor, isHeritageClause),
nodesVisitor((<InterfaceDeclaration>node).members, visitor, isTypeElement));
case SyntaxKind.TypeAliasDeclaration:
return updateTypeAliasDeclaration(<TypeAliasDeclaration>node,
nodesVisitor((<TypeAliasDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<TypeAliasDeclaration>node).modifiers, visitor, isModifier),
visitNode((<TypeAliasDeclaration>node).name, visitor, isIdentifier),
nodesVisitor((<TypeAliasDeclaration>node).typeParameters, visitor, isTypeParameterDeclaration),
visitNode((<TypeAliasDeclaration>node).type, visitor, isTypeNode));
case SyntaxKind.EnumDeclaration:
return updateEnumDeclaration(<EnumDeclaration>node,
nodesVisitor((<EnumDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<EnumDeclaration>node).modifiers, visitor, isModifier),
visitNode((<EnumDeclaration>node).name, visitor, isIdentifier),
nodesVisitor((<EnumDeclaration>node).members, visitor, isEnumMember));
case SyntaxKind.ModuleDeclaration:
return updateModuleDeclaration(<ModuleDeclaration>node,
nodesVisitor((<ModuleDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<ModuleDeclaration>node).modifiers, visitor, isModifier),
visitNode((<ModuleDeclaration>node).name, visitor, isIdentifier),
visitNode((<ModuleDeclaration>node).body, visitor, isModuleBody));
case SyntaxKind.ModuleBlock:
return updateModuleBlock(<ModuleBlock>node,
nodesVisitor((<ModuleBlock>node).statements, visitor, isStatement));
case SyntaxKind.CaseBlock:
return updateCaseBlock(<CaseBlock>node,
nodesVisitor((<CaseBlock>node).clauses, visitor, isCaseOrDefaultClause));
case SyntaxKind.NamespaceExportDeclaration:
return updateNamespaceExportDeclaration(<NamespaceExportDeclaration>node,
visitNode((<NamespaceExportDeclaration>node).name, visitor, isIdentifier));
case SyntaxKind.ImportEqualsDeclaration:
return updateImportEqualsDeclaration(<ImportEqualsDeclaration>node,
nodesVisitor((<ImportEqualsDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<ImportEqualsDeclaration>node).modifiers, visitor, isModifier),
visitNode((<ImportEqualsDeclaration>node).name, visitor, isIdentifier),
visitNode((<ImportEqualsDeclaration>node).moduleReference, visitor, isModuleReference));
case SyntaxKind.ImportDeclaration:
return updateImportDeclaration(<ImportDeclaration>node,
nodesVisitor((<ImportDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<ImportDeclaration>node).modifiers, visitor, isModifier),
visitNode((<ImportDeclaration>node).importClause, visitor, isImportClause),
visitNode((<ImportDeclaration>node).moduleSpecifier, visitor, isExpression));
case SyntaxKind.ImportClause:
return updateImportClause(<ImportClause>node,
visitNode((<ImportClause>node).name, visitor, isIdentifier),
Type-only imports and exports (#35200) * Add type-only support for export declarations * Use a synthetic type alias instead of binding type-only exports as a type alias * Works for re-exports! * isolatedModules works fine * Diagnostic for type-only exporting a value * Start isolated modules codefix * Update for LKG control flow changes * Type-only import clause parsing * Type-only default import checking * Type-only named imports * Fix isolated modules error * Filter namespaces down to type-only * Fix class references * Test nested namespaces * Test circular type-only imports/exports * Fix getTypeAtLocation for type-only import/export specifiers * Fix type-only generic imports * Update public APIs * Remove unused WIP comment * Type-only namespace imports * Fix factory update calls * Add grammar errors for JS usage and mixing default and named bindings * Update updateExportDeclaration API baseline * Fix grammar checking import clauses * Enums, sort of * Dedicated error for type-only enum * Skip past type-only alias symbols in quick info * Update error code in baseline * WIP: convertToTypeOnlyExport * isolatedModules codefix (single export declaration) * isolatedModules code fix (all) * Stop eliding non-type-only imports by default, add compiler flag * Update to match updated diagnostic messages * Update more baselines * Update more tests * Auto-import as type-only * Add codefix for splitting type-only import with default and named bindings * Add more services tests * Add targeted error message for "export type T;" when T exists * Add targeted error for "import type T = require(...)" * Flip emit flag * Add test for preserveUnusedImports option * Fix flag flip on import = * Make compiler option string-valued * Fix merge conflicts * Add --importsNotUsedAsValue=error * Phrasing of messages. Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2020-01-03 23:39:32 +01:00
visitNode((<ImportClause>node).namedBindings, visitor, isNamedImportBindings),
(node as ImportClause).isTypeOnly);
case SyntaxKind.NamespaceImport:
return updateNamespaceImport(<NamespaceImport>node,
visitNode((<NamespaceImport>node).name, visitor, isIdentifier));
case SyntaxKind.NamespaceExport:
return updateNamespaceExport(<NamespaceExport>node,
visitNode((<NamespaceExport>node).name, visitor, isIdentifier));
case SyntaxKind.NamedImports:
return updateNamedImports(<NamedImports>node,
nodesVisitor((<NamedImports>node).elements, visitor, isImportSpecifier));
case SyntaxKind.ImportSpecifier:
return updateImportSpecifier(<ImportSpecifier>node,
visitNode((<ImportSpecifier>node).propertyName, visitor, isIdentifier),
visitNode((<ImportSpecifier>node).name, visitor, isIdentifier));
case SyntaxKind.ExportAssignment:
return updateExportAssignment(<ExportAssignment>node,
nodesVisitor((<ExportAssignment>node).decorators, visitor, isDecorator),
nodesVisitor((<ExportAssignment>node).modifiers, visitor, isModifier),
visitNode((<ExportAssignment>node).expression, visitor, isExpression));
case SyntaxKind.ExportDeclaration:
return updateExportDeclaration(<ExportDeclaration>node,
nodesVisitor((<ExportDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<ExportDeclaration>node).modifiers, visitor, isModifier),
visitNode((<ExportDeclaration>node).exportClause, visitor, isNamedExportBindings),
Type-only imports and exports (#35200) * Add type-only support for export declarations * Use a synthetic type alias instead of binding type-only exports as a type alias * Works for re-exports! * isolatedModules works fine * Diagnostic for type-only exporting a value * Start isolated modules codefix * Update for LKG control flow changes * Type-only import clause parsing * Type-only default import checking * Type-only named imports * Fix isolated modules error * Filter namespaces down to type-only * Fix class references * Test nested namespaces * Test circular type-only imports/exports * Fix getTypeAtLocation for type-only import/export specifiers * Fix type-only generic imports * Update public APIs * Remove unused WIP comment * Type-only namespace imports * Fix factory update calls * Add grammar errors for JS usage and mixing default and named bindings * Update updateExportDeclaration API baseline * Fix grammar checking import clauses * Enums, sort of * Dedicated error for type-only enum * Skip past type-only alias symbols in quick info * Update error code in baseline * WIP: convertToTypeOnlyExport * isolatedModules codefix (single export declaration) * isolatedModules code fix (all) * Stop eliding non-type-only imports by default, add compiler flag * Update to match updated diagnostic messages * Update more baselines * Update more tests * Auto-import as type-only * Add codefix for splitting type-only import with default and named bindings * Add more services tests * Add targeted error message for "export type T;" when T exists * Add targeted error for "import type T = require(...)" * Flip emit flag * Add test for preserveUnusedImports option * Fix flag flip on import = * Make compiler option string-valued * Fix merge conflicts * Add --importsNotUsedAsValue=error * Phrasing of messages. Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2020-01-03 23:39:32 +01:00
visitNode((<ExportDeclaration>node).moduleSpecifier, visitor, isExpression),
(node as ExportDeclaration).isTypeOnly);
case SyntaxKind.NamedExports:
return updateNamedExports(<NamedExports>node,
nodesVisitor((<NamedExports>node).elements, visitor, isExportSpecifier));
case SyntaxKind.ExportSpecifier:
return updateExportSpecifier(<ExportSpecifier>node,
visitNode((<ExportSpecifier>node).propertyName, visitor, isIdentifier),
visitNode((<ExportSpecifier>node).name, visitor, isIdentifier));
// Module references
case SyntaxKind.ExternalModuleReference:
return updateExternalModuleReference(<ExternalModuleReference>node,
visitNode((<ExternalModuleReference>node).expression, visitor, isExpression));
// JSX
case SyntaxKind.JsxElement:
return updateJsxElement(<JsxElement>node,
visitNode((<JsxElement>node).openingElement, visitor, isJsxOpeningElement),
nodesVisitor((<JsxElement>node).children, visitor, isJsxChild),
visitNode((<JsxElement>node).closingElement, visitor, isJsxClosingElement));
case SyntaxKind.JsxSelfClosingElement:
return updateJsxSelfClosingElement(<JsxSelfClosingElement>node,
visitNode((<JsxSelfClosingElement>node).tagName, visitor, isJsxTagNameExpression),
nodesVisitor((<JsxSelfClosingElement>node).typeArguments, visitor, isTypeNode),
visitNode((<JsxSelfClosingElement>node).attributes, visitor, isJsxAttributes));
case SyntaxKind.JsxOpeningElement:
return updateJsxOpeningElement(<JsxOpeningElement>node,
visitNode((<JsxOpeningElement>node).tagName, visitor, isJsxTagNameExpression),
nodesVisitor((<JsxSelfClosingElement>node).typeArguments, visitor, isTypeNode),
visitNode((<JsxOpeningElement>node).attributes, visitor, isJsxAttributes));
case SyntaxKind.JsxClosingElement:
return updateJsxClosingElement(<JsxClosingElement>node,
visitNode((<JsxClosingElement>node).tagName, visitor, isJsxTagNameExpression));
case SyntaxKind.JsxFragment:
return updateJsxFragment(<JsxFragment>node,
visitNode((<JsxFragment>node).openingFragment, visitor, isJsxOpeningFragment),
nodesVisitor((<JsxFragment>node).children, visitor, isJsxChild),
visitNode((<JsxFragment>node).closingFragment, visitor, isJsxClosingFragment));
case SyntaxKind.JsxAttribute:
return updateJsxAttribute(<JsxAttribute>node,
visitNode((<JsxAttribute>node).name, visitor, isIdentifier),
visitNode((<JsxAttribute>node).initializer, visitor, isStringLiteralOrJsxExpression));
case SyntaxKind.JsxAttributes:
return updateJsxAttributes(<JsxAttributes>node,
nodesVisitor((<JsxAttributes>node).properties, visitor, isJsxAttributeLike));
case SyntaxKind.JsxSpreadAttribute:
return updateJsxSpreadAttribute(<JsxSpreadAttribute>node,
visitNode((<JsxSpreadAttribute>node).expression, visitor, isExpression));
case SyntaxKind.JsxExpression:
return updateJsxExpression(<JsxExpression>node,
visitNode((<JsxExpression>node).expression, visitor, isExpression));
// Clauses
case SyntaxKind.CaseClause:
return updateCaseClause(<CaseClause>node,
visitNode((<CaseClause>node).expression, visitor, isExpression),
nodesVisitor((<CaseClause>node).statements, visitor, isStatement));
case SyntaxKind.DefaultClause:
return updateDefaultClause(<DefaultClause>node,
nodesVisitor((<DefaultClause>node).statements, visitor, isStatement));
case SyntaxKind.HeritageClause:
return updateHeritageClause(<HeritageClause>node,
nodesVisitor((<HeritageClause>node).types, visitor, isExpressionWithTypeArguments));
case SyntaxKind.CatchClause:
return updateCatchClause(<CatchClause>node,
visitNode((<CatchClause>node).variableDeclaration, visitor, isVariableDeclaration),
visitNode((<CatchClause>node).block, visitor, isBlock));
// Property assignments
case SyntaxKind.PropertyAssignment:
return updatePropertyAssignment(<PropertyAssignment>node,
visitNode((<PropertyAssignment>node).name, visitor, isPropertyName),
visitNode((<PropertyAssignment>node).initializer, visitor, isExpression));
case SyntaxKind.ShorthandPropertyAssignment:
return updateShorthandPropertyAssignment(<ShorthandPropertyAssignment>node,
visitNode((<ShorthandPropertyAssignment>node).name, visitor, isIdentifier),
visitNode((<ShorthandPropertyAssignment>node).objectAssignmentInitializer, visitor, isExpression));
case SyntaxKind.SpreadAssignment:
return updateSpreadAssignment(<SpreadAssignment>node,
visitNode((<SpreadAssignment>node).expression, visitor, isExpression));
// Enum
case SyntaxKind.EnumMember:
return updateEnumMember(<EnumMember>node,
visitNode((<EnumMember>node).name, visitor, isPropertyName),
visitNode((<EnumMember>node).initializer, visitor, isExpression));
// Top-level nodes
case SyntaxKind.SourceFile:
return updateSourceFileNode(<SourceFile>node,
visitLexicalEnvironment((<SourceFile>node).statements, visitor, context));
// Transformation nodes
case SyntaxKind.PartiallyEmittedExpression:
return updatePartiallyEmittedExpression(<PartiallyEmittedExpression>node,
visitNode((<PartiallyEmittedExpression>node).expression, visitor, isExpression));
case SyntaxKind.CommaListExpression:
return updateCommaList(<CommaListExpression>node,
nodesVisitor((<CommaListExpression>node).elements, visitor, isExpression));
default:
// No need to visit nodes with no children.
return node;
}
}
/**
* Extracts the single node from a NodeArray.
*
* @param nodes The NodeArray.
*/
function extractSingleNode(nodes: readonly Node[]): Node | undefined {
Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
return singleOrUndefined(nodes);
}
}