diff --git a/internal/ast/ast.go b/internal/ast/ast.go index d2961d59c0..72ee46c32f 100644 --- a/internal/ast/ast.go +++ b/internal/ast/ast.go @@ -617,6 +617,8 @@ func (n *Node) StatementList() *NodeList { return n.AsBlock().Statements case KindModuleBlock: return n.AsModuleBlock().Statements + case KindCaseClause, KindDefaultClause: + return n.AsCaseOrDefaultClause().Statements } panic("Unhandled case in Node.StatementList: " + n.Kind.String()) } @@ -1038,6 +1040,10 @@ func (n *Node) Statement() *Statement { return n.AsForStatement().Statement case KindForInStatement, KindForOfStatement: return n.AsForInOrOfStatement().Statement + case KindWithStatement: + return n.AsWithStatement().Statement + case KindLabeledStatement: + return n.AsLabeledStatement().Statement } panic("Unhandled case in Node.Statement: " + n.Kind.String()) } @@ -1068,8 +1074,11 @@ func (n *Node) ElementList() *NodeList { return n.AsNamedExports().Elements case KindObjectBindingPattern, KindArrayBindingPattern: return n.AsBindingPattern().Elements + case KindArrayLiteralExpression: + return n.AsArrayLiteralExpression().Elements + case KindTupleType: + return n.AsTupleTypeNode().Elements } - panic("Unhandled case in Node.ElementList: " + n.Kind.String()) } @@ -1081,22 +1090,22 @@ func (n *Node) Elements() []*Node { return nil } -func (n *Node) postfixToken() *Node { +func (n *Node) PostfixToken() *Node { switch n.Kind { - case KindEnumMember: - return n.AsEnumMember().PostfixToken - case KindPropertyAssignment: - return n.AsPropertyAssignment().PostfixToken + case KindMethodDeclaration: + return n.AsMethodDeclaration().PostfixToken case KindShorthandPropertyAssignment: return n.AsShorthandPropertyAssignment().PostfixToken + case KindMethodSignature: + return n.AsMethodSignatureDeclaration().PostfixToken case KindPropertySignature: return n.AsPropertySignatureDeclaration().PostfixToken + case KindPropertyAssignment: + return n.AsPropertyAssignment().PostfixToken case KindPropertyDeclaration: return n.AsPropertyDeclaration().PostfixToken - case KindMethodSignature: - return n.AsMethodSignatureDeclaration().PostfixToken - case KindMethodDeclaration: - return n.AsMethodDeclaration().PostfixToken + case KindEnumMember: + return n.AsEnumMember().PostfixToken case KindGetAccessor: return n.AsGetAccessorDeclaration().PostfixToken case KindSetAccessor: @@ -1116,7 +1125,7 @@ func (n *Node) QuestionToken() *TokenNode { case KindNamedTupleMember: return n.AsNamedTupleMember().QuestionToken } - postfix := n.postfixToken() + postfix := n.PostfixToken() if postfix != nil && postfix.Kind == KindQuestionToken { return postfix } @@ -1163,26 +1172,6 @@ func (n *Node) ClassName() *Node { panic("Unhandled case in Node.ClassName: " + n.Kind.String()) } -func (n *Node) PostfixToken() *Node { - switch n.Kind { - case KindParameter: - return n.AsParameterDeclaration().QuestionToken - case KindMethodDeclaration: - return n.AsMethodDeclaration().PostfixToken - case KindShorthandPropertyAssignment: - return n.AsShorthandPropertyAssignment().PostfixToken - case KindMethodSignature: - return n.AsMethodSignatureDeclaration().PostfixToken - case KindPropertySignature: - return n.AsPropertySignatureDeclaration().PostfixToken - case KindPropertyAssignment: - return n.AsPropertyAssignment().PostfixToken - case KindPropertyDeclaration: - return n.AsPropertyDeclaration().PostfixToken - } - return nil -} - // Determines if `n` contains `descendant` by walking up the `Parent` pointers from `descendant`. This method panics if // `descendant` or one of its ancestors is not parented except when that node is a `SourceFile`. func (n *Node) Contains(descendant *Node) bool { @@ -11045,7 +11034,7 @@ func (node *SourceFile) computeDeclarationMap() map[string][]*Node { exportClause := node.AsExportDeclaration().ExportClause if exportClause != nil { if IsNamedExports(exportClause) { - for _, element := range exportClause.AsNamedExports().Elements.Nodes { + for _, element := range exportClause.Elements() { visit(element) } } else { @@ -11068,7 +11057,7 @@ func (node *SourceFile) computeDeclarationMap() map[string][]*Node { if namedBindings.Kind == KindNamespaceImport { addDeclaration(namedBindings) } else { - for _, element := range namedBindings.AsNamedImports().Elements.Nodes { + for _, element := range namedBindings.Elements() { visit(element) } } diff --git a/internal/ast/precedence.go b/internal/ast/precedence.go index e23d5278c9..9acf84a78f 100644 --- a/internal/ast/precedence.go +++ b/internal/ast/precedence.go @@ -203,7 +203,7 @@ func getOperator(expression *Expression) Kind { func GetExpressionPrecedence(expression *Expression) OperatorPrecedence { operator := getOperator(expression) var flags OperatorPrecedenceFlags - if expression.Kind == KindNewExpression && expression.AsNewExpression().Arguments == nil { + if expression.Kind == KindNewExpression && expression.ArgumentList() == nil { flags = OperatorPrecedenceFlagsNewWithoutArguments } else if IsOptionalChain(expression) { flags = OperatorPrecedenceFlagsOptionalChain diff --git a/internal/ast/utilities.go b/internal/ast/utilities.go index b1eb903d43..cba6498933 100644 --- a/internal/ast/utilities.go +++ b/internal/ast/utilities.go @@ -197,7 +197,7 @@ func GetAssignmentTarget(node *Node) *Node { } return nil case KindForInStatement, KindForOfStatement: - if parent.AsForInOrOfStatement().Initializer == node { + if parent.Initializer() == node { return parent } return nil @@ -244,7 +244,7 @@ func IsLogicalOrCoalescingAssignmentExpression(expr *Node) bool { func IsLogicalExpression(node *Node) bool { for { if node.Kind == KindParenthesizedExpression { - node = node.AsParenthesizedExpression().Expression + node = node.Expression() } else if node.Kind == KindPrefixUnaryExpression && node.AsPrefixUnaryExpression().Operator == KindExclamationToken { node = node.AsPrefixUnaryExpression().Operand } else { @@ -302,9 +302,9 @@ func IsIdentifierName(node *Node) bool { case KindQualifiedName: return parent.AsQualifiedName().Right == node case KindBindingElement: - return parent.AsBindingElement().PropertyName == node + return parent.PropertyName() == node case KindImportSpecifier: - return parent.AsImportSpecifier().PropertyName == node + return parent.PropertyName() == node case KindExportSpecifier, KindJsxAttribute, KindJsxSelfClosingElement, KindJsxOpeningElement, KindJsxClosingElement: return true } @@ -363,15 +363,7 @@ func IsOptionalChain(node *Node) bool { } func getQuestionDotToken(node *Expression) *TokenNode { - switch node.Kind { - case KindPropertyAccessExpression: - return node.AsPropertyAccessExpression().QuestionDotToken - case KindElementAccessExpression: - return node.AsElementAccessExpression().QuestionDotToken - case KindCallExpression: - return node.AsCallExpression().QuestionDotToken - } - panic("Unhandled case in getQuestionDotToken") + return node.QuestionDotToken() } // Determines if node is the root expression of an OptionalChain @@ -489,7 +481,7 @@ func IsIterationStatement(node *Node, lookInLabeledStatements bool) bool { KindWhileStatement: return true case KindLabeledStatement: - return lookInLabeledStatements && IsIterationStatement((node.AsLabeledStatement()).Statement, lookInLabeledStatements) + return lookInLabeledStatements && IsIterationStatement(node.Statement(), lookInLabeledStatements) } return false @@ -736,18 +728,6 @@ func IsFunctionBlock(node *Node) bool { return node != nil && node.Kind == KindBlock && node.Parent != nil && IsFunctionLike(node.Parent) } -func GetStatementsOfBlock(block *Node) *StatementList { - switch block.Kind { - case KindBlock: - return block.AsBlock().Statements - case KindModuleBlock: - return block.AsModuleBlock().Statements - case KindSourceFile: - return block.AsSourceFile().Statements - } - panic("Unhandled case in getStatementsOfBlock") -} - func IsBlockOrCatchScoped(declaration *Node) bool { return GetCombinedNodeFlags(declaration)&NodeFlagsBlockScoped != 0 || IsCatchClauseVariableDeclarationOrBindingElement(declaration) } @@ -796,7 +776,7 @@ func isJSDocTypeAssertion(_ *Node) bool { func IsPrologueDirective(node *Node) bool { return node.Kind == KindExpressionStatement && - node.AsExpressionStatement().Expression.Kind == KindStringLiteral + node.Expression().Kind == KindStringLiteral } type OuterExpressionKinds int16 @@ -847,7 +827,7 @@ func SkipParentheses(node *Expression) *Expression { func SkipTypeParentheses(node *Node) *Node { for IsParenthesizedTypeNode(node) { - node = node.AsParenthesizedTypeNode().Type + node = node.Type() } return node } @@ -1232,7 +1212,7 @@ func IsVarLet(node *Node) bool { func IsImportMeta(node *Node) bool { if node.Kind == KindMetaProperty { - return node.AsMetaProperty().KeywordToken == KindImportKeyword && node.AsMetaProperty().Name().AsIdentifier().Text == "meta" + return node.AsMetaProperty().KeywordToken == KindImportKeyword && node.AsMetaProperty().Name().Text() == "meta" } return false } @@ -1412,13 +1392,7 @@ func GetNameOfDeclaration(declaration *Node) *Node { } func GetImportClauseOfDeclaration(declaration *Declaration) *ImportClause { - switch declaration.Kind { - case KindImportDeclaration: - return declaration.AsImportDeclaration().ImportClause.AsImportClause() - case KindJSDocImportTag: - return declaration.AsJSDocImportTag().ImportClause.AsImportClause() - } - return nil + return declaration.ImportClause().AsImportClause() } func GetNonAssignedNameOfDeclaration(declaration *Node) *Node { @@ -1436,7 +1410,7 @@ func GetNonAssignedNameOfDeclaration(declaration *Node) *Node { } return nil case KindExportAssignment, KindJSExportAssignment: - expr := declaration.AsExportAssignment().Expression + expr := declaration.Expression() if IsIdentifier(expr) { return expr } @@ -1489,8 +1463,6 @@ const ( /// exports.name = expr /// module.exports.name = expr JSDeclarationKindExportsProperty - /// className.prototype.name = expr - JSDeclarationKindPrototypeProperty /// this.name = expr JSDeclarationKindThisProperty /// F.name = expr, F[name] = expr @@ -1535,7 +1507,7 @@ func IsDynamicName(name *Node) bool { var expr *Node switch name.Kind { case KindComputedPropertyName: - expr = name.AsComputedPropertyName().Expression + expr = name.Expression() case KindElementAccessExpression: expr = SkipParentheses(name.AsElementAccessExpression().ArgumentExpression) default: @@ -1591,7 +1563,7 @@ func HasSamePropertyAccessName(node1, node2 *Node) bool { return node1.Text() == node2.Text() } else if node1.Kind == KindPropertyAccessExpression && node2.Kind == KindPropertyAccessExpression { return node1.AsPropertyAccessExpression().Name().Text() == node2.AsPropertyAccessExpression().Name().Text() && - HasSamePropertyAccessName(node1.AsPropertyAccessExpression().Expression, node2.AsPropertyAccessExpression().Expression) + HasSamePropertyAccessName(node1.Expression(), node2.Expression()) } return false } @@ -1801,7 +1773,7 @@ func GetImmediatelyInvokedFunctionExpression(fn *Node) *Node { prev = parent parent = parent.Parent } - if IsCallExpression(parent) && parent.AsCallExpression().Expression == prev { + if IsCallExpression(parent) && parent.Expression() == prev { return parent } } @@ -1813,7 +1785,7 @@ func IsEnumConst(node *Node) bool { } func ExportAssignmentIsAlias(node *Node) bool { - e := node.AsExportAssignment().Expression + e := node.Expression() return IsEntityNameExpression(e) || IsClassExpression(e) } @@ -1839,19 +1811,17 @@ func IsInJsonFile(node *Node) bool { func GetExternalModuleName(node *Node) *Expression { switch node.Kind { - case KindImportDeclaration, KindJSImportDeclaration: - return node.AsImportDeclaration().ModuleSpecifier - case KindExportDeclaration: - return node.AsExportDeclaration().ModuleSpecifier + case KindImportDeclaration, KindJSImportDeclaration, KindExportDeclaration: + return node.ModuleSpecifier() case KindImportEqualsDeclaration: if node.AsImportEqualsDeclaration().ModuleReference.Kind == KindExternalModuleReference { - return node.AsImportEqualsDeclaration().ModuleReference.AsExternalModuleReference().Expression + return node.AsImportEqualsDeclaration().ModuleReference.Expression() } return nil case KindImportType: return getImportTypeNodeLiteral(node) case KindCallExpression: - return core.FirstOrNil(node.AsCallExpression().Arguments.Nodes) + return core.FirstOrNil(node.Arguments()) case KindModuleDeclaration: if IsStringLiteral(node.AsModuleDeclaration().Name()) { return node.AsModuleDeclaration().Name() @@ -1897,7 +1867,7 @@ func IsExpressionNode(node *Node) bool { return true case KindMetaProperty: // `import.defer` in `import.defer(...)` is not an expression - return !IsImportCall(node.Parent) || node.Parent.AsCallExpression().Expression != node + return !IsImportCall(node.Parent) || node.Parent.Expression() != node case KindExpressionWithTypeArguments: return !IsHeritageClause(node.Parent) case KindQualifiedName: @@ -1922,60 +1892,24 @@ func IsExpressionNode(node *Node) bool { func IsInExpressionContext(node *Node) bool { parent := node.Parent switch parent.Kind { - case KindVariableDeclaration: - return parent.AsVariableDeclaration().Initializer == node - case KindParameter: - return parent.AsParameterDeclaration().Initializer == node - case KindPropertyDeclaration: - return parent.AsPropertyDeclaration().Initializer == node - case KindPropertySignature: - return parent.AsPropertySignatureDeclaration().Initializer == node - case KindEnumMember: - return parent.AsEnumMember().Initializer == node - case KindPropertyAssignment: - return parent.AsPropertyAssignment().Initializer == node - case KindBindingElement: - return parent.AsBindingElement().Initializer == node - case KindExpressionStatement: - return parent.AsExpressionStatement().Expression == node - case KindIfStatement: - return parent.AsIfStatement().Expression == node - case KindDoStatement: - return parent.AsDoStatement().Expression == node - case KindWhileStatement: - return parent.AsWhileStatement().Expression == node - case KindReturnStatement: - return parent.AsReturnStatement().Expression == node - case KindWithStatement: - return parent.AsWithStatement().Expression == node - case KindSwitchStatement: - return parent.AsSwitchStatement().Expression == node - case KindCaseClause, KindDefaultClause: - return parent.AsCaseOrDefaultClause().Expression == node - case KindThrowStatement: - return parent.AsThrowStatement().Expression == node + case KindVariableDeclaration, KindParameter, KindPropertyDeclaration, KindPropertySignature, KindEnumMember, KindPropertyAssignment, KindBindingElement: + return parent.Initializer() == node + case KindExpressionStatement, KindIfStatement, KindDoStatement, KindWhileStatement, KindReturnStatement, KindWithStatement, KindSwitchStatement, + KindCaseClause, KindDefaultClause, KindThrowStatement, KindTypeAssertionExpression, KindAsExpression, KindTemplateSpan, KindComputedPropertyName, + KindSatisfiesExpression: + return parent.Expression() == node case KindForStatement: s := parent.AsForStatement() return s.Initializer == node && s.Initializer.Kind != KindVariableDeclarationList || s.Condition == node || s.Incrementor == node case KindForInStatement, KindForOfStatement: s := parent.AsForInOrOfStatement() return s.Initializer == node && s.Initializer.Kind != KindVariableDeclarationList || s.Expression == node - case KindTypeAssertionExpression: - return parent.AsTypeAssertion().Expression == node - case KindAsExpression: - return parent.AsAsExpression().Expression == node - case KindTemplateSpan: - return parent.AsTemplateSpan().Expression == node - case KindComputedPropertyName: - return parent.AsComputedPropertyName().Expression == node case KindDecorator, KindJsxExpression, KindJsxSpreadAttribute, KindSpreadAssignment: return true case KindExpressionWithTypeArguments: - return parent.AsExpressionWithTypeArguments().Expression == node && !IsPartOfTypeNode(parent) + return parent.Expression() == node && !IsPartOfTypeNode(parent) case KindShorthandPropertyAssignment: return parent.AsShorthandPropertyAssignment().ObjectAssignmentInitializer == node - case KindSatisfiesExpression: - return parent.AsSatisfiesExpression().Expression == node default: return IsExpressionNode(parent) } @@ -2064,25 +1998,21 @@ func IsJSDocTag(node *Node) bool { func isJSXTagName(node *Node) bool { parent := node.Parent switch parent.Kind { - case KindJsxOpeningElement: - return parent.AsJsxOpeningElement().TagName == node - case KindJsxSelfClosingElement: - return parent.AsJsxSelfClosingElement().TagName == node - case KindJsxClosingElement: - return parent.AsJsxClosingElement().TagName == node + case KindJsxOpeningElement, KindJsxSelfClosingElement, KindJsxClosingElement: + return parent.TagName() == node } return false } func IsSuperCall(node *Node) bool { - return IsCallExpression(node) && node.AsCallExpression().Expression.Kind == KindSuperKeyword + return IsCallExpression(node) && node.Expression().Kind == KindSuperKeyword } func IsImportCall(node *Node) bool { if !IsCallExpression(node) { return false } - e := node.AsCallExpression().Expression + e := node.Expression() return e.Kind == KindImportKeyword || IsMetaProperty(e) && e.AsMetaProperty().KeywordToken == KindImportKeyword && e.Text() == "defer" } @@ -2338,7 +2268,7 @@ func getModuleInstanceStateWorker(node *Node, ancestors []*Node, visited map[Nod state := ModuleInstanceStateNonInstantiated ancestors = pushAncestor(ancestors, node) ancestors = pushAncestor(ancestors, decl.ExportClause) - for _, specifier := range decl.ExportClause.AsNamedExports().Elements.Nodes { + for _, specifier := range decl.ExportClause.Elements() { specifierState := getModuleInstanceStateForAliasTarget(specifier, ancestors, visited) if specifierState > state { state = specifierState @@ -2374,21 +2304,16 @@ func getModuleInstanceStateWorker(node *Node, ancestors []*Node, visited map[Nod } func getModuleInstanceStateForAliasTarget(node *Node, ancestors []*Node, visited map[NodeId]ModuleInstanceState) ModuleInstanceState { - spec := node.AsExportSpecifier() - name := spec.PropertyName - if name == nil { - name = spec.Name() - } + name := node.PropertyNameOrName() if name.Kind != KindIdentifier { // Skip for invalid syntax like this: export { "x" } return ModuleInstanceStateInstantiated } for ancestors, p := popAncestor(ancestors, node); p != nil; ancestors, p = popAncestor(ancestors, p) { if IsBlock(p) || IsModuleBlock(p) || IsSourceFile(p) { - statements := GetStatementsOfBlock(p) found := ModuleInstanceStateUnknown statementsAncestors := pushAncestor(ancestors, p) - for _, statement := range statements.Nodes { + for _, statement := range p.Statements() { if NodeHasName(statement, name) { state := getModuleInstanceStateCached(statement, statementsAncestors, visited) if found == ModuleInstanceStateUnknown || state > found { @@ -2418,7 +2343,7 @@ func getModuleInstanceStateForAliasTarget(node *Node, ancestors []*Node, visited func NodeHasName(statement *Node, id *Node) bool { name := statement.Name() if name != nil { - return IsIdentifier(name) && name.AsIdentifier().Text == id.AsIdentifier().Text + return IsIdentifier(name) && name.Text() == id.Text() } if IsVariableStatement(statement) { declarations := statement.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes @@ -2431,22 +2356,10 @@ func IsInternalModuleImportEqualsDeclaration(node *Node) bool { return IsImportEqualsDeclaration(node) && node.AsImportEqualsDeclaration().ModuleReference.Kind != KindExternalModuleReference } -func GetAssertedTypeNode(node *Node) *Node { - switch node.Kind { - case KindAsExpression: - return node.AsAsExpression().Type - case KindSatisfiesExpression: - return node.AsSatisfiesExpression().Type - case KindTypeAssertionExpression: - return node.AsTypeAssertion().Type - } - panic("Unhandled case in getAssertedTypeNode") -} - func IsConstAssertion(node *Node) bool { switch node.Kind { case KindAsExpression, KindTypeAssertionExpression: - return IsConstTypeReference(GetAssertedTypeNode(node)) + return IsConstTypeReference(node.Type()) } return false } @@ -2477,8 +2390,8 @@ func GetDeclarationOfKind(symbol *Symbol, kind Kind) *Node { } func FindConstructorDeclaration(node *ClassLikeDeclaration) *Node { - for _, member := range node.ClassLikeData().Members.Nodes { - if IsConstructorDeclaration(member) && NodeIsPresent(member.AsConstructorDeclaration().Body) { + for _, member := range node.Members() { + if IsConstructorDeclaration(member) && NodeIsPresent(member.Body()) { return member } } @@ -2500,7 +2413,7 @@ func GetFirstIdentifier(node *Node) *Node { func GetNamespaceDeclarationNode(node *Node) *Node { switch node.Kind { case KindImportDeclaration, KindJSImportDeclaration: - importClause := node.AsImportDeclaration().ImportClause + importClause := node.ImportClause() if importClause != nil && importClause.AsImportClause().NamedBindings != nil && IsNamespaceImport(importClause.AsImportClause().NamedBindings) { return importClause.AsImportClause().NamedBindings } @@ -2524,7 +2437,7 @@ func ModuleExportNameIsDefault(node *Node) bool { func IsDefaultImport(node *Node /*ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration*/) bool { switch node.Kind { case KindImportDeclaration, KindJSImportDeclaration: - importClause := node.AsImportDeclaration().ImportClause + importClause := node.ImportClause() return importClause != nil && importClause.AsImportClause().name != nil } return false @@ -2808,9 +2721,9 @@ func IsVariableDeclarationInitializedToRequire(node *Node) bool { } return node.Parent.Parent.ModifierFlags()&ModifierFlagsExport == 0 && - node.AsVariableDeclaration().Initializer != nil && + node.Initializer() != nil && node.Type() == nil && - IsRequireCall(node.AsVariableDeclaration().Initializer, true /*requireStringLiteralLikeArgument*/) + IsRequireCall(node.Initializer(), true /*requireStringLiteralLikeArgument*/) } func IsModuleExportsAccessExpression(node *Node) bool { @@ -2855,12 +2768,12 @@ func IsTypeOnlyImportDeclaration(node *Node) bool { func isTypeOnlyExportDeclaration(node *Node) bool { switch node.Kind { case KindExportSpecifier: - return node.AsExportSpecifier().IsTypeOnly || node.Parent.Parent.AsExportDeclaration().IsTypeOnly + return node.IsTypeOnly() || node.Parent.Parent.IsTypeOnly() case KindExportDeclaration: d := node.AsExportDeclaration() return d.IsTypeOnly && d.ModuleSpecifier != nil && d.ExportClause == nil case KindNamespaceExport: - return node.Parent.AsExportDeclaration().IsTypeOnly + return node.Parent.IsTypeOnly() } return false } @@ -2872,13 +2785,13 @@ func IsTypeOnlyImportOrExportDeclaration(node *Node) bool { func IsExclusivelyTypeOnlyImportOrExport(node *Node) bool { switch node.Kind { case KindExportDeclaration: - return node.AsExportDeclaration().IsTypeOnly + return node.IsTypeOnly() case KindImportDeclaration, KindJSImportDeclaration: - if importClause := node.AsImportDeclaration().ImportClause; importClause != nil { + if importClause := node.ImportClause(); importClause != nil { return importClause.AsImportClause().IsTypeOnly() } case KindJSDocImportTag: - if importClause := node.AsJSDocImportTag().ImportClause; importClause != nil { + if importClause := node.ImportClause(); importClause != nil { return importClause.AsImportClause().IsTypeOnly() } } @@ -3086,7 +2999,7 @@ func GetPropertyNameForPropertyNameNode(name *Node) string { KindNumericLiteral, KindBigIntLiteral, KindJsxNamespacedName: return name.Text() case KindComputedPropertyName: - nameExpression := name.AsComputedPropertyName().Expression + nameExpression := name.Expression() if IsStringOrNumericLiteralLike(nameExpression) { return nameExpression.Text() } @@ -3113,11 +3026,9 @@ func IsPartOfExclusivelyTypeOnlyImportOrExportDeclaration(node *Node) bool { func IsEmittableImport(node *Node) bool { switch node.Kind { case KindImportDeclaration: - return node.AsImportDeclaration().ImportClause != nil && !node.AsImportDeclaration().ImportClause.IsTypeOnly() - case KindExportDeclaration: - return !node.AsExportDeclaration().IsTypeOnly - case KindImportEqualsDeclaration: - return !node.AsImportEqualsDeclaration().IsTypeOnly + return node.ImportClause() != nil && !node.ImportClause().IsTypeOnly() + case KindExportDeclaration, KindImportEqualsDeclaration: + return !node.IsTypeOnly() case KindCallExpression: return IsImportCall(node) } @@ -3169,7 +3080,7 @@ func IsTemplateLiteralToken(node *Node) bool { func GetExternalModuleImportEqualsDeclarationExpression(node *Node) *Node { debug.Assert(IsExternalModuleImportEqualsDeclaration(node)) - return node.AsImportEqualsDeclaration().ModuleReference.AsExternalModuleReference().Expression + return node.AsImportEqualsDeclaration().ModuleReference.Expression() } func CreateModifiersFromModifierFlags(flags ModifierFlags, createModifier func(kind Kind) *Node) []*Node { @@ -3249,7 +3160,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL modifierArray, node.AsParameterDeclaration().DotDotDotToken, node.Name(), - node.AsParameterDeclaration().QuestionToken, + node.QuestionToken(), node.Type(), node.Initializer(), ) @@ -3266,7 +3177,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL node.AsPropertySignatureDeclaration(), modifierArray, node.Name(), - node.AsPropertySignatureDeclaration().PostfixToken, + node.PostfixToken(), node.Type(), node.Initializer(), ) @@ -3275,7 +3186,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL node.AsPropertyDeclaration(), modifierArray, node.Name(), - node.AsPropertyDeclaration().PostfixToken, + node.PostfixToken(), node.Type(), node.Initializer(), ) @@ -3284,7 +3195,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL node.AsMethodSignatureDeclaration(), modifierArray, node.Name(), - node.AsMethodSignatureDeclaration().PostfixToken, + node.PostfixToken(), node.TypeParameterList(), node.ParameterList(), node.Type(), @@ -3295,7 +3206,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL modifierArray, node.AsMethodDeclaration().AsteriskToken, node.Name(), - node.AsMethodDeclaration().PostfixToken, + node.PostfixToken(), node.TypeParameterList(), node.ParameterList(), node.Type(), @@ -3444,8 +3355,8 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL return factory.UpdateImportDeclaration( node.AsImportDeclaration(), modifierArray, - node.AsImportDeclaration().ImportClause, - node.AsImportDeclaration().ModuleSpecifier, + node.ImportClause(), + node.ModuleSpecifier(), node.AsImportDeclaration().Attributes, ) case KindExportAssignment: @@ -3461,7 +3372,7 @@ func ReplaceModifiers(factory *NodeFactory, node *Node, modifierArray *ModifierL modifierArray, node.IsTypeOnly(), node.AsExportDeclaration().ExportClause, - node.AsExportDeclaration().ModuleSpecifier, + node.ModuleSpecifier(), node.AsExportDeclaration().Attributes, ) } @@ -3510,11 +3421,9 @@ func IsTypeDeclaration(node *Node) bool { case KindTypeParameter, KindClassDeclaration, KindInterfaceDeclaration, KindTypeAliasDeclaration, KindJSTypeAliasDeclaration, KindEnumDeclaration: return true case KindImportClause: - return node.AsImportClause().PhaseModifier == KindTypeKeyword - case KindImportSpecifier: - return node.Parent.Parent.AsImportClause().PhaseModifier == KindTypeKeyword - case KindExportSpecifier: - return node.Parent.Parent.AsExportDeclaration().IsTypeOnly + return node.IsTypeOnly() + case KindImportSpecifier, KindExportSpecifier: + return node.Parent.Parent.IsTypeOnly() default: return false } @@ -3552,7 +3461,7 @@ func ShouldTransformImportCall(fileName string, options *core.CompilerOptions, i } func HasQuestionToken(node *Node) bool { - return IsQuestionToken(node.PostfixToken()) + return IsQuestionToken(node.QuestionToken()) } func IsJsxOpeningLikeElement(node *Node) bool { @@ -3663,16 +3572,13 @@ func IsAssignmentPattern(node *Node) bool { func GetElementsOfBindingOrAssignmentPattern(name *Node) []*Node { switch name.Kind { - case KindObjectBindingPattern, KindArrayBindingPattern: + case KindObjectBindingPattern, KindArrayBindingPattern, KindArrayLiteralExpression: // `a` in `{a}` // `a` in `[a]` - return name.AsBindingPattern().Elements.Nodes - case KindArrayLiteralExpression: - // `a` in `[a]` - return name.AsArrayLiteralExpression().Elements.Nodes + return name.Elements() case KindObjectLiteralExpression: // `a` in `{a}` - return name.AsObjectLiteralExpression().Properties.Nodes + return name.Properties() } return nil } @@ -3730,7 +3636,7 @@ func GetTargetOfBindingOrAssignmentElement(bindingElement *Node) *Node { return bindingElement.Name() case KindSpreadAssignment: // `a` in `({ ...a } = ...)` - return GetTargetOfBindingOrAssignmentElement(bindingElement.AsSpreadAssignment().Expression) + return GetTargetOfBindingOrAssignmentElement(bindingElement.Expression()) } // no target @@ -3748,7 +3654,7 @@ func GetTargetOfBindingOrAssignmentElement(bindingElement *Node) *Node { if IsSpreadElement(bindingElement) { // `a` in `[...a] = ...` - return GetTargetOfBindingOrAssignmentElement(bindingElement.AsSpreadElement().Expression) + return GetTargetOfBindingOrAssignmentElement(bindingElement.Expression()) } // `a` in `[a] = ...` @@ -3766,13 +3672,13 @@ func TryGetPropertyNameOfBindingOrAssignmentElement(bindingElement *Node) *Node // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` // `1` in `let { 1: b } = ...` - if bindingElement.AsBindingElement().PropertyName != nil { - propertyName := bindingElement.AsBindingElement().PropertyName + if bindingElement.PropertyName() != nil { + propertyName := bindingElement.PropertyName() // if ast.IsPrivateIdentifier(propertyName) { // return Debug.failBadSyntaxKind(propertyName) // !!! // } - if IsComputedPropertyName(propertyName) && IsStringOrNumericLiteralLike(propertyName.AsComputedPropertyName().Expression) { - return propertyName.AsComputedPropertyName().Expression + if IsComputedPropertyName(propertyName) && IsStringOrNumericLiteralLike(propertyName.Expression()) { + return propertyName.Expression() } return propertyName } @@ -3786,8 +3692,8 @@ func TryGetPropertyNameOfBindingOrAssignmentElement(bindingElement *Node) *Node // if ast.IsPrivateIdentifier(propertyName) { // return Debug.failBadSyntaxKind(propertyName) // !!! // } - if IsComputedPropertyName(propertyName) && IsStringOrNumericLiteralLike(propertyName.AsComputedPropertyName().Expression) { - return propertyName.AsComputedPropertyName().Expression + if IsComputedPropertyName(propertyName) && IsStringOrNumericLiteralLike(propertyName.Expression()) { + return propertyName.Expression() } return propertyName } @@ -3837,11 +3743,11 @@ func ContainsObjectRestOrSpread(node *Node) bool { } func IsEmptyObjectLiteral(expression *Node) bool { - return expression.Kind == KindObjectLiteralExpression && len(expression.AsObjectLiteralExpression().Properties.Nodes) == 0 + return IsObjectLiteralExpression(expression) && len(expression.Properties()) == 0 } func IsEmptyArrayLiteral(expression *Node) bool { - return expression.Kind == KindArrayLiteralExpression && len(expression.AsArrayLiteralExpression().Elements.Nodes) == 0 + return IsArrayLiteralExpression(expression) && len(expression.Elements()) == 0 } func GetRestIndicatorOfBindingOrAssignmentElement(bindingElement *Node) *Node { @@ -3886,7 +3792,7 @@ func IsExpandoInitializer(initializer *Node) bool { return true } if IsInJSFile(initializer) { - return IsClassExpression(initializer) || (IsObjectLiteralExpression(initializer) && len(initializer.AsObjectLiteralExpression().Properties.Nodes) == 0) + return IsClassExpression(initializer) || (IsObjectLiteralExpression(initializer) && len(initializer.Properties()) == 0) } return false } diff --git a/internal/binder/binder.go b/internal/binder/binder.go index 51b02a3124..e813bb7e19 100644 --- a/internal/binder/binder.go +++ b/internal/binder/binder.go @@ -255,9 +255,9 @@ func (b *Binder) declareSymbolEx(symbolTable ast.SymbolTable, parent *ast.Symbol } else { diag = b.createDiagnosticForNode(declarationName, message) } - if ast.IsTypeAliasDeclaration(node) && ast.NodeIsMissing(node.AsTypeAliasDeclaration().Type) && ast.HasSyntacticModifier(node, ast.ModifierFlagsExport) && symbol.Flags&(ast.SymbolFlagsAlias|ast.SymbolFlagsType|ast.SymbolFlagsNamespace) != 0 { + if ast.IsTypeAliasDeclaration(node) && ast.NodeIsMissing(node.Type()) && ast.HasSyntacticModifier(node, ast.ModifierFlagsExport) && symbol.Flags&(ast.SymbolFlagsAlias|ast.SymbolFlagsType|ast.SymbolFlagsNamespace) != 0 { // export type T; - may have meant export type { T }? - diag.AddRelatedInfo(b.createDiagnosticForNode(node, diagnostics.Did_you_mean_0, "export type { "+node.AsTypeAliasDeclaration().Name().AsIdentifier().Text+" }")) + diag.AddRelatedInfo(b.createDiagnosticForNode(node, diagnostics.Did_you_mean_0, "export type { "+node.AsTypeAliasDeclaration().Name().Text()+" }")) } for index, declaration := range symbol.Declarations { var decl *ast.Node = ast.GetNameOfDeclaration(declaration) @@ -329,7 +329,7 @@ func (b *Binder) getDeclarationName(node *ast.Node) string { return name.Text() } if ast.IsComputedPropertyName(name) { - nameExpression := name.AsComputedPropertyName().Expression + nameExpression := name.Expression() // treat computed property names where expression is string/numeric literal as just string/numeric literal if ast.IsStringOrNumericLiteralLike(nameExpression) { return nameExpression.Text() @@ -703,14 +703,14 @@ func (b *Binder) bind(node *ast.Node) bool { case ast.KindExportAssignment, ast.KindJSExportAssignment: b.bindExportAssignment(node) case ast.KindSourceFile: - b.updateStrictModeStatementList(node.AsSourceFile().Statements) + b.updateStrictModeStatementList(node.StatementList()) b.bindSourceFileIfExternalModule() case ast.KindBlock: if ast.IsFunctionLikeOrClassStaticBlockDeclaration(node.Parent) { - b.updateStrictModeStatementList(node.AsBlock().Statements) + b.updateStrictModeStatementList(node.StatementList()) } case ast.KindModuleBlock: - b.updateStrictModeStatementList(node.AsModuleBlock().Statements) + b.updateStrictModeStatementList(node.StatementList()) case ast.KindJsxAttributes: b.bindJsxAttributes(node) case ast.KindJsxAttribute: @@ -781,10 +781,10 @@ func (b *Binder) bindModuleDeclaration(node *ast.Node) { symbol := b.declareSymbolAndAddToSymbolTable(node, ast.SymbolFlagsValueModule, ast.SymbolFlagsValueModuleExcludes) if ast.IsStringLiteral(name) { - pattern := core.TryParsePattern(name.AsStringLiteral().Text) + pattern := core.TryParsePattern(name.Text()) if !pattern.IsValid() { // An invalid pattern - must have multiple wildcards. - b.errorOnFirstToken(name, diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, name.AsStringLiteral().Text) + b.errorOnFirstToken(name, diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, name.Text()) } else if pattern.StarIndex >= 0 { b.file.PatternAmbientModules = append(b.file.PatternAmbientModules, &ast.PatternAmbientModule{Pattern: pattern, Symbol: symbol}) } @@ -793,7 +793,7 @@ func (b *Binder) bindModuleDeclaration(node *ast.Node) { } else { state := b.declareModuleSymbol(node) if state != ast.ModuleInstanceStateNonInstantiated { - symbol := node.AsModuleDeclaration().Symbol + symbol := node.Symbol() if symbol.Flags&(ast.SymbolFlagsFunction|ast.SymbolFlagsClass|ast.SymbolFlagsRegularEnum) != 0 || state != ast.ModuleInstanceStateConstEnumOnly { // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only symbol.Flags &^= ast.SymbolFlagsConstEnumOnlyModule @@ -889,11 +889,11 @@ func (b *Binder) hasExportDeclarations(node *ast.Node) bool { var statements []*ast.Node switch node.Kind { case ast.KindSourceFile: - statements = node.AsSourceFile().Statements.Nodes + statements = node.Statements() case ast.KindModuleDeclaration: - body := node.AsModuleDeclaration().Body + body := node.Body() if body != nil && ast.IsModuleBlock(body) { - statements = body.AsModuleBlock().Statements.Nodes + statements = body.Statements() } } return core.Some(statements, func(s *ast.Node) bool { @@ -906,7 +906,7 @@ func (b *Binder) bindFunctionExpression(node *ast.Node) { bindingName := ast.InternalSymbolNameFunction if ast.IsFunctionExpression(node) && node.AsFunctionExpression().Name() != nil { b.checkStrictModeFunctionName(node) - bindingName = node.AsFunctionExpression().Name().AsIdentifier().Text + bindingName = node.AsFunctionExpression().Name().Text() } b.bindAnonymousDeclaration(node, ast.SymbolFlagsFunction, bindingName) } @@ -932,7 +932,7 @@ func (b *Binder) bindClassLikeDeclaration(node *ast.Node) { case ast.KindClassExpression: nameText := ast.InternalSymbolNameClass if name != nil { - nameText = name.AsIdentifier().Text + nameText = name.Text() b.classifiableNames.Add(nameText) } b.bindAnonymousDeclaration(node, ast.SymbolFlagsClass, nameText) @@ -1011,7 +1011,7 @@ func getInitializerSymbol(symbol *ast.Symbol) *ast.Symbol { // For an assignment 'fn.xxx = ...', where 'fn' is a previously declared function or a previously // declared const variable initialized with a function expression or arrow function, we add expando // property declarations to the function's symbol. - // This also applies to class expressions and empty object literals. + // This also applies to class expressions and empty object literals in JS files. switch { case ast.IsFunctionDeclaration(declaration) || ast.IsInJSFile(declaration) && ast.IsClassDeclaration(declaration): return symbol @@ -1186,10 +1186,9 @@ func (b *Binder) bindTypeParameter(node *ast.Node) { func (b *Binder) lookupEntity(node *ast.Node, container *ast.Node) *ast.Symbol { if ast.IsIdentifier(node) { - return b.lookupName(node.AsIdentifier().Text, container) + return b.lookupName(node.Text(), container) } - if ast.IsPropertyAccessExpression(node) && node.AsPropertyAccessExpression().Expression.Kind == ast.KindThisKeyword || - ast.IsElementAccessExpression(node) && node.AsElementAccessExpression().Expression.Kind == ast.KindThisKeyword { + if (ast.IsPropertyAccessExpression(node) || ast.IsElementAccessExpression(node)) && node.Expression().Kind == ast.KindThisKeyword { if _, symbolTable := b.getThisClassAndSymbolTable(); symbolTable != nil { if name := ast.GetElementOrPropertyAccessName(node); name != nil { return symbolTable[name.Text()] @@ -1225,7 +1224,7 @@ func (b *Binder) checkContextualIdentifier(node *ast.Node) { // Report error only if there are no parse errors in file if len(b.file.Diagnostics()) == 0 && node.Flags&ast.NodeFlagsAmbient == 0 && node.Flags&ast.NodeFlagsJSDoc == 0 && !ast.IsIdentifierName(node) { // strict mode identifiers - originalKeywordKind := scanner.GetIdentifierToken(node.AsIdentifier().Text) + originalKeywordKind := scanner.GetIdentifierToken(node.Text()) if originalKeywordKind == ast.KindIdentifier { return } @@ -1244,7 +1243,7 @@ func (b *Binder) checkContextualIdentifier(node *ast.Node) { } func (b *Binder) checkPrivateIdentifier(node *ast.Node) { - if node.AsPrivateIdentifier().Text == "#constructor" { + if node.Text() == "#constructor" { // Report error only if there are no parse errors in file if len(b.file.Diagnostics()) == 0 { b.errorOnNode(node, diagnostics.X_constructor_is_a_reserved_word, scanner.DeclarationNameToString(node)) @@ -1275,7 +1274,7 @@ func (b *Binder) updateStrictModeStatementList(statements *ast.NodeList) { // Should be called only on prologue directives (ast.IsPrologueDirective(node) should be true) func isUseStrictPrologueDirective(sourceFile *ast.SourceFile, node *ast.Node) bool { - nodeText := scanner.GetSourceTextOfNodeFromSourceFile(sourceFile, node.AsExpressionStatement().Expression, false /*includeTrivia*/) + nodeText := scanner.GetSourceTextOfNodeFromSourceFile(sourceFile, node.Expression(), false /*includeTrivia*/) // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the // string to contain unicode escapes (as per ES5). return nodeText == "\"use strict\"" || nodeText == "'use strict'" @@ -1380,7 +1379,7 @@ func (b *Binder) checkStrictModeLabeledStatement(node *ast.Node) { func isEvalOrArgumentsIdentifier(node *ast.Node) bool { if ast.IsIdentifier(node) { - text := node.AsIdentifier().Text + text := node.Text() return text == "eval" || text == "arguments" } return false @@ -1390,7 +1389,7 @@ func (b *Binder) checkStrictModeEvalOrArguments(contextNode *ast.Node, name *ast if name != nil && isEvalOrArgumentsIdentifier(name) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. - b.errorOnNode(name, b.getStrictModeEvalOrArgumentsMessage(contextNode), name.AsIdentifier().Text) + b.errorOnNode(name, b.getStrictModeEvalOrArgumentsMessage(contextNode), name.Text()) } } @@ -1608,10 +1607,8 @@ func (b *Binder) bindChildren(node *ast.Node) { sourceFile := node.AsSourceFile() b.bindEachStatementFunctionsFirst(sourceFile.Statements) b.bind(sourceFile.EndOfFileToken) - case ast.KindBlock: - b.bindEachStatementFunctionsFirst(node.AsBlock().Statements) - case ast.KindModuleBlock: - b.bindEachStatementFunctionsFirst(node.AsModuleBlock().Statements) + case ast.KindBlock, ast.KindModuleBlock: + b.bindEachStatementFunctionsFirst(node.StatementList()) case ast.KindBindingElement: b.bindBindingElementFlow(node) case ast.KindParameter: @@ -1688,7 +1685,7 @@ func (b *Binder) checkUnreachable(node *ast.Node) bool { isError := unreachableCodeIsError(b.options()) && node.Flags&ast.NodeFlagsAmbient == 0 && (!ast.IsVariableStatement(node) || ast.GetCombinedNodeFlags(node.AsVariableStatement().DeclarationList)&ast.NodeFlagsBlockScoped != 0 || core.Some(node.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes, func(d *ast.Node) bool { - return d.AsVariableDeclaration().Initializer != nil + return d.Initializer() != nil })) b.errorOnEachUnreachableRange(node, isError) } @@ -1704,7 +1701,7 @@ func (b *Binder) shouldReportErrorOnModuleDeclaration(node *ast.Node) bool { func (b *Binder) errorOnEachUnreachableRange(node *ast.Node, isError bool) { if b.isExecutableStatement(node) && ast.IsBlock(node.Parent) { - statements := node.Parent.AsBlock().Statements.Nodes + statements := node.Parent.Statements() index := slices.Index(statements, node) var first, last *ast.Node for _, s := range statements[index:] { @@ -1731,7 +1728,7 @@ func (b *Binder) isExecutableStatement(s *ast.Node) bool { // Don't remove statements that can validly be used before they appear. return !ast.IsFunctionDeclaration(s) && !b.isPurelyTypeDeclaration(s) && !(ast.IsVariableStatement(s) && ast.GetCombinedNodeFlags(s)&ast.NodeFlagsBlockScoped == 0 && core.Some(s.AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes, func(d *ast.Node) bool { - return d.AsVariableDeclaration().Initializer == nil + return d.Initializer() == nil })) } @@ -1793,22 +1790,22 @@ func isLogicalAssignmentExpression(node *ast.Node) bool { func (b *Binder) bindAssignmentTargetFlow(node *ast.Node) { switch node.Kind { case ast.KindArrayLiteralExpression: - for _, e := range node.AsArrayLiteralExpression().Elements.Nodes { + for _, e := range node.Elements() { if e.Kind == ast.KindSpreadElement { - b.bindAssignmentTargetFlow(e.AsSpreadElement().Expression) + b.bindAssignmentTargetFlow(e.Expression()) } else { b.bindDestructuringTargetFlow(e) } } case ast.KindObjectLiteralExpression: - for _, p := range node.AsObjectLiteralExpression().Properties.Nodes { + for _, p := range node.Properties() { switch p.Kind { case ast.KindPropertyAssignment: - b.bindDestructuringTargetFlow(p.AsPropertyAssignment().Initializer) + b.bindDestructuringTargetFlow(p.Initializer()) case ast.KindShorthandPropertyAssignment: b.bindAssignmentTargetFlow(p.AsShorthandPropertyAssignment().Name()) case ast.KindSpreadAssignment: - b.bindAssignmentTargetFlow(p.AsSpreadAssignment().Expression) + b.bindAssignmentTargetFlow(p.Expression()) } } default: @@ -1909,7 +1906,7 @@ func (b *Binder) bindIfStatement(node *ast.Node) { } func (b *Binder) bindReturnStatement(node *ast.Node) { - b.bind(node.AsReturnStatement().Expression) + b.bind(node.Expression()) if b.currentReturnTarget != nil { b.addAntecedent(b.currentReturnTarget, b.currentFlow) } @@ -1919,23 +1916,23 @@ func (b *Binder) bindReturnStatement(node *ast.Node) { } func (b *Binder) bindThrowStatement(node *ast.Node) { - b.bind(node.AsThrowStatement().Expression) + b.bind(node.Expression()) b.currentFlow = b.unreachableFlow b.hasFlowEffects = true } func (b *Binder) bindBreakStatement(node *ast.Node) { - b.bindBreakOrContinueStatement(node.AsBreakStatement().Label, b.currentBreakTarget, (*ActiveLabel).BreakTarget) + b.bindBreakOrContinueStatement(node.Label(), b.currentBreakTarget, (*ActiveLabel).BreakTarget) } func (b *Binder) bindContinueStatement(node *ast.Node) { - b.bindBreakOrContinueStatement(node.AsContinueStatement().Label, b.currentContinueTarget, (*ActiveLabel).ContinueTarget) + b.bindBreakOrContinueStatement(node.Label(), b.currentContinueTarget, (*ActiveLabel).ContinueTarget) } func (b *Binder) bindBreakOrContinueStatement(label *ast.Node, currentTarget *ast.FlowNode, getTarget func(*ActiveLabel) *ast.FlowNode) { b.bind(label) if label != nil { - activeLabel := b.findActiveLabel(label.AsIdentifier().Text) + activeLabel := b.findActiveLabel(label.Text()) if activeLabel != nil { activeLabel.referenced = true b.bindBreakOrContinueFlow(getTarget(activeLabel)) @@ -2071,7 +2068,7 @@ func (b *Binder) bindCaseBlock(node *ast.Node) { var fallthroughFlow *ast.FlowNode = b.unreachableFlow for i := 0; i < len(clauses); i++ { clauseStart := i - for len(clauses[i].AsCaseOrDefaultClause().Statements.Nodes) == 0 && i+1 < len(clauses) { + for len(clauses[i].Statements()) == 0 && i+1 < len(clauses) { if fallthroughFlow == b.unreachableFlow { b.currentFlow = b.preSwitchCaseFlow } @@ -2127,7 +2124,7 @@ func (b *Binder) bindLabeledStatement(node *ast.Node) { postStatementLabel := b.createBranchLabel() b.activeLabelList = &ActiveLabel{ next: b.activeLabelList, - name: stmt.Label.AsIdentifier().Text, + name: stmt.Label.Text(), breakTarget: postStatementLabel, continueTarget: nil, referenced: false, @@ -2284,7 +2281,7 @@ func (b *Binder) bindConditionalExpressionFlow(node *ast.Node) { func (b *Binder) bindVariableDeclarationFlow(node *ast.Node) { b.bindEachChild(node) - if node.AsVariableDeclaration().Initializer != nil || ast.IsForInOrOfStatement(node.Parent.Parent) { + if node.Initializer() != nil || ast.IsForInOrOfStatement(node.Parent.Parent) { b.bindInitializedVariableFlow(node) } } @@ -2298,7 +2295,7 @@ func (b *Binder) bindInitializedVariableFlow(node *ast.Node) { name = node.AsBindingElement().Name() } if name != nil && ast.IsBindingPattern(name) { - for _, child := range name.AsBindingPattern().Elements.Nodes { + for _, child := range name.Elements() { b.bindInitializedVariableFlow(child) } } else { @@ -2369,15 +2366,15 @@ func (b *Binder) bindOptionalExpression(node *ast.Node, trueTarget *ast.FlowLabe func (b *Binder) bindOptionalChainRest(node *ast.Node) bool { switch node.Kind { case ast.KindPropertyAccessExpression: - b.bind(node.AsPropertyAccessExpression().QuestionDotToken) - b.bind(node.AsPropertyAccessExpression().Name()) + b.bind(node.QuestionDotToken()) + b.bind(node.Name()) case ast.KindElementAccessExpression: - b.bind(node.AsElementAccessExpression().QuestionDotToken) + b.bind(node.QuestionDotToken()) b.bind(node.AsElementAccessExpression().ArgumentExpression) case ast.KindCallExpression: - b.bind(node.AsCallExpression().QuestionDotToken) - b.bindNodeList(node.AsCallExpression().TypeArguments) - b.bindEach(node.AsCallExpression().Arguments.Nodes) + b.bind(node.QuestionDotToken()) + b.bindNodeList(node.TypeArgumentList()) + b.bindEach(node.Arguments()) } return false } @@ -2558,7 +2555,7 @@ func GetContainerFlags(node *ast.Node) ContainerFlags { case ast.KindModuleBlock: return ContainerFlagsIsControlFlowContainer case ast.KindPropertyDeclaration: - if node.AsPropertyDeclaration().Initializer != nil { + if node.Initializer() != nil { return ContainerFlagsIsControlFlowContainer | ContainerFlagsIsThisContainer } else { return ContainerFlagsNone @@ -2583,16 +2580,12 @@ func isNarrowingExpression(expr *ast.Node) bool { return containsNarrowableReference(expr) case ast.KindCallExpression: return hasNarrowableArgument(expr) - case ast.KindParenthesizedExpression: - return isNarrowingExpression(expr.AsParenthesizedExpression().Expression) - case ast.KindNonNullExpression: - return isNarrowingExpression(expr.AsNonNullExpression().Expression) + case ast.KindParenthesizedExpression, ast.KindNonNullExpression, ast.KindTypeOfExpression: + return isNarrowingExpression(expr.Expression()) case ast.KindBinaryExpression: return isNarrowingBinaryExpression(expr.AsBinaryExpression()) case ast.KindPrefixUnaryExpression: return expr.AsPrefixUnaryExpression().Operator == ast.KindExclamationToken && isNarrowingExpression(expr.AsPrefixUnaryExpression().Operand) - case ast.KindTypeOfExpression: - return isNarrowingExpression(expr.AsTypeOfExpression().Expression) } return false } @@ -2603,14 +2596,8 @@ func containsNarrowableReference(expr *ast.Node) bool { } if expr.Flags&ast.NodeFlagsOptionalChain != 0 { switch expr.Kind { - case ast.KindPropertyAccessExpression: - return containsNarrowableReference(expr.AsPropertyAccessExpression().Expression) - case ast.KindElementAccessExpression: - return containsNarrowableReference(expr.AsElementAccessExpression().Expression) - case ast.KindCallExpression: - return containsNarrowableReference(expr.AsCallExpression().Expression) - case ast.KindNonNullExpression: - return containsNarrowableReference(expr.AsNonNullExpression().Expression) + case ast.KindPropertyAccessExpression, ast.KindElementAccessExpression, ast.KindCallExpression, ast.KindNonNullExpression: + return containsNarrowableReference(expr.Expression()) } } return false @@ -2620,12 +2607,8 @@ func isNarrowableReference(node *ast.Node) bool { switch node.Kind { case ast.KindIdentifier, ast.KindThisKeyword, ast.KindSuperKeyword, ast.KindMetaProperty: return true - case ast.KindPropertyAccessExpression: - return isNarrowableReference(node.AsPropertyAccessExpression().Expression) - case ast.KindParenthesizedExpression: - return isNarrowableReference(node.AsParenthesizedExpression().Expression) - case ast.KindNonNullExpression: - return isNarrowableReference(node.AsNonNullExpression().Expression) + case ast.KindPropertyAccessExpression, ast.KindParenthesizedExpression, ast.KindNonNullExpression: + return isNarrowableReference(node.Expression()) case ast.KindElementAccessExpression: expr := node.AsElementAccessExpression() return ast.IsStringOrNumericLiteralLike(expr.ArgumentExpression) || @@ -2646,7 +2629,7 @@ func hasNarrowableArgument(expr *ast.Node) bool { } } if ast.IsPropertyAccessExpression(call.Expression) { - if containsNarrowableReference(call.Expression.AsPropertyAccessExpression().Expression) { + if containsNarrowableReference(call.Expression.Expression()) { return true } } @@ -2676,7 +2659,7 @@ func isNarrowingBinaryExpression(expr *ast.BinaryExpression) bool { func isNarrowableOperand(expr *ast.Node) bool { switch expr.Kind { case ast.KindParenthesizedExpression: - return isNarrowableOperand(expr.AsParenthesizedExpression().Expression) + return isNarrowableOperand(expr.Expression()) case ast.KindBinaryExpression: binary := expr.AsBinaryExpression() switch binary.OperatorToken.Kind { @@ -2690,7 +2673,7 @@ func isNarrowableOperand(expr *ast.Node) bool { } func isNarrowingTypeOfOperands(expr1 *ast.Node, expr2 *ast.Node) bool { - return ast.IsTypeOfExpression(expr1) && isNarrowableOperand(expr1.AsTypeOfExpression().Expression) && ast.IsStringLiteralLike(expr2) + return ast.IsTypeOfExpression(expr1) && isNarrowableOperand(expr1.Expression()) && ast.IsStringLiteralLike(expr2) } func (b *Binder) errorOnNode(node *ast.Node, message *diagnostics.Message, args ...any) { @@ -2737,24 +2720,10 @@ func isSignedNumericLiteral(node *ast.Node) bool { } func getOptionalSymbolFlagForNode(node *ast.Node) ast.SymbolFlags { - postfixToken := getPostfixTokenFromNode(node) + postfixToken := node.PostfixToken() return core.IfElse(postfixToken != nil && postfixToken.Kind == ast.KindQuestionToken, ast.SymbolFlagsOptional, ast.SymbolFlagsNone) } -func getPostfixTokenFromNode(node *ast.Node) *ast.Node { - switch node.Kind { - case ast.KindPropertyDeclaration: - return node.AsPropertyDeclaration().PostfixToken - case ast.KindPropertySignature: - return node.AsPropertySignatureDeclaration().PostfixToken - case ast.KindMethodDeclaration: - return node.AsMethodDeclaration().PostfixToken - case ast.KindMethodSignature: - return node.AsMethodSignatureDeclaration().PostfixToken - } - panic("Unhandled case in getPostfixTokenFromNode") -} - func isAsyncFunction(node *ast.Node) bool { switch node.Kind { case ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindArrowFunction, ast.KindMethodDeclaration: @@ -2790,12 +2759,8 @@ func unusedLabelIsError(options core.SourceFileAffectingCompilerOptions) bool { func isStatementCondition(node *ast.Node) bool { switch node.Parent.Kind { - case ast.KindIfStatement: - return node.Parent.AsIfStatement().Expression == node - case ast.KindWhileStatement: - return node.Parent.AsWhileStatement().Expression == node - case ast.KindDoStatement: - return node.Parent.AsDoStatement().Expression == node + case ast.KindIfStatement, ast.KindWhileStatement, ast.KindDoStatement: + return node.Parent.Expression() == node case ast.KindForStatement: return node.Parent.AsForStatement().Condition == node case ast.KindConditionalExpression: diff --git a/internal/binder/nameresolver.go b/internal/binder/nameresolver.go index a14c9319d4..459a2839c1 100644 --- a/internal/binder/nameresolver.go +++ b/internal/binder/nameresolver.go @@ -174,7 +174,7 @@ loop: } } case ast.KindExpressionWithTypeArguments: - if lastLocation == location.AsExpressionWithTypeArguments().Expression && ast.IsHeritageClause(location.Parent) && location.Parent.AsHeritageClause().Token == ast.KindExtendsKeyword { + if lastLocation == location.Expression() && ast.IsHeritageClause(location.Parent) && location.Parent.AsHeritageClause().Token == ast.KindExtendsKeyword { container := location.Parent.Parent if ast.IsClassLike(container) { result = r.lookup(r.getSymbolOfDeclaration(container).Members, name, meaning&ast.SymbolFlagsType) @@ -217,8 +217,8 @@ loop: } if meaning&ast.SymbolFlagsFunction != 0 { functionName := location.AsFunctionExpression().Name() - if functionName != nil && name == functionName.AsIdentifier().Text { - result = location.AsFunctionExpression().Symbol + if functionName != nil && name == functionName.Text() { + result = location.Symbol() break loop } } @@ -267,14 +267,14 @@ loop: case ast.KindInferType: if meaning&ast.SymbolFlagsTypeParameter != 0 { parameterName := location.AsInferTypeNode().TypeParameter.AsTypeParameter().Name() - if parameterName != nil && name == parameterName.AsIdentifier().Text { - result = location.AsInferTypeNode().TypeParameter.AsTypeParameter().Symbol + if parameterName != nil && name == parameterName.Text() { + result = location.AsInferTypeNode().TypeParameter.Symbol() break loop } } case ast.KindExportSpecifier: exportSpecifier := location.AsExportSpecifier() - if lastLocation != nil && lastLocation == exportSpecifier.PropertyName && location.Parent.Parent.AsExportDeclaration().ModuleSpecifier != nil { + if lastLocation != nil && lastLocation == exportSpecifier.PropertyName && location.Parent.Parent.ModuleSpecifier() != nil { location = location.Parent.Parent.Parent } } diff --git a/internal/checker/checker.go b/internal/checker/checker.go index 8cd1623765..5b6fde57ec 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -1627,7 +1627,7 @@ func (c *Checker) maybeMappedType(node *ast.Node, symbol *ast.Symbol) bool { for ast.IsComputedPropertyName(node) || ast.IsPropertySignatureDeclaration(node) { node = node.Parent } - if ast.IsTypeLiteralNode(node) && len(node.AsTypeLiteralNode().Members.Nodes) == 1 { + if ast.IsTypeLiteralNode(node) && len(node.Members()) == 1 { t := c.getDeclaredTypeOfSymbol(symbol) return t.flags&TypeFlagsUnion != 0 && c.allTypesAssignableToKind(t, TypeFlagsStringOrNumberLiteral) } @@ -1828,7 +1828,7 @@ func (c *Checker) isBlockScopedNameDeclaredBeforeUse(declaration *ast.Node, usag if usage.Flags&ast.NodeFlagsJSDoc != 0 || IsInTypeQuery(usage) || c.isInAmbientOrTypeNode(usage) { return true } - if declaration.Pos() <= usage.Pos() && !(ast.IsPropertyDeclaration(declaration) && isThisProperty(usage.Parent) && declaration.Initializer() == nil && !isExclamationToken(declaration.AsPropertyDeclaration().PostfixToken)) { + if declaration.Pos() <= usage.Pos() && !(ast.IsPropertyDeclaration(declaration) && isThisProperty(usage.Parent) && declaration.Initializer() == nil && !isExclamationToken(declaration.PostfixToken())) { // declaration is before usage switch { case declaration.Kind == ast.KindBindingElement: @@ -2360,7 +2360,7 @@ func (c *Checker) checkDeferredNode(node *ast.Node) { case ast.KindTypeAssertionExpression, ast.KindAsExpression: c.checkAssertionDeferred(node) case ast.KindVoidExpression: - c.checkExpression(node.AsVoidExpression().Expression) + c.checkExpression(node.Expression()) case ast.KindBinaryExpression: if ast.IsInstanceOfExpression(node) { c.resolveUntypedCall(node) @@ -2687,7 +2687,7 @@ func (c *Checker) checkConstructorDeclaration(node *ast.Node) { c.error(superCall, diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers) } else { var superCallStatement *ast.Node - for _, statement := range node.Body().AsBlock().Statements.Nodes { + for _, statement := range node.Body().Statements() { if ast.IsExpressionStatement(statement) && isSuperCall(ast.SkipOuterExpressions(statement.Expression(), ast.OEKAll)) { superCallStatement = statement break @@ -2928,7 +2928,7 @@ func (c *Checker) getTypePredicateParent(node *ast.Node) *ast.SignatureDeclarati } func (c *Checker) checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern *ast.Node, predicateVariableNode *ast.Node, predicateVariableName string) bool { - for _, element := range pattern.AsBindingPattern().Elements.Nodes { + for _, element := range pattern.Elements() { name := element.Name() if name == nil { continue @@ -3045,7 +3045,7 @@ func (c *Checker) checkArrayType(node *ast.Node) { func (c *Checker) checkTupleType(node *ast.Node) { seenOptionalElement := false seenRestElement := false - elements := node.AsTupleTypeNode().Elements.Nodes + elements := node.Elements() for _, e := range elements { flags := c.getTupleElementFlags(e) if flags&ElementFlagsVariadic != 0 { @@ -3759,14 +3759,14 @@ func (c *Checker) isSymbolUsedInConditionBody(expr *ast.Node, body *ast.Node, te func (c *Checker) checkDoStatement(node *ast.Node) { c.checkGrammarStatementInAmbientContext(node) - c.checkSourceElement(node.AsDoStatement().Statement) + c.checkSourceElement(node.Statement()) c.checkTruthinessExpression(node.Expression(), CheckModeNormal) } func (c *Checker) checkWhileStatement(node *ast.Node) { c.checkGrammarStatementInAmbientContext(node) c.checkTruthinessExpression(node.Expression(), CheckModeNormal) - c.checkSourceElement(node.AsWhileStatement().Statement) + c.checkSourceElement(node.Statement()) } func (c *Checker) checkForStatement(node *ast.Node) { @@ -3967,7 +3967,7 @@ func (c *Checker) checkWithStatement(node *ast.Node) { sourceFile := ast.GetSourceFileOfNode(node) if !c.hasParseDiagnostics(sourceFile) { start := scanner.GetRangeOfTokenAtPosition(sourceFile, node.Pos()).Pos() - end := node.AsWithStatement().Statement.Pos() + end := node.Statement().Pos() c.grammarErrorAtPos(sourceFile.AsNode(), start, end-start, diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any) } } @@ -3996,7 +3996,7 @@ func (c *Checker) checkSwitchStatement(node *ast.Node) { c.checkTypeComparableTo(caseType, expressionType, clause.Expression(), nil /*headMessage*/) } } - c.checkSourceElements(clause.AsCaseOrDefaultClause().Statements.Nodes) + c.checkSourceElements(clause.Statements()) if c.compilerOptions.NoFallthroughCasesInSwitch.IsTrue() { if flowNode := clause.AsCaseOrDefaultClause().FallthroughFlowNode; flowNode != nil && c.isReachableFlowNode(flowNode) { c.error(clause, diagnostics.Fallthrough_case_in_switch) @@ -4014,7 +4014,7 @@ func (c *Checker) checkLabeledStatement(node *ast.Node) { labelText := labelNode.Text() if !c.checkGrammarStatementInAmbientContext(node) { for current := node.Parent; current != nil && !ast.IsFunctionLike(current); current = current.Parent { - if ast.IsLabeledStatement(current) && current.AsLabeledStatement().Label.Text() == labelText { + if ast.IsLabeledStatement(current) && current.Label().Text() == labelText { c.grammarErrorOnNode(labelNode, diagnostics.Duplicate_label_0, labelText) break } @@ -4024,7 +4024,7 @@ func (c *Checker) checkLabeledStatement(node *ast.Node) { } func (c *Checker) checkThrowStatement(node *ast.Node) { - throwExpr := node.AsThrowStatement().Expression + throwExpr := node.Expression() if !c.checkGrammarStatementInAmbientContext(node) { if ast.IsIdentifier(throwExpr) && len(throwExpr.Text()) == 0 { c.grammarErrorAtPos(node, throwExpr.Pos(), 0 /*length*/, diagnostics.Line_break_not_permitted_here) @@ -4411,7 +4411,7 @@ basePropertyCheck: }) { constructor := ast.FindConstructorDeclaration(ast.GetClassLikeDeclarationOfSymbol(t.symbol)) propName := uninitialized.Name() - if isExclamationToken(uninitialized.AsPropertyDeclaration().PostfixToken) || constructor == nil || !ast.IsIdentifier(propName) || !c.strictNullChecks || !c.isPropertyInitializedInConstructor(propName, t, constructor) { + if isExclamationToken(uninitialized.PostfixToken()) || constructor == nil || !ast.IsIdentifier(propName) || !c.strictNullChecks || !c.isPropertyInitializedInConstructor(propName, t, constructor) { errorMessage := diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration c.error(core.OrElse(ast.GetNameOfDeclaration(derived.ValueDeclaration), derived.ValueDeclaration), errorMessage, c.symbolToString(base), c.TypeToString(baseType)) } @@ -4727,7 +4727,7 @@ func (c *Checker) checkPropertyInitialization(node *ast.Node) { } func (c *Checker) isPropertyWithoutInitializer(node *ast.Node) bool { - return ast.IsPropertyDeclaration(node) && !hasAbstractModifier(node) && !isExclamationToken(node.AsPropertyDeclaration().PostfixToken) && node.Initializer() == nil + return ast.IsPropertyDeclaration(node) && !hasAbstractModifier(node) && !isExclamationToken(node.PostfixToken()) && node.Initializer() == nil } func (c *Checker) isPropertyInitializedInStaticBlocks(propName *ast.Node, propType *Type, staticBlocks []*ast.Node, startPos int, endPos int) bool { @@ -4969,7 +4969,7 @@ func (c *Checker) checkModuleDeclaration(node *ast.Node) { // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). checkBody := isGlobalAugmentation || c.getSymbolOfDeclaration(node).Flags&ast.SymbolFlagsTransient != 0 if checkBody && node.Body() != nil { - for _, statement := range node.Body().AsModuleBlock().Statements.Nodes { + for _, statement := range node.Body().Statements() { c.checkModuleAugmentationElement(statement) } } @@ -5029,7 +5029,7 @@ func (c *Checker) checkModuleAugmentationElement(node *ast.Node) { case ast.KindBindingElement, ast.KindVariableDeclaration: name := node.Name() if ast.IsBindingPattern(name) { - for _, el := range name.AsBindingPattern().Elements.Nodes { + for _, el := range name.Elements() { // mark individual names in binding pattern c.checkModuleAugmentationElement(el) } @@ -5054,8 +5054,8 @@ func (c *Checker) checkImportDeclaration(node *ast.Node) { } if c.checkExternalImportOrExportDeclaration(node) { var resolvedModule *ast.Symbol - importClause := node.AsImportDeclaration().ImportClause - moduleSpecifier := node.AsImportDeclaration().ModuleSpecifier + importClause := node.ImportClause() + moduleSpecifier := node.ModuleSpecifier() if importClause != nil && !c.checkGrammarImportClause(importClause.AsImportClause()) { if importClause.Name() != nil { c.checkImportBinding(importClause) @@ -5065,9 +5065,9 @@ func (c *Checker) checkImportDeclaration(node *ast.Node) { if ast.IsNamespaceImport(namedBindings) { c.checkImportBinding(namedBindings) } else { - resolvedModule = c.resolveExternalModuleName(node, node.AsImportDeclaration().ModuleSpecifier, false) + resolvedModule = c.resolveExternalModuleName(node, node.ModuleSpecifier(), false) if resolvedModule != nil { - for _, binding := range namedBindings.AsNamedImports().Elements.Nodes { + for _, binding := range namedBindings.Elements() { c.checkImportBinding(binding) } } @@ -5257,11 +5257,11 @@ func (c *Checker) checkImportEqualsDeclaration(node *ast.Node) { c.checkTypeNameIsReserved(node.Name(), diagnostics.Import_name_cannot_be_0) } } - if node.AsImportEqualsDeclaration().IsTypeOnly { + if node.IsTypeOnly() { c.grammarErrorOnNode(node, diagnostics.An_import_alias_cannot_use_import_type) } } else { - if core.ModuleKindES2015 <= c.moduleKind && c.moduleKind <= core.ModuleKindESNext && !node.AsImportEqualsDeclaration().IsTypeOnly && node.Flags&ast.NodeFlagsAmbient == 0 { + if core.ModuleKindES2015 <= c.moduleKind && c.moduleKind <= core.ModuleKindESNext && !node.IsTypeOnly() && node.Flags&ast.NodeFlagsAmbient == 0 { // Import equals declaration cannot be emitted as ESM c.grammarErrorOnNode(node, diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead) } @@ -5285,7 +5285,7 @@ func (c *Checker) checkExportDeclaration(node *ast.Node) { if exportDecl.ExportClause != nil && !ast.IsNamespaceExport(exportDecl.ExportClause) { // export { x, y } // export { x, y } from "foo" - for _, binding := range exportDecl.ExportClause.AsNamedExports().Elements.Nodes { + for _, binding := range exportDecl.ExportClause.Elements() { c.checkExportSpecifier(binding) } inAmbientExternalModule := ast.IsModuleBlock(node.Parent) && ast.IsAmbientModule(node.Parent.Parent) @@ -5310,8 +5310,8 @@ func (c *Checker) checkExportDeclaration(node *ast.Node) { func (c *Checker) checkExportSpecifier(node *ast.Node) { c.checkAliasSymbol(node) - hasModuleSpecifier := node.Parent.Parent.AsExportDeclaration().ModuleSpecifier != nil - c.checkModuleExportName(node.AsExportSpecifier().PropertyName, hasModuleSpecifier) + hasModuleSpecifier := node.Parent.Parent.ModuleSpecifier() != nil + c.checkModuleExportName(node.PropertyName(), hasModuleSpecifier) c.checkModuleExportName(node.Name(), true /*allowStringLiteral*/) if !hasModuleSpecifier { @@ -5575,7 +5575,7 @@ func (c *Checker) checkVariableLikeDeclaration(node *ast.Node) { } // For a binding pattern, check contained binding elements if ast.IsBindingPattern(name) { - c.checkSourceElements(name.AsBindingPattern().Elements.Nodes) + c.checkSourceElements(name.Elements()) } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body if initializer != nil && ast.IsPartOfParameterDeclaration(node) && ast.NodeIsMissing(ast.GetContainingFunction(node).Body()) { @@ -5588,7 +5588,7 @@ func (c *Checker) checkVariableLikeDeclaration(node *ast.Node) { return } needCheckInitializer := initializer != nil && node.Parent.Parent.Kind != ast.KindForInStatement - needCheckWidenedType := !core.Some(name.AsBindingPattern().Elements.Nodes, func(n *ast.Node) bool { return n.Name() != nil }) + needCheckWidenedType := !core.Some(name.Elements(), func(n *ast.Node) bool { return n.Name() != nil }) if needCheckInitializer || needCheckWidenedType { // Don't validate for-in initializer as it is already an error widenedType := c.getWidenedTypeForVariableLikeDeclaration(node, false /*reportErrors*/) @@ -6575,7 +6575,7 @@ func (c *Checker) checkTypeAliasDeclaration(node *ast.Node) { } c.checkExportsOnMergedDeclarations(node) - typeNode := node.AsTypeAliasDeclaration().Type + typeNode := node.Type() typeParameters := node.TypeParameters() c.checkTypeParameters(typeParameters) if typeNode != nil && typeNode.Kind == ast.KindIntrinsicKeyword { @@ -6890,7 +6890,7 @@ func (c *Checker) reportUnusedParameters(node *ast.Node) { } func (c *Checker) reportUnusedBindingElements(node *ast.Node) { - declarations := node.AsBindingPattern().Elements.Nodes + declarations := node.Elements() if len(declarations) > 1 && core.Every(declarations, c.isUnreferencedVariableDeclaration) { c.reportUnusedVariable(node, NewDiagnosticForNode(node, diagnostics.All_destructured_elements_are_unused)) } else { @@ -6917,14 +6917,14 @@ func (c *Checker) isUnreferencedVariableDeclaration(node *ast.Node) bool { return true } if ast.IsBindingPattern(name) { - return core.Every(node.Name().AsBindingPattern().Elements.Nodes, c.isUnreferencedVariableDeclaration) + return core.Every(node.Name().Elements(), c.isUnreferencedVariableDeclaration) } if c.symbolReferenceLinks.Get(c.getSymbolOfDeclaration(node)).referenceKinds&ast.SymbolFlagsVariable != 0 { return false } if ast.IsBindingElement(node) && ast.IsObjectBindingPattern(node.Parent) { // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. - lastElement := core.LastOrNil(node.Parent.AsBindingPattern().Elements.Nodes) + lastElement := core.LastOrNil(node.Parent.Elements()) if node != lastElement && hasDotDotDotToken(lastElement) { return false } @@ -6945,7 +6945,7 @@ func (c *Checker) reportUnusedImports(node *ast.Node, unuseds []*ast.Node) { if ast.IsNamespaceImport(namedBindings) { declarationCount++ } else { - declarationCount += len(namedBindings.AsNamedImports().Elements.Nodes) + declarationCount += len(namedBindings.Elements()) } } if declarationCount > 1 && declarationCount == len(unuseds) { @@ -7022,7 +7022,7 @@ func (c *Checker) checkUnusedRenamedBindingElements() { func (c *Checker) checkExpressionStatement(node *ast.Node) { // Grammar checking c.checkGrammarStatementInAmbientContext(node) - c.checkExpression(node.AsExpressionStatement().Expression) + c.checkExpression(node.Expression()) } // Returns the type of an expression. Unlike checkExpression, this function is simply concerned @@ -7787,7 +7787,7 @@ func (c *Checker) checkRegularExpressionLiteral(node *ast.Node) *Type { } func (c *Checker) checkArrayLiteral(node *ast.Node, checkMode CheckMode) *Type { - elements := node.AsArrayLiteralExpression().Elements.Nodes + elements := node.Elements() elementTypes := make([]*Type, len(elements)) elementInfos := make([]TupleElementInfo, len(elements)) c.pushCachedContextualType(node) @@ -7801,7 +7801,7 @@ func (c *Checker) checkArrayLiteral(node *ast.Node, checkMode CheckMode) *Type { for i, e := range elements { switch { case ast.IsSpreadElement(e): - spreadType := c.checkExpressionEx(e.AsSpreadElement().Expression, checkMode) + spreadType := c.checkExpressionEx(e.Expression(), checkMode) switch { case c.isArrayLikeType(spreadType): elementTypes[i] = spreadType @@ -8098,7 +8098,7 @@ func (c *Checker) checkCallExpression(node *ast.Node, checkMode CheckMode) *Type } } if ast.IsInJSFile(node) && c.isCommonJSRequire(node) { - return c.resolveExternalModuleTypeByLiteral(node.AsCallExpression().Arguments.Nodes[0]) + return c.resolveExternalModuleTypeByLiteral(node.Arguments()[0]) } returnType := c.getReturnTypeOfSignature(signature) // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property @@ -8106,7 +8106,7 @@ func (c *Checker) checkCallExpression(node *ast.Node, checkMode CheckMode) *Type if returnType.flags&TypeFlagsESSymbolLike != 0 && c.isSymbolOrSymbolForCall(node) { return c.getESSymbolLikeTypeForNode(ast.WalkUpParenthesizedExpressions(node.Parent)) } - if ast.IsCallExpression(node) && node.AsCallExpression().QuestionDotToken == nil && ast.IsExpressionStatement(node.Parent) && returnType.flags&TypeFlagsVoid != 0 && c.getTypePredicateOfSignature(signature) != nil { + if ast.IsCallExpression(node) && node.QuestionDotToken() == nil && ast.IsExpressionStatement(node.Parent) && returnType.flags&TypeFlagsVoid != 0 && c.getTypePredicateOfSignature(signature) != nil { if !ast.IsDottedName(node.Expression()) { c.error(node.Expression(), diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name) } else if c.getEffectsSignature(node) == nil { @@ -9667,10 +9667,8 @@ func (c *Checker) resolveUntypedCall(node *ast.Node) *Signature { switch node.Kind { case ast.KindTaggedTemplateExpression: c.checkExpression(node.AsTaggedTemplateExpression().Template) - case ast.KindJsxOpeningElement: - c.checkExpression(node.AsJsxOpeningElement().Attributes) - case ast.KindJsxSelfClosingElement: - c.checkExpression(node.AsJsxSelfClosingElement().Attributes) + case ast.KindJsxOpeningElement, ast.KindJsxSelfClosingElement: + c.checkExpression(node.Attributes()) case ast.KindBinaryExpression: c.checkExpression(node.AsBinaryExpression().Left) case ast.KindCallExpression, ast.KindNewExpression: @@ -10040,7 +10038,7 @@ func (c *Checker) isAritySmaller(signature *Signature, target *ast.Node) bool { targetParameterCount := 0 for targetParameterCount < len(parameters) { param := parameters[targetParameterCount] - if param.Initializer() != nil || param.AsParameterDeclaration().QuestionToken != nil || hasDotDotDotToken(param) { + if param.Initializer() != nil || param.QuestionToken() != nil || hasDotDotDotToken(param) { break } targetParameterCount++ @@ -10133,7 +10131,7 @@ func (c *Checker) assignParameterType(parameter *ast.Symbol, contextualType *Typ // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push // the destructured type into the contained binding elements. func (c *Checker) assignBindingElementTypes(pattern *ast.Node, parentType *Type) { - for _, element := range pattern.AsBindingPattern().Elements.Nodes { + for _, element := range pattern.Elements() { name := element.Name() if name != nil { t := c.getBindingElementTypeFromParentType(element, parentType, false /*noTupleBoundsCheck*/) @@ -10351,7 +10349,7 @@ func (c *Checker) checkMetaProperty(node *ast.Node) *Type { return c.checkNewTargetMetaProperty(node) case ast.KindImportKeyword: if node.Name().Text() == "defer" { - debug.Assert(!ast.IsCallExpression(node.Parent) || node.Parent.AsCallExpression().Expression != node, "Trying to get the type of `import.defer` in `import.defer(...)`") + debug.Assert(!ast.IsCallExpression(node.Parent) || node.Parent.Expression() != node, "Trying to get the type of `import.defer` in `import.defer(...)`") return c.errorType } return c.checkImportMetaProperty(node) @@ -11288,7 +11286,7 @@ func (c *Checker) checkPropertyNotUsedBeforeDeclaration(prop *ast.Symbol, node * } func (c *Checker) isOptionalPropertyDeclaration(node *ast.Node) bool { - return ast.IsPropertyDeclaration(node) && !ast.HasAccessorModifier(node) && ast.IsQuestionToken(node.AsPropertyDeclaration().PostfixToken) + return ast.IsPropertyDeclaration(node) && !ast.HasAccessorModifier(node) && ast.IsQuestionToken(node.PostfixToken()) } func (c *Checker) isPropertyDeclaredInAncestorClass(prop *ast.Symbol) bool { @@ -11556,8 +11554,8 @@ func (c *Checker) getEnclosingClassFromThisParameter(node *ast.Node) *Type { // 1. The type of a syntactic 'this' parameter in the enclosing function scope thisParameter := getThisParameterFromNodeContext(node) var thisType *Type - if thisParameter != nil && thisParameter.AsParameterDeclaration().Type != nil { - thisType = c.getTypeFromTypeNode(thisParameter.AsParameterDeclaration().Type) + if thisParameter != nil && thisParameter.Type() != nil { + thisType = c.getTypeFromTypeNode(thisParameter.Type()) } if thisType != nil { // 2. The constraint of a type parameter used for an explicit 'this' parameter @@ -12123,7 +12121,7 @@ func (c *Checker) checkDestructuringAssignment(node *ast.Node, sourceType *Type, } func (c *Checker) checkObjectLiteralAssignment(node *ast.Node, sourceType *Type, rightIsThis bool) *Type { - properties := node.AsObjectLiteralExpression().Properties + properties := node.PropertyList() if c.strictNullChecks && len(properties.Nodes) == 0 { return c.checkNonNullType(sourceType, node) } @@ -12135,7 +12133,7 @@ func (c *Checker) checkObjectLiteralAssignment(node *ast.Node, sourceType *Type, // Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided func (c *Checker) checkObjectLiteralDestructuringPropertyAssignment(node *ast.Node, objectLiteralType *Type, propertyIndex int, allProperties *ast.NodeList, rightIsThis bool) *Type { - properties := node.AsObjectLiteralExpression().Properties.Nodes + properties := node.Properties() property := properties[propertyIndex] if ast.IsPropertyAssignment(property) || ast.IsShorthandPropertyAssignment(property) { name := property.Name() @@ -12178,15 +12176,15 @@ func (c *Checker) checkObjectLiteralDestructuringPropertyAssignment(node *ast.No } func (c *Checker) checkArrayLiteralAssignment(node *ast.Node, sourceType *Type, checkMode CheckMode) *Type { - elements := node.AsArrayLiteralExpression().Elements + elements := node.Elements() // This elementType will be used if the specific property corresponding to this index is not // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). possiblyOutOfBoundsType := core.OrElse(c.checkIteratedTypeOrElementType(IterationUseDestructuring|IterationUsePossiblyOutOfBounds, sourceType, c.undefinedType, node), c.errorType) inBoundsType := core.IfElse(c.compilerOptions.NoUncheckedIndexedAccess == core.TSTrue, nil, possiblyOutOfBoundsType) - for i := range elements.Nodes { + for i := range elements { t := possiblyOutOfBoundsType - if elements.Nodes[i].Kind == ast.KindSpreadElement { + if elements[i].Kind == ast.KindSpreadElement { if inBoundsType == nil { inBoundsType = core.OrElse(c.checkIteratedTypeOrElementType(IterationUseDestructuring, sourceType, c.undefinedType, node), c.errorType) } @@ -12198,7 +12196,7 @@ func (c *Checker) checkArrayLiteralAssignment(node *ast.Node, sourceType *Type, } func (c *Checker) checkArrayLiteralDestructuringElementAssignment(node *ast.Node, sourceType *Type, elementIndex int, elementType *Type, checkMode CheckMode) *Type { - elements := node.AsArrayLiteralExpression().Elements + elements := node.ElementList() element := elements.Nodes[elementIndex] if !ast.IsOmittedExpression(element) { if !ast.IsSpreadElement(element) { @@ -12701,7 +12699,7 @@ func (c *Checker) checkObjectLiteral(node *ast.Node, checkMode CheckMode) *Type // Spreads may cause an early bail; ensure computed names are always checked (this is cached) // As otherwise they may not be checked until exports for the type at this position are retrieved, // which may never occur. - for _, elem := range node.AsObjectLiteralExpression().Properties.Nodes { + for _, elem := range node.Properties() { if elem.Name() != nil && ast.IsComputedPropertyName(elem.Name()) { c.checkComputedPropertyName(elem.Name()) } @@ -12733,11 +12731,11 @@ func (c *Checker) checkObjectLiteral(node *ast.Node, checkMode CheckMode) *Type return result } // expando object literals have empty properties but filled exports -- skip straight to type creation - if len(node.AsObjectLiteralExpression().Properties.Nodes) == 0 && node.Symbol() != nil && len(node.Symbol().Exports) > 0 { + if len(node.Properties()) == 0 && node.Symbol() != nil && len(node.Symbol().Exports) != 0 { propertiesTable = node.Symbol().Exports return createObjectLiteralType() } - for _, memberDecl := range node.AsObjectLiteralExpression().Properties.Nodes { + for _, memberDecl := range node.Properties() { member := c.getSymbolOfDeclaration(memberDecl) var computedNameType *Type if memberDecl.Name() != nil && memberDecl.Name().Kind == ast.KindComputedPropertyName { @@ -13121,7 +13119,7 @@ func (c *Checker) hasDefaultValue(node *ast.Node) bool { func (c *Checker) isConstContext(node *ast.Node) bool { parent := node.Parent - return isConstAssertion(parent) || + return ast.IsConstAssertion(parent) || c.isValidConstAssertionArgument(node) && c.isConstTypeVariable(c.getContextualType(node, ContextFlagsNone), 0) || (ast.IsParenthesizedExpression(parent) || ast.IsArrayLiteralExpression(parent) || ast.IsSpreadElement(parent)) && c.isConstContext(parent) || (ast.IsPropertyAssignment(parent) || ast.IsShorthandPropertyAssignment(parent) || ast.IsTemplateSpan(parent)) && c.isConstContext(parent.Parent) @@ -13254,7 +13252,7 @@ func (c *Checker) getNarrowedTypeOfSymbol(symbol *ast.Symbol, location *ast.Node // the binding pattern AST instance for '{ kind, payload }' as a pseudo-reference and narrow this reference // as if it occurred in the specified location. We then recompute the narrowed binding element type by // destructuring from the narrowed parent type. - if ast.IsBindingElement(declaration) && declaration.Initializer() == nil && !hasDotDotDotToken(declaration) && len(declaration.Parent.AsBindingPattern().Elements.Nodes) >= 2 { + if ast.IsBindingElement(declaration) && declaration.Initializer() == nil && !hasDotDotDotToken(declaration) && len(declaration.Parent.Elements()) >= 2 { parent := declaration.Parent.Parent rootDeclaration := ast.GetRootDeclaration(parent) if ast.IsVariableDeclaration(rootDeclaration) && c.getCombinedNodeFlagsCached(rootDeclaration)&ast.NodeFlagsConstant != 0 || ast.IsParameter(rootDeclaration) { @@ -13369,7 +13367,7 @@ func (c *Checker) getResolvedSymbol(node *ast.Node) *ast.Symbol { if links.resolvedSymbol == nil { var symbol *ast.Symbol if !ast.NodeIsMissing(node) { - symbol = c.resolveName(node, node.AsIdentifier().Text, ast.SymbolFlagsValue|ast.SymbolFlagsExportValue, + symbol = c.resolveName(node, node.Text(), ast.SymbolFlagsValue|ast.SymbolFlagsExportValue, c.getCannotFindNameDiagnosticForName(node), !ast.IsWriteOnlyAccess(node), false /*excludeGlobals*/) } links.resolvedSymbol = core.OrElse(symbol, c.unknownSymbol) @@ -13382,7 +13380,7 @@ func (c *Checker) getResolvedSymbolOrNil(node *ast.Node) *ast.Symbol { } func (c *Checker) getCannotFindNameDiagnosticForName(node *ast.Node) *diagnostics.Message { - switch node.AsIdentifier().Text { + switch node.Text() { case "document", "console": return diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom case "$": @@ -14097,10 +14095,10 @@ func (c *Checker) reportNonDefaultExport(moduleSymbol *ast.Symbol, node *ast.Nod } if exportStar != nil { defaultExport := core.Find(exportStar.Declarations, func(decl *ast.Declaration) bool { - if !(ast.IsExportDeclaration(decl) && decl.AsExportDeclaration().ModuleSpecifier != nil) { + if !(ast.IsExportDeclaration(decl) && decl.ModuleSpecifier() != nil) { return false } - resolvedExternalModuleName := c.resolveExternalModuleName(decl, decl.AsExportDeclaration().ModuleSpecifier, false /*ignoreErrors*/) + resolvedExternalModuleName := c.resolveExternalModuleName(decl, decl.ModuleSpecifier(), false /*ignoreErrors*/) return resolvedExternalModuleName != nil && resolvedExternalModuleName.Exports[ast.InternalSymbolNameDefault] != nil }) if defaultExport != nil { @@ -14231,7 +14229,7 @@ func (c *Checker) getExternalModuleMember(node *ast.Node, specifier *ast.Node, d func (c *Checker) getPropertyOfVariable(symbol *ast.Symbol, name string) *ast.Symbol { if symbol.Flags&ast.SymbolFlagsVariable != 0 { - typeAnnotation := symbol.ValueDeclaration.AsVariableDeclaration().Type + typeAnnotation := symbol.ValueDeclaration.Type() if typeAnnotation != nil { return c.resolveSymbol(c.getPropertyOfType(c.getTypeFromTypeNode(typeAnnotation), name)) } @@ -14443,7 +14441,7 @@ func (c *Checker) getTargetOfExportSpecifier(node *ast.Node, meaning ast.SymbolF exportDeclaration := node.Parent.Parent var resolved *ast.Symbol switch { - case exportDeclaration.AsExportDeclaration().ModuleSpecifier != nil: + case exportDeclaration.ModuleSpecifier() != nil: resolved = c.getExternalModuleMember(exportDeclaration, node, dontResolveAlias) case ast.IsStringLiteral(name): resolved = nil @@ -14455,7 +14453,7 @@ func (c *Checker) getTargetOfExportSpecifier(node *ast.Node, meaning ast.SymbolF } func (c *Checker) getTargetOfExportAssignment(node *ast.Node, dontResolveAlias bool) *ast.Symbol { - resolved := c.getTargetOfAliasLikeExpression(node.AsExportAssignment().Expression, dontResolveAlias) + resolved := c.getTargetOfAliasLikeExpression(node.Expression(), dontResolveAlias) c.markSymbolOfAliasDeclarationIfTypeOnly(node, nil /*immediateTarget*/, resolved, false /*overwriteEmpty*/, nil, "") return resolved } @@ -14506,7 +14504,7 @@ func (c *Checker) getModuleSpecifierForImportOrExport(node *ast.Node) *ast.Node return getModuleSpecifierFromNode(node.Parent) case ast.KindImportEqualsDeclaration: if ast.IsExternalModuleReference(node.AsImportEqualsDeclaration().ModuleReference) { - return node.AsImportEqualsDeclaration().ModuleReference.AsExternalModuleReference().Expression + return node.AsImportEqualsDeclaration().ModuleReference.Expression() } else { return nil } @@ -14525,9 +14523,9 @@ func (c *Checker) getModuleSpecifierForImportOrExport(node *ast.Node) *ast.Node func getModuleSpecifierFromNode(node *ast.Node) *ast.Node { switch node.Kind { case ast.KindImportDeclaration, ast.KindJSImportDeclaration: - return node.AsImportDeclaration().ModuleSpecifier + return node.ModuleSpecifier() case ast.KindExportDeclaration: - return node.AsExportDeclaration().ModuleSpecifier + return node.ModuleSpecifier() } panic("Unhandled case in getModuleSpecifierFromNode") } @@ -14623,31 +14621,31 @@ func (c *Checker) resolveExternalModule(location *ast.Node, moduleReference stri contextSpecifier = location.AsModuleDeclaration().Name() } else if ast.IsLiteralImportTypeNode(location) { contextSpecifier = location.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal - } else if ast.IsVariableDeclaration(location) && location.AsVariableDeclaration().Initializer != nil && ast.IsRequireCall(location.AsVariableDeclaration().Initializer, true /*requireStringLiteralLikeArgument*/) { - contextSpecifier = location.AsVariableDeclaration().Initializer.AsCallExpression().Arguments.Nodes[0] + } else if ast.IsVariableDeclaration(location) && location.Initializer() != nil && ast.IsRequireCall(location.Initializer(), true /*requireStringLiteralLikeArgument*/) { + contextSpecifier = location.Initializer().Arguments()[0] } else { ancestor := ast.FindAncestor(location, ast.IsImportCall) if ancestor != nil { - contextSpecifier = ancestor.AsCallExpression().Arguments.Nodes[0] + contextSpecifier = ancestor.Arguments()[0] } if ancestor == nil { ancestor = ast.FindAncestor(location, ast.IsImportDeclarationOrJSImportDeclaration) if ancestor != nil { - contextSpecifier = ancestor.AsImportDeclaration().ModuleSpecifier + contextSpecifier = ancestor.ModuleSpecifier() } } if ancestor == nil { ancestor = ast.FindAncestor(location, ast.IsExportDeclaration) if ancestor != nil { - contextSpecifier = ancestor.AsExportDeclaration().ModuleSpecifier + contextSpecifier = ancestor.ModuleSpecifier() } } if ancestor == nil { ancestor = ast.FindAncestor(location, ast.IsImportEqualsDeclaration) if ancestor != nil { if moduleRefrence := ancestor.AsImportEqualsDeclaration().ModuleReference; moduleRefrence.Kind == ast.KindExternalModuleReference { - contextSpecifier = moduleRefrence.AsExternalModuleReference().Expression + contextSpecifier = moduleRefrence.Expression() } } } @@ -14784,7 +14782,7 @@ func (c *Checker) resolveExternalModule(location *ast.Node, moduleReference stri } var message *diagnostics.Message - if overrideHost != nil && overrideHost.Kind == ast.KindImportDeclaration && overrideHost.AsImportDeclaration().ImportClause != nil && overrideHost.AsImportDeclaration().ImportClause.IsTypeOnly() { + if overrideHost != nil && overrideHost.Kind == ast.KindImportDeclaration && overrideHost.ImportClause() != nil && overrideHost.ImportClause().IsTypeOnly() { message = diagnostics.Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute } else if overrideHost != nil && overrideHost.Kind == ast.KindImportType { message = diagnostics.Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute @@ -15036,9 +15034,9 @@ func (c *Checker) resolveESModuleSymbol(moduleSymbol *ast.Symbol, referencingLoc if namespaceImport != nil || ast.IsImportCall(referenceParent) { var reference *ast.Node if ast.IsImportCall(referenceParent) { - reference = referenceParent.AsCallExpression().Arguments.Nodes[0] + reference = referenceParent.Arguments()[0] } else { - reference = referenceParent.AsImportDeclaration().ModuleSpecifier + reference = referenceParent.ModuleSpecifier() } typ := c.getTypeOfSymbol(symbol) defaultOnlyType := c.getTypeWithSyntheticDefaultOnly(typ, symbol, moduleSymbol, reference) @@ -15244,7 +15242,7 @@ func (c *Checker) resolveEntityName(name *ast.Node, meaning ast.SymbolFlags, ign if resolveLocation == nil { resolveLocation = name } - symbol = c.getMergedSymbol(c.resolveName(resolveLocation, name.AsIdentifier().Text, meaning, message, true /*isUse*/, false /*excludeGlobals*/)) + symbol = c.getMergedSymbol(c.resolveName(resolveLocation, name.Text(), meaning, message, true /*isUse*/, false /*excludeGlobals*/)) case ast.KindQualifiedName: qualified := name.AsQualifiedName() symbol = c.resolveQualifiedName(name, qualified.Left, qualified.Right, meaning, ignoreErrors, dontResolveAlias, location) @@ -15280,9 +15278,9 @@ func (c *Checker) resolveQualifiedName(name *ast.Node, left *ast.Node, right *as ast.IsInJSFile(namespace.ValueDeclaration) && c.compilerOptions.GetModuleResolutionKind() != core.ModuleResolutionKindBundler && ast.IsVariableDeclaration(namespace.ValueDeclaration) && - namespace.ValueDeclaration.AsVariableDeclaration().Initializer != nil && - c.isCommonJSRequire(namespace.ValueDeclaration.AsVariableDeclaration().Initializer) { - moduleName := namespace.ValueDeclaration.AsVariableDeclaration().Initializer.AsCallExpression().Arguments.Nodes[0] + namespace.ValueDeclaration.Initializer() != nil && + c.isCommonJSRequire(namespace.ValueDeclaration.Initializer()) { + moduleName := namespace.ValueDeclaration.Initializer().Arguments()[0] moduleSym := c.resolveExternalModuleName(moduleName, moduleName, false /*ignoreErrors*/) if moduleSym != nil { resolvedModuleSymbol := c.resolveExternalModuleSymbol(moduleSym, false /*dontResolveAlias*/) @@ -15291,7 +15289,7 @@ func (c *Checker) resolveQualifiedName(name *ast.Node, left *ast.Node, right *as } } } - text := right.AsIdentifier().Text + text := right.Text() symbol := c.getMergedSymbol(c.getSymbol(c.getExportsOfSymbol(namespace), text, meaning)) if symbol == nil && namespace.Flags&ast.SymbolFlagsAlias != 0 { // `namespace` can be resolved further if there was a symbol merge with a re-export @@ -15320,7 +15318,7 @@ func (c *Checker) resolveQualifiedName(name *ast.Node, left *ast.Node, right *as exportedTypeSymbol := c.getMergedSymbol(c.getSymbol(c.getExportsOfSymbol(namespace), text, ast.SymbolFlagsType)) if exportedTypeSymbol != nil { qualified := name.Parent.AsQualifiedName() - c.error(qualified.Right, diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, c.symbolToString(exportedTypeSymbol), qualified.Right.AsIdentifier().Text) + c.error(qualified.Right, diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, c.symbolToString(exportedTypeSymbol), qualified.Right.Text()) return nil } } @@ -15333,14 +15331,14 @@ func (c *Checker) resolveQualifiedName(name *ast.Node, left *ast.Node, right *as func (c *Checker) tryGetQualifiedNameAsValue(node *ast.Node) *ast.Symbol { id := ast.GetFirstIdentifier(node) - symbol := c.resolveName(id, id.AsIdentifier().Text, ast.SymbolFlagsValue, nil /*nameNotFoundMessage*/, true /*isUse*/, false /*excludeGlobals*/) + symbol := c.resolveName(id, id.Text(), ast.SymbolFlagsValue, nil /*nameNotFoundMessage*/, true /*isUse*/, false /*excludeGlobals*/) if symbol == nil { return nil } n := id for ast.IsQualifiedName(n.Parent) { t := c.getTypeOfSymbol(symbol) - symbol = c.getPropertyOfType(t, n.Parent.AsQualifiedName().Right.AsIdentifier().Text) + symbol = c.getPropertyOfType(t, n.Parent.AsQualifiedName().Right.Text()) if symbol == nil { return nil } @@ -15599,8 +15597,8 @@ func (c *Checker) getExportsOfModuleWorker(moduleSymbol *ast.Symbol) (exports as nestedSymbols := make(ast.SymbolTable) lookupTable := make(ExportCollisionTable) for _, node := range exportStars.Declarations { - resolvedModule := c.resolveExternalModuleName(node, node.AsExportDeclaration().ModuleSpecifier, false /*ignoreErrors*/) - exportedSymbols := visit(resolvedModule, node, isTypeOnly || node.AsExportDeclaration().IsTypeOnly) + resolvedModule := c.resolveExternalModuleName(node, node.ModuleSpecifier(), false /*ignoreErrors*/) + exportedSymbols := visit(resolvedModule, node, isTypeOnly || node.IsTypeOnly()) c.extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node) } for id, s := range lookupTable { @@ -15614,7 +15612,7 @@ func (c *Checker) getExportsOfModuleWorker(moduleSymbol *ast.Symbol) (exports as } c.extendExportSymbols(symbols, nestedSymbols, nil, nil) } - if exportStar != nil && exportStar.AsExportDeclaration().IsTypeOnly { + if exportStar != nil && exportStar.IsTypeOnly() { if typeOnlyExportStarMap == nil { typeOnlyExportStarMap = make(map[string]*ast.Node) } @@ -15650,7 +15648,7 @@ func (c *Checker) extendExportSymbols(target ast.SymbolTable, source ast.SymbolT target[id] = sourceSymbol if lookupTable != nil && exportNode != nil { lookupTable[id] = &ExportCollision{ - specifierText: scanner.GetTextOfNode(exportNode.AsExportDeclaration().ModuleSpecifier), + specifierText: scanner.GetTextOfNode(exportNode.ModuleSpecifier()), } } } else if lookupTable != nil && exportNode != nil && c.resolveSymbol(targetSymbol) != c.resolveSymbol(sourceSymbol) { @@ -15763,7 +15761,7 @@ func (c *Checker) getSymbolFlagsEx(symbol *ast.Symbol, excludeTypeOnlyMeanings b var typeOnlyResolution *ast.Symbol if typeOnlyDeclaration != nil { if typeOnlyDeclarationIsExportStar { - moduleSpecifier := typeOnlyDeclaration.AsExportDeclaration().ModuleSpecifier + moduleSpecifier := typeOnlyDeclaration.ModuleSpecifier() typeOnlyResolution = c.resolveExternalModuleName(moduleSpecifier, moduleSpecifier /*ignoreErrors*/, true) } else { typeOnlyResolution = c.resolveAlias(typeOnlyDeclaration.Symbol()) @@ -16001,7 +15999,7 @@ func (c *Checker) getTypeOfVariableOrParameterOrPropertyWorker(symbol *ast.Symbo debug.AssertIsDefined(symbol.ValueDeclaration) declaration := symbol.ValueDeclaration if ast.IsSourceFile(declaration) && ast.IsJsonSourceFile(declaration.AsSourceFile()) { - statements := declaration.AsSourceFile().Statements.Nodes + statements := declaration.Statements() if len(statements) == 0 { return c.emptyObjectType } @@ -16026,7 +16024,7 @@ func (c *Checker) getTypeOfVariableOrParameterOrPropertyWorker(symbol *ast.Symbo if declaration.Type() != nil { result = c.getTypeFromTypeNode(declaration.Type()) } else { - result = c.widenTypeForVariableLikeDeclaration(c.checkExpressionCached(declaration.AsExportAssignment().Expression), declaration, false /*reportErrors*/) + result = c.widenTypeForVariableLikeDeclaration(c.checkExpressionCached(declaration.Expression()), declaration, false /*reportErrors*/) } case ast.KindBinaryExpression: result = c.getWidenedTypeForAssignmentDeclaration(symbol) @@ -16035,7 +16033,7 @@ func (c *Checker) getTypeOfVariableOrParameterOrPropertyWorker(symbol *ast.Symbo case ast.KindEnumMember: result = c.getTypeOfEnumMember(symbol) case ast.KindCommonJSExport: - result = c.checkExpression(declaration.AsCommonJSExport().Initializer) + result = c.checkExpression(declaration.Initializer()) default: panic("Unhandled case in getTypeOfVariableOrParameterOrPropertyWorker: " + declaration.Kind.String()) } @@ -16228,7 +16226,7 @@ func (c *Checker) checkDeclarationInitializer(declaration *ast.Node, checkMode C func (c *Checker) padObjectLiteralType(t *Type, pattern *ast.Node) *Type { var missingElements []*ast.Node - for _, e := range pattern.AsBindingPattern().Elements.Nodes { + for _, e := range pattern.Elements() { if e.Initializer() != nil { name := c.getPropertyNameFromBindingElement(e) if name != ast.InternalSymbolNameMissing && c.getPropertyOfType(t, name) == nil { @@ -16262,7 +16260,7 @@ func (c *Checker) getPropertyNameFromBindingElement(e *ast.Node) string { } func (c *Checker) padTupleType(t *Type, pattern *ast.Node) *Type { - patternElements := pattern.AsBindingPattern().Elements.Nodes + patternElements := pattern.Elements() if t.TargetTupleType().combinedFlags&ElementFlagsVariable != 0 || c.getTypeReferenceArity(t) >= len(patternElements) { return t } @@ -16560,14 +16558,14 @@ func (c *Checker) getInferredTypeParameterConstraint(t *Type, omitTypeReferences inferences = append(inferences, c.stringType) case ast.IsTypeParameterDeclaration(parent) && ast.IsMappedTypeNode(parent.Parent): inferences = append(inferences, c.stringNumberSymbolType) - case ast.IsMappedTypeNode(parent) && parent.AsMappedTypeNode().Type != nil && - ast.SkipParentheses(parent.AsMappedTypeNode().Type) == declaration.Parent && + case ast.IsMappedTypeNode(parent) && parent.Type() != nil && + ast.SkipParentheses(parent.Type()) == declaration.Parent && ast.IsConditionalTypeNode(parent.Parent) && parent.Parent.AsConditionalTypeNode().ExtendsType == parent && ast.IsMappedTypeNode(parent.Parent.AsConditionalTypeNode().CheckType) && - parent.Parent.AsConditionalTypeNode().CheckType.AsMappedTypeNode().Type != nil: + parent.Parent.AsConditionalTypeNode().CheckType.Type() != nil: checkMappedType := parent.Parent.AsConditionalTypeNode().CheckType - nodeType := c.getTypeFromTypeNode(checkMappedType.AsMappedTypeNode().Type) + nodeType := c.getTypeFromTypeNode(checkMappedType.Type()) checkMappedTypeParameter := checkMappedType.AsMappedTypeNode().TypeParameter mapper := newSimpleTypeMapper(c.getDeclaredTypeOfTypeParameter(c.getSymbolOfDeclaration(checkMappedTypeParameter)), core.IfElse(checkMappedTypeParameter.AsTypeParameter().Constraint != nil, @@ -17140,7 +17138,7 @@ func (c *Checker) getBindingElementTypeFromParentType(declaration *ast.Node, par c.error(declaration, diagnostics.Rest_types_may_only_be_created_from_object_types) return c.errorType } - elements := pattern.AsBindingPattern().Elements.Nodes + elements := pattern.Elements() literalMembers := make([]*ast.Node, 0, len(elements)) for _, element := range elements { if !hasDotDotDotToken(element) { @@ -17161,7 +17159,7 @@ func (c *Checker) getBindingElementTypeFromParentType(declaration *ast.Node, par // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). elementType := c.checkIteratedTypeOrElementType(IterationUseDestructuring|core.IfElse(hasDotDotDotToken(declaration), 0, IterationUsePossiblyOutOfBounds), parentType, c.undefinedType, pattern) - index := slices.Index(pattern.AsBindingPattern().Elements.Nodes, declaration) + index := slices.Index(pattern.Elements(), declaration) if hasDotDotDotToken(declaration) { // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same @@ -17336,7 +17334,7 @@ func (c *Checker) getTypeFromObjectBindingPattern(pattern *ast.Node, includePatt members := make(ast.SymbolTable) var stringIndexInfo *IndexInfo objectFlags := ObjectFlagsObjectLiteral | ObjectFlagsContainsObjectOrArrayLiteral - for _, e := range pattern.AsBindingPattern().Elements.Nodes { + for _, e := range pattern.Elements() { name := e.PropertyNameOrName() if hasDotDotDotToken(e) { stringIndexInfo = c.newIndexInfo(c.stringType, c.anyType, false /*isReadonly*/, nil, nil) @@ -17369,7 +17367,7 @@ func (c *Checker) getTypeFromObjectBindingPattern(pattern *ast.Node, includePatt // Return the type implied by an array binding pattern func (c *Checker) getTypeFromArrayBindingPattern(pattern *ast.Node, includePatternInType bool, reportErrors bool) *Type { - elements := pattern.AsBindingPattern().Elements.Nodes + elements := pattern.Elements() lastElement := core.LastOrNil(elements) var restElement *ast.Node if lastElement != nil && ast.IsBindingElement(lastElement) && hasDotDotDotToken(lastElement) { @@ -18947,7 +18945,7 @@ func (c *Checker) getIndexInfosOfIndexSymbol(indexSymbol *ast.Symbol, siblingSym parameters := declaration.Parameters() returnTypeNode := declaration.Type() if len(parameters) == 1 { - typeNode := parameters[0].AsParameterDeclaration().Type + typeNode := parameters[0].Type() if typeNode != nil { valueType := c.anyType if returnTypeNode != nil { @@ -19175,7 +19173,7 @@ func (c *Checker) getSignatureFromDeclaration(declaration *ast.Node) *Signature isOptionalParameter := isOptionalDeclaration(param) || param.Initializer() != nil || isRestParameter(param) || - iife != nil && len(parameters) > len(iife.AsCallExpression().Arguments.Nodes) && typeNode == nil + iife != nil && len(parameters) > len(iife.Arguments()) && typeNode == nil if !isOptionalParameter { minArgumentCount = len(parameters) } @@ -19293,7 +19291,7 @@ func isLateBindableAST(node *ast.Node) bool { var expr *ast.Node switch { case ast.IsComputedPropertyName(node): - expr = node.AsComputedPropertyName().Expression + expr = node.Expression() case ast.IsElementAccessExpression(node): expr = node.AsElementAccessExpression().ArgumentExpression } @@ -21257,7 +21255,7 @@ func (c *Checker) getTypeArguments(t *Type) []*Type { case ast.KindArrayType: typeArguments = []*Type{c.getTypeFromTypeNode(node.AsArrayTypeNode().ElementType)} case ast.KindTupleType: - typeArguments = core.Map(node.AsTupleTypeNode().Elements.Nodes, c.getTypeFromTypeNode) + typeArguments = core.Map(node.Elements(), c.getTypeFromTypeNode) default: panic("Unhandled case in getTypeArguments") } @@ -22162,9 +22160,9 @@ func (c *Checker) getTypeFromTypeNodeWorker(node *ast.Node) *Type { case ast.KindAnyKeyword, ast.KindJSDocAllType: return c.anyType case ast.KindJSDocNonNullableType: - return c.getTypeFromTypeNode(node.AsJSDocNonNullableType().Type) + return c.getTypeFromTypeNode(node.Type()) case ast.KindJSDocNullableType: - t := c.getTypeFromTypeNode(node.AsJSDocNullableType().Type) + t := c.getTypeFromTypeNode(node.Type()) if c.strictNullChecks { return c.getNullableType(t, TypeFlagsNull) } else { @@ -22173,7 +22171,7 @@ func (c *Checker) getTypeFromTypeNodeWorker(node *ast.Node) *Type { case ast.KindJSDocVariadicType: return c.createArrayType(c.getTypeFromTypeNode(node.AsJSDocVariadicType().Type)) case ast.KindJSDocOptionalType: - return c.addOptionality(c.getTypeFromTypeNode(node.AsJSDocOptionalType().Type)) + return c.addOptionality(c.getTypeFromTypeNode(node.Type())) case ast.KindUnknownKeyword: return c.unknownType case ast.KindStringKeyword: @@ -22222,7 +22220,7 @@ func (c *Checker) getTypeFromTypeNodeWorker(node *ast.Node) *Type { case ast.KindNamedTupleMember: return c.getTypeFromNamedTupleTypeNode(node) case ast.KindParenthesizedType: - return c.getTypeFromTypeNode(node.AsParenthesizedTypeNode().Type) + return c.getTypeFromTypeNode(node.Type()) case ast.KindRestType: return c.getTypeFromRestTypeNode(node) case ast.KindFunctionType, ast.KindConstructorType, ast.KindTypeLiteral: @@ -22309,7 +22307,7 @@ func (c *Checker) getTypeFromIndexedAccessTypeNode(node *ast.Node) *Type { func (c *Checker) getTypeFromTypeOperatorNode(node *ast.Node) *Type { links := c.typeNodeLinks.Get(node) if links.resolvedType == nil { - argType := node.AsTypeOperatorNode().Type + argType := node.Type() switch node.AsTypeOperatorNode().Operator { case ast.KindKeyOfKeyword: links.resolvedType = c.getIndexType(c.getTypeFromTypeNode(argType)) @@ -22529,7 +22527,7 @@ func (c *Checker) isDeferredTypeReferenceNode(node *ast.Node, hasDefaultTypeArgu case ast.KindArrayType: return c.mayResolveTypeAlias(node.AsArrayTypeNode().ElementType) case ast.KindTupleType: - return core.Some(node.AsTupleTypeNode().Elements.Nodes, c.mayResolveTypeAlias) + return core.Some(node.Elements(), c.mayResolveTypeAlias) case ast.KindTypeReference: return hasDefaultTypeArguments || core.Some(node.TypeArguments(), c.mayResolveTypeAlias) } @@ -22562,15 +22560,11 @@ func (c *Checker) mayResolveTypeAlias(node *ast.Node) bool { case ast.KindTypeQuery: return true case ast.KindTypeOperator: - return node.AsTypeOperatorNode().Operator != ast.KindUniqueKeyword && c.mayResolveTypeAlias(node.AsTypeOperatorNode().Type) - case ast.KindParenthesizedType: - return c.mayResolveTypeAlias(node.AsParenthesizedTypeNode().Type) - case ast.KindOptionalType: - return c.mayResolveTypeAlias(node.AsOptionalTypeNode().Type) - case ast.KindNamedTupleMember: - return c.mayResolveTypeAlias(node.AsNamedTupleMember().Type) + return node.AsTypeOperatorNode().Operator != ast.KindUniqueKeyword && c.mayResolveTypeAlias(node.Type()) + case ast.KindParenthesizedType, ast.KindOptionalType, ast.KindNamedTupleMember: + return c.mayResolveTypeAlias(node.Type()) case ast.KindRestType: - return node.AsRestTypeNode().Type.Kind != ast.KindArrayType || c.mayResolveTypeAlias(node.AsRestTypeNode().Type.AsArrayTypeNode().ElementType) + return node.Type().Kind != ast.KindArrayType || c.mayResolveTypeAlias(node.Type().AsArrayTypeNode().ElementType) case ast.KindUnionType: return core.Some(node.AsUnionTypeNode().Types.Nodes, c.mayResolveTypeAlias) case ast.KindIntersectionType: @@ -22982,7 +22976,7 @@ func getTypeReferenceName(node *ast.Node) *ast.Node { case ast.KindExpressionWithTypeArguments: // We only support expressions that are simple qualified names. For other // expressions this produces nil - expr := node.AsExpressionWithTypeArguments().Expression + expr := node.Expression() if ast.IsEntityNameExpression(expr) { return expr } @@ -23125,7 +23119,7 @@ func (c *Checker) getDeclaredTypeOfTypeAlias(symbol *ast.Symbol) *Type { return c.errorType } declaration := core.Find(symbol.Declarations, ast.IsTypeOrJSTypeAliasDeclaration) - typeNode := declaration.AsTypeAliasDeclaration().Type + typeNode := declaration.Type() t := c.getTypeFromTypeNode(typeNode) if c.popTypeResolution() { typeParameters := c.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) @@ -23263,7 +23257,7 @@ func (c *Checker) computeEnumMemberValue(member *ast.Node, autoValue jsnum.Numbe c.error(member.Name(), diagnostics.Enum_member_must_have_initializer) return evaluator.NewResult(nil, false, false, false) } - if c.compilerOptions.GetIsolatedModules() && previous != nil && previous.AsEnumMember().Initializer != nil { + if c.compilerOptions.GetIsolatedModules() && previous != nil && previous.Initializer() != nil { prevValue := c.getEnumMemberValue(previous) _, prevIsNum := prevValue.Value.(jsnum.Number) if !prevIsNum || prevValue.ResolvedOtherFiles { @@ -23400,8 +23394,8 @@ func (c *Checker) getTypeFromArrayOrTupleTypeNode(node *ast.Node) *Type { target := c.getArrayOrTupleTargetType(node) if target == c.emptyGenericType { links.resolvedType = c.emptyObjectType - } else if !(node.Kind == ast.KindTupleType && core.Some(node.AsTupleTypeNode().Elements.Nodes, c.isVariadicTupleElement)) && c.isDeferredTypeReferenceNode(node, false) { - if node.Kind == ast.KindTupleType && len(node.AsTupleTypeNode().Elements.Nodes) == 0 { + } else if !(node.Kind == ast.KindTupleType && core.Some(node.Elements(), c.isVariadicTupleElement)) && c.isDeferredTypeReferenceNode(node, false) { + if node.Kind == ast.KindTupleType && len(node.Elements()) == 0 { links.resolvedType = target } else { links.resolvedType = c.createDeferredTypeReference(target, node, nil /*mapper*/, nil /*alias*/) @@ -23411,7 +23405,7 @@ func (c *Checker) getTypeFromArrayOrTupleTypeNode(node *ast.Node) *Type { if node.Kind == ast.KindArrayType { elementTypes = []*Type{c.getTypeFromTypeNode(node.AsArrayTypeNode().ElementType)} } else { - elementTypes = core.Map(node.AsTupleTypeNode().Elements.Nodes, c.getTypeFromTypeNode) + elementTypes = core.Map(node.Elements(), c.getTypeFromTypeNode) } links.resolvedType = c.createNormalizedTypeReference(target, elementTypes) } @@ -23432,7 +23426,7 @@ func (c *Checker) getArrayOrTupleTargetType(node *ast.Node) *Type { } return c.globalArrayType } - return c.getTupleTargetType(core.Map(node.AsTupleTypeNode().Elements.Nodes, c.getTupleElementInfo), readonly) + return c.getTupleTargetType(core.Map(node.Elements(), c.getTupleElementInfo), readonly) } func (c *Checker) isReadonlyTypeOperator(node *ast.Node) bool { @@ -23445,7 +23439,7 @@ func (c *Checker) getTypeFromNamedTupleTypeNode(node *ast.Node) *Type { if node.AsNamedTupleMember().DotDotDotToken != nil { links.resolvedType = c.getTypeFromRestTypeNode(node) } else { - links.resolvedType = c.addOptionalityEx(c.getTypeFromTypeNode(node.Type()), true /*isProperty*/, node.AsNamedTupleMember().QuestionToken != nil) + links.resolvedType = c.addOptionalityEx(c.getTypeFromTypeNode(node.Type()), true /*isProperty*/, node.QuestionToken() != nil) } } return links.resolvedType @@ -23463,15 +23457,15 @@ func (c *Checker) getTypeFromRestTypeNode(node *ast.Node) *Type { func (c *Checker) getArrayElementTypeNode(node *ast.Node) *ast.Node { switch node.Kind { case ast.KindParenthesizedType: - return c.getArrayElementTypeNode(node.AsParenthesizedTypeNode().Type) + return c.getArrayElementTypeNode(node.Type()) case ast.KindTupleType: - if len(node.AsTupleTypeNode().Elements.Nodes) == 1 { - node = node.AsTupleTypeNode().Elements.Nodes[0] + if len(node.Elements()) == 1 { + node = node.Elements()[0] if node.Kind == ast.KindRestType { - return c.getArrayElementTypeNode(node.AsRestTypeNode().Type) + return c.getArrayElementTypeNode(node.Type()) } if node.Kind == ast.KindNamedTupleMember && node.AsNamedTupleMember().DotDotDotToken != nil { - return c.getArrayElementTypeNode(node.AsNamedTupleMember().Type) + return c.getArrayElementTypeNode(node.Type()) } } case ast.KindArrayType: @@ -23481,7 +23475,7 @@ func (c *Checker) getArrayElementTypeNode(node *ast.Node) *ast.Node { } func (c *Checker) getTypeFromOptionalTypeNode(node *ast.Node) *Type { - return c.addOptionalityEx(c.getTypeFromTypeNode(node.AsOptionalTypeNode().Type), true /*isProperty*/, true /*isOptional*/) + return c.addOptionalityEx(c.getTypeFromTypeNode(node.Type()), true /*isProperty*/, true /*isOptional*/) } func (c *Checker) getTypeFromUnionTypeNode(node *ast.Node) *Type { @@ -23523,7 +23517,7 @@ func (c *Checker) getTypeFromTemplateTypeNode(node *ast.Node) *Type { texts[0] = node.AsTemplateLiteralTypeNode().Head.Text() for i, span := range spans.Nodes { texts[i+1] = span.AsTemplateLiteralTypeSpan().Literal.Text() - types[i] = c.getTypeFromTypeNode(span.AsTemplateLiteralTypeSpan().Type) + types[i] = c.getTypeFromTypeNode(span.Type()) } links.resolvedType = c.getTemplateLiteralType(texts, types) } @@ -23602,7 +23596,7 @@ func (c *Checker) getConditionalType(root *ConditionalRoot, mapper *TypeMapper, // When the check and extends types are simple tuple types of the same arity, we defer resolution of the // conditional type when any tuple elements are generic. This is such that non-distributable conditional // types can be written `[X] extends [Y] ? ...` and be deferred similarly to `X extends Y ? ...`. - checkTuples := c.isSimpleTupleType(checkTypeNode) && c.isSimpleTupleType(extendsTypeNode) && len(checkTypeNode.AsTupleTypeNode().Elements.Nodes) == len(extendsTypeNode.AsTupleTypeNode().Elements.Nodes) + checkTuples := c.isSimpleTupleType(checkTypeNode) && c.isSimpleTupleType(extendsTypeNode) && len(checkTypeNode.Elements()) == len(extendsTypeNode.Elements()) checkTypeDeferred := c.isDeferredType(checkType, checkTuples) var combinedMapper *TypeMapper if len(root.inferTypeParameters) != 0 { @@ -23745,8 +23739,8 @@ func (c *Checker) getTailRecursionRoot(newType *Type, newMapper *TypeMapper) (*C } func (c *Checker) isSimpleTupleType(node *ast.Node) bool { - return ast.IsTupleTypeNode(node) && len(node.AsTupleTypeNode().Elements.Nodes) > 0 && !core.Some(node.AsTupleTypeNode().Elements.Nodes, func(e *ast.Node) bool { - return ast.IsOptionalTypeNode(e) || ast.IsRestTypeNode(e) || ast.IsNamedTupleMember(e) && (e.AsNamedTupleMember().QuestionToken != nil || e.AsNamedTupleMember().DotDotDotToken != nil) + return ast.IsTupleTypeNode(node) && len(node.Elements()) > 0 && !core.Some(node.Elements(), func(e *ast.Node) bool { + return ast.IsOptionalTypeNode(e) || ast.IsRestTypeNode(e) || ast.IsNamedTupleMember(e) && (e.QuestionToken() != nil || e.AsNamedTupleMember().DotDotDotToken != nil) }) } @@ -23979,7 +23973,7 @@ func (c *Checker) getTupleElementFlags(node *ast.Node) ElementFlags { case ast.KindOptionalType: return ElementFlagsOptional case ast.KindRestType: - return core.IfElse(c.getArrayElementTypeNode(node.AsRestTypeNode().Type) != nil, ElementFlagsRest, ElementFlagsVariadic) + return core.IfElse(c.getArrayElementTypeNode(node.Type()) != nil, ElementFlagsRest, ElementFlagsVariadic) case ast.KindNamedTupleMember: named := node.AsNamedTupleMember() switch { @@ -24234,7 +24228,7 @@ func (c *Checker) getConditionalFlowTypeOfType(t *Type, node *ast.Node) *Type { if constraint != nil { constraints = append(constraints, constraint) } - } else if t.flags&TypeFlagsTypeParameter != 0 && ast.IsMappedTypeNode(parent) && parent.AsMappedTypeNode().NameType == nil && node == parent.AsMappedTypeNode().Type { + } else if t.flags&TypeFlagsTypeParameter != 0 && ast.IsMappedTypeNode(parent) && parent.AsMappedTypeNode().NameType == nil && node == parent.Type() { mappedType := c.getTypeFromTypeNode(parent) if c.getTypeParameterFromMappedType(mappedType) == c.getActualTypeVariable(t) { typeParameter := c.getHomomorphicTypeVariable(mappedType) @@ -24257,7 +24251,7 @@ func (c *Checker) getConditionalFlowTypeOfType(t *Type, node *ast.Node) *Type { func (c *Checker) getImpliedConstraint(t *Type, checkNode *ast.Node, extendsNode *ast.Node) *Type { switch { case isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode): - return c.getImpliedConstraint(t, checkNode.AsTupleTypeNode().Elements.Nodes[0], extendsNode.AsTupleTypeNode().Elements.Nodes[0]) + return c.getImpliedConstraint(t, checkNode.Elements()[0], extendsNode.Elements()[0]) case c.getActualTypeVariable(c.getTypeFromTypeNode(checkNode)) == c.getActualTypeVariable(t): return c.getTypeFromTypeNode(extendsNode) } @@ -24265,7 +24259,7 @@ func (c *Checker) getImpliedConstraint(t *Type, checkNode *ast.Node, extendsNode } func isUnaryTupleTypeNode(node *ast.Node) bool { - return ast.IsTupleTypeNode(node) && len(node.AsTupleTypeNode().Elements.Nodes) == 1 + return ast.IsTupleTypeNode(node) && len(node.Elements()) == 1 } func (c *Checker) newType(flags TypeFlags, objectFlags ObjectFlags, data TypeData) *Type { @@ -26469,7 +26463,7 @@ func getIndexNodeForAccessExpression(accessNode *ast.Node) *ast.Node { case ast.KindIndexedAccessType: return accessNode.AsIndexedAccessTypeNode().IndexType case ast.KindComputedPropertyName: - return accessNode.AsComputedPropertyName().Expression + return accessNode.Expression() } return accessNode } @@ -27282,7 +27276,7 @@ func (c *Checker) getModifiersTypeFromMappedType(t *Type) *Type { // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves // 'keyof T' to a literal union type and we can't recover T from that type. - m.modifiersType = c.instantiateType(c.getTypeFromTypeNode(c.getConstraintDeclarationForMappedType(t).AsTypeOperatorNode().Type), m.mapper) + m.modifiersType = c.instantiateType(c.getTypeFromTypeNode(c.getConstraintDeclarationForMappedType(t).Type()), m.mapper) } else { // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', @@ -27434,10 +27428,10 @@ func isExportOrExportExpression(location *ast.Node) bool { parent := n.Parent if parent != nil { if ast.IsAnyExportAssignment(parent) { - return parent.AsExportAssignment().Expression == n && ast.IsEntityNameExpression(n) + return parent.Expression() == n && ast.IsEntityNameExpression(n) } if ast.IsExportSpecifier(parent) { - return parent.AsExportSpecifier().Name() == n || parent.AsExportSpecifier().PropertyName == n + return parent.AsExportSpecifier().Name() == n || parent.PropertyName() == n } } return false @@ -27452,12 +27446,12 @@ func shouldMarkIdentifierAliasReferenced(node *ast.IdentifierNode) bool { return false } // Next two check for an identifier inside a type only export. - if ast.IsExportSpecifier(parent) && parent.AsExportSpecifier().IsTypeOnly { + if ast.IsExportSpecifier(parent) && parent.IsTypeOnly() { return false } if parent.Parent != nil { greatGrandparent := parent.Parent.Parent - if greatGrandparent != nil && ast.IsExportDeclaration(greatGrandparent) && greatGrandparent.AsExportDeclaration().IsTypeOnly { + if greatGrandparent != nil && ast.IsExportDeclaration(greatGrandparent) && greatGrandparent.IsTypeOnly() { return false } } @@ -27480,7 +27474,7 @@ func (c *Checker) markIdentifierAliasReferenced(location *ast.IdentifierNode) { func (c *Checker) markPropertyAliasReferenced(location *ast.Node /*PropertyAccessExpression | QualifiedName*/, propSymbol *ast.Symbol, parentType *Type) { var left *ast.Node if ast.IsPropertyAccessExpression(location) { - left = location.AsPropertyAccessExpression().Expression + left = location.Expression() } else { left = location.AsQualifiedName().Left } @@ -27609,11 +27603,8 @@ func (c *Checker) markImportEqualsAliasReferenced(location *ast.Node /*ImportEqu } func (c *Checker) markExportSpecifierAliasReferenced(location *ast.ExportSpecifierNode) { - if location.Parent.Parent.AsExportDeclaration().ModuleSpecifier == nil && !location.AsExportSpecifier().IsTypeOnly && !location.Parent.Parent.AsExportDeclaration().IsTypeOnly { - exportedName := location.PropertyName() - if exportedName == nil { - exportedName = location.Name() - } + if location.Parent.Parent.ModuleSpecifier() == nil && !location.IsTypeOnly() && !location.Parent.Parent.IsTypeOnly() { + exportedName := location.PropertyNameOrName() if exportedName.Kind == ast.KindStringLiteral { return // Skip for invalid syntax like this: export { "x" } } @@ -28204,10 +28195,10 @@ func (c *Checker) getContextualType(node *ast.Node, contextFlags ContextFlags) * case ast.KindDecorator: return c.getContextualTypeForDecorator(parent) case ast.KindTypeAssertionExpression, ast.KindAsExpression: - if isConstAssertion(parent) { + if ast.IsConstAssertion(parent) { return c.getContextualType(parent, contextFlags) } - return c.getTypeFromTypeNode(getAssertedTypeNode(parent)) + return c.getTypeFromTypeNode(parent.Type()) case ast.KindBinaryExpression: return c.getContextualTypeForBinaryOperand(node, contextFlags) case ast.KindPropertyAssignment, @@ -28217,9 +28208,9 @@ func (c *Checker) getContextualType(node *ast.Node, contextFlags ContextFlags) * return c.getContextualType(parent.Parent, contextFlags) case ast.KindArrayLiteralExpression: t := c.getApparentTypeOfContextualType(parent, contextFlags) - elementIndex := ast.IndexOfNode(parent.AsArrayLiteralExpression().Elements.Nodes, node) + elementIndex := ast.IndexOfNode(parent.Elements(), node) firstSpreadIndex, lastSpreadIndex := c.getSpreadIndices(parent) - return c.getContextualTypeForElementExpression(t, elementIndex, len(parent.AsArrayLiteralExpression().Elements.Nodes), firstSpreadIndex, lastSpreadIndex) + return c.getContextualTypeForElementExpression(t, elementIndex, len(parent.Elements()), firstSpreadIndex, lastSpreadIndex) case ast.KindConditionalExpression: return c.getContextualTypeForConditionalOperand(node, contextFlags) case ast.KindTemplateSpan: @@ -28229,7 +28220,7 @@ func (c *Checker) getContextualType(node *ast.Node, contextFlags ContextFlags) * case ast.KindNonNullExpression: return c.getContextualType(parent, contextFlags) case ast.KindSatisfiesExpression: - return c.getTypeFromTypeNode(parent.AsSatisfiesExpression().Type) + return c.getTypeFromTypeNode(parent.Type()) case ast.KindExportAssignment, ast.KindJSExportAssignment, ast.KindCommonJSExport: return c.tryGetTypeFromTypeNode(parent) case ast.KindJsxExpression: @@ -28263,7 +28254,7 @@ func (c *Checker) getContextualTypeForInitializerExpression(node *ast.Node, cont if result != nil { return result } - if contextFlags&ContextFlagsSkipBindingPatterns == 0 && ast.IsBindingPattern(declaration.Name()) && len(declaration.Name().AsBindingPattern().Elements.Nodes) > 0 { + if contextFlags&ContextFlagsSkipBindingPatterns == 0 && ast.IsBindingPattern(declaration.Name()) && len(declaration.Name().Elements()) > 0 { return c.getTypeFromBindingPattern(declaration.Name(), true /*includePatternInType*/, false /*reportErrors*/) } } @@ -28431,7 +28422,7 @@ func (c *Checker) getContextualTypeForBindingElement(declaration *ast.Node, cont return nil } if ast.IsArrayBindingPattern(parent.Name()) { - index := slices.Index(declaration.Parent.AsBindingPattern().Elements.Nodes, declaration) + index := slices.Index(declaration.Parent.Elements(), declaration) if index < 0 { return nil } @@ -28891,7 +28882,7 @@ func (c *Checker) getEffectiveCallArguments(node *ast.Node) []*ast.Node { // Handles instanceof operator return []*ast.Node{node.AsBinaryExpression().Left} case ast.IsJsxOpeningLikeElement(node): - if len(node.Attributes().AsJsxAttributes().Properties.Nodes) != 0 || (ast.IsJsxOpeningElement(node) && len(node.Parent.Children().Nodes) != 0) { + if len(node.Attributes().Properties()) != 0 || (ast.IsJsxOpeningElement(node) && len(node.Parent.Children().Nodes) != 0) { return []*ast.Node{node.Attributes()} } return nil @@ -28952,7 +28943,7 @@ func (c *Checker) getSpreadIndices(node *ast.Node) (int, int) { links := c.arrayLiteralLinks.Get(node) if !links.indicesComputed { first, last := -1, -1 - for i, element := range node.AsArrayLiteralExpression().Elements.Nodes { + for i, element := range node.Elements() { if ast.IsSpreadElement(element) { if first < 0 { first = i @@ -29586,7 +29577,7 @@ func (c *Checker) discriminateContextualTypeByObjectMembers(node *ast.Node, cont } discriminated := c.getMatchingUnionConstituentForObjectLiteral(contextualType, node) if discriminated == nil { - discriminantProperties := core.Filter(node.AsObjectLiteralExpression().Properties.Nodes, func(p *ast.Node) bool { + discriminantProperties := core.Filter(node.Properties(), func(p *ast.Node) bool { symbol := p.Symbol() if symbol == nil { return false @@ -29612,7 +29603,7 @@ func (c *Checker) discriminateContextualTypeByObjectMembers(node *ast.Node, cont func (c *Checker) getMatchingUnionConstituentForObjectLiteral(unionType *Type, node *ast.Node) *Type { keyPropertyName := c.getKeyPropertyName(unionType) if keyPropertyName != "" { - propNode := core.Find(node.AsObjectLiteralExpression().Properties.Nodes, func(p *ast.Node) bool { + propNode := core.Find(node.Properties(), func(p *ast.Node) bool { return p.Symbol() != nil && ast.IsPropertyAssignment(p) && p.Symbol().Name == keyPropertyName && c.isPossiblyDiscriminantValue(p.Initializer()) }) if propNode != nil { @@ -29634,7 +29625,7 @@ func (c *Checker) isPossiblyDiscriminantValue(node *ast.Node) bool { case ast.KindPropertyAccessExpression, ast.KindParenthesizedExpression: return c.isPossiblyDiscriminantValue(node.Expression()) case ast.KindJsxExpression: - return node.AsJsxExpression().Expression == nil || c.isPossiblyDiscriminantValue(node.AsJsxExpression().Expression) + return node.Expression() == nil || c.isPossiblyDiscriminantValue(node.Expression()) } return false } @@ -29721,9 +29712,9 @@ func (c *Checker) isContextSensitive(node *ast.Node) bool { case ast.KindFunctionExpression, ast.KindArrowFunction, ast.KindMethodDeclaration, ast.KindFunctionDeclaration: return c.isContextSensitiveFunctionLikeDeclaration(node) case ast.KindObjectLiteralExpression: - return core.Some(node.AsObjectLiteralExpression().Properties.Nodes, c.isContextSensitive) + return core.Some(node.Properties(), c.isContextSensitive) case ast.KindArrayLiteralExpression: - return core.Some(node.AsArrayLiteralExpression().Elements.Nodes, c.isContextSensitive) + return core.Some(node.Elements(), c.isContextSensitive) case ast.KindConditionalExpression: return c.isContextSensitive(node.AsConditionalExpression().WhenTrue) || c.isContextSensitive(node.AsConditionalExpression().WhenFalse) case ast.KindBinaryExpression: @@ -29734,7 +29725,7 @@ func (c *Checker) isContextSensitive(node *ast.Node) bool { case ast.KindParenthesizedExpression: return c.isContextSensitive(node.Expression()) case ast.KindJsxAttributes: - return core.Some(node.AsJsxAttributes().Properties.Nodes, c.isContextSensitive) || ast.IsJsxOpeningElement(node.Parent) && core.Some(node.Parent.Parent.Children().Nodes, c.isContextSensitive) + return core.Some(node.Properties(), c.isContextSensitive) || ast.IsJsxOpeningElement(node.Parent) && core.Some(node.Parent.Parent.Children().Nodes, c.isContextSensitive) case ast.KindJsxAttribute: // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. initializer := node.Initializer() @@ -30291,7 +30282,7 @@ func (c *Checker) isSomeSymbolAssignedWorker(node *ast.Node) bool { if node.Kind == ast.KindIdentifier { return c.isSymbolAssigned(c.getSymbolOfDeclaration(node.Parent)) } - return core.Some(node.AsBindingPattern().Elements.Nodes, func(e *ast.Node) bool { + return core.Some(node.Elements(), func(e *ast.Node) bool { return e.Name() != nil && c.isSomeSymbolAssignedWorker(e.Name()) }) } @@ -30722,7 +30713,7 @@ func (c *Checker) getSymbolOfNameOrPropertyAccessExpression(name *ast.Node) *ast } func (c *Checker) isThisPropertyAndThisTyped(node *ast.Node) bool { - if node.AsPropertyAccessExpression().Expression.Kind == ast.KindThisKeyword { + if node.Expression().Kind == ast.KindThisKeyword { container := c.getThisContainer(node, false /*includeArrowFunctions*/, false /*includeClassComputedPropertyName*/) if ast.IsFunctionLike(container) { containingLiteral := getContainingObjectLiteral(container) @@ -30954,7 +30945,7 @@ func (c *Checker) containsArgumentsReference(node *ast.Node) bool { case ast.KindPropertyAccessExpression, ast.KindElementAccessExpression: return visit(node.Expression()) case ast.KindPropertyAssignment: - return visit(node.AsPropertyAssignment().Initializer) + return visit(node.Initializer()) } if nodeStartsNewLexicalEnvironment(node) || ast.IsPartOfTypeNode(node) { return false diff --git a/internal/checker/checker_test.go b/internal/checker/checker_test.go index c5029ecbc9..2dcda5d528 100644 --- a/internal/checker/checker_test.go +++ b/internal/checker/checker_test.go @@ -51,7 +51,7 @@ foo.bar;` file := p.GetSourceFile("/foo.ts") interfaceId := file.Statements.Nodes[0].Name() varId := file.Statements.Nodes[1].AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes[0].Name() - propAccess := file.Statements.Nodes[2].AsExpressionStatement().Expression + propAccess := file.Statements.Nodes[2].Expression() nodes := []*ast.Node{interfaceId, varId, propAccess} for _, node := range nodes { symbol := c.GetSymbolAtLocation(node) diff --git a/internal/checker/emitresolver.go b/internal/checker/emitresolver.go index de9311820c..a40d49b2a9 100644 --- a/internal/checker/emitresolver.go +++ b/internal/checker/emitresolver.go @@ -149,7 +149,7 @@ func (r *EmitResolver) determineIfDeclarationIsVisible(node *ast.Node) bool { ast.KindImportEqualsDeclaration: if ast.IsVariableDeclaration(node) { if ast.IsBindingPattern(node.Name()) && - len(node.Name().AsBindingPattern().Elements.Nodes) == 0 { + len(node.Name().Elements()) == 0 { // If the binding pattern is empty, this variable declaration is not visible return false } @@ -240,7 +240,7 @@ func (r *EmitResolver) PrecalculateDeclarationEmitVisibility(file *ast.SourceFil func (r *EmitResolver) aliasMarkingVisitorWorker(node *ast.Node) bool { switch node.Kind { case ast.KindExportAssignment, ast.KindJSExportAssignment: - if node.AsExportAssignment().Expression.Kind == ast.KindIdentifier { + if node.Expression().Kind == ast.KindIdentifier { r.markLinkedAliases(node.Expression()) } case ast.KindExportSpecifier: @@ -254,7 +254,7 @@ func (r *EmitResolver) aliasMarkingVisitorWorker(node *ast.Node) bool { func (r *EmitResolver) markLinkedAliases(node *ast.Node) { var exportSymbol *ast.Symbol if node.Kind != ast.KindStringLiteral && node.Parent != nil && node.Parent.Kind == ast.KindExportAssignment { - exportSymbol = r.checker.resolveName(node, node.AsIdentifier().Text, ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace|ast.SymbolFlagsAlias /*nameNotFoundMessage*/, nil /*isUse*/, false, false) + exportSymbol = r.checker.resolveName(node, node.Text(), ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace|ast.SymbolFlagsAlias /*nameNotFoundMessage*/, nil /*isUse*/, false, false) } else if node.Parent.Kind == ast.KindExportSpecifier { exportSymbol = r.checker.getTargetOfExportSpecifier(node.Parent, ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace|ast.SymbolFlagsAlias, false) } @@ -275,7 +275,7 @@ func (r *EmitResolver) markLinkedAliases(node *ast.Node) { // Add the referenced top container visible internalModuleReference := declaration.AsImportEqualsDeclaration().ModuleReference firstIdentifier := ast.GetFirstIdentifier(internalModuleReference) - importSymbol := r.checker.resolveName(declaration, firstIdentifier.AsIdentifier().Text, ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace|ast.SymbolFlagsAlias /*nameNotFoundMessage*/, nil /*isUse*/, false, false) + importSymbol := r.checker.resolveName(declaration, firstIdentifier.Text(), ast.SymbolFlagsValue|ast.SymbolFlagsType|ast.SymbolFlagsNamespace|ast.SymbolFlagsAlias /*nameNotFoundMessage*/, nil /*isUse*/, false, false) nextSymbol = importSymbol } } @@ -296,8 +296,8 @@ func getMeaningOfEntityNameReference(entityName *ast.Node) ast.SymbolFlags { if entityName.Kind == ast.KindQualifiedName || entityName.Kind == ast.KindPropertyAccessExpression || entityName.Parent.Kind == ast.KindImportEqualsDeclaration || (entityName.Parent.Kind == ast.KindQualifiedName && entityName.Parent.AsQualifiedName().Left == entityName) || - (entityName.Parent.Kind == ast.KindPropertyAccessExpression && (entityName.Parent.AsPropertyAccessExpression()).Expression == entityName) || - (entityName.Parent.Kind == ast.KindElementAccessExpression && (entityName.Parent.AsElementAccessExpression()).Expression == entityName) { + (entityName.Parent.Kind == ast.KindPropertyAccessExpression && entityName.Parent.Expression() == entityName) || + (entityName.Parent.Kind == ast.KindElementAccessExpression && entityName.Parent.Expression() == entityName) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration return ast.SymbolFlagsNamespace @@ -520,7 +520,7 @@ func (r *EmitResolver) IsDefinitelyReferenceToGlobalSymbolObject(node *ast.Node) return false } if node.Expression().Kind == ast.KindIdentifier { - if node.Expression().AsIdentifier().Text != "Symbol" { + if node.Expression().Text() != "Symbol" { return false } r.checkerMu.Lock() @@ -528,7 +528,7 @@ func (r *EmitResolver) IsDefinitelyReferenceToGlobalSymbolObject(node *ast.Node) // Exactly `Symbol.something` and `Symbol` either does not resolve or definitely resolves to the global Symbol return r.checker.getResolvedSymbol(node.Expression()) == r.checker.getGlobalSymbol("Symbol", ast.SymbolFlagsValue|ast.SymbolFlagsExportValue, nil /*diagnostic*/) } - if node.Expression().Expression().Kind != ast.KindIdentifier || node.Expression().Expression().AsIdentifier().Text != "globalThis" || node.Expression().Name().Text() != "Symbol" { + if node.Expression().Expression().Kind != ast.KindIdentifier || node.Expression().Expression().Text() != "globalThis" || node.Expression().Name().Text() != "Symbol" { return false } r.checkerMu.Lock() @@ -605,7 +605,7 @@ func (r *EmitResolver) isOptionalParameter(node *ast.Node) bool { // if (hasEffectiveQuestionToken(node)) { // return true; // } - if ast.IsParameter(node) && node.AsParameterDeclaration().QuestionToken != nil { + if ast.IsParameter(node) && node.QuestionToken() != nil { return true } if !ast.IsParameter(node) { @@ -719,9 +719,9 @@ func (r *EmitResolver) isValueAliasDeclarationWorker(node *ast.Node) bool { case ast.KindExportDeclaration: exportClause := node.AsExportDeclaration().ExportClause return exportClause != nil && (ast.IsNamespaceExport(exportClause) || - core.Some(exportClause.AsNamedExports().Elements.Nodes, r.isValueAliasDeclaration)) + core.Some(exportClause.Elements(), r.isValueAliasDeclaration)) case ast.KindExportAssignment, ast.KindJSExportAssignment: - if node.AsExportAssignment().Expression != nil && node.AsExportAssignment().Expression.Kind == ast.KindIdentifier { + if node.Expression() != nil && node.Expression().Kind == ast.KindIdentifier { return r.isAliasResolvedToValue(c.getSymbolOfDeclaration(node), true /*excludeTypeOnlyValues*/) } return true @@ -1042,8 +1042,8 @@ func (r *EmitResolver) CreateLateBoundIndexSignatures(emitContext *printer.EmitC allComponentComputedNamesSerializable := enclosingDeclaration != nil && core.Every(info.components, func(c *ast.Node) bool { return c.Name() != nil && ast.IsComputedPropertyName(c.Name()) && - ast.IsEntityNameExpression(c.Name().AsComputedPropertyName().Expression) && - r.isEntityNameVisible(c.Name().AsComputedPropertyName().Expression, enclosingDeclaration, false).Accessibility == printer.SymbolAccessibilityAccessible + ast.IsEntityNameExpression(c.Name().Expression()) && + r.isEntityNameVisible(c.Name().Expression(), enclosingDeclaration, false).Accessibility == printer.SymbolAccessibilityAccessible }) if allComponentComputedNamesSerializable { for _, c := range info.components { @@ -1078,11 +1078,8 @@ func (r *EmitResolver) CreateLateBoundIndexSignatures(emitContext *printer.EmitC node := requestNodeBuilder.IndexInfoToIndexSignatureDeclaration(info, enclosingDeclaration, flags, internalFlags, tracker) if node != nil && isStatic { modNodes := []*ast.Node{emitContext.Factory.NewModifier(ast.KindStaticKeyword)} - mods := node.Modifiers() - if mods != nil { - modNodes = append(modNodes, mods.Nodes...) - } - mods = emitContext.Factory.NewModifierList(modNodes) + modNodes = append(modNodes, node.ModifierNodes()...) + mods := emitContext.Factory.NewModifierList(modNodes) node = emitContext.Factory.UpdateIndexSignatureDeclaration( node.AsIndexSignatureDeclaration(), mods, diff --git a/internal/checker/flow.go b/internal/checker/flow.go index eafd7fde95..1952dd2ba9 100644 --- a/internal/checker/flow.go +++ b/internal/checker/flow.go @@ -1549,7 +1549,7 @@ func (c *Checker) createFinalArrayType(elementType *Type) *Type { func (c *Checker) reportFlowControlError(node *ast.Node) { block := ast.FindAncestor(node, ast.IsFunctionOrModuleBlock) sourceFile := ast.GetSourceFileOfNode(node) - span := scanner.GetRangeOfTokenAtPosition(sourceFile, ast.GetStatementsOfBlock(block).Pos()) + span := scanner.GetRangeOfTokenAtPosition(sourceFile, block.StatementList().Pos()) c.diagnostics.Add(ast.NewDiagnostic(sourceFile, span, diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)) } @@ -1759,11 +1759,8 @@ func (c *Checker) getDestructuringPropertyName(node *ast.Node) (string, bool) { if ast.IsPropertyAssignment(node) || ast.IsShorthandPropertyAssignment(node) { return c.getLiteralPropertyNameText(node.Name()) } - if ast.IsArrayBindingPattern(parent) { - return strconv.Itoa(slices.Index(parent.AsBindingPattern().Elements.Nodes, node)), true - } - if ast.IsArrayLiteralExpression(parent) { - return strconv.Itoa(slices.Index(parent.AsArrayLiteralExpression().Elements.Nodes, node)), true + if ast.IsArrayLiteralExpression(parent) || ast.IsArrayBindingPattern(parent) { + return strconv.Itoa(slices.Index(parent.Elements(), node)), true } return "", false } @@ -2099,7 +2096,7 @@ func (c *Checker) getTypeOfDottedName(node *ast.Node, diagnostic *ast.Diagnostic case ast.KindSuperKeyword: return c.checkSuperExpression(node) case ast.KindPropertyAccessExpression: - t := c.getTypeOfDottedName(node.AsPropertyAccessExpression().Expression, diagnostic) + t := c.getTypeOfDottedName(node.Expression(), diagnostic) if t != nil { name := node.Name() var prop *ast.Symbol @@ -2115,7 +2112,7 @@ func (c *Checker) getTypeOfDottedName(node *ast.Node, diagnostic *ast.Diagnostic } } case ast.KindParenthesizedExpression: - return c.getTypeOfDottedName(node.AsParenthesizedExpression().Expression, diagnostic) + return c.getTypeOfDottedName(node.Expression(), diagnostic) } } return nil @@ -2243,7 +2240,7 @@ func (c *Checker) getInitialTypeOfBindingElement(node *ast.Node) *Type { case ast.IsObjectBindingPattern(pattern): t = c.getTypeOfDestructuredProperty(parentType, getBindingElementPropertyName(node)) case !hasDotDotDotToken(node): - t = c.getTypeOfDestructuredArrayElement(parentType, slices.Index(pattern.AsBindingPattern().Elements.Nodes, node)) + t = c.getTypeOfDestructuredArrayElement(parentType, slices.Index(pattern.Elements(), node)) default: t = c.getTypeOfDestructuredSpreadExpression(parentType) } @@ -2286,7 +2283,7 @@ func (c *Checker) getAssignedTypeOfBinaryExpression(node *ast.Node) *Type { } func (c *Checker) getAssignedTypeOfArrayLiteralElement(node *ast.Node, element *ast.Node) *Type { - return c.getTypeOfDestructuredArrayElement(c.getAssignedType(node), slices.Index(node.AsArrayLiteralExpression().Elements.Nodes, element)) + return c.getTypeOfDestructuredArrayElement(c.getAssignedType(node), slices.Index(node.Elements(), element)) } func (c *Checker) getTypeOfDestructuredArrayElement(t *Type, index int) *Type { @@ -2682,11 +2679,8 @@ func (c *Checker) markNodeAssignmentsWorker(node *ast.Node) bool { return false case ast.KindExportSpecifier: exportDeclaration := node.AsExportSpecifier().Parent.Parent.AsExportDeclaration() - name := node.AsExportSpecifier().PropertyName - if name == nil { - name = node.Name() - } - if !node.AsExportSpecifier().IsTypeOnly && !exportDeclaration.IsTypeOnly && exportDeclaration.ModuleSpecifier == nil && !ast.IsStringLiteral(name) { + name := node.PropertyNameOrName() + if !node.IsTypeOnly() && !exportDeclaration.IsTypeOnly && exportDeclaration.ModuleSpecifier == nil && !ast.IsStringLiteral(name) { symbol := c.resolveEntityName(name, ast.SymbolFlagsValue, true /*ignoreErrors*/, true /*dontResolveAlias*/, nil) if symbol != nil && c.isParameterOrMutableLocalVariable(symbol) { links := c.markedAssignmentSymbolLinks.Get(symbol) diff --git a/internal/checker/grammarchecks.go b/internal/checker/grammarchecks.go index 338f755318..e271e66e01 100644 --- a/internal/checker/grammarchecks.go +++ b/internal/checker/grammarchecks.go @@ -232,10 +232,7 @@ func (c *Checker) checkGrammarModifiers(node *ast.Node /*Union[HasModifiers, Has // [...leadingDecorators, ...leadingModifiers, ...trailingDecorators, ...trailingModifiers]. It is an error to // have both leading and trailing decorators. hasLeadingDecorators := false - var modifiers []*ast.Node - if node.Modifiers() != nil { - modifiers = node.Modifiers().Nodes - } + modifiers := node.ModifierNodes() for _, modifier := range modifiers { if ast.IsDecorator(modifier) { if !nodeCanBeDecorated(c.legacyDecorators, node, node.Parent, node.Parent.Parent) { @@ -587,16 +584,11 @@ func (c *Checker) reportObviousModifierErrors(node *ast.Node) bool { } func (c *Checker) findFirstModifierExcept(node *ast.Node, allowedModifier ast.Kind) *ast.Node { - modifiers := node.Modifiers() - if modifiers == nil { - return nil - } - modifier := core.Find(modifiers.Nodes, ast.IsModifier) + modifier := core.Find(node.ModifierNodes(), ast.IsModifier) if modifier != nil && modifier.Kind != allowedModifier { return modifier - } else { - return nil } + return nil } func (c *Checker) findFirstIllegalModifier(node *ast.Node) *ast.Node { @@ -627,10 +619,7 @@ func (c *Checker) findFirstIllegalModifier(node *ast.Node) *ast.Node { ast.KindShorthandPropertyAssignment, ast.KindNamespaceExportDeclaration, ast.KindMissingDeclaration: - if modifiers := node.Modifiers(); modifiers != nil { - return core.Find(modifiers.Nodes, ast.IsModifier) - } - return nil + return core.Find(node.ModifierNodes(), ast.IsModifier) default: if node.Parent.Kind == ast.KindModuleBlock || node.Parent.Kind == ast.KindSourceFile { return nil @@ -644,17 +633,12 @@ func (c *Checker) findFirstIllegalModifier(node *ast.Node) *ast.Node { case ast.KindClassExpression, ast.KindInterfaceDeclaration, ast.KindTypeAliasDeclaration: - if modifiers := node.Modifiers(); modifiers != nil { - return core.Find(modifiers.Nodes, ast.IsModifier) - } - return nil + return core.Find(node.ModifierNodes(), ast.IsModifier) case ast.KindVariableStatement: if node.AsVariableStatement().DeclarationList.Flags&ast.NodeFlagsUsing != 0 { return c.findFirstModifierExcept(node, ast.KindAwaitKeyword) - } else if modifiers := node.Modifiers(); modifiers != nil { - return core.Find(modifiers.Nodes, ast.IsModifier) } - return nil + return core.Find(node.ModifierNodes(), ast.IsModifier) case ast.KindEnumDeclaration: return c.findFirstModifierExcept(node, ast.KindConstKeyword) default: @@ -673,7 +657,7 @@ func (c *Checker) reportObviousDecoratorErrors(node *ast.Node) bool { func (c *Checker) findFirstIllegalDecorator(node *ast.Node) *ast.Node { if ast.CanHaveIllegalDecorators(node) { - decorator := core.Find(node.Modifiers().Nodes, ast.IsDecorator) + decorator := core.Find(node.ModifierNodes(), ast.IsDecorator) return decorator } else { return nil @@ -749,7 +733,7 @@ func (c *Checker) checkGrammarForUseStrictSimpleParameterList(node *ast.Node) bo body := node.Body() var useStrictDirective *ast.Node if body != nil && ast.IsBlock(body) { - useStrictDirective = binder.FindUseStrictPrologue(ast.GetSourceFileOfNode(node), body.AsBlock().Statements.Nodes) + useStrictDirective = binder.FindUseStrictPrologue(ast.GetSourceFileOfNode(node), body.Statements()) } if useStrictDirective != nil { nonSimpleParameters := core.Filter(node.Parameters(), func(n *ast.Node) bool { @@ -791,7 +775,7 @@ func (c *Checker) checkGrammarFunctionLikeDeclaration(node *ast.Node) bool { func (c *Checker) checkGrammarClassLikeDeclaration(node *ast.Node) bool { file := ast.GetSourceFileOfNode(node) - return c.checkGrammarClassDeclarationHeritageClauses(node, file) || c.checkGrammarTypeParameterList(node.ClassLikeData().TypeParameters, file) + return c.checkGrammarClassDeclarationHeritageClauses(node, file) || c.checkGrammarTypeParameterList(node.TypeParameterList(), file) } func (c *Checker) checkGrammarArrowFunction(node *ast.Node, file *ast.SourceFile) bool { @@ -949,11 +933,11 @@ func (c *Checker) checkGrammarClassDeclarationHeritageClauses(node *ast.ClassLik for _, tag := range j.AsJSDoc().Tags.Nodes { if tag.Kind == ast.KindJSDocAugmentsTag { target := typeNodes[0].AsExpressionWithTypeArguments() - source := tag.AsJSDocAugmentsTag().ClassName.AsExpressionWithTypeArguments() + source := tag.ClassName().AsExpressionWithTypeArguments() if !ast.HasSamePropertyAccessName(target.Expression, source.Expression) && target.Expression.Kind == ast.KindIdentifier && source.Expression.Kind == ast.KindIdentifier { - return c.grammarErrorOnNode(tag.AsJSDocAugmentsTag().ClassName, diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, tag.AsJSDocAugmentsTag().TagName.Text(), source.Expression.Text(), target.Expression.Text()) + return c.grammarErrorOnNode(tag.ClassName(), diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, tag.TagName().Text(), source.Expression.Text(), target.Expression.Text()) } } } @@ -1092,15 +1076,15 @@ func (c *Checker) checkGrammarObjectLiteralExpression(node *ast.ObjectLiteralExp } // Modifiers are never allowed on properties except for 'async' on a method declaration - if modifiers := prop.Modifiers(); modifiers != nil { + if modifiers := prop.ModifierNodes(); len(modifiers) != 0 { if ast.CanHaveModifiers(prop) { - for _, mod := range modifiers.Nodes { + for _, mod := range modifiers { if ast.IsModifier(mod) && (mod.Kind != ast.KindAsyncKeyword || prop.Kind != ast.KindMethodDeclaration) { c.grammarErrorOnNode(mod, diagnostics.X_0_modifier_cannot_be_used_here, scanner.GetTextOfNode(mod)) } } } else if ast.CanHaveIllegalModifiers(prop) { - for _, mod := range modifiers.Nodes { + for _, mod := range modifiers { if ast.IsModifier(mod) { c.grammarErrorOnNode(mod, diagnostics.X_0_modifier_cannot_be_used_here, scanner.GetTextOfNode(mod)) } @@ -1185,7 +1169,7 @@ func (c *Checker) checkGrammarJsxElement(node *ast.Node) bool { c.checkGrammarJsxName(node.TagName()) c.checkGrammarTypeArguments(node, node.TypeArgumentList()) var seen collections.Set[string] - for _, attrNode := range node.Attributes().AsJsxAttributes().Properties.Nodes { + for _, attrNode := range node.Attributes().Properties() { if attrNode.Kind == ast.KindJsxSpreadAttribute { continue } @@ -1399,7 +1383,7 @@ func (c *Checker) doesAccessorHaveCorrectParameterCount(accessor *ast.AccessorDe func (c *Checker) checkGrammarTypeOperatorNode(node *ast.TypeOperatorNode) bool { if node.Operator == ast.KindUniqueKeyword { - innerType := node.AsTypeOperatorNode().Type + innerType := node.Type if innerType.Kind != ast.KindSymbolKeyword { return c.grammarErrorOnNode(innerType, diagnostics.X_0_expected, scanner.TokenToString(ast.KindSymbolKeyword)) } @@ -1428,7 +1412,7 @@ func (c *Checker) checkGrammarTypeOperatorNode(node *ast.TypeOperatorNode) bool return c.grammarErrorOnNode(node.AsNode(), diagnostics.X_unique_symbol_types_are_not_allowed_here) } } else if node.Operator == ast.KindReadonlyKeyword { - innerType := node.AsTypeOperatorNode().Type + innerType := node.Type if innerType.Kind != ast.KindArrayType && innerType.Kind != ast.KindTupleType { return c.grammarErrorOnFirstToken(node.AsNode(), diagnostics.X_readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, scanner.TokenToString(ast.KindSymbolKeyword)) } @@ -1509,16 +1493,7 @@ func (c *Checker) checkGrammarMethod(node *ast.Node /*Union[MethodDeclaration, M } func (c *Checker) checkGrammarBreakOrContinueStatement(node *ast.Node) bool { - var targetLabel *ast.IdentifierNode - switch node.Kind { - case ast.KindBreakStatement: - targetLabel = node.AsBreakStatement().Label - case ast.KindContinueStatement: - targetLabel = node.AsContinueStatement().Label - default: - panic(fmt.Sprintf("Unexpected node kind %q", node.Kind)) - } - + targetLabel := node.Label() var current *ast.Node = node for current != nil { if ast.IsFunctionLikeOrClassStaticBlockDeclaration(current) { @@ -1527,10 +1502,10 @@ func (c *Checker) checkGrammarBreakOrContinueStatement(node *ast.Node) bool { switch current.Kind { case ast.KindLabeledStatement: - if targetLabel != nil && (current.AsLabeledStatement()).Label.Text() == targetLabel.Text() { + if targetLabel != nil && current.Label().Text() == targetLabel.Text() { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - isMisplacedContinueLabel := node.Kind == ast.KindContinueStatement && !ast.IsIterationStatement((current.AsLabeledStatement()).Statement, true /*lookInLabeledStatements*/) + isMisplacedContinueLabel := node.Kind == ast.KindContinueStatement && !ast.IsIterationStatement(current.Statement(), true /*lookInLabeledStatements*/) if isMisplacedContinueLabel { return c.grammarErrorOnNode(node, diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement) @@ -1575,7 +1550,7 @@ func (c *Checker) checkGrammarBreakOrContinueStatement(node *ast.Node) bool { func (c *Checker) checkGrammarBindingElement(node *ast.BindingElement) bool { if node.DotDotDotToken != nil { - elements := node.Parent.AsBindingPattern().Elements + elements := node.Parent.ElementList() if node.AsNode() != core.LastOrNil(elements.Nodes) { return c.grammarErrorOnNode(&node.Node, diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern) } @@ -1657,7 +1632,7 @@ func (c *Checker) checkGrammarForEsModuleMarkerInBindingName(name *ast.Node) boo return c.grammarErrorOnNodeSkippedOnNoEmit(name, diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules) } } else { - for _, element := range name.AsBindingPattern().Elements.Nodes { + for _, element := range name.Elements() { if element.Name() != nil { return c.checkGrammarForEsModuleMarkerInBindingName(element.Name()) } @@ -1668,11 +1643,11 @@ func (c *Checker) checkGrammarForEsModuleMarkerInBindingName(name *ast.Node) boo func (c *Checker) checkGrammarNameInLetOrConstDeclarations(name *ast.Node /*Union[Identifier, BindingPattern]*/) bool { if name.Kind == ast.KindIdentifier { - if name.AsIdentifier().Text == "let" { + if name.Text() == "let" { return c.grammarErrorOnNode(name, diagnostics.X_let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations) } } else { - elements := name.AsBindingPattern().Elements.Nodes + elements := name.Elements() for _, element := range elements { bindingElement := element.AsBindingElement() if bindingElement.Name() != nil { @@ -1876,7 +1851,7 @@ func (c *Checker) checkGrammarMetaProperty(node *ast.MetaProperty) bool { } case ast.KindImportKeyword: if nameText != "meta" { - isCallee := ast.IsCallExpression(node.Parent) && node.Parent.AsCallExpression().Expression == node.AsNode() + isCallee := ast.IsCallExpression(node.Parent) && node.Parent.Expression() == node.AsNode() if nameText == "defer" { if !isCallee { return c.grammarErrorAtPos(node.AsNode(), node.AsNode().End(), 0, diagnostics.X_0_expected, "(") @@ -1928,7 +1903,7 @@ func (c *Checker) checkGrammarProperty(node *ast.Node /*Union[PropertyDeclaratio if c.checkGrammarForInvalidDynamicName(propertyName, diagnostics.A_computed_property_name_in_a_class_property_declaration_must_have_a_simple_literal_type_or_a_unique_symbol_type) { return true } - if ast.IsAutoAccessorPropertyDeclaration(node) && c.checkGrammarForInvalidQuestionMark(node.AsPropertyDeclaration().PostfixToken, diagnostics.An_accessor_property_cannot_be_declared_optional) { + if ast.IsAutoAccessorPropertyDeclaration(node) && c.checkGrammarForInvalidQuestionMark(node.PostfixToken(), diagnostics.An_accessor_property_cannot_be_declared_optional) { return true } } else if ast.IsInterfaceDeclaration(node.Parent) { @@ -1939,7 +1914,7 @@ func (c *Checker) checkGrammarProperty(node *ast.Node /*Union[PropertyDeclaratio // Interfaces cannot contain property declarations panic(fmt.Sprintf("Unexpected node kind %q", node.Kind)) } - if initializer := node.AsPropertySignatureDeclaration().Initializer; initializer != nil { + if initializer := node.Initializer(); initializer != nil { return c.grammarErrorOnNode(initializer, diagnostics.An_interface_property_cannot_have_an_initializer) } } else if ast.IsTypeLiteralNode(node.Parent) { @@ -1950,7 +1925,7 @@ func (c *Checker) checkGrammarProperty(node *ast.Node /*Union[PropertyDeclaratio // Type literals cannot contain property declarations panic(fmt.Sprintf("Unexpected node kind %q", node.Kind)) } - if initializer := node.AsPropertySignatureDeclaration().Initializer; initializer != nil { + if initializer := node.Initializer(); initializer != nil { return c.grammarErrorOnNode(initializer, diagnostics.A_type_literal_property_cannot_have_an_initializer) } } @@ -2178,21 +2153,15 @@ func (c *Checker) checkGrammarImportClause(node *ast.ImportClause) bool { } func (c *Checker) checkGrammarTypeOnlyNamedImportsOrExports(namedBindings *ast.Node) bool { - var nodeList *ast.NodeList - if namedBindings.Kind == ast.KindNamedImports { - nodeList = namedBindings.AsNamedImports().Elements - } else { - nodeList = namedBindings.AsNamedExports().Elements - } - + nodeList := namedBindings.ElementList() for _, specifier := range nodeList.Nodes { var specifierIsTypeOnly bool var message *diagnostics.Message if specifier.Kind == ast.KindImportSpecifier { - specifierIsTypeOnly = specifier.AsImportSpecifier().IsTypeOnly + specifierIsTypeOnly = specifier.IsTypeOnly() message = diagnostics.The_type_modifier_cannot_be_used_on_a_named_import_when_import_type_is_used_on_its_import_statement } else { - specifierIsTypeOnly = specifier.AsExportSpecifier().IsTypeOnly + specifierIsTypeOnly = specifier.IsTypeOnly() message = diagnostics.The_type_modifier_cannot_be_used_on_a_named_export_when_export_type_is_used_on_its_export_statement } diff --git a/internal/checker/jsx.go b/internal/checker/jsx.go index 8512920510..9ab6699ea1 100644 --- a/internal/checker/jsx.go +++ b/internal/checker/jsx.go @@ -267,7 +267,7 @@ func (c *Checker) discriminateContextualTypeByJSXAttributes(node *ast.Node, cont return discriminated } jsxChildrenPropertyName := c.getJsxElementChildrenPropertyName(c.getJsxNamespaceAt(node)) - discriminantProperties := core.Filter(node.AsJsxAttributes().Properties.Nodes, func(p *ast.Node) bool { + discriminantProperties := core.Filter(node.Properties(), func(p *ast.Node) bool { symbol := p.Symbol() if symbol == nil || !ast.IsJsxAttribute(p) { return false @@ -293,7 +293,7 @@ func (c *Checker) discriminateContextualTypeByJSXAttributes(node *ast.Node, cont func (c *Checker) elaborateJsxComponents(node *ast.Node, source *Type, target *Type, relation *Relation, diagnosticOutput *[]*ast.Diagnostic) bool { reportedError := false - for _, prop := range node.AsJsxAttributes().Properties.Nodes { + for _, prop := range node.Properties() { if !ast.IsJsxSpreadAttribute(prop) && !isHyphenatedJsxName(prop.Name().Text()) { nameType := c.getStringLiteralType(prop.Name().Text()) if nameType != nil && nameType.flags&TypeFlagsNever == 0 { @@ -719,7 +719,7 @@ func (c *Checker) createJsxAttributesTypeFromAttributesProperty(openingLikeEleme // Create anonymous type from given attributes symbol table. // @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable // @param attributesTable a symbol table of attributes property - for _, attributeDecl := range attributes.AsJsxAttributes().Properties.Nodes { + for _, attributeDecl := range attributes.Properties() { member := attributeDecl.Symbol() if ast.IsJsxAttribute(attributeDecl) { exprType := c.checkJsxAttribute(attributeDecl, checkMode) @@ -796,11 +796,11 @@ func (c *Checker) createJsxAttributesTypeFromAttributesProperty(openingLikeEleme case ast.IsJsxElement(parent): // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if parent.AsJsxElement().OpeningElement == openingLikeElement { - children = parent.AsJsxElement().Children.Nodes + children = parent.Children().Nodes } case ast.IsJsxFragment(parent): if parent.AsJsxFragment().OpeningFragment == openingLikeElement { - children = parent.AsJsxFragment().Children.Nodes + children = parent.Children().Nodes } } return len(ast.GetSemanticJsxChildren(children)) != 0 @@ -939,7 +939,7 @@ func (c *Checker) getJsxPropsTypeFromClassType(sig *Signature, context *ast.Node attributesType = c.getReturnTypeOfSignature(sig) default: attributesType = c.getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) - if attributesType == nil && len(context.Attributes().AsJsxAttributes().Properties.Nodes) != 0 { + if attributesType == nil && len(context.Attributes().Properties()) != 0 { // There is no property named 'props' on this instance type c.error(context, diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, forcedLookupLocation) } diff --git a/internal/checker/nodebuilderimpl.go b/internal/checker/nodebuilderimpl.go index c689adb3b9..f1f4c7ad2a 100644 --- a/internal/checker/nodebuilderimpl.go +++ b/internal/checker/nodebuilderimpl.go @@ -163,7 +163,7 @@ func (b *NodeBuilderImpl) appendReferenceToType(root *ast.TypeNode, ref *ast.Typ qualifier = id } } - return b.f.UpdateImportTypeNode(imprt, imprt.IsTypeOf, imprt.Argument, imprt.Attributes, qualifier, ref.AsTypeReferenceNode().TypeArguments) + return b.f.UpdateImportTypeNode(imprt, imprt.IsTypeOf, imprt.Argument, imprt.Attributes, qualifier, ref.TypeArgumentList()) } else { // first shift type arguments // !!! In the old emitter, an Identifier could have type arguments for use with quickinfo: @@ -185,7 +185,7 @@ func (b *NodeBuilderImpl) appendReferenceToType(root *ast.TypeNode, ref *ast.Typ for _, id := range ids { typeName = b.f.NewQualifiedName(typeName, id) } - return b.f.UpdateTypeReferenceNode(root.AsTypeReferenceNode(), typeName, ref.AsTypeReferenceNode().TypeArguments) + return b.f.UpdateTypeReferenceNode(root.AsTypeReferenceNode(), typeName, ref.TypeArgumentList()) } } @@ -670,7 +670,7 @@ func (b *NodeBuilderImpl) createAccessFromSymbolChain(chain []*ast.Symbol, index break } } - if name != nil && ast.IsComputedPropertyName(name) && ast.IsEntityName(name.AsComputedPropertyName().Expression) { + if name != nil && ast.IsComputedPropertyName(name) && ast.IsEntityName(name.Expression()) { lhs := b.createAccessFromSymbolChain(chain, index-1, stopper, overrideTypeArguments) if ast.IsEntityName(lhs) { return b.f.NewIndexedAccessTypeNode( @@ -1093,38 +1093,34 @@ func tryGetModuleSpecifierFromDeclarationWorker(node *ast.Node) *ast.Node { if requireCall == nil { return nil } - return requireCall.AsCallExpression().Arguments.Nodes[0] - case ast.KindImportDeclaration: - return node.AsImportDeclaration().ModuleSpecifier - case ast.KindExportDeclaration: - return node.AsExportDeclaration().ModuleSpecifier - case ast.KindJSDocImportTag: - return node.AsJSDocImportTag().ModuleSpecifier + return requireCall.Arguments()[0] + case ast.KindImportDeclaration, ast.KindExportDeclaration, ast.KindJSDocImportTag: + return node.ModuleSpecifier() case ast.KindImportEqualsDeclaration: ref := node.AsImportEqualsDeclaration().ModuleReference if ref.Kind != ast.KindExternalModuleReference { return nil } - return ref.AsExternalModuleReference().Expression + return ref.Expression() case ast.KindImportClause: if ast.IsImportDeclaration(node.Parent) { - return node.Parent.AsImportDeclaration().ModuleSpecifier + return node.Parent.ModuleSpecifier() } - return node.Parent.AsJSDocImportTag().ModuleSpecifier + return node.Parent.ModuleSpecifier() case ast.KindNamespaceExport: - return node.Parent.AsExportDeclaration().ModuleSpecifier + return node.Parent.ModuleSpecifier() case ast.KindNamespaceImport: if ast.IsImportDeclaration(node.Parent.Parent) { - return node.Parent.Parent.AsImportDeclaration().ModuleSpecifier + return node.Parent.Parent.ModuleSpecifier() } - return node.Parent.Parent.AsJSDocImportTag().ModuleSpecifier + return node.Parent.Parent.ModuleSpecifier() case ast.KindExportSpecifier: - return node.Parent.Parent.AsExportDeclaration().ModuleSpecifier + return node.Parent.Parent.ModuleSpecifier() case ast.KindImportSpecifier: if ast.IsImportDeclaration(node.Parent.Parent.Parent) { - return node.Parent.Parent.Parent.AsImportDeclaration().ModuleSpecifier + return node.Parent.Parent.Parent.ModuleSpecifier() } - return node.Parent.Parent.Parent.AsJSDocImportTag().ModuleSpecifier + return node.Parent.Parent.Parent.ModuleSpecifier() case ast.KindImportType: if ast.IsLiteralImportTypeNode(node) { return node.AsImportTypeNode().Argument.AsLiteralTypeNode().Literal @@ -1312,7 +1308,7 @@ func (b *NodeBuilderImpl) typeParameterToName(typeParameter *Type) *ast.Identifi b.ctx.typeParameterNamesByTextNextNameCount = make(map[string]int) } - rawText := result.AsIdentifier().Text + rawText := result.Text() i := 0 cached, ok := b.ctx.typeParameterNamesByTextNextNameCount[rawText] if ok { @@ -1434,7 +1430,7 @@ func (b *NodeBuilderImpl) createMappedTypeNodeFromType(t *Type) *ast.TypeNode { // wrap it with a conditional like `SomeModifiersType extends infer U ? {..the mapped type...} : never` to ensure the resulting // type stays homomorphic - rawConstraintTypeFromDeclaration := b.getTypeFromTypeNode(mapped.declaration.TypeParameter.AsTypeParameter().Constraint.AsTypeOperatorNode().Type, false) + rawConstraintTypeFromDeclaration := b.getTypeFromTypeNode(mapped.declaration.TypeParameter.AsTypeParameter().Constraint.Type(), false) if rawConstraintTypeFromDeclaration != nil { rawConstraintTypeFromDeclaration = b.ch.getConstraintOfTypeParameter(rawConstraintTypeFromDeclaration) } @@ -1556,7 +1552,7 @@ func (b *NodeBuilderImpl) symbolToParameterDeclaration(parameterSymbol *ast.Symb parameterTypeNode := b.serializeTypeForDeclaration(parameterDeclaration, parameterType, parameterSymbol) var modifiers *ast.ModifierList if b.ctx.flags&nodebuilder.FlagsOmitParameterModifiers == 0 && preserveModifierFlags && parameterDeclaration != nil && ast.CanHaveModifiers(parameterDeclaration) { - originals := core.Filter(parameterDeclaration.Modifiers().Nodes, ast.IsModifier) + originals := core.Filter(parameterDeclaration.ModifierNodes(), ast.IsModifier) clones := core.Map(originals, func(node *ast.Node) *ast.Node { return node.Clone(b.f) }) if len(clones) > 0 { modifiers = b.f.NewModifierList(clones) @@ -2108,7 +2104,7 @@ func (b *NodeBuilderImpl) isStringNamed(d *ast.Declaration) bool { return false } if ast.IsComputedPropertyName(name) { - t := b.ch.checkExpression(name.AsComputedPropertyName().Expression) + t := b.ch.checkExpression(name.Expression()) return t.flags&TypeFlagsStringLike != 0 } if ast.IsElementAccessExpression(name) { diff --git a/internal/checker/relater.go b/internal/checker/relater.go index 25432d8b58..199eb76ad9 100644 --- a/internal/checker/relater.go +++ b/internal/checker/relater.go @@ -443,7 +443,7 @@ func (c *Checker) elaborateError(node *ast.Node, source *Type, target *Type, rel } switch node.Kind { case ast.KindAsExpression: - if !isConstAssertion(node) { + if !ast.IsConstAssertion(node) { break } fallthrough @@ -493,7 +493,7 @@ func (c *Checker) elaborateObjectLiteral(node *ast.Node, source *Type, target *T return false } reportedError := false - for _, prop := range node.AsObjectLiteralExpression().Properties.Nodes { + for _, prop := range node.Properties() { if ast.IsSpreadAssignment(prop) { continue } @@ -525,7 +525,7 @@ func (c *Checker) elaborateArrayLiteral(node *ast.Node, source *Type, target *Ty } } reportedError := false - for i, element := range node.AsArrayLiteralExpression().Elements.Nodes { + for i, element := range node.Elements() { if ast.IsOmittedExpression(element) || c.isTupleLikeType(target) && c.getPropertyOfType(target, jsnum.Number(i).String()) == nil { continue } @@ -1963,7 +1963,7 @@ func (c *Checker) getTupleElementLabelFromBindingElement(node *ast.Node, index i return name + "_n" case ast.KindArrayBindingPattern: if hasDotDotDotToken(node) { - elements := node.Name().AsBindingPattern().Elements.Nodes + elements := node.Name().Elements() lastElement := core.LastOrNil(elements) lastElementIsBindingElementRest := lastElement != nil && ast.IsBindingElement(lastElement) && hasDotDotDotToken(lastElement) elementCount := len(elements) - core.IfElse(lastElementIsBindingElementRest, 1, 0) diff --git a/internal/checker/services.go b/internal/checker/services.go index c86aa7b2be..cec934f547 100644 --- a/internal/checker/services.go +++ b/internal/checker/services.go @@ -450,7 +450,7 @@ func (c *Checker) GetExportSpecifierLocalTargetSymbol(node *ast.Node) *ast.Symbo // node should be ExportSpecifier | Identifier switch node.Kind { case ast.KindExportSpecifier: - if node.Parent.Parent.AsExportDeclaration().ModuleSpecifier != nil { + if node.Parent.Parent.ModuleSpecifier() != nil { return c.getExternalModuleMember(node.Parent.Parent, node, false /*dontResolveAlias*/) } name := node.PropertyNameOrName() @@ -799,7 +799,7 @@ func (c *Checker) getTypeOfAssignmentPattern(expr *ast.Node) *Type { if ast.IsPropertyAssignment(expr.Parent) { node := expr.Parent.Parent typeOfParentObjectLiteral := core.OrElse(c.getTypeOfAssignmentPattern(node), c.errorType) - propertyIndex := slices.Index(node.AsObjectLiteralExpression().Properties.Nodes, expr.Parent) + propertyIndex := slices.Index(node.Properties(), expr.Parent) return c.checkObjectLiteralDestructuringPropertyAssignment(node, typeOfParentObjectLiteral, propertyIndex, nil, false) } // Array literal assignment - array destructuring pattern @@ -807,7 +807,7 @@ func (c *Checker) getTypeOfAssignmentPattern(expr *ast.Node) *Type { // [{ property1: p1, property2 }] = elems; typeOfArrayLiteral := core.OrElse(c.getTypeOfAssignmentPattern(node), c.errorType) elementType := core.OrElse(c.checkIteratedTypeOrElementType(IterationUseDestructuring, typeOfArrayLiteral, c.undefinedType, expr.Parent), c.errorType) - return c.checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, slices.Index(node.AsArrayLiteralExpression().Elements.Nodes, expr), elementType, CheckModeNormal) + return c.checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, slices.Index(node.Elements(), expr), elementType, CheckModeNormal) } func (c *Checker) GetSignatureFromDeclaration(node *ast.Node) *Signature { diff --git a/internal/checker/symbolaccessibility.go b/internal/checker/symbolaccessibility.go index d9741f18a5..a30e193cdf 100644 --- a/internal/checker/symbolaccessibility.go +++ b/internal/checker/symbolaccessibility.go @@ -534,7 +534,7 @@ func isUMDExportSymbol(symbol *ast.Symbol) bool { } func isNamespaceReexportDeclaration(node *ast.Node) bool { - return ast.IsNamespaceExport(node) && node.Parent.AsExportDeclaration().ModuleSpecifier != nil + return ast.IsNamespaceExport(node) && node.Parent.ModuleSpecifier() != nil } func (ch *Checker) getCandidateListForSymbol( diff --git a/internal/checker/utilities.go b/internal/checker/utilities.go index 617e2f80b7..60af0257ea 100644 --- a/internal/checker/utilities.go +++ b/internal/checker/utilities.go @@ -85,7 +85,7 @@ func isStaticPrivateIdentifierProperty(s *ast.Symbol) bool { } func isEmptyObjectLiteral(expression *ast.Node) bool { - return expression.Kind == ast.KindObjectLiteralExpression && len(expression.AsObjectLiteralExpression().Properties.Nodes) == 0 + return ast.IsObjectLiteralExpression(expression) && len(expression.Properties()) == 0 } type AssignmentKind int32 @@ -136,26 +136,6 @@ func isCompoundLikeAssignment(assignment *ast.Node) bool { return right.Kind == ast.KindBinaryExpression && isShiftOperatorOrHigher(right.AsBinaryExpression().OperatorToken.Kind) } -func getAssertedTypeNode(node *ast.Node) *ast.Node { - switch node.Kind { - case ast.KindAsExpression: - return node.AsAsExpression().Type - case ast.KindSatisfiesExpression: - return node.AsSatisfiesExpression().Type - case ast.KindTypeAssertionExpression: - return node.AsTypeAssertion().Type - } - panic("Unhandled case in getAssertedTypeNode") -} - -func isConstAssertion(node *ast.Node) bool { - switch node.Kind { - case ast.KindAsExpression, ast.KindTypeAssertionExpression: - return isConstTypeReference(getAssertedTypeNode(node)) - } - return false -} - func isConstTypeReference(node *ast.Node) bool { return ast.IsTypeReferenceNode(node) && len(node.TypeArguments()) == 0 && ast.IsIdentifier(node.AsTypeReferenceNode().TypeName) && node.AsTypeReferenceNode().TypeName.Text() == "const" } @@ -243,7 +223,7 @@ func isShorthandAmbientModuleSymbol(moduleSymbol *ast.Symbol) bool { func isShorthandAmbientModule(node *ast.Node) bool { // The only kind of module that can be missing a body is a shorthand ambient module. - return node != nil && node.Kind == ast.KindModuleDeclaration && node.AsModuleDeclaration().Body == nil + return node != nil && node.Kind == ast.KindModuleDeclaration && node.Body() == nil } func getAliasDeclarationFromName(node *ast.Node) *ast.Node { @@ -269,7 +249,7 @@ func entityNameToString(name *ast.Node) string { case ast.KindQualifiedName: return entityNameToString(name.AsQualifiedName().Left) + "." + entityNameToString(name.AsQualifiedName().Right) case ast.KindPropertyAccessExpression: - return entityNameToString(name.AsPropertyAccessExpression().Expression) + "." + entityNameToString(name.AsPropertyAccessExpression().Name()) + return entityNameToString(name.Expression()) + "." + entityNameToString(name.AsPropertyAccessExpression().Name()) case ast.KindJsxNamespacedName: return entityNameToString(name.AsJsxNamespacedName().Namespace) + ":" + entityNameToString(name.AsJsxNamespacedName().Name()) } @@ -285,12 +265,12 @@ func getContainingQualifiedNameNode(node *ast.Node) *ast.Node { func isSideEffectImport(node *ast.Node) bool { ancestor := ast.FindAncestor(node, ast.IsImportDeclaration) - return ancestor != nil && ancestor.AsImportDeclaration().ImportClause == nil + return ancestor != nil && ancestor.ImportClause() == nil } func getExternalModuleRequireArgument(node *ast.Node) *ast.Node { if ast.IsVariableDeclarationInitializedToRequire(node) { - return node.AsVariableDeclaration().Initializer.AsCallExpression().Arguments.Nodes[0] + return node.Initializer().Arguments()[0] } return nil } @@ -354,27 +334,11 @@ func isExclamationToken(node *ast.Node) bool { } func isOptionalDeclaration(declaration *ast.Node) bool { - switch declaration.Kind { - case ast.KindParameter: - return declaration.AsParameterDeclaration().QuestionToken != nil - case ast.KindPropertyDeclaration: - return ast.IsQuestionToken(declaration.AsPropertyDeclaration().PostfixToken) - case ast.KindPropertySignature: - return ast.IsQuestionToken(declaration.AsPropertySignatureDeclaration().PostfixToken) - case ast.KindMethodDeclaration: - return ast.IsQuestionToken(declaration.AsMethodDeclaration().PostfixToken) - case ast.KindMethodSignature: - return ast.IsQuestionToken(declaration.AsMethodSignatureDeclaration().PostfixToken) - case ast.KindPropertyAssignment: - return ast.IsQuestionToken(declaration.AsPropertyAssignment().PostfixToken) - case ast.KindShorthandPropertyAssignment: - return ast.IsQuestionToken(declaration.AsShorthandPropertyAssignment().PostfixToken) - } - return false + return ast.HasQuestionToken(declaration) } func isEmptyArrayLiteral(expression *ast.Node) bool { - return ast.IsArrayLiteralExpression(expression) && len(expression.AsArrayLiteralExpression().Elements.Nodes) == 0 + return ast.IsArrayLiteralExpression(expression) && len(expression.Elements()) == 0 } func declarationBelongsToPrivateAmbientMember(declaration *ast.Node) bool { @@ -1049,7 +1013,7 @@ func isThisInitializedObjectBindingExpression(node *ast.Node) bool { } func isThisInitializedDeclaration(node *ast.Node) bool { - return node != nil && ast.IsVariableDeclaration(node) && node.AsVariableDeclaration().Initializer != nil && node.AsVariableDeclaration().Initializer.Kind == ast.KindThisKeyword + return node != nil && ast.IsVariableDeclaration(node) && node.Initializer() != nil && node.Initializer().Kind == ast.KindThisKeyword } func isInfinityOrNaNString(name string) bool { @@ -1098,23 +1062,11 @@ func isNonNullAccess(node *ast.Node) bool { } func getTagNameOfNode(node *ast.Node) *ast.Node { - switch node.Kind { - case ast.KindJsxOpeningElement: - return node.AsJsxOpeningElement().TagName - case ast.KindJsxClosingElement: - return node.AsJsxClosingElement().TagName - case ast.KindJsxSelfClosingElement: - return node.AsJsxSelfClosingElement().TagName - } - panic("Unhandled case in getTagNameOfNode") + return node.TagName() } func getBindingElementPropertyName(node *ast.Node) *ast.Node { - name := node.AsBindingElement().PropertyName - if name != nil { - return name - } - return node.Name() + return node.PropertyNameOrName() } func isCallChain(node *ast.Node) bool { @@ -1140,16 +1092,10 @@ func isSuperProperty(node *ast.Node) bool { func getMembersOfDeclaration(node *ast.Node) []*ast.Node { switch node.Kind { - case ast.KindInterfaceDeclaration: - return node.AsInterfaceDeclaration().Members.Nodes - case ast.KindClassDeclaration: - return node.AsClassDeclaration().Members.Nodes - case ast.KindClassExpression: - return node.AsClassExpression().Members.Nodes - case ast.KindTypeLiteral: - return node.AsTypeLiteralNode().Members.Nodes + case ast.KindInterfaceDeclaration, ast.KindClassDeclaration, ast.KindClassExpression, ast.KindTypeLiteral: + return node.Members() case ast.KindObjectLiteralExpression: - return node.AsObjectLiteralExpression().Properties.Nodes + return node.Properties() } return nil } @@ -1196,7 +1142,7 @@ func isInRightSideOfImportOrExportAssignment(node *ast.EntityName) bool { } return node.Parent.Kind == ast.KindImportEqualsDeclaration && node.Parent.AsImportEqualsDeclaration().ModuleReference == node || - (node.Parent.Kind == ast.KindExportAssignment || node.Parent.Kind == ast.KindJSExportAssignment) && node.Parent.AsExportAssignment().Expression == node + (node.Parent.Kind == ast.KindExportAssignment || node.Parent.Kind == ast.KindJSExportAssignment) && node.Parent.Expression() == node } func isJsxIntrinsicTagName(tagName *ast.Node) bool { @@ -1397,10 +1343,8 @@ func minAndMax[T any](slice []T, getValue func(value T) int) (int, int) { func getNonModifierTokenRangeOfNode(node *ast.Node) core.TextRange { pos := node.Pos() - if node.Modifiers() != nil { - if last := ast.FindLastVisibleNode(node.Modifiers().Nodes); last != nil { - pos = last.Pos() - } + if last := ast.FindLastVisibleNode(node.ModifierNodes()); last != nil { + pos = last.Pos() } return scanner.GetRangeOfTokenAtPosition(ast.GetSourceFileOfNode(node), pos) } diff --git a/internal/compiler/program.go b/internal/compiler/program.go index ce89aaa601..87665c0099 100644 --- a/internal/compiler/program.go +++ b/internal/compiler/program.go @@ -664,7 +664,7 @@ func (p *Program) verifyCompilerOptions() { return tsoptions.ForEachPropertyAssignment(pathProp.Initializer.AsObjectLiteralExpression(), key, func(keyProps *ast.PropertyAssignment) *ast.Diagnostic { initializer := keyProps.Initializer if ast.IsArrayLiteralExpression(initializer) { - elements := initializer.AsArrayLiteralExpression().Elements + elements := initializer.ElementList() if elements != nil && len(elements.Nodes) > valueIndex { diag := tsoptions.CreateDiagnosticForNodeInSourceFile(sourceFile(), elements.Nodes[valueIndex], message, args...) p.programDiagnostics = append(p.programDiagnostics, diag) diff --git a/internal/format/indent.go b/internal/format/indent.go index 170873c2a4..98299f0307 100644 --- a/internal/format/indent.go +++ b/internal/format/indent.go @@ -130,7 +130,7 @@ func getActualIndentationForNode(current *ast.Node, parent *ast.Node, cuurentLin } func isArgumentAndStartLineOverlapsExpressionBeingCalled(parent *ast.Node, child *ast.Node, childStartLine int, sourceFile *ast.SourceFile) bool { - if !(ast.IsCallExpression(parent) && slices.Contains(parent.AsCallExpression().Arguments.Nodes, child)) { + if !(ast.IsCallExpression(parent) && slices.Contains(parent.Arguments(), child)) { return false } expressionOfCallExpressionEnd := parent.Expression().End() @@ -271,13 +271,13 @@ func getListByRange(start int, end int, node *ast.Node, sourceFile *ast.SourceFi r := core.NewTextRange(start, end) switch node.Kind { case ast.KindTypeReference: - return getList(node.AsTypeReferenceNode().TypeArguments, r, node, sourceFile) + return getList(node.TypeArgumentList(), r, node, sourceFile) case ast.KindObjectLiteralExpression: - return getList(node.AsObjectLiteralExpression().Properties, r, node, sourceFile) + return getList(node.PropertyList(), r, node, sourceFile) case ast.KindArrayLiteralExpression: - return getList(node.AsArrayLiteralExpression().Elements, r, node, sourceFile) + return getList(node.ElementList(), r, node, sourceFile) case ast.KindTypeLiteral: - return getList(node.AsTypeLiteralNode().Members, r, node, sourceFile) + return getList(node.MemberList(), r, node, sourceFile) case ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindArrowFunction, @@ -308,12 +308,8 @@ func getListByRange(start int, end int, node *ast.Node, sourceFile *ast.SourceFi return getList(node.ArgumentList(), r, node, sourceFile) case ast.KindVariableDeclarationList: return getList(node.AsVariableDeclarationList().Declarations, r, node, sourceFile) - case ast.KindNamedImports: - return getList(node.AsNamedImports().Elements, r, node, sourceFile) - case ast.KindNamedExports: - return getList(node.AsNamedExports().Elements, r, node, sourceFile) - case ast.KindObjectBindingPattern, ast.KindArrayBindingPattern: - return getList(node.AsBindingPattern().Elements, r, node, sourceFile) + case ast.KindObjectBindingPattern, ast.KindArrayBindingPattern, ast.KindNamedImports, ast.KindNamedExports: + return getList(node.ElementList(), r, node, sourceFile) } return nil // TODO: should this be a panic? It isn't in strada. } diff --git a/internal/format/rulecontext.go b/internal/format/rulecontext.go index 690af63fc6..cb2b57f89b 100644 --- a/internal/format/rulecontext.go +++ b/internal/format/rulecontext.go @@ -225,7 +225,7 @@ func isTypeAnnotationContext(context *FormattingContext) bool { } func isOptionalPropertyContext(context *FormattingContext) bool { - return ast.IsPropertyDeclaration(context.contextNode) && context.contextNode.AsPropertyDeclaration().PostfixToken != nil && context.contextNode.AsPropertyDeclaration().PostfixToken.Kind == ast.KindQuestionToken + return ast.IsPropertyDeclaration(context.contextNode) && ast.HasQuestionToken(context.contextNode) } func isNonOptionalPropertyContext(context *FormattingContext) bool { @@ -539,7 +539,7 @@ func isVoidOpContext(context *FormattingContext) bool { } func isYieldOrYieldStarWithOperand(context *FormattingContext) bool { - return context.contextNode.Kind == ast.KindYieldExpression && context.contextNode.AsYieldExpression().Expression != nil + return context.contextNode.Kind == ast.KindYieldExpression && context.contextNode.Expression() != nil } func isNonNullAssertionContext(context *FormattingContext) bool { diff --git a/internal/format/span.go b/internal/format/span.go index de5b4df29a..f4b73ec58b 100644 --- a/internal/format/span.go +++ b/internal/format/span.go @@ -206,7 +206,7 @@ func newFormatSpanWorker( func getNonDecoratorTokenPosOfNode(node *ast.Node, file *ast.SourceFile) int { var lastDecorator *ast.Node if ast.HasDecorators(node) { - lastDecorator = core.FindLast(node.Modifiers().Nodes, ast.IsDecorator) + lastDecorator = core.FindLast(node.ModifierNodes(), ast.IsDecorator) } if file == nil { file = ast.GetSourceFileOfNode(node) @@ -1171,7 +1171,7 @@ func (i *dynamicIndenter) shouldAddDelta(line int, kind ast.Kind, container *ast func getFirstNonDecoratorTokenOfNode(node *ast.Node) ast.Kind { if ast.CanHaveModifiers(node) { - modifier := core.Find(node.Modifiers().Nodes[core.FindIndex(node.Modifiers().Nodes, ast.IsDecorator):], ast.IsModifier) + modifier := core.Find(node.ModifierNodes()[core.FindIndex(node.ModifierNodes(), ast.IsDecorator):], ast.IsModifier) if modifier != nil { return modifier.Kind } diff --git a/internal/format/util.go b/internal/format/util.go index 0bf8bc7048..e060b80dbe 100644 --- a/internal/format/util.go +++ b/internal/format/util.go @@ -90,10 +90,10 @@ func isGrammarError(parent *ast.Node, child *ast.Node) bool { return child == parent.AsTypeParameter().Expression } if ast.IsPropertySignatureDeclaration(parent) { - return child == parent.AsPropertySignatureDeclaration().Initializer + return child == parent.Initializer() } if ast.IsPropertyDeclaration(parent) { - return ast.IsAutoAccessorPropertyDeclaration(parent) && child == parent.AsPropertyDeclaration().PostfixToken && child.Kind == ast.KindQuestionToken + return ast.IsAutoAccessorPropertyDeclaration(parent) && child == parent.PostfixToken() && child.Kind == ast.KindQuestionToken } if ast.IsPropertyAssignment(parent) { pa := parent.AsPropertyAssignment() @@ -106,16 +106,16 @@ func isGrammarError(parent *ast.Node, child *ast.Node) bool { return child == sp.EqualsToken || child == sp.PostfixToken || (mods != nil && isGrammarErrorElement(&mods.NodeList, child, ast.IsModifierLike)) } if ast.IsMethodDeclaration(parent) { - return child == parent.AsMethodDeclaration().PostfixToken && child.Kind == ast.KindExclamationToken + return child == parent.PostfixToken() && child.Kind == ast.KindExclamationToken } if ast.IsConstructorDeclaration(parent) { - return child == parent.AsConstructorDeclaration().Type || isGrammarErrorElement(parent.AsConstructorDeclaration().TypeParameters, child, ast.IsTypeParameterDeclaration) + return child == parent.AsConstructorDeclaration().Type || isGrammarErrorElement(parent.TypeParameterList(), child, ast.IsTypeParameterDeclaration) } if ast.IsGetAccessorDeclaration(parent) { - return isGrammarErrorElement(parent.AsGetAccessorDeclaration().TypeParameters, child, ast.IsTypeParameterDeclaration) + return isGrammarErrorElement(parent.TypeParameterList(), child, ast.IsTypeParameterDeclaration) } if ast.IsSetAccessorDeclaration(parent) { - return child == parent.AsSetAccessorDeclaration().Type || isGrammarErrorElement(parent.AsSetAccessorDeclaration().TypeParameters, child, ast.IsTypeParameterDeclaration) + return child == parent.AsSetAccessorDeclaration().Type || isGrammarErrorElement(parent.TypeParameterList(), child, ast.IsTypeParameterDeclaration) } if ast.IsNamespaceExportDeclaration(parent) { mods := parent.AsNamespaceExportDeclaration().Modifiers() diff --git a/internal/ls/completions.go b/internal/ls/completions.go index 8d37b93b94..a3dbd9df94 100644 --- a/internal/ls/completions.go +++ b/internal/ls/completions.go @@ -1051,10 +1051,7 @@ func (l *LanguageService) getCompletionData( numberIndexType := typeChecker.GetNumberIndexType(t) isNewIdentifierLocation = stringIndexType != nil || numberIndexType != nil typeMembers = getPropertiesForObjectExpression(instantiatedType, completionsType, objectLikeContainer, typeChecker) - properties := objectLikeContainer.AsObjectLiteralExpression().Properties - if properties != nil { - existingMembers = properties.Nodes - } + existingMembers = objectLikeContainer.Properties() if len(typeMembers) == 0 { // Edge case: If NumberIndexType exists @@ -1107,10 +1104,7 @@ func (l *LanguageService) getCompletionData( ) }, ) - elements := objectLikeContainer.AsBindingPattern().Elements - if elements != nil { - existingMembers = elements.Nodes - } + existingMembers = objectLikeContainer.Elements() } } @@ -2098,7 +2092,7 @@ func (l *LanguageService) createCompletionItem( insertText = name } - if insertQuestionDot || data.propertyAccessToConvert.AsPropertyAccessExpression().QuestionDotToken != nil { + if insertQuestionDot || data.propertyAccessToConvert.QuestionDotToken() != nil { insertText = "?." + insertText } @@ -3524,7 +3518,7 @@ func getContextualKeywords(file *ast.SourceFile, contextToken *ast.Node, positio tokenLine, _ := scanner.GetECMALineAndCharacterOfPosition(file, contextToken.End()) currentLine, _ := scanner.GetECMALineAndCharacterOfPosition(file, position) if (ast.IsImportDeclaration(parent) || - ast.IsExportDeclaration(parent) && parent.AsExportDeclaration().ModuleSpecifier != nil) && + ast.IsExportDeclaration(parent) && parent.ModuleSpecifier() != nil) && contextToken == parent.ModuleSpecifier() && tokenLine == currentLine { entries = append(entries, &lsproto.CompletionItem{ @@ -4001,10 +3995,10 @@ func filterObjectMembersList( if ast.IsSpreadAssignment(member) { setMemberDeclaredBySpreadAssignment(member, &membersDeclaredBySpreadAssignment, typeChecker) - } else if ast.IsBindingElement(member) && member.AsBindingElement().PropertyName != nil { + } else if ast.IsBindingElement(member) && member.PropertyName() != nil { // include only identifiers in completion list - if member.AsBindingElement().PropertyName.Kind == ast.KindIdentifier { - existingName = member.AsBindingElement().PropertyName.Text() + if member.PropertyName().Kind == ast.KindIdentifier { + existingName = member.PropertyName().Text() } } else { // TODO: Account for computed property name @@ -4092,7 +4086,7 @@ func tryGetObjectTypeDeclarationCompletionContainer( } return nil case ast.KindEndOfFile: - stmtList := location.Parent.AsSourceFile().Statements + stmtList := location.Parent.StatementList() if stmtList != nil && len(stmtList.Nodes) > 0 && ast.IsObjectTypeDeclaration(stmtList.Nodes[len(stmtList.Nodes)-1]) { cls := stmtList.Nodes[len(stmtList.Nodes)-1] if findChildOfKind(cls, ast.KindCloseBraceToken, file) == nil { @@ -5445,7 +5439,7 @@ func (l *LanguageService) getImportStatementCompletionInfo(contextToken *ast.Nod result.replacementSpan = l.getSingleLineReplacementSpanForImportCompletionNode(candidate) result.couldBeTypeOnlyImportSpecifier = couldBeTypeOnlyImportSpecifier(candidate, contextToken) if ast.IsImportDeclaration(candidate) { - result.isTopLevelTypeOnly = candidate.AsImportDeclaration().ImportClause.IsTypeOnly() + result.isTopLevelTypeOnly = candidate.ImportClause().IsTypeOnly() } else if candidate.Kind == ast.KindImportEqualsDeclaration { result.isTopLevelTypeOnly = candidate.IsTypeOnly() } diff --git a/internal/ls/documenthighlights.go b/internal/ls/documenthighlights.go index a29261249f..8a3b832f1d 100644 --- a/internal/ls/documenthighlights.go +++ b/internal/ls/documenthighlights.go @@ -556,12 +556,9 @@ func getAsyncAndAwaitOccurrences(node *ast.Node, sourceFile *ast.SourceFile) []* var keywords []*ast.Node - modifiers := fun.Modifiers() - if modifiers != nil { - for _, modifier := range modifiers.Nodes { - if modifier.Kind == ast.KindAsyncKeyword { - keywords = append(keywords, modifier) - } + for _, modifier := range fun.ModifierNodes() { + if modifier.Kind == ast.KindAsyncKeyword { + keywords = append(keywords, modifier) } } @@ -678,11 +675,9 @@ func getNodesToSearchForModifier(declaration *ast.Node, modifierFlag ast.Modifie } func findModifier(node *ast.Node, kind ast.Kind) *ast.Node { - if modifiers := node.Modifiers(); modifiers != nil { - for _, modifier := range modifiers.Nodes { - if modifier.Kind == kind { - return modifier - } + for _, modifier := range node.ModifierNodes() { + if modifier.Kind == kind { + return modifier } } return nil diff --git a/internal/ls/findallreferences.go b/internal/ls/findallreferences.go index 5786eae181..545b274993 100644 --- a/internal/ls/findallreferences.go +++ b/internal/ls/findallreferences.go @@ -1150,7 +1150,7 @@ func (l *LanguageService) getReferencedSymbolsForModule(ctx context.Context, pro var node *ast.Node // At `module.exports = ...`, reference node is `module` if ast.IsBinaryExpression(decl) && ast.IsPropertyAccessExpression(decl.AsBinaryExpression().Left) { - node = decl.AsBinaryExpression().Left.AsPropertyAccessExpression().Expression + node = decl.AsBinaryExpression().Left.Expression() } else if ast.IsExportAssignment(decl) { // Find the export keyword node = findChildOfKind(decl, ast.KindExportKeyword, sourceFile) @@ -1428,14 +1428,14 @@ func isNewExpressionTarget(node *ast.Node) bool { if node.Parent == nil { return false } - return node.Parent.Kind == ast.KindNewExpression && node.Parent.AsNewExpression().Expression == node + return node.Parent.Kind == ast.KindNewExpression && node.Parent.Expression() == node } func isCallExpressionTarget(node *ast.Node) bool { if node.Parent == nil { return false } - return node.Parent.Kind == ast.KindCallExpression && node.Parent.AsCallExpression().Expression == node + return node.Parent.Kind == ast.KindCallExpression && node.Parent.Expression() == node } func isMethodOrAccessor(node *ast.Node) bool { diff --git a/internal/ls/hover.go b/internal/ls/hover.go index 002de77956..6d5dffee0d 100644 --- a/internal/ls/hover.go +++ b/internal/ls/hover.go @@ -89,7 +89,7 @@ func (l *LanguageService) getDocumentationFromDeclaration(c *checker.Checker, de case ast.KindJSDocParameterTag, ast.KindJSDocPropertyTag: writeOptionalEntityName(&b, tag.Name()) case ast.KindJSDocAugmentsTag: - writeOptionalEntityName(&b, tag.AsJSDocAugmentsTag().ClassName) + writeOptionalEntityName(&b, tag.ClassName()) case ast.KindJSDocSeeTag: writeOptionalEntityName(&b, tag.AsJSDocSeeTag().NameExpression) case ast.KindJSDocTemplateTag: diff --git a/internal/ls/importTracker.go b/internal/ls/importTracker.go index f2d45dc3e9..88f6febb4c 100644 --- a/internal/ls/importTracker.go +++ b/internal/ls/importTracker.go @@ -304,7 +304,7 @@ func findNamespaceReExports(sourceFileLike *ast.Node, name *ast.Node, checker *c return false } exportClause := statement.AsExportDeclaration().ExportClause - moduleSpecifier := statement.AsExportDeclaration().ModuleSpecifier + moduleSpecifier := statement.ModuleSpecifier() return moduleSpecifier == nil && exportClause != nil && ast.IsNamedExports(exportClause) && core.Some(exportClause.Elements(), func(element *ast.Node) bool { return checker.GetExportSpecifierLocalTargetSymbol(element) == namespaceImportSymbol }) diff --git a/internal/ls/inlay_hints.go b/internal/ls/inlay_hints.go index 9ac0ddc574..215752091e 100644 --- a/internal/ls/inlay_hints.go +++ b/internal/ls/inlay_hints.go @@ -282,8 +282,8 @@ func (s *inlayHintState) addParameterTypeHint(node *ast.ParameterDeclarationNode return } var pos int - if node.AsParameterDeclaration().QuestionToken != nil { - pos = node.AsParameterDeclaration().QuestionToken.End() + if node.QuestionToken() != nil { + pos = node.QuestionToken().End() } else { pos = node.Name().End() } @@ -488,7 +488,7 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node) []*lsproto.Inlay parts = append(parts, &lsproto.InlayHintLabelPart{Value: "..."}) } visitForDisplayParts(node.Name()) - if node.AsParameterDeclaration().QuestionToken != nil { + if node.QuestionToken() != nil { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "?"}) } if node.Type() != nil { @@ -528,7 +528,7 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node) []*lsproto.Inlay parts = append(parts, &lsproto.InlayHintLabelPart{Value: "..."}) } visitForDisplayParts(node.Name()) - if node.AsNamedTupleMember().QuestionToken != nil { + if node.QuestionToken() != nil { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "?"}) } parts = append(parts, &lsproto.InlayHintLabelPart{Value: ": "}) @@ -587,10 +587,10 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node) []*lsproto.Inlay visitForDisplayParts(node.AsMappedTypeNode().NameType) } parts = append(parts, &lsproto.InlayHintLabelPart{Value: "]"}) - if node.AsMappedTypeNode().QuestionToken != nil { - if node.AsMappedTypeNode().QuestionToken.Kind == ast.KindPlusToken { + if node.QuestionToken() != nil { + if node.QuestionToken().Kind == ast.KindPlusToken { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "+"}) - } else if node.AsMappedTypeNode().QuestionToken.Kind == ast.KindMinusToken { + } else if node.QuestionToken().Kind == ast.KindMinusToken { parts = append(parts, &lsproto.InlayHintLabelPart{Value: "-"}) } parts = append(parts, &lsproto.InlayHintLabelPart{Value: "?"}) @@ -628,11 +628,11 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node) []*lsproto.Inlay parts = append(parts, &lsproto.InlayHintLabelPart{Value: " "}) } visitForDisplayParts(node.Name()) - if node.AsPropertySignatureDeclaration().PostfixToken != nil { + if node.PostfixToken() != nil { parts = append( parts, &lsproto.InlayHintLabelPart{ - Value: scanner.TokenToString(node.AsPropertySignatureDeclaration().PostfixToken.Kind), + Value: scanner.TokenToString(node.PostfixToken().Kind), }) } if node.Type() != nil { @@ -653,11 +653,11 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node) []*lsproto.Inlay parts = append(parts, &lsproto.InlayHintLabelPart{Value: " "}) } visitForDisplayParts(node.Name()) - if node.AsMethodSignatureDeclaration().PostfixToken != nil { + if node.PostfixToken() != nil { parts = append( parts, &lsproto.InlayHintLabelPart{ - Value: scanner.TokenToString(node.AsMethodSignatureDeclaration().PostfixToken.Kind), + Value: scanner.TokenToString(node.PostfixToken().Kind), }) } visitParametersAndTypeParameters(node) @@ -715,7 +715,7 @@ func (s *inlayHintState) getInlayHintLabelParts(node *ast.Node) []*lsproto.Inlay parts = append(parts, &lsproto.InlayHintLabelPart{Value: "this"}) case ast.KindComputedPropertyName: parts = append(parts, &lsproto.InlayHintLabelPart{Value: "["}) - visitForDisplayParts(node.AsComputedPropertyName().Expression) + visitForDisplayParts(node.Expression()) parts = append(parts, &lsproto.InlayHintLabelPart{Value: "]"}) default: debug.FailBadSyntaxKind(node) diff --git a/internal/ls/organizeimports/organizeimports.go b/internal/ls/organizeimports/organizeimports.go index f44271f109..57ac06331d 100644 --- a/internal/ls/organizeimports/organizeimports.go +++ b/internal/ls/organizeimports/organizeimports.go @@ -39,11 +39,11 @@ func getModuleSpecifierExpression(declaration *ast.Statement) *ast.Expression { case ast.KindImportEqualsDeclaration: importEquals := declaration.AsImportEqualsDeclaration() if importEquals.ModuleReference.Kind == ast.KindExternalModuleReference { - return importEquals.ModuleReference.AsExternalModuleReference().Expression + return importEquals.ModuleReference.Expression() } return nil case ast.KindImportDeclaration: - return declaration.AsImportDeclaration().ModuleSpecifier + return declaration.ModuleSpecifier() case ast.KindVariableStatement: // For require statements: const x = require('...') variableStatement := declaration.AsVariableStatement() diff --git a/internal/ls/signaturehelp.go b/internal/ls/signaturehelp.go index 7ce6e6c35f..508c74877a 100644 --- a/internal/ls/signaturehelp.go +++ b/internal/ls/signaturehelp.go @@ -610,7 +610,7 @@ func isSyntacticOwner(startingToken *ast.Node, node *ast.CallLikeExpression, sou case ast.KindOpenParenToken, ast.KindCommaToken: return slices.Contains(invocationChildren, startingToken) case ast.KindLessThanToken: - return containsPrecedingToken(startingToken, sourceFile, node.AsCallExpression().Expression) + return containsPrecedingToken(startingToken, sourceFile, node.Expression()) default: return false } diff --git a/internal/ls/string_completions.go b/internal/ls/string_completions.go index cb34509554..35d8b697da 100644 --- a/internal/ls/string_completions.go +++ b/internal/ls/string_completions.go @@ -354,10 +354,7 @@ func (l *LanguageService) getStringLiteralCompletionEntries( } exports := typeChecker.GetExportsAndPropertiesOfModule(moduleSpecifierSymbol) existing := collections.NewSetFromItems(core.Map(namedImportsOrExports.Elements(), func(n *ast.Node) string { - if n.PropertyName() != nil { - return n.PropertyName().Text() - } - return n.Name().Text() + return n.PropertyNameOrName().Text() })...) uniques := core.Filter(exports, func(e *ast.Symbol) bool { return e.Name != ast.InternalSymbolNameDefault && !existing.Has(e.Name) diff --git a/internal/ls/utilities.go b/internal/ls/utilities.go index c46faf93f8..465761bc56 100644 --- a/internal/ls/utilities.go +++ b/internal/ls/utilities.go @@ -81,7 +81,7 @@ func isModuleSpecifierLike(node *ast.Node) bool { } if ast.IsRequireCall(node.Parent, false /*requireStringLiteralLikeArgument*/) || ast.IsImportCall(node.Parent) { - return node.Parent.AsCallExpression().Arguments.Nodes[0] == node + return node.Parent.Arguments()[0] == node } return node.Parent.Kind == ast.KindExternalModuleReference || @@ -157,7 +157,7 @@ func isExportSpecifierAlias(referenceLocation *ast.Identifier, exportSpecifier * } else { // `export { foo } from "foo"` is a re-export. // `export { foo };` is not a re-export, it creates an alias for the local variable `foo`. - return exportSpecifier.Parent.Parent.AsExportDeclaration().ModuleSpecifier == nil + return exportSpecifier.Parent.Parent.ModuleSpecifier() == nil } } @@ -368,7 +368,7 @@ func isThis(node *ast.Node) bool { return true case ast.KindIdentifier: // 'this' as a parameter - return node.AsIdentifier().Text == "this" && node.Parent.Kind == ast.KindParameter + return node.Text() == "this" && node.Parent.Kind == ast.KindParameter default: return false } @@ -672,7 +672,7 @@ func isCompletedNode(n *ast.Node, sourceFile *ast.SourceFile) bool { return isCompletedNode(n.AsCatchClause().Block, sourceFile) case ast.KindNewExpression: - if n.AsNewExpression().Arguments == nil { + if n.ArgumentList() == nil { return true } fallthrough @@ -707,7 +707,7 @@ func isCompletedNode(n *ast.Node, sourceFile *ast.SourceFile) bool { return hasChildOfKind(n, ast.KindCloseParenToken, sourceFile) case ast.KindModuleDeclaration: - return n.AsModuleDeclaration().Body != nil && isCompletedNode(n.AsModuleDeclaration().Body, sourceFile) + return n.Body() != nil && isCompletedNode(n.Body(), sourceFile) case ast.KindIfStatement: if n.AsIfStatement().ElseStatement != nil { @@ -716,7 +716,7 @@ func isCompletedNode(n *ast.Node, sourceFile *ast.SourceFile) bool { return isCompletedNode(n.AsIfStatement().ThenStatement, sourceFile) case ast.KindExpressionStatement: - return isCompletedNode(n.AsExpressionStatement().Expression, sourceFile) || + return isCompletedNode(n.Expression(), sourceFile) || hasChildOfKind(n, ast.KindSemicolonToken, sourceFile) case ast.KindArrayLiteralExpression, @@ -747,7 +747,7 @@ func isCompletedNode(n *ast.Node, sourceFile *ast.SourceFile) bool { if hasChildOfKind(n, ast.KindWhileKeyword, sourceFile) { return nodeEndsWith(n, ast.KindCloseParenToken, sourceFile) } - return isCompletedNode(n.AsDoStatement().Statement, sourceFile) + return isCompletedNode(n.Statement(), sourceFile) case ast.KindTypeQuery: return isCompletedNode(n.AsTypeQueryNode().ExprName, sourceFile) @@ -858,7 +858,7 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF // specially by `getSymbolAtLocation`. isModifier := func(node *ast.Node) bool { if ast.IsModifier(node) && (forRename || node.Kind != ast.KindDefaultKeyword) { - return ast.CanHaveModifiers(parent) && parent.Modifiers() != nil && slices.Contains(parent.Modifiers().NodeList.Nodes, node) + return ast.CanHaveModifiers(parent) && slices.Contains(parent.ModifierNodes(), node) } switch node.Kind { case ast.KindClassKeyword: @@ -925,8 +925,8 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF // export { propertyName /**/as [|name|] } ... // export * /**/as [|name|] ... if node.Kind == ast.KindAsKeyword { - if parent.Kind == ast.KindImportSpecifier && parent.AsImportSpecifier().PropertyName != nil || - parent.Kind == ast.KindExportSpecifier && parent.AsExportSpecifier().PropertyName != nil || + if parent.Kind == ast.KindImportSpecifier && parent.PropertyName() != nil || + parent.Kind == ast.KindExportSpecifier && parent.PropertyName() != nil || parent.Kind == ast.KindNamespaceImport || parent.Kind == ast.KindNamespaceExport { return parent.Name() @@ -963,21 +963,18 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF // /**/export default [|name|]; // /**/export = [|name|]; if parent.Kind == ast.KindExportAssignment { - return ast.SkipOuterExpressions(parent.AsExportAssignment().Expression, ast.OEKAll) + return ast.SkipOuterExpressions(parent.Expression(), ast.OEKAll) } } // import name = /**/require("[|module|]"); if node.Kind == ast.KindRequireKeyword && parent.Kind == ast.KindExternalModuleReference { - return parent.AsExternalModuleReference().Expression + return parent.Expression() } // import ... /**/from "[|module|]"; // export ... /**/from "[|module|]"; if node.Kind == ast.KindFromKeyword { - if parent.Kind == ast.KindImportDeclaration && parent.AsImportDeclaration().ModuleSpecifier != nil { - return parent.AsImportDeclaration().ModuleSpecifier - } - if parent.Kind == ast.KindImportDeclaration && parent.AsExportDeclaration().ModuleSpecifier != nil { - return parent.AsExportDeclaration().ModuleSpecifier + if (parent.Kind == ast.KindImportDeclaration || parent.Kind == ast.KindExportDeclaration) && parent.ModuleSpecifier() != nil { + return parent.ModuleSpecifier() } } // class ... /**/extends [|name|] ... @@ -1077,7 +1074,7 @@ func getAdjustedLocation(node *ast.Node, forRename bool, sourceFile *ast.SourceF // for (... /**/of [|name|]) if node.Kind == ast.KindInKeyword && parent.Kind == ast.KindForInStatement || node.Kind == ast.KindOfKeyword && parent.Kind == ast.KindForOfStatement { - return ast.SkipOuterExpressions(parent.AsForInOrOfStatement().Expression, ast.OEKAll) + return ast.SkipOuterExpressions(parent.Expression(), ast.OEKAll) } } @@ -1095,9 +1092,7 @@ func getAdjustedLocationForDeclaration(node *ast.Node, forRename bool, sourceFil case ast.KindClassDeclaration, ast.KindFunctionDeclaration: // for class and function declarations, use the `default` modifier // when the declaration is unnamed. - if node.Modifiers() != nil { - return core.Find(node.Modifiers().NodeList.Nodes, func(*ast.Node) bool { return node.Kind == ast.KindDefaultKeyword }) - } + return core.Find(node.ModifierNodes(), func(*ast.Node) bool { return node.Kind == ast.KindDefaultKeyword }) case ast.KindClassExpression: // for class expressions, use the `class` keyword when the class is unnamed return findChildOfKind(node, ast.KindClassKeyword, sourceFile) @@ -1132,11 +1127,11 @@ func getAdjustedLocationForImportDeclaration(node *ast.ImportDeclaration, forRen switch namedBindings.Kind { case ast.KindNamedImports: // do nothing if there is more than one binding - elements := namedBindings.AsNamedImports().Elements - if len(elements.Nodes) != 1 { + elements := namedBindings.Elements() + if len(elements) != 1 { return nil } - return elements.Nodes[0].Name() + return elements[0].Name() case ast.KindNamespaceImport: return namedBindings.Name() @@ -1164,11 +1159,11 @@ func getAdjustedLocationForExportDeclaration(node *ast.ExportDeclaration, forRen switch node.ExportClause.Kind { case ast.KindNamedExports: // do nothing if there is more than one binding - elements := node.ExportClause.AsNamedExports().Elements - if len(elements.Nodes) != 1 { + elements := node.ExportClause.Elements() + if len(elements) != 1 { return nil } - return elements.Nodes[0].Name() + return elements[0].Name() case ast.KindNamespaceExport: return node.ExportClause.Name() } @@ -1388,8 +1383,8 @@ func getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol *ast.Symb func getTargetLabel(referenceNode *ast.Node, labelName string) *ast.Node { // todo: rewrite as `ast.FindAncestor` for referenceNode != nil { - if referenceNode.Kind == ast.KindLabeledStatement && referenceNode.AsLabeledStatement().Label.Text() == labelName { - return referenceNode.AsLabeledStatement().Label + if referenceNode.Kind == ast.KindLabeledStatement && referenceNode.Label().Text() == labelName { + return referenceNode.Label() } referenceNode = referenceNode.Parent } diff --git a/internal/modulespecifiers/specifiers.go b/internal/modulespecifiers/specifiers.go index fd040fc14e..d5a4c10767 100644 --- a/internal/modulespecifiers/specifiers.go +++ b/internal/modulespecifiers/specifiers.go @@ -81,8 +81,8 @@ func GetModuleSpecifiersWithInfo( func tryGetModuleNameFromAmbientModule(moduleSymbol *ast.Symbol, checker CheckerShape) string { for _, decl := range moduleSymbol.Declarations { - if isNonGlobalAmbientModule(decl) && (!ast.IsModuleAugmentationExternal(decl) || !tspath.IsExternalModuleNameRelative(decl.Name().AsStringLiteral().Text)) { - return decl.Name().AsStringLiteral().Text + if isNonGlobalAmbientModule(decl) && (!ast.IsModuleAugmentationExternal(decl) || !tspath.IsExternalModuleNameRelative(decl.Name().Text())) { + return decl.Name().Text() } } @@ -123,7 +123,7 @@ func tryGetModuleNameFromAmbientModule(moduleSymbol *ast.Symbol, checker Checker } // TODO: Possible strada bug - isn't this insufficient in the presence of merge symbols? if exportSymbol == d.Symbol() { - return possibleContainer.Name().AsStringLiteral().Text + return possibleContainer.Name().Text() } } return "" diff --git a/internal/parser/jsdoc.go b/internal/parser/jsdoc.go index 477628c0d5..a3eec501ce 100644 --- a/internal/parser/jsdoc.go +++ b/internal/parser/jsdoc.go @@ -711,7 +711,7 @@ func isObjectOrObjectArrayTypeReference(node *ast.TypeNode) bool { default: if ast.IsTypeReferenceNode(node) { ref := node.AsTypeReferenceNode() - return ast.IsIdentifier(ref.TypeName) && ref.TypeName.AsIdentifier().Text == "Object" && ref.TypeArguments == nil + return ast.IsIdentifier(ref.TypeName) && ref.TypeName.Text() == "Object" && ref.TypeArguments == nil } return false } @@ -759,7 +759,7 @@ func (p *Parser) parseNestedTypeLiteral(typeExpression *ast.Node, name *ast.Enti if child.Kind == ast.KindJSDocParameterTag || child.Kind == ast.KindJSDocPropertyTag { children = append(children, child) } else if child.Kind == ast.KindJSDocTemplateTag { - p.parseErrorAtRange(child.AsJSDocTemplateTag().TagName.Loc, diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag) + p.parseErrorAtRange(child.TagName().Loc, diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag) } } if children != nil { @@ -967,7 +967,7 @@ func (p *Parser) parseCallbackTagParameters(indent int) *ast.NodeList { break } if child.Kind == ast.KindJSDocTemplateTag { - p.parseErrorAtRange(child.AsJSDocTemplateTag().TagName.Loc, diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag) + p.parseErrorAtRange(child.TagName().Loc, diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag) break } parameters = append(parameters, child) @@ -1033,7 +1033,7 @@ func textsEqual(a *ast.EntityName, b *ast.EntityName) bool { return false } } - return a.AsIdentifier().Text == b.AsIdentifier().Text + return a.Text() == b.Text() } func (p *Parser) parseChildPropertyTag(indent int) *ast.Node { diff --git a/internal/parser/parser.go b/internal/parser/parser.go index 7f9e570c83..01899cb985 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -1894,7 +1894,7 @@ func (p *Parser) parseErrorForMissingSemicolonAfter(node *ast.Node) { // Otherwise, if this isn't a well-known keyword-like identifier, give the generic fallback message. var expressionText string if node.Kind == ast.KindIdentifier { - expressionText = node.AsIdentifier().Text + expressionText = node.Text() } if expressionText == "" { p.parseErrorAtCurrentToken(diagnostics.X_0_expected, scanner.TokenToString(ast.KindSemicolonToken)) @@ -2115,7 +2115,7 @@ func (p *Parser) parseImportDeclarationOrImportEqualsDeclaration(pos int, hasJSD identifier = p.parseIdentifier() } phaseModifier := ast.KindUnknown - if identifier != nil && identifier.AsIdentifier().Text == "type" && + if identifier != nil && identifier.Text() == "type" && (p.token != ast.KindFromKeyword || p.isIdentifier() && p.lookAhead((*Parser).nextTokenIsFromKeywordOrEqualsToken)) && (p.isIdentifier() || p.tokenAfterImportDefinitelyProducesImportDeclaration()) { phaseModifier = ast.KindTypeKeyword @@ -2123,7 +2123,7 @@ func (p *Parser) parseImportDeclarationOrImportEqualsDeclaration(pos int, hasJSD if p.isIdentifier() { identifier = p.parseIdentifier() } - } else if identifier != nil && identifier.AsIdentifier().Text == "defer" { + } else if identifier != nil && identifier.Text() == "defer" { var shouldParseAsDeferModifier bool if p.token == ast.KindFromKeyword { shouldParseAsDeferModifier = !p.lookAhead((*Parser).nextTokenIsTokenStringLiteral) @@ -2298,7 +2298,7 @@ func (p *Parser) parseImportOrExportSpecifier(kind ast.Kind) (isTypeOnly bool, p disallowKeywords := kind == ast.KindImportSpecifier var nameOk bool name, nameOk = p.parseModuleExportName(disallowKeywords) - if name.Kind == ast.KindIdentifier && name.AsIdentifier().Text == "type" { + if name.Kind == ast.KindIdentifier && name.Text() == "type" { // If the first token of an import specifier is 'type', there are a lot of possibilities, // especially if we see 'as' afterwards: // @@ -4259,7 +4259,7 @@ func (p *Parser) parseParenthesizedArrowFunctionExpression(allowAmbiguity bool, // So we need just a bit of lookahead to ensure that it can only be a signature. unwrappedType := returnType for unwrappedType != nil && unwrappedType.Kind == ast.KindParenthesizedType { - unwrappedType = unwrappedType.AsParenthesizedTypeNode().Type // Skip parens if need be + unwrappedType = unwrappedType.Type() // Skip parens if need be } if !allowAmbiguity && p.token != ast.KindEqualsGreaterThanToken && p.token != ast.KindOpenBraceToken { // Returning undefined here will cause our caller to rewind to where we started from. @@ -4321,10 +4321,8 @@ func typeHasArrowFunctionBlockingParseError(node *ast.TypeNode) bool { switch node.Kind { case ast.KindTypeReference: return ast.NodeIsMissing(node.AsTypeReference().TypeName) - case ast.KindFunctionType, ast.KindConstructorType: + case ast.KindFunctionType, ast.KindConstructorType, ast.KindParenthesizedType: return typeHasArrowFunctionBlockingParseError(node.Type()) - case ast.KindParenthesizedType: - return typeHasArrowFunctionBlockingParseError(node.AsParenthesizedTypeNode().Type) } return false } @@ -4600,8 +4598,8 @@ func (p *Parser) parseJsxElementOrSelfClosingElementOrFragment(inExpressionConte var closingElement *ast.Node lastChild := core.LastOrNil(children.Nodes) if lastChild != nil && lastChild.Kind == ast.KindJsxElement && - !tagNamesAreEquivalent(lastChild.AsJsxElement().OpeningElement.AsJsxOpeningElement().TagName, lastChild.AsJsxElement().ClosingElement.AsJsxClosingElement().TagName) && - tagNamesAreEquivalent(opening.AsJsxOpeningElement().TagName, lastChild.AsJsxElement().ClosingElement.AsJsxClosingElement().TagName) { + !tagNamesAreEquivalent(lastChild.AsJsxElement().OpeningElement.TagName(), lastChild.AsJsxElement().ClosingElement.TagName()) && + tagNamesAreEquivalent(opening.TagName(), lastChild.AsJsxElement().ClosingElement.TagName()) { // when an unclosed JsxOpeningElement incorrectly parses its parent's JsxClosingElement, // restructure (